Programs & Examples On #Shiro

Apache Shiro is a Java security framework that performs authentication, authorization, cryptography, and session management.

How to trim a list in Python

You just subindex it with [:5] indicating that you want (up to) the first 5 elements.

>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]

Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!

>>> x[5:]
[11, 12]

Saving numpy array to txt file row wise

I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:

numpy.savetxt(filename, [a], delimiter='\t')

How to run SQL in shell script

Code

PL_CONNECT_STRING="$DB_USERNAME/$DB_PASSWORD@$DB_SERVICE"

OUTPUT=$(sqlplus -s $PL_CONNECT_STRING <<-END-OF-SQL
           select count(*) from table;
exit;
END-OF-SQL)
echo "COMPLETED GATHER STATS $OUTPUT";

Explanation:

PL_CONNECT_STRING carry database username, password and it service name

sqlplus is used to connect the Database with PL_CONNECT_STRING details

END-OF-SQL tag contain the query which you want to execute

echo is used to print the output of the query

NOTE: You can give multiple Query inside the END-OF-SQL tag, so its useful for batch execution as well

What is the difference between T(n) and O(n)?

f(n) belongs to O(n) if exists positive k as f(n)<=k*n

f(n) belongs to T(n) if exists positive k1, k2 as k1*n<=f(n)<=k2*n

Wikipedia article on Big O Notation

Corrupted Access .accdb file: "Unrecognized Database Format"

Sometimes it might depend on whether you are using code to access the database or not. If you are using "DriverJet" in your code instead of "DriverACE" (or an older version of the DAO library) such a problem is highly probable to happen. You just need to replace "DriverJet" with "DriverACE" and test.

Show ImageView programmatically

int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp = 
    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);        
imageView.setImageResource(id);        
someLinearLayout.addView(imageView); 

How to do an INNER JOIN on multiple columns

If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:

SELECT
   Flights.*,fromAirports.*,toAirports.*
FROM
   Flights
INNER JOIN 
   Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN 
   Airports toAirports on Flights.tairport = toAirports.code
WHERE
 ...

Multi-dimensional arrays in Bash

Expanding on Paul's answer - here's my version of working with associative sub-arrays in bash:

declare -A SUB_1=(["name1key"]="name1val" ["name2key"]="name2val")
declare -A SUB_2=(["name3key"]="name3val" ["name4key"]="name4val")
STRING_1="string1val"
STRING_2="string2val"
MAIN_ARRAY=(
  "${SUB_1[*]}"
  "${SUB_2[*]}"
  "${STRING_1}"
  "${STRING_2}"
)
echo "COUNT: " ${#MAIN_ARRAY[@]}
for key in ${!MAIN_ARRAY[@]}; do
    IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}
    echo "VALUE: " ${val[@]}
    if [[ ${#val[@]} -gt 1 ]]; then
        for subkey in ${!val[@]}; do
            subval=${val[$subkey]}
            echo "SUBVALUE: " ${subval}
        done
    fi
done

It works with mixed values in the main array - strings/arrays/assoc. arrays

The key here is to wrap the subarrays in single quotes and use * instead of @ when storing a subarray inside the main array so it would get stored as a single, space separated string: "${SUB_1[*]}"

Then it makes it easy to parse an array out of that when looping through values with IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}

The code above outputs:

COUNT:  4
VALUE:  name1val name2val
SUBVALUE:  name1val
SUBVALUE:  name2val
VALUE:  name4val name3val
SUBVALUE:  name4val
SUBVALUE:  name3val
VALUE:  string1val
VALUE:  string2val

Why is there no tuple comprehension in Python?

We can generate tuples from a list comprehension. The following one adds two numbers sequentially into a tuple and gives a list from numbers 0-9.

>>> print k
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> r= [tuple(k[i:i+2]) for i in xrange(10) if not i%2]
>>> print r
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

HTTP Ajax Request via HTTPS Page

From the javascript I tried from several ways and I could not.

You need an server side solution, for example on c# I did create an controller that call to the http, en deserialize the object, and the result is that when I call from javascript, I'm doing an request from my https://domain to my htpps://domain. Please see my c# code:

[Authorize]
public class CurrencyServicesController : Controller
{
    HttpClient client;
    //GET: CurrencyServices/Consultar?url=valores?moedas=USD&alt=json
    public async Task<dynamic> Consultar(string url)
    {
        client = new HttpClient();
        client.BaseAddress = new Uri("http://api.promasters.net.br/cotacao/v1/");
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        System.Net.Http.HttpResponseMessage response = client.GetAsync(url).Result;

        var FromURL = response.Content.ReadAsStringAsync().Result;

        return JsonConvert.DeserializeObject(FromURL);
    }

And let me show to you my client side (Javascript)

<script async>
$(document).ready(function (data) {

    var TheUrl = '@Url.Action("Consultar", "CurrencyServices")?url=valores';
    $.getJSON(TheUrl)
        .done(function (data) {
            $('#DolarQuotation').html(
                '$ ' + data.valores.USD.valor.toFixed(2) + ','
            );
            $('#EuroQuotation').html(
                '€ ' + data.valores.EUR.valor.toFixed(2) + ','
            );

            $('#ARGPesoQuotation').html(
                'Ar$ ' + data.valores.ARS.valor.toFixed(2) + ''
            );

        });       

});

I wish that this help you! Greetings

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

How do I convert a double into a string in C++?

You can use std::to_string in C++11

double d = 3.0;
std::string str = std::to_string(d);

Check mySQL version on Mac 10.8.5

You should be able to open terminal and just type

mysql -v

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

How to verify if nginx is running or not?

The modern (systemctl) way of doing it:

systemctl is-active nginx

You can use the exit value in your shell scripts as follows:

systemctl -q is-active nginx && echo "It is active, do something"

Intersect Two Lists in C#

If you have objects, not structs (or strings), then you'll have to intersect their keys first, and then select objects by those keys:

var ids = list1.Select(x => x.Id).Intersect(list2.Select(x => x.Id));
var result = list1.Where(x => ids.Contains(x.Id));

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Kotlin:

var ver: String = packageManager.getPackageInfo(packageName, 0).versionName

Instagram API: How to get all user media?

See http://instagram.com/developer/endpoints/ for information on pagination. You need to subsequentially step through the result pages, each time requesting the next part with the next_url that the result specifies in the pagination object.

The smallest difference between 2 Angles

x is the target angle. y is the source or starting angle:

atan2(sin(x-y), cos(x-y))

It returns the signed delta angle. Note that depending on your API the order of the parameters for the atan2() function might be different.

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

Go to first line in a file in vim?

In command mode (press Esc if you are not sure) you can use:

  • gg,
  • :1,
  • 1G,
  • or 1gg.

Calling a function every 60 seconds

If you don't care if the code within the timer may take longer than your interval, use setInterval():

setInterval(function, delay)

That fires the function passed in as first parameter over and over.

A better approach is, to use setTimeout along with a self-executing anonymous function:

(function(){
    // do some stuff
    setTimeout(arguments.callee, 60000);
})();

that guarantees, that the next call is not made before your code was executed. I used arguments.callee in this example as function reference. It's a better way to give the function a name and call that within setTimeout because arguments.callee is deprecated in ecmascript 5.

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

How to install popper.js with Bootstrap 4?

Bootstrap 4 has two dependencies: jQuery 1.9.1 and popper.js 1.12.3. When you install Bootstrap 4, you need to install these two dependencies.

For Bootstrap 4.1

How to convert a String to long in javascript?

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

Tkinter understanding mainloop

I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).

In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!

As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.

import Tkinter as tk

class Window(tk.Frame):
    def __init__(self, master=None, view=None ):
        tk.Frame.__init__( self, master )
        self.view_ = view       
        """ Setup window linking it to the view... """

class GuiView( MyViewSuperClass ):

    def open( self ):
        self.tkRoot_ = tk.Tk()
        self.window_ = Window( master=None, view=self )
        self.window_.pack()
        self.refresh()
        self.onOpen()
        self.tkRoot_.mainloop()         

    def onOpen( self ):        
        """ Do some initial tasks... """

    def refresh( self ):        
        self.tkRoot_.update()

Validating input using java.util.Scanner

what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input

Scanner s=new Scanner(System.in);

    int a=s.nextInt();
    while(a<0)
    {
    System.out.println("please provide non negative integer input ");
    a=s.nextInt();
    }
    System.out.println("the non negative integer input is "+a);

Here, you need to take the character input first and check whether user gave character or not if not than again take the character input

    char ch = s.findInLine(".").charAt(0);
    while(!Charcter.isLetter(ch))
    {
    System.out.println("please provide a character input ");
    ch=s.findInLine(".").charAt(0);
    }
    System.out.println("the character  input is "+ch);

How make background image on newsletter in outlook?

The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.

The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.

<td bgcolor="#your_color" background="your_image.jpg">

<!--[if gte mso 9]>

<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>

<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>

<![endif]-->

<p>Text over background image.</p>

<!--[if gte mso 9]>

</v:shape>

<![endif]-->

</td>

source

Constraint Layout Vertical Align Center

If you have a ConstraintLayout with some size, and a child View with some smaller size, you can achieve centering by constraining the child's two edges to the same two edges of the parent. That is, you can write:

app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"

or

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"

Because the view is smaller, these constraints are impossible. But ConstraintLayout will do the best it can, and each constraint will "pull" at the child view equally, thereby centering it.

This concept works with any target view, not just the parent.

Update

Below is XML that achieves your desired UI with no nesting of views and no Guidelines (though guidelines are not inherently evil).

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#eee">

    <TextView
        android:id="@+id/title1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="22sp"
        android:text="10"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/divider1"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/label1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="12sp"
        android:text="Streak"
        app:layout_constraintTop_toBottomOf="@+id/title1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/divider1"/>

    <View
        android:id="@+id/divider1"
        android:layout_width="1dp"
        android:layout_height="55dp"
        android:layout_marginTop="12dp"
        android:layout_marginBottom="12dp"
        android:background="#ccc"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/title1"
        app:layout_constraintRight_toLeftOf="@+id/title2"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/title2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="22sp"
        android:text="243"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/divider1"
        app:layout_constraintRight_toLeftOf="@+id/divider2"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/label2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="12sp"
        android:text="Calories Burned"
        app:layout_constraintTop_toBottomOf="@+id/title2"
        app:layout_constraintLeft_toRightOf="@+id/divider1"
        app:layout_constraintRight_toLeftOf="@+id/divider2"/>

    <View
        android:id="@+id/divider2"
        android:layout_width="1dp"
        android:layout_height="55dp"
        android:layout_marginTop="12dp"
        android:layout_marginBottom="12dp"
        android:background="#ccc"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/title2"
        app:layout_constraintRight_toLeftOf="@+id/title3"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/title3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="22sp"
        android:text="3200"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/divider2"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/label3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#777"
        android:textSize="12sp"
        android:text="Steps"
        app:layout_constraintTop_toBottomOf="@+id/title3"
        app:layout_constraintLeft_toRightOf="@+id/divider2"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>

enter image description here

Cannot bulk load. Operating system error code 5 (Access is denied.)

This error appears when you are using SQL Server Authentication and SQL Server is not allowed to access the bulk load folder.

So giving SQL server access to the folder will solve the issue. enter image description here

Here is how to: Go to the folder right click ->properties->Security tab->Edit->Add(on the new window) ->Advanced -> Find Now. Under the users list in the search results, find something like SQLServerMSSQLUser$UserName$SQLExpress and click ok, to all the dialogs opened.

How to remove square brackets in string using regex?

here you go

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

Show all current locks from get_lock

I found following way which can be used if you KNOW name of lock

select IS_USED_LOCK('lockname');

however i not found any info about how to list all names.

How to make a great R reproducible example

Here is a good guide.

The most important point is: Just make sure that you make a small piece of code that we can run to see what the problem is. A useful function for this is dput(), but if you have very large data, you might want to make a small sample dataset or only use the first 10 lines or so.

EDIT:

Also make sure that you identified where the problem is yourself. The example should not be an entire R script with "On line 200 there is an error". If you use the debugging tools in R (I love browser()) and Google you should be able to really identify where the problem is and reproduce a trivial example in which the same thing goes wrong.

Function to calculate distance between two coordinates

As said before, your function is calculating a straight line distance to the destination point. If you want the driving distance/route, you can use Google Maps Distance Matrix Service:

getDrivingDistanceBetweenTwoLatLong(origin, destination) {

 return new Observable(subscriber => {
  let service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [new google.maps.LatLng(origin.lat, origin.long)],
      destinations: [new google.maps.LatLng(destination.lat, destination.long)],
      travelMode: 'DRIVING'
    }, (response, status) => {
      if (status !== google.maps.DistanceMatrixStatus.OK) {
        console.log('Error:', status);
        subscriber.error({error: status, status: status});
      } else {
        console.log(response);
        try {
          let valueInMeters = response.rows[0].elements[0].distance.value;
          let valueInKms = valueInMeters / 1000;
          subscriber.next(valueInKms);
          subscriber.complete();
        }
       catch(error) {
        subscriber.error({error: error, status: status});
       }
      }
    });
});
}

jQuery: get parent, parent id?

Here are 3 examples:

_x000D_
_x000D_
$(document).on('click', 'ul li a', function (e) {_x000D_
    e.preventDefault();_x000D_
_x000D_
    var example1 = $(this).parents('ul:first').attr('id');_x000D_
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
    var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
  _x000D_
    var example3 = $(this).closest('ul').attr('id');_x000D_
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
  _x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
  <li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
  <h1>Results:</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Let me know whether it was helpful.

How do I change the formatting of numbers on an axis with ggplot?

Another option is to format your axis tick labels with commas is by using the package scales, and add

 scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = comma)

to your ggplot statement.

If you don't want to load the package, use:

scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = scales::comma)

Route [login] not defined

**Adding this for the future me.**
I encountered this because I was reusing Laravel's "HomeController", and adding my custom functions to it. Note that this controller calls the auth middleware in its __construct() method as shown below, which means that all functions must be authenticated. No wonder it tries to take you to login page first. So, if you are not using Laravel's authentication scafffolding, you will be in a mess. Disable the constructor, or do as you seem fit, now that you know what is happening.

public function __construct()
{
    $this->middleware('auth');
}

How do I export an Android Studio project?

In the Android Studio go to File then Close Project. Then take the folder (in the workspace folder) of the project and copy it to a flash memory or whatever. Then when you get comfortable at home, copy this folder in the workspace folder you've already created, open the Android Studio and go to File then Open and import this project into your workspace.

The problem you have with this is that you're searching for the wrong term here, because in Android, exporting a project means compiling it to .apk file (not exporting the project). Import/Export is used for the .apk management, what you need is Open/Close project, the other thing is just copy/paste.

How to get EditText value and display it on screen through TextView?

EditText ein=(EditText)findViewById(R.id.edittext1);
TextView t=new TextView(this);
t.setText("Your Text is="+ein.getText());
setContentView(t);

Environment Variable with Maven

Another solution would be to set MAVEN_OPTS (or other environment variables) in ${user.home}/.mavenrc (or %HOME%\mavenrc_pre.bat on windows).

Since Maven 3.3.1 there are new possibilities to set mvn command line parameters, if this is what you actually want:

  • ${maven.projectBasedir}/.mvn/maven.config
  • ${maven.projectBasedir}/.mvn/jvm.config

How can I count the number of elements of a given value in a matrix?

Use nnz instead of sum. No need for the double call to collapse matrices to vectors and it is likely faster than sum.

nnz(your_matrix == 5)

Doc

Subtract minute from DateTime in SQL Server 2005

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); 

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); 

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)

How to find the remainder of a division in C?

You can use the % operator to find the remainder of a division, and compare the result with 0.

Example:

if (number % divisor == 0)
{
    //code for perfect divisor
}
else
{
    //the number doesn't divide perfectly by divisor
}

Summing elements in a list

You can use sum to sum the elements of a list, however if your list is coming from raw_input, you probably want to convert the items to int or float first:

l = raw_input().split(' ')
sum(map(int, l))

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

Update for those using Python3: You can simply use conda install mysqlclient to install the libraries required to use MySQLdb as it currently exists. The following SO question was a helpful clue: Python 3 ImportError: No module named 'ConfigParser' . Installing mysqlclient will install mysqlclient, mysql-connector, and llvmdev (at least, it installed these 3 libraries on my machine).

Here is the tale of my rambling experience with this problem. Would love to see it edited or generalised if you have better experience of the issue... apply a bit of that SO magic.

Note: Comments in next paragraph applied to Snow Leopard, but not to Lion, which appears to require 64-bit MySQL

First off, the author (still?) of MySQLdb says here that one of the most pernicious problems is that OS X comes installed with a 32 bit version of Python, but most average joes (myself included) probably jump to install the 64 bit version of MySQL. Bad move... remove the 64 bit version if you have installed it (instructions on this fiddly task are available on SO here), then download and install the 32 bit version (package here)

There are numerous step-by-steps on how to build and install the MySQLdb libraries. They often have subtle differences. This seemed the most popular to me, and provided the working solution. I've reproduced it with a couple of edits below

Step 0: Before I start, I assume that you have MySQL, Python, and GCC installed on the mac.

Step 1: Download the latest MySQL for Python adapter from SourceForge.

Step 2: Extract your downloaded package:

tar xzvf MySQL-python-1.2.2.tar.gz

Step 3: Inside the folder, clean the package:

sudo python setup.py clean

COUPLE OF EXTRA STEPS, (from this comment)

Step 3b: Remove everything under your MySQL-python-1.2.2/build/* directory -- don't trust the "python setup.py clean" to do it for you

Step 3c: Remove the egg under Users/$USER/.python-eggs

Step 4: Originally required editing _mysql.c, but is now NO LONGER NECESSARY. MySQLdb community seem to have fixed this bug now.

Step 5: Create a symbolic link under lib to point to a sub-directory called mysql. This is where it looks for during compilation.

sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql

Step 6: Edit the setup_posix.py and change the following

mysql_config.path = "mysql_config"

to

mysql_config.path = "/usr/local/mysql/bin/mysql_config"

Step 7: In the same directory, rebuild your package (ignore the warnings that comes with it)

sudo python setup.py build

Step 8: Install the package and you are done.

sudo python setup.py install

Step 9: Test if it's working. It works if you can import MySQLdb.

python

>>> import MySQLdb

Step 10: If upon trying to import you receive an error complaining that Library not loaded: libmysqlclient.18.dylib ending with: Reason: image not found you need to create one additional symlink which is:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

You should then be able to import MySQLdb without any errors.

One final hiccup though is that if you start Python from the build directory you will get this error:

/Library/Python/2.5/site-packages/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Python/2.5/site-packages/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg/_mysql.pyc, but XXXX/MySQL-python-1.2.3c1 is being added to sys.path

This is pretty easy to Google, but to save you the trouble you will end up here (or maybe not... not a particularly future-proof URL) and figure out that you need to cd .. out of build directory and the error should disappear.

As I wrote at the top, I'd love to see this answer generalised, as there are numerous other specific experiences of this horrible problem out there. Edit away, or provide your own, better answer.

IE8 css selector

I'm not going to get in a debate about whether or not this method should be used, but this will let you set specific css attributes for IE8-9 only (note: it is not a selector, so a bit different than what you asked):

Use '\0/' after each css declaration, so:

#nav li ul  {
  left: -39px\0/ !important;
}

And to build off another answer, you can do this to assign variou styles to IE6, IE7, and IE8:

#nav li ul  {
   *left: -7px    !important; /* IE 7 (IE6 also uses this, so put it first) */
   _left: -6px    !important; /* IE 6 */
    left: -8px\0/ !important; /* IE 8-9 */
}

source: http://dimox.net/personal-css-hacks-for-ie6-ie7-ie8/

What is the difference between a process and a thread?

Process:

  1. Process is a heavy weight process.
  2. Process is a separate program that has separate memory,data,resources ect.
  3. Process are created using fork() method.
  4. Context switch between the process is time consuming.

Example:
Say, opening any browser (mozilla, Chrome, IE). At this point new process will start to execute.

Threads:

  1. Threads are light weight processes.Threads are bundled inside the process.
  2. Threads have a shared memory,data,resources,files etc.
  3. Threads are created using clone() method.
  4. Context switch between the threads are not much time consuming as Process.

Example:
Opening multiple tabs in the browser.

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

Is there StartsWith or Contains in t sql with variables?

StartsWith

a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1

Contains

charindex('Express Edition', @edition) >= 1

Examples

left function

set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end

iif function (starting with SQL Server 2012)

set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);

charindex function

set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);

Javascript receipt printing using POS Printer

You could try using https://www.printnode.com which is essentially exactly the service that you are looking for. You download and install a desktop client onto the users computer - https://www.printnode.com/download. You can then discover and print to any printers on that user's computer using their JSON API https://www.printnode.com/docs/api/curl/. They have lots of libs here: https://github.com/PrintNode/

What does the @Valid annotation indicate in Spring?

Just adding to the above answer, In a web application @valid is used where the bean to be validated is also annotated with validation annotations e.g. @NotNull, @Email(hibernate annotation) so when while getting input from user the values can be validated and binding result will have the validation results. bindingResult.hasErrors() will tell if any validation failed.

What does the KEY keyword mean?

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

column_definition:
      data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      ...

Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Docker-compose: node_modules not present in a volume after npm install succeeds

There is also some simple solution without mapping node_module directory into another volume. It's about to move installing npm packages into final CMD command.

Disadvantage of this approach:

  • run npm install each time you run container (switching from npm to yarn might also speed up this process a bit).

worker/Dockerfile

FROM node:0.12
WORKDIR /worker
COPY package.json /worker/
COPY . /worker/
CMD /bin/bash -c 'npm install; npm start'

docker-compose.yml

redis:
    image: redis
worker:
    build: ./worker
    ports:
        - "9730:9730"
    volumes:
        - worker/:/worker/
    links:
        - redis

htaccess remove index.php from url

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]

How to return a dictionary | Python

What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:

def query(id):
    for line in file:
        table = {}
        (table["ID"],table["name"],table["city"]) = line.split(";")
        if id == int(table["ID"]):
             file.close()
             return table
    # ID not found; close file and return empty dict
    file.close()
    return {}

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Sleeping in a batch file

Just put this in your batch file where you want the wait.

@ping 127.0.0.1 -n 11 -w 1000 > null

HttpURLConnection timeout settings

You can set timeout like this,

con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);

MySQL string replace

Yes, MySQL has a REPLACE() function:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
    -> 'WwWwWw.mysql.com'

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

Note that it's easier if you make that an alias when using SELECT

SELECT REPLACE(string_column, 'search', 'replace') as url....

TypeError: 'dict' object is not callable

strikes  = [number_map[int(x)] for x in input_str.split()]

You get an element from a dict using these [] brackets, not these ().

sqlite database default time value 'now'

If you want millisecond precision, try this:

CREATE TABLE my_table (
    timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);

This will save the timestamp as text, though.

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

Maven Installation OSX Error Unsupported major.minor version 51.0

A dynamic $HOME/.zshrc solution, if you're like me ie. Linux @ work; MBP/A @ home

if [[ $(uname) == "Darwin" ]]; then export OSX=1; fi
if [[ $(uname) ==  "Linux" ]]; then export LINUX=1; fi

if [[ -n $OSX ]]; then
        export JAVA_HOME=$(/usr/libexec/java_home)
else
        export JAVA_HOME=/usr/lib/jvm/default-java
fi

Why do we have to specify FromBody and FromUri?

The default behavior is:

  1. If the parameter is a primitive type (int, bool, double, ...), Web API tries to get the value from the URI of the HTTP request.

  2. For complex types (your own object, for example: Person), Web API tries to read the value from the body of the HTTP request.

So, if you have:

  • a primitive type in the URI, or
  • a complex type in the body

...then you don't have to add any attributes (neither [FromBody] nor [FromUri]).

But, if you have a primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)

Or, if you have a complex type in your URI, then you must add [FromUri]. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)

Primitive types:

public class UsersController : ApiController
{
    // api/users
    public HttpResponseMessage Post([FromBody]int id)
    {

    }
    // api/users/id
    public HttpResponseMessage Post(int id)
    {

    }       
}

Complex types:

public class UsersController : ApiController
{       
    // api/users
    public HttpResponseMessage Post(User user)
    {

    }

    // api/users/user
    public HttpResponseMessage Post([FromUri]User user)
    {

    }       
}

This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:

public class MyModel
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
    // model.MyProperty;
    // model.MyProperty2;
}

From Microsoft's documentation for parameter binding in ASP.NET Web API:

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

This should work:

public HttpResponseMessage Post([FromBody] string name) { ... }

This will not work:

// Caution: This won't work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

You can use

str1.compareTo(str2);

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

E.g.,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1
"b".compareTo(null); // throws java.lang.NullPointerException

select from one table, insert into another table oracle sql query

try this query below:

Insert into tab1 (tab1.column1,tab1.column2) 
select tab2.column1, 'hard coded  value' 
from tab2 
where tab2.column='value';

Nested objects in javascript, best practices

var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

Splitting a Java String by the pipe symbol using split("|")

Use proper escaping: string.split("\\|")

Or, in Java 5+, use the helper Pattern.quote() which has been created for exactly this purpose:

string.split(Pattern.quote("|"))

which works with arbitrary input strings. Very useful when you need to quote / escape user input.

Changing Tint / Background color of UITabBar

 [[UITabBar appearance] setTintColor:[UIColor redColor]];
 [[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];

Selenium WebDriver and DropDown Boxes

Try the Select helper class and see if that makes any difference?

String valueToSelect= "Germany";
WebElement select = driver.findElement(By.id("selection"));
Select dropDown = new Select(select);           
String selected = dropDown.getFirstSelectedOption().getText();
if(selected.equals(valueToSelect)) {//do stuff already selected}
List<WebElement> Options = dropDown.getOptions();
for(WebElement option:Options){
  if(option.getText().equals(valueToSelect)){
       option.click();  
  }
}

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

Changing background color of text box input not working when empty

on body tag's onLoad try setting it like

document.getElementById("subEmail").style.backgroundColor = "yellow";

and after that on change of that input field check if some value is there, or paint it yellow like

function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
    inputVal.style.backgroundColor = "yellow";
            }
    }

How to center a WPF app on screen?

There is no WPF equivalent. System.Windows.Forms.Screen is still part of the .NET framework and can be used from WPF though.

See this question for more details, but you can use the calls relating to screens by using the WindowInteropHelper class to wrap your WPF control.

MySQL Daemon Failed to Start - centos 6

I had the same issue happening. When I checked the error.log I found that my disk was full.

Use:

df -h 

on the command line. it will tell you how much space you have left. mine was full. found my error.log file was 4.77GB. I downloaded it and then deleted it. Then I used service mysqld start and it worked.

Insert into C# with SQLCommand

using (SqlConnection connection = new SqlConnection(connectionString)) 
{
    connection.Open(); 
    using (SqlCommand command = connection.CreateCommand()) 
    { 
        command.CommandText = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";  

        command.Parameters.AddWithValue("@param1", klantId));  
        command.Parameters.AddWithValue("@param2", klantNaam));  
        command.Parameters.AddWithValue("@param3", klantVoornaam));  

        command.ExecuteNonQuery(); 
    } 
}

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

If you are running webpack-dev-server in a container and are sending requests to it via its container name, you will get this error. To allow requests from other containers on the same network, simply provide the container name (or whatever name is used to resolve the container) using the --public option. This is better than disabling the security check entirely.

In my case, I was running webpack-dev-server in a container named assets with docker-compose. I changed the start command to this:

webpack-dev-server --mode development --host 0.0.0.0 --public assets

And the other container was now able to make requests via http://assets:5000.

Best way to structure a tkinter application?

This isn't a bad structure; it will work just fine. However, you do have to have functions in a function to do commands when someone clicks on a button or something

So what you could do is write classes for these then have methods in the class that handle commands for the button clicks and such.

Here's an example:

import tkinter as tk

class Window1:
    def __init__(self, master):
        pass
        # Create labels, entries,buttons
    def button_click(self):
        pass
        # If button is clicked, run this method and open window 2


class Window2:
    def __init__(self, master):
        #create buttons,entries,etc

    def button_method(self):
        #run this when button click to close window
        self.master.destroy()

def main(): #run mianloop 
    root = tk.Tk()
    app = Window1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Usually tk programs with multiple windows are multiple big classes and in the __init__ all the entries, labels etc are created and then each method is to handle button click events

There isn't really a right way to do it, whatever works for you and gets the job done as long as its readable and you can easily explain it because if you cant easily explain your program, there probably is a better way to do it.

Take a look at Thinking in Tkinter.

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

Control the dashed border stroke length and distance between strokes

There's a cool tool made by @kovart called the dashed border generator.

It uses an svg as a background image to allow setting the stroke dash array you desire, and is pretty convenient.

You would then simply use it as the background property on your element in place of the border:

div {
  background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' stroke='black' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
  padding: 20px;
  display: inline-block;
}

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

In my case the following solved the problem:

  1. Downloading the "32-bit Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio" from http://www.oracle.com/technetwork/topics/dotnet/utilsoft-086879.html
  2. Then adding reference oracle.dataaccess.dll to the bin file by browsing the file location or just from the refence list in .NET tab.

SQL "IF", "BEGIN", "END", "END IF"?

Off hand the code looks right. What if you try using an 'Else' and see what happens?

IF @SchoolCategoryCode = 'Elem' 

--- We now have determined we are processing an elementary school...

BEGIN

---- Only do the following if the variable @Term equals a 3 - if it does not, skip just this first part

    IF @Term = 3
    BEGIN
        INSERT INTO @Classes

        SELECT              
            XXXXXX  
        FROM XXXX blah blah blah

        INSERT INTO @Classes    
        SELECT
        XXXXXXXX    
        FROM XXXXXX (more code) 
    END   <----(Should this be ENDIF?)
    ELSE
    BEGIN


        INSERT INTO @Classes    
        SELECT
        XXXXXXXX    
        FROM XXXXXX (more code) 
    END
END

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

There you go: (a-zA-Z)

function codeToChar( number ) {
  if ( number >= 0 && number <= 25 ) // a-z
    number = number + 97;
  else if ( number >= 26 && number <= 51 ) // A-Z
    number = number + (65-26);
  else
    return false; // range error
  return String.fromCharCode( number );
}

input: 0-51, or it will return false (range error);

OR:

var codeToChar = function() {
  var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
  return function( code ) {
    return abc[code];
  };
})();

returns undefined in case of range error. NOTE: the array will be created only once and because of closure it will be available for the the new codeToChar function. I guess it's even faster then the first method (it's just a lookup basically).

how I can show the sum of in a datagridview column?

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();

Converting HTML to XML

Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.

This link is helpful: How to read HTML as XML?

More here - difference between HTML and XML

Python handling socket.error: [Errno 104] Connection reset by peer

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

Spring Boot Multiple Datasource

MySqlBDConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager")
public class MySqlBDConfig{

@Autowired
private Environment env;

@Bean(name="mysqlProperities")
@ConfigurationProperties(prefix="spring.mysql")
public DataSourceProperties mysqlProperities(){
    return new  DataSourceProperties();
}


@Bean(name="mysqlDataSource")
public DataSource interfaceDS(@Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){
    return dataSourceProperties.initializeDataSourceBuilder().build();

}

@Primary
@Bean(name="mysqlEmFactory")
public LocalContainerEntityManagerFactoryBean mysqlEmFactory(@Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){
    return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build();
}


@Bean(name="mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEmFactory")EntityManagerFactory factory){
    return new JpaTransactionManager(factory);
}
}

H2DBConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager")
public class H2DBConfig{

        @Autowired
        private Environment env;

        @Bean(name="dsProperities")
        @ConfigurationProperties(prefix="spring.h2")
        public DataSourceProperties dsProperities(){
            return new  DataSourceProperties();
        }


    @Bean(name="dsDataSource")
    public DataSource dsDataSource(@Qualifier("dsProperities")DataSourceProperties dataSourceProperties){
        return dataSourceProperties.initializeDataSourceBuilder().build();

    }

    @Bean(name="dsEmFactory")
    public LocalContainerEntityManagerFactoryBean dsEmFactory(@Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean em =  builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build();
        HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(ven);
        HashMap<String, Object> prop = new HashMap<>();
        prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
        prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));

        em.setJpaPropertyMap(prop);
        em.afterPropertiesSet();
        return em;
    }


    @Bean(name="dsTransactionManager")
    public PlatformTransactionManager dsTransactionManager(@Qualifier("dsEmFactory")EntityManagerFactory factory){
        return new JpaTransactionManager(factory);
    }
}

application.properties

#---mysql DATASOURCE---
spring.mysql.driverClassName = com.mysql.jdbc.Driver
spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test
spring.mysql.username = root
spring.mysql.password = root
#----------------------

#---H2 DATASOURCE----
spring.h2.driverClassName = org.h2.Driver
spring.h2.url = jdbc:h2:file:~/test
spring.h2.username = root
spring.h2.password = root
#---------------------------

#------JPA----- 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Application.java

@SpringBootApplication
public class Application {


    public static void main(String[] args)   {
        ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args);
        UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class)
        //for exemple save a new user using your repository 
        userRepository.save(new UserMysql());

    }
}

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

How to make use of ng-if , ng-else in angularJS

<span ng-if="verifyName.indicator == 1"><i class="fa fa-check"></i></span>
<span ng-if="verifyName.indicator == 0"><i class="fa fa-times"></i></span>

try this code. here verifyName.indicator value is coming from controller. this works for me.

Why is Spring's ApplicationContext.getBean considered bad?

The idea is that you rely on dependency injection (inversion of control, or IoC). That is, your components are configured with the components they need. These dependencies are injected (via the constructor or setters) - you don't get then yourself.

ApplicationContext.getBean() requires you to name a bean explicitly within your component. Instead, by using IoC, your configuration can determine what component will be used.

This allows you to rewire your application with different component implementations easily, or configure objects for testing in a straightforward fashion by providing mocked variants (e.g. a mocked DAO so you don't hit a database during testing)

Round to 5 (or other number) in Python

Another way to do this (without explicit multiplication or division operators):

def rnd(x, b=5):
    return round(x + min(-(x % b), b - (x % b), key=abs))

How to convert an enum type variable to a string?

What I made is a combination of what I have seen here and in similar questions on this site. I made this is Visual Studio 2013. I have not tested it with other compilers.

First of all I define a set of macros that will do the tricks.

// concatenation macros
#define CONCAT_(A, B) A ## B
#define CONCAT(A, B)  CONCAT_(A, B)

// generic expansion and stringification macros
#define EXPAND(X)           X
#define STRINGIFY(ARG)      #ARG
#define EXPANDSTRING(ARG)   STRINGIFY(ARG)        

// number of arguments macros
#define NUM_ARGS_(X100, X99, X98, X97, X96, X95, X94, X93, X92, X91, X90, X89, X88, X87, X86, X85, X84, X83, X82, X81, X80, X79, X78, X77, X76, X75, X74, X73, X72, X71, X70, X69, X68, X67, X66, X65, X64, X63, X62, X61, X60, X59, X58, X57, X56, X55, X54, X53, X52, X51, X50, X49, X48, X47, X46, X45, X44, X43, X42, X41, X40, X39, X38, X37, X36, X35, X34, X33, X32, X31, X30, X29, X28, X27, X26, X25, X24, X23, X22, X21, X20, X19, X18, X17, X16, X15, X14, X13, X12, X11, X10, X9, X8, X7, X6, X5, X4, X3, X2, X1, N, ...) N
#define NUM_ARGS(...) EXPAND(NUM_ARGS_(__VA_ARGS__, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1))

// argument extraction macros
#define FIRST_ARG(ARG, ...) ARG
#define REST_ARGS(ARG, ...) __VA_ARGS__

// arguments to strings macros
#define ARGS_STR__(N, ...)  ARGS_STR_##N(__VA_ARGS__)
#define ARGS_STR_(N, ...)   ARGS_STR__(N, __VA_ARGS__)
#define ARGS_STR(...)       ARGS_STR_(NUM_ARGS(__VA_ARGS__), __VA_ARGS__)

#define ARGS_STR_1(ARG)     EXPANDSTRING(ARG)
#define ARGS_STR_2(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_1(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_3(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_2(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_4(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_3(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_5(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_4(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_6(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_5(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_7(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_6(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_8(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_7(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_9(...)     EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_8(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_10(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_9(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_11(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_10(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_12(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_11(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_13(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_12(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_14(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_13(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_15(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_14(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_16(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_15(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_17(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_16(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_18(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_17(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_19(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_18(EXPAND(REST_ARGS(__VA_ARGS__)))
#define ARGS_STR_20(...)    EXPANDSTRING(FIRST_ARG(__VA_ARGS__)), ARGS_STR_19(EXPAND(REST_ARGS(__VA_ARGS__)))
// expand until _100 or as much as you need

Next define a single macro that will create the enum class and the functions to get the strings.

#define ENUM(NAME, ...)                                                                                             \
    enum class NAME                                                                                                 \
    {                                                                                                               \
        __VA_ARGS__                                                                                                 \
    };                                                                                                              \
                                                                                                                    \
    static const std::array<std::string, NUM_ARGS(__VA_ARGS__)> CONCAT(NAME, Strings) = { ARGS_STR(__VA_ARGS__) };  \
                                                                                                                    \
    inline const std::string& ToString(NAME value)                                                                  \
    {                                                                                                               \
        return CONCAT(NAME, Strings)[static_cast<std::underlying_type<NAME>::type>(value)];                         \
    }                                                                                                               \
                                                                                                                    \
    inline std::ostream& operator<<(std::ostream& os, NAME value)                                                   \
    {                                                                                                               \
        os << ToString(value);                                                                                      \
        return os;                                                                                                  \
    }

Now defining an enum type and have strings for it becomes really easy. All you need to do is:

ENUM(MyEnumType, A, B, C);

The following lines can be used to test it.

int main()
{
    std::cout << MyEnumTypeStrings.size() << std::endl;

    std::cout << ToString(MyEnumType::A) << std::endl;
    std::cout << ToString(MyEnumType::B) << std::endl;
    std::cout << ToString(MyEnumType::C) << std::endl;

    std::cout << MyEnumType::A << std::endl;
    std::cout << MyEnumType::B << std::endl;
    std::cout << MyEnumType::C << std::endl;

    auto myVar = MyEnumType::A;
    std::cout << myVar << std::endl;
    myVar = MyEnumType::B;
    std::cout << myVar << std::endl;
    myVar = MyEnumType::C;
    std::cout << myVar << std::endl;

    return 0;
}

This will output:

3
A
B
C
A
B
C
A
B
C

I believe it is very clean and easy to use. There are some limitations:

  • You cannot assign values to the enum members.
  • The enum member's values are used as index, but that should be fine, because everything is defined in a single macro.
  • You cannot use it to define an enum type inside a class.

If you can work around this. I think, especially how to use it, this is nice and lean. Advantages:

  • Easy to use.
  • No string splitting at runtime required.
  • Separate strings are available at compile time.
  • Easy to read. The first set of macros may need an extra second, but aren't really that complicated.

Difference between Method and Function?

In C#, they are interchangeable (although method is the proper term) because you cannot write a method without incorporating it into a class. If it were independent of a class, then it would be a function. Methods are functions that operate through a designated class.

Server Client send/receive simple text

Server:

namespace SocketServer    
{
    class Program
    {
        static Socket klient; 
        static void Main(string[] args)
        {
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888); 
            server.Bind(endPoint);
            server.Listen(20);
            while(true)
            {
                Console.WriteLine("Waiting...");
                klient = server.Accept();

                Console.WriteLine("Client connected");
                Task t = new Task(ServisClient);
                t.Start();
            }
        }

        static void ServisClient()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[64];
                    Console.WriteLine("Waiting for answer...");
                    klient.Receive(buffer, 0, buffer.Length, 0);
                    string message = Encoding.UTF8.GetString(buffer);
                    Console.WriteLine("Answer: " + message);

                    string answer = "Actualy date is " + DateTime.Now;
                    buffer = Encoding.UTF8.GetBytes(answer);
                    Console.WriteLine("Sending {0}", answer);
                    klient.Send(buffer);
                }
            }
            catch
            {
                Console.WriteLine("Disconnected");
            }
        }
    }
}

Floating point inaccuracy examples

A cute piece of numerical weirdness may be observed if one converts 9999999.4999999999 to a float and back to a double. The result is reported as 10000000, even though that value is obviously closer to 9999999, and even though 9999999.499999999 correctly rounds to 9999999.

MongoError: connect ECONNREFUSED 127.0.0.1:27017

because you didn't start mongod process before you try starting mongo shell.

Start mongod server

mongod

Open another terminal window

Start mongo shell

mongo

What is the difference between DSA and RSA?

Referring, https://web.archive.org/web/20140212143556/http://courses.cs.tamu.edu:80/pooch/665_spring2008/Australian-sec-2006/less19.html

RSA
RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)

RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms. It creates a 320 bit signature, but with 512-1024 bit security again rests on difficulty of computing discrete logarithms has been quite widely accepted.

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.

DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k<q
compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures

DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

new Runnable() but no new thread?

A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.

Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.

In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.

Below a useless code is given, but it will suffice to do away with your some confusions about Runnable. It will print "Hello World".

class NamedRunnable implements Runnable {

    public void run() { // The run method prints a message to standard output.
        System.out.println("Hello World");
    }

    public static void main(String[]arg){ 
        NamedRunnable namedRunnable = new NamedRunnable( );
        namedRunnable.run();
    } 
}

Test if a vector contains a given element

Also to find the position of the element "which" can be used as

pop <- c(3,4,5,7,13)

which(pop==13)

and to find the elements which are not contained in the target vector, one may do this:

pop <- c(1,2,4,6,10)

Tset <- c(2,10,7)   # Target set

pop[which(!(pop%in%Tset))]

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

I know it's mighty late to post this but here's a tiny hack to achieve your outcome ;)

Simply add a dummy view below your viewpager:

<android.support.v4.view.ViewPager
     android:layout_width="match_parent"
     android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

<RelativeLayout
     android:id="@+id/dummyView"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
</RelativeLayout>

Then add a OnClickListener to your RelativeLayout.

dummyView = (RelativeLayout) findViewById(R.id.dummyView);

dummyView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         //Just leave this empty
    }
});

Get a bit creative with layouts, their placements and their behaviour and you'll learn to find a way to do absolutely anything that you imagine :)

Good luck!

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

How can Bash execute a command in a different directory context?

You can use the cd builtin, or the pushd and popd builtins for this purpose. For example:

# do something with /etc as the working directory
cd /etc
:

# do something with /tmp as the working directory
cd /tmp
:

You use the builtins just like any other command, and can change directory context as many times as you like in a script.

Android Studio-No Module

In the "project" page on the top left corner in android studio.

From dropdown goto Android >> Gradle Scripts >> Build Gradle(Module :app)

make sure the first line of this file is like this.

apply plugin: 'com.android.application'

not like this

apply plugin: 'com.android.library'

Efficiently replace all accented characters in a string?

If you want to achieve sorting where "ä" comes after "a" and is not treated as the same, then you can use a function like mine.

You can always change the alphabet to get different or even weird sortings. However, if you want some letters to be equivalent, then you have to manipulate the strings like a = a.replace(/ä/, 'a') or similar, as many have already replied above. I've included the uppercase letters if someone wants to have all uppercase words before all lowercase words (then you have to ommit .toLowerCase()).

function sortbyalphabet(a,b) {
        alphabet = "0123456789AaÀàÁáÂâÃãÄäBbCcÇçDdÈèÉéÊêËëFfGgHhÌìÍíÎîÏïJjKkLlMmNnÑñOoÒòÓóÔôÕõÖöPpQqRrSsTtÙùÚúÛûÜüVvWwXxÝýŸÿZz";
        a = a.toLowerCase();
        b = b.toLowerCase();
        shorterone = (a.length > b.length ? a : b);
        for (i=0; i<shorterone.length; i++){
            diff = alphabet.indexOf(a.charAt(i)) - alphabet.indexOf(b.charAt(i));
            if (diff!=0){
                return diff;
            }
        }
        // sort the shorter first
        return a.length - b.length;
    }
    var n = ["ast", "Äste", "apfel", "äpfel", "à"];
    console.log(n.sort(sortbyalphabet));
    // should return ["apfel", "ast", "à", "äpfel", "äste"]

Public class is inaccessible due to its protection level

You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.

How to make shadow on border-bottom?

funny, that in the most answer you create a box with the text (or object), instead of it create the text (or object) div and under that a box with 100% width (or at least what it should) and with height what equal with your "border" px... So, i think this is the most simple and perfect answer:

<h3>Your Text</h3><div class="border-shadow"></div>

and the css:

    .shadow {
        width:100%;
        height:1px; // = "border height (without the shadow)!"
        background:#000; // = "border color!"
        -webkit-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        -moz-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"

}

Here you can experiment with the radius, etc. easy: https://www.cssmatic.com/box-shadow

Travel/Hotel API's?

HotelsCombined has an easy-to-access and useful service to download the data feed files with hotels. Not exactly API, but something you can get, parse and use. Here is how you do it:

  1. Go to http://www.hotelscombined.com/Affiliates.aspx
  2. Register there (no company or bank data is needed)
  3. Open “Data feeds” page
  4. Choose “Standard data feed” -> “Single file” -> “CSV format” (you may get XML as well)

If you are interested in details, you may find the sample Python code to filter CSV file to get hotels for a specific city here:

http://mikhail.io/2012/05/17/api-to-get-the-list-of-hotels/

Update:

Unfortunately, HotelsCombined.com has introduced the new regulations: they've restricted the access to data feeds by default. To get the access, a partner must submit some information on why one needs the data. The HC team will review it and then (maybe) will grant access.

What is context in _.each(list, iterator, [context])?

Simple use of _.each

_x000D_
_x000D_
_.each(['Hello', 'World!'], function(word){_x000D_
    console.log(word);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Here's simple example that could use _.each:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
_x000D_
var x = new basket();_x000D_
x.addItem('banana');_x000D_
x.addItem('apple');_x000D_
x.addItem('kiwi');_x000D_
x.show();
_x000D_
_x000D_
_x000D_

Output:

items:  [ 'banana', 'apple', 'kiwi' ]

Instead of calling addItem multiple times you could use underscore this way:

_.each(['banana', 'apple', 'kiwi'], function(item) { x.addItem(item); });

which is identical to calling addItem three times sequentially with these items. Basically it iterates your array and for each item calls your anonymous callback function that calls x.addItem(item). The anonymous callback function is similar to addItem member function (e.g. it takes an item) and is kind of pointless. So, instead of going through anonymous function it's better that _.each avoids this indirection and calls addItem directly:

_.each(['banana', 'apple', 'kiwi'], x.addItem);

but this won't work, as inside basket's addItem member function this won't refer to your x basket that you created. That's why you have an option to pass your basket x to be used as [context]:

_.each(['banana', 'apple', 'kiwi'], x.addItem, x);

Full example that uses _.each and context:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In short, if callback function that you pass to _.each in any way uses this then you need to specify what this should be referring to inside your callback function. It may seem like x is redundant in my example, but x.addItem is just a function and could be totally unrelated to x or basket or any other object, for example:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
function addItem(item) {_x000D_
    this.items.push(item);_x000D_
};_x000D_
_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In other words, you bind some value to this inside your callback, or you may as well use bind directly like this:

_.each(['banana', 'apple', 'kiwi'], addItem.bind(x));

how this feature can be useful with some different underscore methods?

In general, if some underscorejs method takes a callback function and if you want that callback be called on some member function of some object (e.g. a function that uses this) then you may bind that function to some object or pass that object as the [context] parameter and that's the primary intention. And at the top of underscorejs documentation, that's exactly what they state: The iteratee is bound to the context object, if one is passed

Enable UTF-8 encoding for JavaScript

I think you just need to make

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

Before calling your .js files or code

Turn off deprecated errors in PHP 5.3

You can do it in code by calling the following functions.

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

or

error_reporting(E_ALL ^ E_DEPRECATED);

Convert spark DataFrame column to python list

See, why this way that you are doing is not working. First, you are trying to get integer from a Row Type, the output of your collect is like this:

>>> mvv_list = mvv_count_df.select('mvv').collect()
>>> mvv_list[0]
Out: Row(mvv=1)

If you take something like this:

>>> firstvalue = mvv_list[0].mvv
Out: 1

You will get the mvv value. If you want all the information of the array you can take something like this:

>>> mvv_array = [int(row.mvv) for row in mvv_list.collect()]
>>> mvv_array
Out: [1,2,3,4]

But if you try the same for the other column, you get:

>>> mvv_count = [int(row.count) for row in mvv_list.collect()]
Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method'

This happens because count is a built-in method. And the column has the same name as count. A workaround to do this is change the column name of count to _count:

>>> mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count")
>>> mvv_count = [int(row._count) for row in mvv_list.collect()]

But this workaround is not needed, as you can access the column using the dictionary syntax:

>>> mvv_array = [int(row['mvv']) for row in mvv_list.collect()]
>>> mvv_count = [int(row['count']) for row in mvv_list.collect()]

And it will finally work!

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

I was getting following error on a fedora 18 box:


1. /usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory compilation terminated.

I Installed glibc.i686 and glibc-devel.i686, then compilation failed with following error:

2. /usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.7.2/libgcc_s.so when searching for -lgcc_s /usr/bin/ld: cannot find -lgcc_s collect2: error: ld returned 1 exit status

Solution:

I installed (yum install) glibc.i686 glibc-devel.i386 and libgcc.i686 to get rid of the compilation issue.

Now compilation for 32 bit (-m32) works fine.

Getting file names without extensions

You can use Path.GetFileNameWithoutExtension:

foreach (FileInfo fi in smFiles)
{
    builder.Append(Path.GetFileNameWithoutExtension(fi.Name));
    builder.Append(", ");
}

Although I am surprised there isn't a way to get this directly from the FileInfo (or at least I can't see it).

JSON find in JavaScript

I had come across this issue for a complex model with several nested objects. A good example of what I was looking at doing would be this: Lets say you have a polaroid of yourself. And that picture is then put into a trunk of a car. The car is inside of a large crate. The crate is in the hold of a large ship with many other crates. I had to search the hold, look in the crates, check the trunk, and then look for an existing picture of me.

I could not find any good solutions online to use, and using .filter() only works on arrays. Most solutions suggested just checking to see if model["yourpicture"] existed. This was very undesirable because, from the example, that would only search the hold of the ship and I needed a way to get them from farther down the rabbit hole.

This is the recursive solution I made. In comments, I confirmed from T.J. Crowder that a recursive version would be required. I thought I would share it in case anyone came across a similar complex situation.

function ContainsKeyValue( obj, key, value ){
    if( obj[key] === value ) return true;
    for( all in obj )
    {
        if( obj[all] != null && obj[all][key] === value ){
            return true;
        }
        if( typeof obj[all] == "object" && obj[all]!= null ){
            var found = ContainsKeyValue( obj[all], key, value );
            if( found == true ) return true;
        }
    }
    return false;
}

This will start from a given object inside of the graph, and recurse down any objects found. I use it like this:

var liveData = [];
for( var items in viewmodel.Crates )
{
    if( ContainsKeyValue( viewmodel.Crates[items], "PictureId", 6 ) === true )
    {
        liveData.push( viewmodel.Crates[items] );
    }
}

Which will produce an array of the Crates which contained my picture.

Invert "if" statement to reduce nesting

The idea of only returning at the end of a function came back from the days before languages had support for exceptions. It enabled programs to rely on being able to put clean-up code at the end of a method, and then being sure it would be called and some other programmer wouldn't hide a return in the method that caused the cleanup code to be skipped. Skipped cleanup code could result in a memory or resource leak.

However, in a language that supports exceptions, it provides no such guarantees. In a language that supports exceptions, the execution of any statement or expression can cause a control flow that causes the method to end. This means clean-up must be done through using the finally or using keywords.

Anyway, I'm saying I think a lot of people quote the 'only return at the end of a method' guideline without understanding why it was ever a good thing to do, and that reducing nesting to improve readability is probably a better aim.

Cookies vs. sessions

when you save the #ID as the cookie to recognize logged in users, you actually are showing data to users that is not related to them. In addition, if a third party tries to set random IDs as cookie data in their browser, they will be able to convince the server that they are a user while they actually are not. That's a lack of security.

You have used cookies, and as you said you have already completed most of the project. besides cookie has the privilege of remaining for a long time, while sessions end more quickly. So sessions are not suitable in this case. In reality many famous and popular websites and services use cookie and you can stay logged-in for a long time. But how can you use their method to create a safer log-in process?

here's the idea: you can help the way you use cookies: If you use random keys instead of IDs to recognize logged-in users, first, you don't leak your primary data to random users, and second, If you consider the Random key large enough, It will be harder for anyone to guess a key or create a random one. for example you can save a 40 length key like this in User's browser: "KUYTYRFU7987gJHFJ543JHBJHCF5645UYTUYJH54657jguthfn" and it will be less likely for anyone to create the exact key and pretend to be someone else.

DateTime.Compare how to check if a date is less than 30 days old?

No you are not using it correctly.

See here for details.

DateTime t1 = new DateTime(100);
DateTime t2 = new DateTime(20);

if (DateTime.Compare(t1, t2) >  0) Console.WriteLine("t1 > t2"); 
if (DateTime.Compare(t1, t2) == 0) Console.WriteLine("t1 == t2"); 
if (DateTime.Compare(t1, t2) <  0) Console.WriteLine("t1 < t2");

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

You can use concat:

In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
Out[11]: 
                 df1       df2
2014-01-01       NaN -0.978535
2014-01-02 -0.106510 -0.519239
2014-01-03 -0.846100 -0.313153
2014-01-04 -0.014253 -1.040702
2014-01-05  0.315156 -0.329967
2014-01-06 -0.510577 -0.940901
2014-01-07       NaN -0.024608
2014-01-08       NaN -1.791899

[8 rows x 2 columns]

The axis argument determines the way the DataFrames are stacked:

df1 = pd.DataFrame([1, 2, 3])
df2 = pd.DataFrame(['a', 'b', 'c'])

pd.concat([df1, df2], axis=0)
   0
0  1
1  2
2  3
0  a
1  b
2  c

pd.concat([df1, df2], axis=1)

   0  0
0  1  a
1  2  b
2  3  c

Are the days of passing const std::string & as a parameter over?

The reason Herb said what he said is because of cases like this.

Let's say I have function A which calls function B, which calls function C. And A passes a string through B and into C. A does not know or care about C; all A knows about is B. That is, C is an implementation detail of B.

Let's say that A is defined as follows:

void A()
{
  B("value");
}

If B and C take the string by const&, then it looks something like this:

void B(const std::string &str)
{
  C(str);
}

void C(const std::string &str)
{
  //Do something with `str`. Does not store it.
}

All well and good. You're just passing pointers around, no copying, no moving, everyone's happy. C takes a const& because it doesn't store the string. It simply uses it.

Now, I want to make one simple change: C needs to store the string somewhere.

void C(const std::string &str)
{
  //Do something with `str`.
  m_str = str;
}

Hello, copy constructor and potential memory allocation (ignore the Short String Optimization (SSO)). C++11's move semantics are supposed to make it possible to remove needless copy-constructing, right? And A passes a temporary; there's no reason why C should have to copy the data. It should just abscond with what was given to it.

Except it can't. Because it takes a const&.

If I change C to take its parameter by value, that just causes B to do the copy into that parameter; I gain nothing.

So if I had just passed str by value through all of the functions, relying on std::move to shuffle the data around, we wouldn't have this problem. If someone wants to hold on to it, they can. If they don't, oh well.

Is it more expensive? Yes; moving into a value is more expensive than using references. Is it less expensive than the copy? Not for small strings with SSO. Is it worth doing?

It depends on your use case. How much do you hate memory allocations?

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

You can do this:

IEnumerable<object> list = new List<object>(){1, 4, 5}.AsEnumerable();
CallFunction(list);

How to Generate a random number of fixed length using JavaScript?

You can use the below code to generate a random number that will always be 6 digits:

Math.random().toString().substr(2, 6)

Hope this works for everyone :)

Briefly how this works is Math.random() generates a random number between 0 and 1 which we convert to a string and using .toString() and take a 6 digit sample from said string using .substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters.

This can be used for any length number.

If you want to do more reading on this here are some links to the docs to save you some googling:

Math.random(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

.toString(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

.substr(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

How to automatically generate a stacktrace when my program crashes

On Linux/unix/MacOSX use core files (you can enable them with ulimit or compatible system call). On Windows use Microsoft error reporting (you can become a partner and get access to your application crash data).

Using group by and having clause

What type of sql database are using (MSSQL, Oracle etc)? I believe what you have written is correct.

You could also write the first query like this:

SELECT s.sid, s.name
FROM Supplier s
WHERE (SELECT COUNT(DISTINCT pr.jid)
       FROM Supplies su, Projects pr
       WHERE su.sid = s.sid 
           AND pr.jid = su.jid) >= 2

It's a little more readable, and less mind-bending than trying to do it with GROUP BY. Performance may differ though.

Python in Xcode 4+?

I figured it out! The steps make it look like it will take more effort than it actually does.

These instructions are for creating a project from scratch. If you have existing Python scripts that you wish to include in this project, you will obviously need to slightly deviate from these instructions.

If you find that these instructions no longer work or are unclear due to changes in Xcode updates, please let me know. I will make the necessary corrections.

  1. Open Xcode. The instructions for either are the same.
  2. In the menu bar, click “File” ? “New” ? “New Project…”.
  3. Select “Other” in the left pane, then "External Build System" in the right page, and next click "Next".
  4. Enter the product name, organization name, or organization identifier.
  5. For the “Build Tool” field, type in /usr/local/bin/python3 for Python 3 or /usr/bin/python for Python 2 and then click “Next”. Note that this assumes you have the symbolic link (that is setup by default) that resolves to the Python executable. If you are unsure as to where your Python executables are, enter either of these commands into Terminal: which python3 and which python.
  6. Click “Next”.
  7. Choose where to save it and click “Create”.
  8. In the menu bar, click “File” ? “New” ? “New File…”.
  9. Select “Other” under “OS X”.
  10. Select “Empty” and click “Next”.
  11. Navigate to the project folder (it will not work, otherwise), enter the name of the Python file (including the “.py” extension), and click “Create”.
  12. In the menu bar, click “Product” ? “Scheme” ? “Edit Scheme…”.
  13. Click “Run” in the left pane.
  14. In the “Info” tab, click the “Executable” field and then click “Other…”.
  15. Navigate to the executable from Step 5. You might need to use ??G to type in the directory if it is hidden.
  16. Select the executable and click "Choose".
  17. Uncheck “Debug executable”. If you skip this step, Xcode will try to debug the Python executable itself. I am unaware of a way to integrate an external debugging tool into Xcode.
  18. Click the “+” icon under “Arguments Passed On Launch”. You might have to expand that section by clicking on the triangle pointing to the right.
  19. Type in $(SRCROOT)/ (or $(SOURCE_ROOT)/) and then the name of the Python file you want to test. Remember, the Python program must be in the project folder. Otherwise, you will have to type out the full path (or relative path if it's in a subfolder of the project folder) here. If there are spaces anywhere in the full path, you must include quotation marks at the beginning and end of this.
  20. Click “Close”.

Note that if you open the "Utilities" panel, with the "Show the File inspector" tab active, the file type is automatically set to "Default - Python script". Feel free to look through all the file type options it has, to gain an idea as to what all it is capable of doing. The method above can be applied to any interpreted language. As of right now, I have yet to figure out exactly how to get it to work with Java; then again, I haven't done too much research. Surely there is some documentation floating around on the web about all of this.

Running without administrative privileges:

If you do not have administrative privileges or are not in the Developer group, you can still use Xcode for Python programming (but you still won't be able to develop in languages that require compiling). Instead of using the play button, in the menu bar, click "Product" ? "Perform Action" ? "Run Without Building" or simply use the keyboard shortcut ^?R.

Other Notes:

To change the text encoding, line endings, and/or indentation settings, open the "Utilities" panel and click "Show the File inspector" tab active. There, you will find these settings.

For more information about Xcode's build settings, there is no better source than this. I'd be interested in hearing from somebody who got this to work with unsupported compiled languages. This process should work for any other interpreted language. Just be sure to change Step 5 and Step 16 accordingly.

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

I didn't think it would be that simple! go to this link: https://www.codeproject.com/Articles/18399/Localizing-System-MessageBox

Download the source. Take the MessageBoxManager.cs file, add it to your project. Now just register it once in your code (for example in the Main() method inside your Program.cs file) and it will work every time you call MessageBox.Show():

    MessageBoxManager.OK = "Alright";
    MessageBoxManager.Yes = "Yep!";
    MessageBoxManager.No = "Nope";
    MessageBoxManager.Register();

See this answer for the source code here for MessageBoxManager.cs.

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

DateDiff to output hours and minutes

Try this query

select
    *,
    Days          = datediff(dd,0,DateDif),
    Hours         = datepart(hour,DateDif),
    Minutes       = datepart(minute,DateDif),
    Seconds       = datepart(second,DateDif),
    MS            = datepart(ms,DateDif)
from
    (select
         DateDif = EndDate-StartDate,
         aa.*
     from
         (  -- Test Data
          Select
              StartDate = convert(datetime,'20090213 02:44:37.923'),
              EndDate   = convert(datetime,'20090715 13:24:45.837')) aa
    ) a

Output

DateDif                  StartDate                EndDate                 Days Hours Minutes Seconds MS
-----------------------  -----------------------  ----------------------- ---- ----- ------- ------- ---
1900-06-02 10:40:07.913  2009-02-13 02:44:37.923  2009-07-15 13:24:45.837 152  10    40      7       913

(1 row(s) affected)

Format telephone and credit card numbers in AngularJS

I created an AngularJS module to handle this issue regarding phonenumbers for myself with a custom directive and accompanying filter.

jsfiddle example: http://jsfiddle.net/aberke/s0xpkgmq/

Filter use example: <p>{{ phonenumberValue | phonenumber }}</p>

Filter code:

.filter('phonenumber', function() {
    /* 
    Format phonenumber as: c (xxx) xxx-xxxx
        or as close as possible if phonenumber length is not 10
        if c is not '1' (country code not USA), does not use country code
    */

    return function (number) {
        /* 
        @param {Number | String} number - Number that will be formatted as telephone number
        Returns formatted number: (###) ###-####
            if number.length < 4: ###
            else if number.length < 7: (###) ###

        Does not handle country codes that are not '1' (USA)
        */
        if (!number) { return ''; }

        number = String(number);

        // Will return formattedNumber. 
        // If phonenumber isn't longer than an area code, just show number
        var formattedNumber = number;

        // if the first character is '1', strip it out and add it back
        var c = (number[0] == '1') ? '1 ' : '';
        number = number[0] == '1' ? number.slice(1) : number;

        // # (###) ###-#### as c (area) front-end
        var area = number.substring(0,3);
        var front = number.substring(3, 6);
        var end = number.substring(6, 10);

        if (front) {
            formattedNumber = (c + "(" + area + ") " + front);  
        }
        if (end) {
            formattedNumber += ("-" + end);
        }
        return formattedNumber;
    };
});

Directive use example:

<phonenumber-directive placeholder="'Input phonenumber here'" model='myModel.phonenumber'></phonenumber-directive>

Directive code:

.directive('phonenumberDirective', ['$filter', function($filter) {
    /*
    Intended use:
        <phonenumber-directive placeholder='prompt' model='someModel.phonenumber'></phonenumber-directive>
    Where:
        someModel.phonenumber: {String} value which to bind only the numeric characters [0-9] entered
            ie, if user enters 617-2223333, value of 6172223333 will be bound to model
        prompt: {String} text to keep in placeholder when no numeric input entered
    */

    function link(scope, element, attributes) {

        // scope.inputValue is the value of input element used in template
        scope.inputValue = scope.phonenumberModel;

        scope.$watch('inputValue', function(value, oldValue) {

            value = String(value);
            var number = value.replace(/[^0-9]+/g, '');
            scope.phonenumberModel = number;
            scope.inputValue = $filter('phonenumber')(number);
        });
    }

    return {
        link: link,
        restrict: 'E',
        scope: {
            phonenumberPlaceholder: '=placeholder',
            phonenumberModel: '=model',
        },
        // templateUrl: '/static/phonenumberModule/template.html',
        template: '<input ng-model="inputValue" type="tel" class="phonenumber" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format: (999) 9999-9999)">',
    };
}])

Full code with module and how to use it: https://gist.github.com/aberke/042eef0f37dba1138f9e

Reading content from URL with Node.js

A slightly modified version of @sidanmor 's code. The main point is, not every webpage is purely ASCII, user should be able to handle the decoding manually (even encode into base64)

function httpGet(url) {
  return new Promise((resolve, reject) => {
    const http = require('http'),
      https = require('https');

    let client = http;

    if (url.toString().indexOf("https") === 0) {
      client = https;
    }

    client.get(url, (resp) => {
      let chunks = [];

      // A chunk of data has been recieved.
      resp.on('data', (chunk) => {
        chunks.push(chunk);
      });

      // The whole response has been received. Print out the result.
      resp.on('end', () => {
        resolve(Buffer.concat(chunks));
      });

    }).on("error", (err) => {
      reject(err);
    });
  });
}

(async(url) => {
  var buf = await httpGet(url);
  console.log(buf.toString('utf-8'));
})('https://httpbin.org/headers');

How to store Emoji Character in MySQL Database

Emoji support for application having tech stack - mysql, java, springboot, hibernate

Apply below changes in mysql for unicode support.

  1. ALTER DATABASE <database-name> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
  2. ALTER TABLE <table-name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

DB Connection - jdbc url change:

jdbc:mysql://localhost:3306/<database-name>?useUnicode=yes&characterEncoding=UTF-8

Note - If the above step is not working please update mysql-connector version to 8.0.15. (mysql 5.7 works with connector version 8.0.15 for unicode support)

How to set an image's width and height without stretching it?

Make a div and give it a class. Then drop a img in it.

<div class="mydiv">

<img src="location/of/your/image" ></img>

</div>

Set the size of your div and make it relative.

    .mydiv {
        position: relative;
        height:300px;
        width: 100%;
        overflow: hidden;
    }

then style your image

img {
    width: 100%;
    height: auto;
    overflow: hidden;
}

Hope that helps

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

How do I see if Wi-Fi is connected on Android?

val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?        
         if (wifi!!.isWifiEnabled) 
              //do action here
    
         else 
             //do action here
    
        
                    

Get name of property as a string

it's how I implemented it , the reason behind is if the class that you want to get the name from it's member is not static then you need to create an instanse of that and then get the member's name. so generic here comes to help

public static string GetName<TClass>(Expression<Func<TClass, object>> exp)
{
    MemberExpression body = exp.Body as MemberExpression;

    if (body == null)
    {
         UnaryExpression ubody = (UnaryExpression)exp.Body;
         body = ubody.Operand as MemberExpression;
    }

     return body.Member.Name;
}

the usage is like this

var label = ClassExtension.GetName<SomeClass>(x => x.Label); //x is refering to 'SomeClass'

How to remove all white spaces from a given text file

Easiest way for me ->

        echo "Hello my name is Donald" | sed  s/\ //g

Properly escape a double quote in CSV

Use 2 quotes:

"Samsung U600 24"""

Free Rest API to retrieve current datetime as string (timezone irrelevant)

This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:

{
  "time": {
    "daysInMonth": 31,
    "millisecond": 283,
    "second": 42,
    "minute": 55,
    "hour": 1,
    "date": 6,
    "day": 3,
    "week": 10,
    "month": 2,
    "year": 2013,
    "zone": "+0000"
  },
  "formatted": {
    "weekday": "Wednesday",
    "month": "March",
    "ago": "a few seconds",
    "calendar": "Today at 1:55 AM",
    "generic": "2013-03-06T01:55:42+00:00",
    "time": "1:55 AM",
    "short": "03/06/2013",
    "slim": "3/6/2013",
    "hand": "Mar 6 2013",
    "handTime": "Mar 6 2013 1:55 AM",
    "longhand": "March 6 2013",
    "longhandTime": "March 6 2013 1:55 AM",
    "full": "Wednesday, March 6 2013 1:55 AM",
    "fullSlim": "Wed, Mar 6 2013 1:55 AM"
  },
  "array": [
    2013,
    2,
    6,
    1,
    55,
    42,
    283
  ],
  "offset": 1362534942283,
  "unix": 1362534942,
  "utc": "2013-03-06T01:55:42.283Z",
  "valid": true,
  "integer": false,
  "zone": 0
}

dispatch_after - GCD in Swift?

Swift 4 has a pretty short way of doing this:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
    // Your stuff here
    print("hello")
}

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

Angular and debounce

For anyone using lodash, it is extremely easy to debounce any function:

changed = _.debounce(function() {
    console.log("name changed!");
}, 400);

then just throw something like this into your template:

<(input)="changed($event.target.value)" />

Path to Powershell.exe (v 2.0)

I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version (Determine installed PowerShell version) shows it's 2.0.

Another option is type $PSVersionTable at the command prompt. If you are running v2.0, the output will be:

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4927
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

If you're running version 1.0, the variable doesn't exist and there will be no output.

Localization PowerShell version 1.0, 2.0, 3.0, 4.0:

  • 64 bits version: C:\Windows\System32\WindowsPowerShell\v1.0\
  • 32 bits version: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

Read url to string in few lines of java code

Now that some time has passed since the original answer was accepted, there's a better approach:

String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();

If you want a slightly fuller implementation, which is not a single line, do this:

public static String readStringFromURL(String requestURL) throws IOException
{
    try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),
            StandardCharsets.UTF_8.toString()))
    {
        scanner.useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }
}

Plot multiple lines (data series) each with unique color in R

Here is a sample code that includes a legend if that is of interest.

# First create an empty plot.
plot(1, type = 'n', xlim = c(xminp, xmaxp), ylim = c(0, 1), 
     xlab = "log transformed coverage", ylab = "frequency")

# Create a list of 22 colors to use for the lines.
cl <- rainbow(22)

# Now fill plot with the log transformed coverage data from the
# files one by one.
for(i in 1:length(data)) {
    lines(density(log(data[[i]]$coverage)), col = cl[i])
    plotcol[i] <- cl[i]
}
legend("topright", legend = c(list.files()), col = plotcol, lwd = 1,
       cex = 0.5)

How to write Unicode characters to the console?

It's likely that your output encoding is set to ASCII. Try using this before sending output:

Console.OutputEncoding = System.Text.Encoding.UTF8;

(MSDN link to supporting documentation.)

And here's a little console test app you may find handy:

C#

using System;
using System.Text;

public static class ConsoleOutputTest {
    public static void Main() {
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        for (var i = 0; i <= 1000; i++) {
            Console.Write(Strings.ChrW(i));
            if (i % 50 == 0) { // break every 50 chars
                Console.WriteLine();
            }
        }
        Console.ReadKey();
    }
}

VB.NET

imports Microsoft.VisualBasic
imports System

public module ConsoleOutputTest 
    Sub Main()
        Console.OutputEncoding = System.Text.Encoding.UTF8
        dim i as integer
        for i = 0 to 1000
            Console.Write(ChrW(i))
            if i mod 50 = 0 'break every 50 chars 
                Console.WriteLine()
            end if
        next
    Console.ReadKey()
    End Sub
end module

It's also possible that your choice of Console font does not support that particular character. Click on the Windows Tool-bar Menu (icon like C:.) and select Properties -> Font. Try some other fonts to see if they display your character properly:

picture of console font edit

ASP MVC href to a controller/view

Try the following:

<a asp-controller="Users" asp-action="Index"></a>

(Valid for ASP.NET 5 and MVC 6)

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Bearer authentication in OpenAPI 3.0.0

OpenAPI 3.0 now supports Bearer/JWT authentication natively. It's defined like this:

openapi: 3.0.0
...

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT  # optional, for documentation purposes only

security:
  - bearerAuth: []

This is supported in Swagger UI 3.4.0+ and Swagger Editor 3.1.12+ (again, for OpenAPI 3.0 specs only!).

UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx header.

Adding Authorization header programmatically (Swagger UI 3.x)

If you use Swagger UI and, for some reason, need to add the Authorization header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor. This solution is for Swagger UI 3.x; UI 2.x used a different technique.

// index.html

const ui = SwaggerUIBundle({
  url: "http://your.server.com/swagger.json",
  ...

  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer xxxxxxx"
    return req
  }
})

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

OS X Terminal Colors

If you are using tcsh, then edit your ~/.cshrc file to include the lines:

setenv CLICOLOR 1
setenv LSCOLORS dxfxcxdxbxegedabagacad

Where, like Martin says, LSCOLORS specifies the color scheme you want to use.

To generate the LSCOLORS you want to use, checkout this site

How do you get the index of the current iteration of a foreach loop?

Just add your own index. Keep it simple.

int i = 0;
foreach (var item in Collection)
{
    item.index = i;
    ++i;
}

How to set a timer in android

this example start the timer unitl destroyed in Kotlin

private lateinit var timerTask: TimerTask

 timerTask = object : TimerTask() {
        override fun run() {
            Log.d("KTZ", "$minutes:$seconds");
            timeRecordingLiveData.postValue("$minutes:$seconds")
            seconds += 1;
            if (seconds == 60) {
                Log.d("KTZ", "$minutes:$seconds");
                timeRecordingLiveData.postValue("$minutes:$seconds")
                seconds = 0;
                minutes += 1;
            }
        }

    }

Cancel the timertask in onDestroy()

timerTask.cancel()

What is the maximum recursion depth in Python, and how to increase it?

I wanted to give you an example for using memoization to compute Fibonacci as this will allow you to compute significantly larger numbers using recursion:

cache = {}
def fib_dp(n):
    if n in cache:
        return cache[n]
    if n == 0: return 0
    elif n == 1: return 1
    else:
        value = fib_dp(n-1) + fib_dp(n-2)
    cache[n] = value
    return value

print(fib_dp(998))

This is still recursive, but uses a simple hashtable that allows the reuse of previously calculated Fibonacci numbers instead of doing them again.

How do I get unique elements in this array?

This should work for you:

Consider Table1 has a column by the name of activity which may have the same value in more than one record. This is how you will extract ONLY the unique entries of activity field within Table1.

#An array of multiple data entries
@table1 = Table1.find(:all) 

#extracts **activity** for each entry in the array @table1, and returns only the ones which are unique 

@unique_activities = @table1.map{|t| t.activity}.uniq 

Count(*) vs Count(1) - SQL Server

As this question comes up again and again, here is one more answer. I hope to add something for beginners wondering about "best practice" here.

SELECT COUNT(*) FROM something counts records which is an easy task.

SELECT COUNT(1) FROM something retrieves a 1 per record and than counts the 1s that are not null, which is essentially counting records, only more complicated.

Having said this: Good dbms notice that the second statement will result in the same count as the first statement and re-interprete it accordingly, as not to do unnecessary work. So usually both statements will result in the same execution plan and take the same amount of time.

However from the point of readability you should use the first statement. You want to count records, so count records, not expressions. Use COUNT(expression) only when you want to count non-null occurences of something.

Angular directives - when and how to use compile, controller, pre-link and post-link

In which order the directive functions are executed?

For a single directive

Based on the following plunk, consider the following HTML markup:

<body>
    <div log='some-div'></div>
</body>

With the following directive declaration:

myApp.directive('log', function() {
  
    return {
        controller: function( $scope, $element, $attrs, $transclude ) {
            console.log( $attrs.log + ' (controller)' );
        },
        compile: function compile( tElement, tAttributes ) {
            console.log( tAttributes.log + ' (compile)'  );
            return {
                pre: function preLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (pre-link)'  );
                },
                post: function postLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (post-link)'  );
                }
            };
         }
     };  
     
});

The console output will be:

some-div (compile)
some-div (controller)
some-div (pre-link)
some-div (post-link)

We can see that compile is executed first, then controller, then pre-link and last is post-link.

For nested directives

Note: The following does not apply to directives that render their children in their link function. Quite a few Angular directives do so (like ngIf, ngRepeat, or any directive with transclude). These directives will natively have their link function called before their child directives compile is called.

The original HTML markup is often made of nested elements, each with its own directive. Like in the following markup (see plunk):

<body>
    <div log='parent'>
        <div log='..first-child'></div>
        <div log='..second-child'></div>
    </div>
</body>

The console output will look like this:

// The compile phase
parent (compile)
..first-child (compile)
..second-child (compile)

// The link phase   
parent (controller)
parent (pre-link)
..first-child (controller)
..first-child (pre-link)
..first-child (post-link)
..second-child (controller)
..second-child (pre-link)
..second-child (post-link)
parent (post-link)

We can distinguish two phases here - the compile phase and the link phase.

The compile phase

When the DOM is loaded Angular starts the compile phase, where it traverses the markup top-down, and calls compile on all directives. Graphically, we could express it like so:

An image illustrating the compilation loop for children

It is perhaps important to mention that at this stage, the templates the compile function gets are the source templates (not instance template).

The link phase

DOM instances are often simply the result of a source template being rendered to the DOM, but they may be created by ng-repeat, or introduced on the fly.

Whenever a new instance of an element with a directive is rendered to the DOM, the link phase starts.

In this phase, Angular calls controller, pre-link, iterates children, and call post-link on all directives, like so:

An illustration demonstrating the link phase steps

Any reason to prefer getClass() over instanceof when generating .equals()?

It depends if you consider if a subclass of a given class is equals to its parent.

class LastName
{
(...)
}


class FamilyName
extends LastName
{
(..)
}

here I would use 'instanceof', because I want a LastName to be compared to FamilyName

class Organism
{
}

class Gorilla extends Organism
{
}

here I would use 'getClass', because the class already says that the two instances are not equivalent.

Performing Inserts and Updates with Dapper

Using Dapper.Contrib it is as simple as this:

Insert list:

public int Insert(IEnumerable<YourClass> yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Insert(yourClass) ;
    }
}

Insert single:

public int Insert(YourClass yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Insert(yourClass) ;
    }
}

Update list:

public bool Update(IEnumerable<YourClass> yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Update(yourClass) ;
    }
}

Update single:

public bool Update(YourClass yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Update(yourClass) ;
    }
}

Source: https://github.com/StackExchange/Dapper/tree/master/Dapper.Contrib

How to cache Google map tiles for offline usage?

On Android platforms, Oruxmaps (http://www.oruxmaps.com) does a great job at caching all WMS sources. It is available in the play store. I use it daily in remote areas without any connectivity, works like a charm.

Click a button programmatically - JS

I have never developed with HangOut. I ran into the same problems with FB-login and I was trying so hard to get it to click programatically. Then later I discovered that the sdk won't allow you to programatically click the button because of some security reasons. The user has to physically click on the button. This also happens with async asp fileupload button. So please check if HangOut does allow you to programatically click a buttton. All above codes are correct and they should work. If you dig deep enough you will see that my answer is the right answer for your situation you.

What's the difference between a null pointer and a void pointer?

Void refers to the type. Basically the type of data that it points to is unknown.

Null refers to the value. It's essentially a pointer to nothing, and is invalid to use.

Disable form autofill in Chrome without disabling autocomplete

One solution would be to auto-fill the inputs with whitespace characters, and have them clear on focus.

Example: http://nfdb.net/autofill.php

<!doctype html>
<html>
    <head>
        <title>Autofill Test</title>
        <script>
            var userfield;

            // After the document has loaded, manipulate DOM elements.
            window.addEventListener('load', function() {

                // Get the username field element.
                userfield = document.getElementById('user');

                // Listen to the 'focus' event on the input element.
                userfield.addEventListener('focus', function() {

                    // Checks if the value is the EM space character,
                    // and removes it when the input is recieves focus.
                    if (this.value == '\u2003') this.value = ''

                }, false);

                // Listen to the 'blur' event on the input element.
                // Triggered when the user focuses on another element or window.
                userfield.addEventListener('blur', function() {

                    // Checks if the value is empty (the user hasn't typed)
                    // and inserts the EM space character if necessary.
                    if (this.value == '') this.value = '\u2003';

                }, false);
            }, false);
        </script>
    </head>
    <body>
        <form method="GET" action="">
            <input id="user" name="username" type="text" value="&#8195;"/><br/>
            <input name="password" type="password" value=""/><br/>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

This should stop the browser from auto-filling the fields, but still allow them to auto-complete.

Here's another example that clears the form inputs after the page loads. The advantage of this method is that the inputs never have any whitespace characters in them, the disadvantage is that there's a small possibility that the auto-filled values may be visible for a few milliseconds.

http://nfdb.net/autofill2.php

<!doctype html>
<html>
    <head>
        <title>Autofill Test</title>
        <script>
            var userfield, passfield;

            // Wait for the document to load, then call the clear function.
            window.addEventListener('load', function() {

                // Get the fields we want to clear.
                userfield = document.getElementById('user');
                passfield = document.getElementById('pass');

                // Clear the fields.
                userfield.value = '';
                passfield.value = '';

                // Clear the fields again after a very short period of time, in case the auto-complete is delayed.
                setTimeout(function() { userfield.value = ''; passfield.value = ''; }, 50);
                setTimeout(function() { userfield.value = ''; passfield.value = ''; }, 100);

            }, false);
        </script>
    </head>
    <body>
        <div>This form has autofill disabled:</div>
        <form name="login" method="GET" action="./autofill2.php">
            <input id="user" name="username" type="text" value=""/><br/>
            <input id="pass" name="password" type="password" value=""/><br/>
            <input type="submit" value="Login">
        </form>
        <div>This form is untouched:</div>
        <form name="login" method="GET" action="./autofill2.php">
            <input name="username" type="text" value=""/><br/>
            <input name="password" type="password" value=""/><br/>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

Access: Move to next record until EOF

If (Not IsNull(Me.id.Value)) Then
DoCmd.GoToRecord , , acNext
End If

Hi, you need to put this in form activate, and have an id field named id...

this way it passes until it reaches the one without id (AKA new one)...

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

Sort a list by multiple attributes?

A key can be a function that returns a tuple:

s = sorted(s, key = lambda x: (x[1], x[2]))

Or you can achieve the same using itemgetter (which is faster and avoids a Python function call):

import operator
s = sorted(s, key = operator.itemgetter(1, 2))

And notice that here you can use sort instead of using sorted and then reassigning:

s.sort(key = operator.itemgetter(1, 2))

Limiting number of displayed results when using ngRepeat

A little late to the party, but this worked for me. Hopefully someone else finds it useful.

<div ng-repeat="video in videos" ng-if="$index < 3">
    ...
</div>

Similarity String Comparison in Java

There are indeed a lot of string similarity measures out there:

  • Levenshtein edit distance;
  • Damerau-Levenshtein distance;
  • Jaro-Winkler similarity;
  • Longest Common Subsequence edit distance;
  • Q-Gram (Ukkonen);
  • n-Gram distance (Kondrak);
  • Jaccard index;
  • Sorensen-Dice coefficient;
  • Cosine similarity;
  • ...

You can find explanation and java implementation of these here: https://github.com/tdebatty/java-string-similarity

Return a `struct` from a function in C

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

works fine with newer versions of compilers. Just like id, content of the name gets copied to the assigned structure variable.

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Oracle: How to find out if there is a transaction pending?

This is the query I normally use,

select s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from v$transaction t
inner join v$session s on t.addr = s.taddr;

Java "user.dir" property - what exactly does it mean?

It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

So if you cd into /somedir, then run your program, user.dir will be /somedir.

A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

See here for a list of system properties and their descriptions.

Split a string into an array of strings based on a delimiter

Using the SysUtils.TStringHelper.Split function, introduced in Delphi XE3:

var
  MyString: String;
  Splitted: TArray<String>;
begin
  MyString := 'word:doc,txt,docx';
  Splitted := MyString.Split([':']);
end.

This will split a string with a given delimiter into an array of strings.

How to discard uncommitted changes in SourceTree?

Ok I just noticed that my question was already answered in the question title.

To unstage files use

git reset HEAD /file/name

And to undo the changes to a file

git checkout -- /file/name

If you have a batch of files inside a folder you can undo the whole folder

git checkout -- /folder/name

Note that all these commands are already displayed when you git status

Here I created a dummy repo and listed all 3 possibilities

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   test
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   test2
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       test3

System.web.mvc missing

Easiest way to solve this problem is install ASP.NET MVC 3 from Web Platforms installer.

enter image description here

http://www.microsoft.com/web/downloads/

Or by using Nuget command

Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

INSTALL_FAILED_NO_MATCHING_ABIS is when you are trying to install an app that has native libraries and it doesn't have a native library for your cpu architecture. For example if you compiled an app for armv7 and are trying to install it on an emulator that uses the Intel architecture instead it will not work.

Using Xamarin on Visual Studio 2015. Fix this issue by:

  1. Open your xamarin .sln
  2. Right click your android project
  3. Click properties
  4. Click Android Options
  5. Click the 'Advanced' tab
  6. Under "Supported architectures" make the following checked:

    1. armeabi-v7a
    2. x86
  7. save

  8. F5 (build)

Edit: This solution has been reported as working on Visual Studio 2017 as well.

Edit 2: This solution has been reported as working on Visual Studio 2017 for Mac as well.

How to bind WPF button to a command in ViewModelBase?

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

the code behind for the window:

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

The ViewModel:

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

    public void MyAction()
    {

    }
}

Command Handler:

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

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

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

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

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

I hope this will give you the idea.

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

just write "java -d64 -version" or d32 and if you have It installed it will give a response with current version installed

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

Use PPK file in Mac Terminal to connect to remote connection over SSH

You can ssh directly from the Terminal on Mac, but you need to use a .PEM key rather than the putty .PPK key. You can use PuttyGen on Windows to convert from .PEM to .PPK, I'm not sure about the other way around though.

You can also convert the key using putty for Mac via port or brew:

sudo port install putty

or

brew install putty

This will also install puttygen. To get puttygen to output a .PEM file:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Once you have the key, open a terminal window and:

ssh -i privatekey.pem [email protected]

The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.

chmod go-rw privatekey.pem

JPA - Returning an auto generated id after persist()

em.persist(abc);
em.refresh(abc);
return abc;

xml.LoadData - Data at the root level is invalid. Line 1, position 1

I've solved this issue by directly editing the byte array. Collect the UTF8 preamble and remove directly the header. Afterward you can transform the byte[]to a string with GetString method, see below. The \r and \t I've removed as well, just as precaution.

XmlDocument configurationXML = new XmlDocument();
List<byte> byteArray = new List<byte>(webRequest.downloadHandler.data);

foreach(byte singleByte in Encoding.UTF8.GetPreamble())
{
     byteArray.RemoveAt(byteArray.IndexOf(singleByte));
}
string xml = System.Text.Encoding.UTF8.GetString(byteArray.ToArray());
       xml = xml.Replace("\\r", "");
       xml = xml.Replace("\\t", "");

Find row where values for column is maximal in a pandas DataFrame

If you want the entire row instead of just the id, you can use df.nlargest and pass in how many 'top' rows you want and you can also pass in for which column/columns you want it for.

df.nlargest(2,['A'])

will give you the rows corresponding to the top 2 values of A.

use df.nsmallest for min values.

How to detect orientation change?

According to the Apple docs:

This method is called when the view controller's view's size is changed by its parent (i.e. for the root view controller when its window rotates or is resized).

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    }
    if UIDevice.current.orientation.isFlat {
        print("Flat")
    } else {
        print("Portrait")
    }
}

How to grep (search) committed code in the Git history

So are you trying to grep through older versions of the code looking to see where something last exists?

If I were doing this, I would probably use git bisect. Using bisect, you can specify a known good version, a known bad version, and a simple script that does a check to see if the version is good or bad (in this case a grep to see if the code you are looking for is present). Running this will find when the code was removed.

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with

$my_url = urlencode("my url");

and then calling

file_get_contents($my_url);

and see if you have better luck.

What JSON library to use in Scala?

Play released its module for dealing with JSON independently from Play Framework, Play WS

Made a blog post about that, check it out at http://pedrorijo.com/blog/scala-json/

Using case classes, and Play WS (already included in Play Framework) you case convert between json and case classes with a simple one-liner implicit

case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)

object User {
  implicit val userJsonFormat = Json.format[User]
}

Why am I getting error CS0246: The type or namespace name could not be found?

i also faced same problem,

Reason: why i faced this error is, rather then creating new partial view, i have created class and then renamed its extension from ".cs" to ".cshtml".

Solution: Just delete that rename view and re-create proper partial/full view. it will work fine after that.

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Here is a really fast and easy way of setting it permanently

NB: running SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); is temporary and on server restart you will still end up with the error. To fix this permanently do the below

  1. Login to your server as root
  2. in your terminal run wget https://gist.githubusercontent.com/nfourtythree/90fb8ef5eeafdf478f522720314c60bd/raw/disable-strict-mode.sh
  3. Make the script executable by running chmod +x disable-strict-mode.sh
  4. Run the script by running ./disable-strict-mode.sh

And your done , changes will be made to mysql and it will be restarted

Mod of negative number is melting my brain

Please note that C# and C++'s % operator is actually NOT a modulo, it's remainder. The formula for modulo that you want, in your case, is:

float nfmod(float a,float b)
{
    return a - b * floor(a / b);
}

You have to recode this in C# (or C++) but this is the way you get modulo and not a remainder.

How to create a temporary directory?

The following snippet will safely create a temporary directory (-d) and store its name into the TMPDIR. (An example use of TMPDIR variable is shown later in the code where it's used for storing original files that will be possibly modified.)

The first trap line executes exit 1 command when any of the specified signals is received. The second trap line removes (cleans up) the $TMPDIR on program's exit (both normal and abnormal). We initialize these traps after we check that mkdir -d succeeded to avoid accidentally executing the exit trap with $TMPDIR in an unknown state.

#!/bin/bash

# Create a temporary directory and store its name in a variable ...
TMPDIR=$(mktemp -d)

# Bail out if the temp directory wasn't created successfully.
if [ ! -e $TMPDIR ]; then
    >&2 echo "Failed to create temp directory"
    exit 1
fi

# Make sure it gets removed even if the script exits abnormally.
trap "exit 1"           HUP INT PIPE QUIT TERM
trap 'rm -rf "$TMPDIR"' EXIT

# Example use of TMPDIR:
for f in *.csv; do
    cp "$f" "$TMPDIR"
    # remove duplicate lines but keep order
    perl -ne 'print if ++$k{$_}==1' "$TMPDIR/$f" > "$f"
done

Is it possible to use pip to install a package from a private GitHub repository?

When I was installing from GitHub I was able to use:

pip install git+ssh://[email protected]/<username>/<projectname>.git#egg=<eggname>

But, since I had to run pip as sudo, the SSH keys were not working with GitHub any more, and "git clone" failed on "Permission denied (publickey)". Using git+https allowed me to run the command as sudo, and have GitHub ask me for my user/password.

sudo pip install git+https://github.com/<username>/<projectname>.git#egg=<eggname>

Android: disabling highlight on listView click

Add this to your xml:

android:listSelector="@android:color/transparent"

And for the problem this may work (I'm not sure and I don't know if there are better solutions):

You could apply a ColorStateList to your TextView.

How to update SQLAlchemy row entry?

With the help of user=User.query.filter_by(username=form.username.data).first() statement you will get the specified user in user variable.

Now you can change the value of the new object variable like user.no_of_logins += 1 and save the changes with the session's commit method.