Programs & Examples On #Sqldatasource

The SqlDataSource control enables you to use a Web control to access data located in a relational database, including Microsoft SQL Server and Oracle databases. The SqlDataSource control uses ADO.NET classes to interact with any database supported by ADO.NET. You can use the SqlDataSource control with other controls that display data, such as the GridView, FormView and DetailsView controls to display and manipulate data using little or no code.

How to pass a variable to the SelectCommand of a SqlDataSource?

Just add a custom property to the page which will return the variable of your choice. You can then use the built-in "control" parameter type.

In the code behind, add:

Dim MyVariable as Long


ReadOnly Property MyCustomProperty As Long
    Get
        Return MyVariable
    End Get
End Property

In the select parameters section add:

<asp:ControlParameter ControlID="__Page" Name="MyParameter" 
PropertyName="MyCustomProperty" Type="Int32" />

How to clear exisiting dropdownlist items when its content changes?

Using ddl.Items.Clear() will clear the dropdownlist however you must be sure that your dropdownlist is not set to:

AppendDataBoundItems="True"

This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.

SOLUTION

Add AppendDataBoundItems="False" to your dropdownlist.

Now when data is rebound it will automatically clear all existing data beforehand.

Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
    ddl2.DataSource = sql2
    ddl2.DataBind()
End Sub

NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.


TOP TIP

Still want a default list item adding to your dropdown but need to rebind data?

Use AppendDataBoundItems="False" to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.

ddl.Items.Insert(0, New ListItem("Select ...", ""))

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

How do I calculate someone's age in Java?

If you are using GWT you will be limited to using java.util.Date, here is a method that takes the date as integers, but still uses java.util.Date:

public int getAge(int year, int month, int day) {
    Date now = new Date();
    int nowMonth = now.getMonth()+1;
    int nowYear = now.getYear()+1900;
    int result = nowYear - year;

    if (month > nowMonth) {
        result--;
    }
    else if (month == nowMonth) {
        int nowDay = now.getDate();

        if (day > nowDay) {
            result--;
        }
    }
    return result;
}

Nullable property to entity field, Entity Framework through Code First

Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

This worked for me though:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}

What's the purpose of the LEA instruction?

From the "Zen of Assembly" by Abrash:

LEA, the only instruction that performs memory addressing calculations but doesn't actually address memory. LEA accepts a standard memory addressing operand, but does nothing more than store the calculated memory offset in the specified register, which may be any general purpose register.

What does that give us? Two things that ADD doesn't provide:

  1. the ability to perform addition with either two or three operands, and
  2. the ability to store the result in any register; not just one of the source operands.

And LEA does not alter the flags.

Examples

  • LEA EAX, [ EAX + EBX + 1234567 ] calculates EAX + EBX + 1234567 (that's three operands)
  • LEA EAX, [ EBX + ECX ] calculates EBX + ECX without overriding either with the result.
  • multiplication by constant (by two, three, five or nine), if you use it like LEA EAX, [ EBX + N * EBX ] (N can be 1,2,4,8).

Other usecase is handy in loops: the difference between LEA EAX, [ EAX + 1 ] and INC EAX is that the latter changes EFLAGS but the former does not; this preserves CMP state.

How to change button text or link text in JavaScript?

Remove Quote. and use innerText instead of text

function toggleText(button_id) 
{                      //-----\/ 'button_id' - > button_id
   if (document.getElementById(button_id).innerText == "Lock") 
   {
       document.getElementById(button_id).innerText = "Unlock";
   }
   else 
   {
     document.getElementById(button_id).innerText = "Lock";
   }
}

How to update-alternatives to Python 3 without breaking apt?

replace

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3

with

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3

e.g. installing into /usr/local/bin instead of /usr/bin.

and ensure the /usr/local/bin is before /usr/bin in PATH.

i.e.

[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin

Ensure this always is the case by adding

export PATH=/usr/local/bin:$PATH

to the end of your ~/.bashrc file. Prefixing the PATH environment variable with custom bin folder such as /usr/local/bin or /opt/<some install>/bin is generally recommended to ensure that customizations are found before the default system ones.

How to compare DateTime in C#?

MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.


The conventional operators

are available for DateTime since .NET Framework 1.1. Also, addition and subtraction of DateTime objects are also possible using conventional operators + and -.

One example from MSDN:

Equality:
System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);

// areEqual gets false.
bool areEqual = april19 == otherDate;

otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;

Other operators can be used likewise.

Here is the list all operators available for DateTime.

JavaScript validation for empty input field

Customizing the input message using HTML validation when clicking on Javascript button

_x000D_
_x000D_
function msgAlert() {
  const nameUser = document.querySelector('#nameUser');
  const passUser = document.querySelector('#passUser');

  if (nameUser.value === ''){
    console.log('Input name empty!');
    nameUser.setCustomValidity('Insert a name!');
  } else {
    nameUser.setCustomValidity('');
    console.log('Input name ' + nameUser.value);
  }
}

const v = document.querySelector('.btn-petroleo');
v.addEventListener('click', msgAlert, false);
_x000D_
.container{display:flex;max-width:960px;}
.w-auto {
    width: auto!important;
}
.p-3 {
    padding: 1rem!important;
}
.align-items-center {
    -ms-flex-align: center!important;
    align-items: center!important;
}
.form-row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;
}
.mb-2, .my-2 {
    margin-bottom: .5rem!important;
}
.d-flex {
    display: -ms-flexbox!important;
    display: flex!important;
}
.d-inline-block {
    display: inline-block!important;
}
.col {
    -ms-flex-preferred-size: 0;
    flex-basis: 0;
    -ms-flex-positive: 1;
    flex-grow: 1;
    max-width: 100%;
}
.mr-sm-2, .mx-sm-2 {
    margin-right: .5rem!important;
}
label {
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    color: #007081;
    font-weight: 400;
    letter-spacing: 1px;
    text-transform: uppercase;
}
label {
    display: inline-block;
    margin-bottom: .5rem;
}
.x-input {
    background-color: #eaf3f8;
    font-family: "Montserrat", sans-serif;
    font-size: 14px;
}
.login-input {
    border: none !important;
    width: 100%;
}
.p-4 {
    padding: 1.5rem!important;
}
.form-control {
    display: block;
    width: 100%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
button, input {
    overflow: visible;
    margin: 0;
}
.form-row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -5px;
    margin-left: -5px;
}
.form-row>.col, .form-row>[class*=col-] {
    padding-right: 5px;
    padding-left: 5px;
}
.col-lg-12 {
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
}
.mt-1, .my-1 {
    margin-top: .25rem!important;
}
.mt-2, .my-2 {
    margin-top: .5rem!important;
}
.mb-2, .my-2 {
    margin-bottom: .5rem!important;
}
.btn:not(:disabled):not(.disabled) {
    cursor: pointer;
}
.btn-petroleo {
    background-color: #007081;
    color: white;
    font-family: "Oswald", sans-serif;
    font-size: 12px;
    text-transform: uppercase;
    padding: 8px 30px;
    letter-spacing: 2px;
}
.btn-xg {
    padding: 20px 100px;
    width: 100%;
    display: block;
}
.btn {
    display: inline-block;
    font-weight: 400;
    color: #212529;
    text-align: center;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-color: transparent;
    border: 1px solid transparent;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    border-radius: .25rem;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
input {
    -webkit-writing-mode: horizontal-tb !important;
    text-rendering: auto;
    color: -internal-light-dark(black, white);
    letter-spacing: normal;
    word-spacing: normal;
    text-transform: none;
    text-indent: 0px;
    text-shadow: none;
    display: inline-block;
    text-align: start;
    appearance: textfield;
    background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
    -webkit-rtl-ordering: logical;
    cursor: text;
    margin: 0em;
    font: 400 13.3333px Arial;
    padding: 1px 2px;
    border-width: 2px;
    border-style: inset;
    border-color: -internal-light-dark(rgb(118, 118, 118), rgb(195, 195, 195));
    border-image: initial;
}
_x000D_
<div class="container">
              <form name="myFormLogin" class="w-auto p-3 mw-10">
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="nameUser">Usuário</label><br>
                    <input type="text" class="form-control mr-sm-2 x-input login-input p-4" id="nameUser"
                           name="nameUser" placeholder="Name" required>
                  </div>
                </div>
                <div class="form-row align-items-center">
                  <div class="col w-auto p-3 h-auto d-inline-block my-2">
                    <label class="mr-sm-2" for="passUser">Senha</label><br>
                    <input type="password" class="form-control mb-3 mr-sm-2 x-input login-input p-4" id="passUser"
                           name="passUser" placeholder="Password" required>
                    <div class="help">Esqueci meu usuário ou senha</div>
                  </div>
                </div>
                <div class="form-row d-flex align-items-center">
                  <div class="col-lg-12 my-1 mt-2 mb-2">
                    <button type="submit" value="Submit" class="btn btn-petroleo btn-lg btn-xg btn-block p-4">Entrar</button>
                  </div>
                </div>
                <div class="form-row align-items-center d-flex">
                  <div class="col-lg-12 my-1">
                    <div class="nova-conta">Ainda não é cadastrado? <a href="">Crie seu acesso</a></div>
                  </div>
                </div>
              </form>
            </div>
_x000D_
_x000D_
_x000D_

Avoid dropdown menu close on click inside

This should help as well

$(document).on('click', 'someyourContainer .dropdown-menu', function (e) {
  e.stopPropagation();
});

box-shadow on bootstrap 3 container

For those wanting the box-shadow on the col-* container itself and not on the .container, you can add another div just inside the col-* element, and add the shadow to that. This element will not have the padding, and therefor not interfere.

The first image has the box-shadow on the col-* element. Because of the 15px padding on the col element, the shadow is pushed to the outside of the div element rather than on the visual edges of it.

box-shadow on col-* element

<div class="col-md-4" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
    <div class="thumbnail">
        {!! HTML::image('images/sampleImage.png') !!}
    </div>
</div>

The second image has a wrapper div with the box-shadow on it. This will place the box-shadow on the visual edges of the element.

box-shadow on wrapper div

<div class="col-md-4">
    <div id="wrapper-div" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
        <div class="thumbnail">
            {!! HTML::image('images/sampleImage.png') !!}
        </div>
    </div>
</div>

How to use Selenium with Python?

There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples

You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.

Find if value in column A contains value from column B?

You can try this. :) simple solution!

=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")

VB.NET Empty String Array

The array you created by Dim s(0) As String IS NOT EMPTY

In VB.Net, the subscript you use in the array is index of the last element. VB.Net by default starts indexing at 0, so you have an array that already has one element.

You should instead try using System.Collections.Specialized.StringCollection or (even better) System.Collections.Generic.List(Of String). They amount to pretty much the same thing as an array of string, except they're loads better for adding and removing items. And let's be honest: you'll rarely create an empty string array without wanting to add at least one element to it.

If you really want an empty string array, declare it like this:

Dim s As String()

or

Dim t() As String

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

Python: Select subset from list based on index set

Use the built in function zip

property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]

EDIT

Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.

http://docs.python.org/library/itertools.html#itertools.compress

itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F

Oracle: how to UPSERT (update or insert into a table?)

An alternative to MERGE (the "old fashioned way"):

begin
   insert into t (mykey, mystuff) 
      values ('X', 123);
exception
   when dup_val_on_index then
      update t 
      set    mystuff = 123 
      where  mykey = 'X';
end;   

What is a stored procedure?

In Stored Procedures statements are written only once and reduces network traffic between clients and servers. We can also avoid Sql Injection Attacks.

  • Incase if you are using a third party program in your application for processing payments, here database should only expose the information it needed and activity that this third party has been authorized, by this we can achieve data confidentiality by setting permissions using Stored Procedures.
  • The updation of table should only done to the table it is targeting but it shouldn't update any other table, by which we can achieve data integrity using transaction processing and error handling.
  • If you want to return one or more items with a data type then it is better to use an output parameter.
  • In Stored Procedures, we use an output parameter for anything that needs to be returned. If you want to return only one item with only an integer data type then better use a return value. Actually the return value is only to inform success or failure of the Stored Procedure.

Setting the correct encoding when piping stdout in Python

You may want to try changing the environment variable "PYTHONIOENCODING" to "utf_8". I have written a page on my ordeal with this problem.

Tl;dr of the blog post:

import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))

gives you

utf_8
False
ANSI_X3.4-1968
ascii
utf_8
ö ? ?

How to control the line spacing in UILabel

I thought about adding something new to this answer, so I don't feel as bad... Here is a Swift answer:

import Cocoa

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 40

let attrString = NSMutableAttributedString(string: "Swift Answer")
attrString.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

var tableViewCell = NSTableCellView()
tableViewCell.textField.attributedStringValue = attrString

"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels."

See: Set UILabel line spacing


This is a really old answer, and other have already addded the new and better way to handle this.. Please see the up to date answers provided below.

How to roundup a number to the closest ten?

Use ROUND but with num_digits = -1

=ROUND(A1,-1)

Also applies to ROUNDUP and ROUNDDOWN

From Excel help:

  • If num_digits is greater than 0 (zero), then number is rounded to the specified number of decimal places.
  • If num_digits is 0, then number is rounded to the nearest integer.
  • If num_digits is less than 0, then number is rounded to the left of the decimal point.

EDIT: To get the numbers to always round up use =ROUNDUP(A1,-1)

Convert Xml to DataTable

You can use this code(Recommended)

 MemoryStream objMS = new MemoryStream();
 DataTable oDT = new DataTable();//Your DataTable which you want to convert
 oDT.WriteXml(objMS);
 objMS.Position = 0;
 XPathDocument result = new XPathDocument(objMS);

This is another way but first ex. is recommended

StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();

Set color of TextView span in Android

Another way that could be used in some situations is to set the link color in the properties of the view that is taking the Spannable.

If your Spannable is going to be used in a TextView, for example, you can set the link color in the XML like this:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="@color/your_color"
</TextView>

You can also set it in the code with:

TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);

How to make GREP select only numeric values?

You can use Perl style regular expressions as well. A digit is just \d then.

grep -Po "\\d+" filename

-P Interpret PATTERNS as Perl-compatible regular expressions (PCREs).

-o Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

How can I find which tables reference a given table in Oracle SQL Developer?

SQL Developer 4.1, released in May of 2015, added a Model tab which shows table foreign keys which refer to your table in an Entity Relationship Diagram format.

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

How to convert String to long in Java?

It's quite simple, use Long.valueOf(String s);

For example:

String s;
long l;

Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);

You're done!!!

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

How to insert strings containing slashes with sed?

add \ before special characters:

s/\?page=one&/page\/one\//g

etc.

Append integer to beginning of list in Python

Based on some (minimal) benchmarks using the timeit module it seems that the following has similar if not better performance than the accepted answer

new_lst = [a, *lst]

As with [a] + list this will create a new list and not mutate lst.

If your intention is to mutate the list then use lst.insert(0, a).

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

Reselecting key file in a combobox and entering password helps on this for us.

But it is needed to do each time the key file changes and it seems to be not OK.

How do I unload (reload) a Python module?

if 'myModule' in sys.modules:  
    del sys.modules["myModule"]

How to get JSON object from Razor Model object in javascript

If You want make json object from yor model do like this :

  foreach (var item in Persons)
   {
    var jsonObj=["FirstName":"@item.FirstName"]
   }

Or Use Json.Net to make json from your model :

string json = JsonConvert.SerializeObject(person);

Including one C source file in another?

The extension of the file does not matter to most C compilers, so it will work.

However, depending on your makefile or project settings the included c file might generate a separate object file. When linking that might lead to double defined symbols.

How do I get the directory from a file's full path?

Path.GetDirectoryName(Context.Parameters["assemblypath"])

Evaluating a mathematical expression in a string

I think I would use eval(), but would first check to make sure the string is a valid mathematical expression, as opposed to something malicious. You could use a regex for the validation.

eval() also takes additional arguments which you can use to restrict the namespace it operates in for greater security.

How to get the number of threads in a Java process

Using Linux Top command

top -H -p (process id)

you could get process id of one program by this method :

ps aux | grep (your program name)

for example :

ps aux | grep user.py

How to integrate sourcetree for gitlab

There does not seem to be a way to set up a GitLab account within SourceTree, but if you just clone a remote repo it will use your SSH key correctly.

Edit: After SourceTree 3.0 it is possible to add various non-Atlassian git accounts, including GitLab.

"Exception has been thrown by the target of an invocation" error (mscorlib)

Encounter the same error when tried to connect to SQLServer2017 through Management Studio 2014

enter image description here

The reason was backward compatibility

So I just downloaded the Management Studio 2017 and tried to connect to SQLServer2017.

Problem Solve!!

multiple conditions for filter in spark data frames

Instead of:

df2 = df1.filter("Status=2" || "Status =3")

Try:

df2 = df1.filter($"Status" === 2 || $"Status" === 3)

How to open a local disk file with JavaScript?

Others here have given quite elaborate code for this. Perhaps more elaborate code was needed at that time, I don't know. Anyway, I upvoted one of them, but here is a very much simplified version that works the same:

_x000D_
_x000D_
function openFile() {
  document.getElementById('inp').click();
}
function readFile(e) {
  var file = e.target.files[0];
  if (!file) return;
  var reader = new FileReader();
  reader.onload = function(e) {
    document.getElementById('contents').innerHTML = e.target.result;
  }
  reader.readAsText(file)
}
_x000D_
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile()">Open a file</button>
<input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
<pre id="contents"></pre>
_x000D_
_x000D_
_x000D_

Define static method in source-file with declaration in header-file in C++

Remove static keyword in method definition. Keep it just in your class definition.

static keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.

PHP "php://input" vs $_POST

Simple example of how to use it

 <?php  
     if(!isset($_POST) || empty($_POST)) { 
     ?> 
        <form name="form1" method="post" action=""> 
          <input type="text" name="textfield"><br /> 
          <input type="submit" name="Submit" value="submit"> 
        </form> 
   <?php  
        } else { 
        $example = file_get_contents("php://input");
        echo $example;  }  
   ?>

How to change MySQL data directory?

This solution works in Windows 7 using Workbench. You will need Administrator privileges to do this. It creates a junction (like a shortcut) to wherever you really want to store your data

Open Workbench and select INSTANCE - Startup / Shutdown Stop the server

Install Junction Master from https://bitsum.com/junctionmaster.php

Navigate to C:\ProgramData\MySQL\MySQL Server 5.6

Right click on Data and select "MOVE and then LINK folder to ..." Accept the warning Point destination to "Your new data directory here without the quotes" Click MOVE AND LINK

Now go to "Your new data directory here without the quotes"

Right click on Data Go to the security tab Click Edit Click Add Type NETWORK SERVICE then Check Names Click OK Click the Allow Full Control checkbox and then OK

Go back to Workbench and Start the server

This method worked for me using MySQL Workbench 6.2 on Windows 7 Enterprise.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

Get a list of all threads currently running in Java

You can use getAllThreadIds that Returns all live thread IDs. Some threads included in the returned array may have been terminated when this method returns.

ManagementFactory.getThreadMXBean().getAllThreadIds()

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

Mac OS X and multiple Java versions

SDKMAN! is a great tool for using multiple versions of Java, Gradle, Groovy, Kotlin, and other JVM tools on Mac OS. Installation and usage doc are plainly on the main site.

(I have no affiliation, just a happy user).

As an example usage, if I type the following in a Terminal window, there is a list of available Java SDK versions (edited for brevity):

$ sdk list java
Available Java Versions
   + 9ea170                                                                        
 > + 8u131                                                                         
     7u141-zulu                     

Here + denotes that the version is installed. > denotes which version is currently in use. To install a version:

$ sdk install java 7u141-zulu

To use a version in this Terminal window:

$ sdk use java 9ea170

PHP: maximum execution time when importing .SQL data file

The following might help you:

ini_set('max_execution_time', 100000);

And in your mysql - max_allowed_packet=100M in some cases where queries are too long sql also produce and error "MySQL server has gone away";

Change the values to whatever you need.

Matrix Multiplication in pure Python?

All the below answers would return you the list.Your need to convert it to matrix

def MATMUL(X, Y):
    rows_A = len(X)
    cols_A = len(X[0])
    rows_B = len(Y)
    cols_B = len(Y[0])

    if cols_A != rows_B:
        print "Matrices are not compatible to Multiply. Check condition C1==R2"
        return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]

    C = numpy.matrix(C).reshape(len(A),len(B[0]))

    return C

Printing reverse of any String without using any predefined function?

Code will be as below:

   public class A{
       public static void main(String args[]){

      String str="hello";
      for(int i=str.length()-1;i>=0;i--){
        String str1=str.charAt(i);
        system.out.print(str1);
      }

   }
}

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

What is the difference between the kernel space and the user space?

The correct answer is: There is no such thing as kernel space and user space. The processor instruction set has special permissions to set destructive things like the root of the page table map, or access hardware device memory, etc.

Kernel code has the highest level privileges, and user code the lowest. This prevents user code from crashing the system, modifying other programs, etc.

Generally kernel code is kept under a different memory map than user code (just as user spaces are kept in different memory maps than each other). This is where the "kernel space" and "user space" terms come from. But that is not a hard and fast rule. For example, since the x86 indirectly requires its interrupt/trap handlers to be mapped at all times, part (or some OSes all) of the kernel must be mapped into user space. Again, this does not mean that such code has user privileges.

Why is the kernel/user divide necessary? Some designers disagree that it is, in fact, necessary. Microkernel architecture is based on the idea that the highest privileged sections of code should be as small as possible, with all significant operations done in user privileged code. You would need to study why this might be a good idea, it is not a simple concept (and is famous for both having advantages and drawbacks).

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

What is a raw type and why shouldn't we use it?

Avoid raw types

Raw types refer to using a generic type without specifying a type parameter.

For example,

A list is a raw type, while List<String> is a parameterized type.

When generics were introduced in JDK 1.5, raw types were retained only to maintain backwards compatibility with older versions of Java. Although using raw types is still possible,

They should be avoided:

  • They usually require casts
  • They aren't type safe, and some important kinds of errors will only appear at runtime
  • They are less expressive, and don't self-document in the same way as parameterized types Example

    import java.util.*;
    
    public final class AvoidRawTypes {
    
    void withRawType() {
    
        //Raw List doesn't self-document, 
        //doesn't state explicitly what it can contain
    
        List stars = Arrays.asList("Arcturus", "Vega", "Altair");
    
        Iterator iter = stars.iterator();
    
        while (iter.hasNext()) {
    
            String star = (String) iter.next(); //cast needed
    
            log(star);
        }
    
    }
    
    void withParameterizedType() {
    
        List < String > stars = Arrays.asList("Spica", "Regulus", "Antares");
    
        for (String star: stars) {
    
            log(star);
        }
    
    }
    
    private void log(Object message) {
    
        System.out.println(Objects.toString(message));
    
    }
    
    }
    

For reference: https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html

How do I check if the user is pressing a key?

Try this:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

        char ch = event.getKeyChar();

        System.out.println(event.getKeyChar());

    }

}

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

I used

View.inflate(getContext(), R.layout.whatever, null)

The using of View.inflate prevents the warning of using null at getLayoutInflater().inflate().

What does it mean: The serializable class does not declare a static final serialVersionUID field?

The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.

Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).

If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial").

If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.

Object creation on the stack/heap?

A)

Object* o;
o = new Object();

`` B)

Object* o = new Object();

I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.

One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).

Remove all child elements of a DOM node in JavaScript

element.innerHTML = "" (or .textContent) is by far the fastest solution

Most of the answers here are based on flawed tests

For example: https://jsperf.com/innerhtml-vs-removechild/15
This test does not add new children to the element between each iteration. The first iteration will remove the element's contents, and every other iteration will then do nothing. In this case, while (box.lastChild) box.removeChild(box.lastChild) was faster because box.lastChild was null 99% of the time

Here is a proper test: https://jsperf.com/innerhtml-conspiracy

Finally, do not use node.parentNode.replaceChild(node.cloneNode(false), node). This will replace the node with a copy of itself without its children. However, this does not preserve event listeners and breaks any other references to the node.

Android: Rotate image in imageview by an angle

If you're supporting API 11 or higher, you can just use the following XML attribute:

android:rotation="90"

It might not display correctly in Android Studio xml preview, but it works as expected.

Are there such things as variables within an Excel formula?

I know it's a little off-topic, but following up with the solution presented by Jonas Bøhmer, actually I think that MOD is the best solution to your example.

If your intention was to limit the result to one digit, MOD is the best approach to achieve it.

ie. Let's suppose that VLOOKUP(A1, B:B, 1, 0) returns 23. Your IF formula would simply make this calculation: 23 - 10 and return 13 as the result.

On the other hand, MOD(VLOOKUP(A1, B:B, 1, 0), 10) would divide 23 by 10 and show the remainder: 3.

Back to the main topic, when I need to use a formula that repeats some part, I usually put it on another cell and then hide it as some people already suggested.

The type java.lang.CharSequence cannot be resolved in package declaration

Java 8 supports default methods in interfaces. And in JDK 8 a lot of old interfaces now have new default methods. For example, now in CharSequence we have chars and codePoints methods.
If source level of your project is lower than 1.8, then compiler doesn't allow you to use default methods in interfaces. So it cannot compile classes that directly on indirectly depend on this interfaces.
If I get your problem right, then you have two solutions. First solution is to rollback to JDK 7, then you will use old CharSequence interface without default methods. Second solution is to set source level of your project to 1.8, then your compiler will not complain about default methods in interfaces.

Core dumped, but core file is not in the current directory?

Read /usr/src/linux/Documentation/sysctl/kernel.txt.

[/proc/sys/kernel/]core_pattern is used to specify a core dumpfile pattern name.

  • If the first character of the pattern is a '|', the kernel will treat the rest of the pattern as a command to run. The core dump will be written to the standard input of that program instead of to a file.

Instead of writing the core dump to disk, your system is configured to send it to the abrt program instead. Automated Bug Reporting Tool is possibly not as documented as it should be...

In any case, the quick answer is that you should be able to find your core file in /var/cache/abrt, where abrt stores it after being invoked. Similarly, other systems using Apport may squirrel away cores in /var/crash, and so on.

Loop through a comma-separated shell variable

Not messing with IFS
Not calling external command

variable=abc,def,ghij
for i in ${variable//,/ }
do
    # call your procedure/other scripts here below
    echo "$i"
done

Using bash string manipulation http://www.tldp.org/LDP/abs/html/string-manipulation.html

Best way to simulate "group by" from bash?

It seems that you have to either use a big amount of code to simulate hashes in bash to get linear behavior or stick to the quadratic superlinear versions.

Among those versions, saua's solution is the best (and simplest):

sort -n ip_addresses.txt | uniq -c

I found http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-11/0118.html. But it's ugly as hell...

Better way to get type of a Javascript variable?

My 2¢! Really, part of the reason I'm throwing this up here, despite the long list of answers, is to provide a little more all in one type solution and get some feed back in the future on how to expand it to include more real types.

With the following solution, as aforementioned, I combined a couple of solutions found here, as well as incorporate a fix for returning a value of jQuery on jQuery defined object if available. I also append the method to the native Object prototype. I know that is often taboo, as it could interfere with other such extensions, but I leave that to user beware. If you don't like this way of doing it, simply copy the base function anywhere you like and replace all variables of this with an argument parameter to pass in (such as arguments[0]).

;(function() {  //  Object.realType
    function realType(toLower) {
        var r = typeof this;
        try {
            if (window.hasOwnProperty('jQuery') && this.constructor && this.constructor == jQuery) r = 'jQuery';
            else r = this.constructor && this.constructor.name ? this.constructor.name : Object.prototype.toString.call(this).slice(8, -1);
        }
        catch(e) { if (this['toString']) r = this.toString().slice(8, -1); }
        return !toLower ? r : r.toLowerCase();
    }
    Object['defineProperty'] && !Object.prototype.hasOwnProperty('realType')
        ? Object.defineProperty(Object.prototype, 'realType', { value: realType }) : Object.prototype['realType'] = realType;
})();

Then simply use with ease, like so:

obj.realType()  //  would return 'Object'
obj.realType(true)  //  would return 'object'

Note: There is 1 argument passable. If is bool of true, then the return will always be in lowercase.

More Examples:

true.realType();                            //  "Boolean"
var a = 4; a.realType();                    //  "Number"
$('div:first').realType();                   // "jQuery"
document.createElement('div').realType()    //  "HTMLDivElement"

If you have anything to add that maybe helpful, such as defining when an object was created with another library (Moo, Proto, Yui, Dojo, etc...) please feel free to comment or edit this and keep it going to be more accurate and precise. OR roll on over to the GitHub I made for it and let me know. You'll also find a quick link to a cdn min file there.

postgresql COUNT(DISTINCT ...) very slow

-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';

\echo original
EXPLAIN ANALYZE
SELECT
        COUNT (distinct val) as aantal
FROM one
        ;

\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
        distinct val
       -- , COUNT(*)
FROM one
GROUP BY val;

\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
    SELECT distinct val
    FROM one
    GROUP BY val
    )
SELECT COUNT (*) as aantal
FROM agg
        ;

Results:

original                                                      QUERY PLAN                                                      
----------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
   ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
 Total runtime: 1766.642 ms
(3 rows)

group by+count(*)
                                                         QUERY PLAN                                                         
----------------------------------------------------------------------------------------------------------------------------
 HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
   ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
         ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
 Total runtime: 412.686 ms
(4 rows)

with CTE
                                                             QUERY PLAN                                                             
------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
   CTE agg
     ->  HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
           ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
                 ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
       ->  CTE Scan on agg  (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
     Total runtime: 408.300 ms
    (7 rows)

The same plan as for the CTE could probably also be produced by other methods (window functions)

Resolve Git merge conflicts in favor of their changes during a pull

git pull -s recursive -X theirs <remoterepo or other repo>

Or, simply, for the default repository:

git pull -X theirs

If you're already in conflicted state...

git checkout --theirs path/to/file

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

Objective-C: Reading a file line by line

This will work for general reading a String from Text. If you would like to read longer text (large size of text), then use the method that other people here were mentioned such as buffered (reserve the size of the text in memory space).

Say you read a Text File.

NSString* filePath = @""//file path...
NSString* fileRoot = [[NSBundle mainBundle] 
               pathForResource:filePath ofType:@"txt"];

You want to get rid of new line.

// read everything from text
NSString* fileContents = 
      [NSString stringWithContentsOfFile:fileRoot 
       encoding:NSUTF8StringEncoding error:nil];

// first, separate by new line
NSArray* allLinedStrings = 
      [fileContents componentsSeparatedByCharactersInSet:
      [NSCharacterSet newlineCharacterSet]];

// then break down even further 
NSString* strsInOneLine = 
      [allLinedStrings objectAtIndex:0];

// choose whatever input identity you have decided. in this case ;
NSArray* singleStrs = 
      [currentPointString componentsSeparatedByCharactersInSet:
      [NSCharacterSet characterSetWithCharactersInString:@";"]];

There you have it.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

I was facing the same issue today what worked for is below down

For ANDROID STUDIO... Enable Instant Run

In File->Preferences->Build, Execution, Deployment->Instant Run-> Check Enable Instant run for hot swap...

Hope it helps

How can I show the table structure in SQL Server query?

For SQL Server, if using a newer version, you can use

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'

There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection's GetSchema method or the DataReader'sGetSchemaTable method.

Provided that you have a reader for the for the query, you can do something like this:

using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
    var schema = reader.GetSchemaTable();
    foreach(DataRow row in schema.Rows)
    {
        Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
    }
}

See this article for further details.

jQuery get value of select onChange

jQuery(document).ready(function(){

    jQuery("#id").change(function() {
      var value = jQuery(this).children(":selected").attr("value");
     alert(value);

    });
})

How to write a large buffer into a binary file in C++, fast?

Try using open()/write()/close() API calls and experiment with the output buffer size. I mean do not pass the whole "many-many-bytes" buffer at once, do a couple of writes (i.e., TotalNumBytes / OutBufferSize). OutBufferSize can be from 4096 bytes to megabyte.

Another try - use WinAPI OpenFile/CreateFile and use this MSDN article to turn off buffering (FILE_FLAG_NO_BUFFERING). And this MSDN article on WriteFile() shows how to get the block size for the drive to know the optimal buffer size.

Anyway, std::ofstream is a wrapper and there might be blocking on I/O operations. Keep in mind that traversing the entire N-gigabyte array also takes some time. While you are writing a small buffer, it gets to the cache and works faster.

Can I update a component's props in React.js?

Much has changed with hooks, e.g. componentWillReceiveProps turned into useEffect+useRef (as shown in this other SO answer), but Props are still Read-Only, so only the caller method should update it.

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

The JDK does not install a JVM in the default path.

Unless you need external tools to run like ant, the non-JDK is enough for Eclipse to run. The easiest way to install such a JVM is to go to http://java.com and let it install whatever it want to install.

Then double-click the Eclipse binary again.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

To add ANDROID_HOME value permanently,

gedit ~/.bashrc

and add the following lines

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools

Save the file and you need not update ANDROID_HOME value everytime.

Why does Date.parse give incorrect results?

While CMS is correct that passing strings into the parse method is generally unsafe, the new ECMA-262 5th Edition (aka ES5) specification in section 15.9.4.2 suggests that Date.parse() actually should handle ISO-formatted dates. The old specification made no such claim. Of course, old browsers and some current browsers still do not provide this ES5 functionality.

Your second example isn't wrong. It is the specified date in UTC, as implied by Date.prototype.toISOString(), but is represented in your local timezone.

How to detect a loop in a linked list?

public boolean isCircular() {

    if (head == null)
        return false;

    Node temp1 = head;
    Node temp2 = head;

    try {
        while (temp2.next != null) {

            temp2 = temp2.next.next.next;
            temp1 = temp1.next;

            if (temp1 == temp2 || temp1 == temp2.next) 
                return true;    

        }
    } catch (NullPointerException ex) {
        return false;

    }

    return false;

}

Building a complete online payment gateway like Paypal

What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.

You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.

Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).

Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org

Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.

In summary then: it all depends on your region.

  • Contact a major bank and try to get through to their card acquiring arm.
  • Explain that you're setting up as a payment service provider, and request details on comms format for authorization requests and end of day settlement files
  • Set up a test merchant account and develop auth/settlement software and go through the accreditation process. Most acquirers help you through this process for free, but when you want to register as an accredited PSP some will request a fee.
  • you will need to comply with some regulations too, for example you may need to register as a payment institution

Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.

Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.

PHP: HTTP or HTTPS?

$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';

$protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

These should both work

How to add element into ArrayList in HashMap

HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();

public synchronized void addToList(String mapKey, Item myItem) {
    List<Item> itemsList = items.get(mapKey);

    // if list does not exist create it
    if(itemsList == null) {
         itemsList = new ArrayList<Item>();
         itemsList.add(myItem);
         items.put(mapKey, itemsList);
    } else {
        // add if item is not already in list
        if(!itemsList.contains(myItem)) itemsList.add(myItem);
    }
}

How to remove leading and trailing whitespace in a MySQL field?

I know its already accepted, but for thoses like me who look for "remove ALL whitespaces" (not just at the begining and endingof the string):

select SUBSTRING_INDEX('1234 243', ' ', 1);
// returns '1234'

EDIT 2019/6/20 : Yeah, that's not good. The function returns the part of the string since "when the character space occured for the first time". So, I guess that saying this remove the leading and trailling whitespaces and returns the first word :

select SUBSTRING_INDEX(TRIM(' 1234 243'), ' ', 1);

How can I find out if I have Xcode commandline tools installed?

First of all, be sure that you have downloaded it or not. Open up your terminal application, and enter $ gcc if you have not installed it you will get an alert. You can verify that you have installed it by

$ xcode-select -p
/Library/Developer/CommandLineTools

And to be sure then enter $ gcc --version

You can read more about the process here: Xcode command line tools for Mavericks

phpinfo() - is there an easy way for seeing it?

From the CLI the best way is to use grep like:

php -i | grep libxml

Search for a string in Enum and return the Enum

(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0

undefined offset PHP error

How to reproduce this error in PHP:

Create an empty array and ask for the value given a key like this:

php> $foobar = array();

php> echo gettype($foobar);
array

php> echo $foobar[0];

PHP Notice:  Undefined offset: 0 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What happened?

You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.

It looked for your key in the array, and found undefined.

How to make the error not happen?

Ask if the key exists first before you go asking for its value.

php> echo array_key_exists(0, $foobar) == false;
1

If the key exists, then get the value, if it doesn't exist, no need to query for its value.

Undefined behavior and sequence points

In C99(ISO/IEC 9899:TC3) which seems absent from this discussion thus far the following steteents are made regarding order of evaluaiton.

[...]the order of evaluation of subexpressions and the order in which side effects take place are both unspecified. (Section 6.5 pp 67)

The order of evaluation of the operands is unspecified. If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior[sic] is undefined.(Section 6.5.16 pp 91)

Git refusing to merge unrelated histories on rebase

I see the most voted answer doesn't solve this question, which is in the context of rebasing.

The only way to synchronize the two diverged branches is to merge them back together, resulting in an extra merge commit and two sets of commits that contain the same changes (the original ones, and the ones from your rebased branch). Needless to say, this is a very confusing situation.

So, before you run git rebase, always ask yourself, “Is anyone else looking at this branch?” If the answer is yes, take your hands off the keyboard and start thinking about a non-destructive way to make your changes (e.g., the git revert command). Otherwise, you’re safe to re-write history as much as you like.

Reference: https://www.atlassian.com/git/tutorials/merging-vs-rebasing#the-golden-rule-of-rebasing

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

brew install mysql on macOS

Okay I had the same issue and solved it. For some reason the mysql_secure_installation script doesn't work out of the box when using Homebrew to install mysql, so I did it manually. On the CLI enter:

mysql -u root

That should get you into mysql. Now do the following (taken from mysql_secure_installation):

UPDATE mysql.user SET Password=PASSWORD('your_new_pass') WHERE User='root';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'
DROP DATABASE test;
FLUSH PRIVILEGES;

Now exit and get back into mysql with: mysql -u root -p

gcc-arm-linux-gnueabi command not found

If you are on a 64bit build of ubuntu or debian (see e.g. 'cat /proc/version') you should simply use the 64bit cross compilers, if you cloned

git clone https://github.com/raspberrypi/tools

then the 64bit tools are in

tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64

use that directory for the gcc-toolchain. A useful tutorial for compiling that I followed is available here Building and compiling Raspberry PI Kernel (use the -x64 path from above as ${CCPREFIX})

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

How to determine the current shell I'm working on

My variant on printing the parent process:

ps -p $$ | awk '$1 == PP {print $4}' PP=$$

Don't run unnecessary applications when AWK can do it for you.

Identifying and removing null characters in UNIX

I discovered the following, which prints out which lines, if any, have null characters:

perl -ne '/\000/ and print;' file-with-nulls

Also, an octal dump can tell you if there are nulls:

od file-with-nulls | grep ' 000'

Node.js Web Application examples/tutorials

The Node Knockout competition wrapped up recently, and many of the submissions are available on github. The competition site doesn't appear to be working right now, but I'm sure you could Google up a few entries to check out.

Spark dataframe: collect () vs select ()

Select is used for projecting some or all fields of a dataframe. It won't give you an value as an output but a new dataframe. Its a transformation.

How to make modal dialog in WPF?

Did you try showing your window using the ShowDialog method?

Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

How to count how many values per level in a given factor?

Here 2 ways to do it:

set.seed(1)
tt <- sample(letters,100,rep=TRUE)

## using table
table(tt)
tt
a b c d e f g h i j k l m n o p q r s t u v w x y z 
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1 
## using tapply
tapply(tt,tt,length)
a b c d e f g h i j k l m n o p q r s t u v w x y z 
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1 

Creating an Array from a Range in VBA

If we do it just like this:

Dim myArr as Variant
myArr = Range("A1:A10")

the new array will be with two dimensions. Which is not always somehow comfortable to work with:

enter image description here

To get away of the two dimensions, when getting a single column to array, we may use the built-in Excel function “Transpose”. With it, the data becomes in one dimension:

enter image description here

If we have the data in a row, a single transpose will not do the job. We need to use the Transpose function twice:

enter image description here

Note: As you see from the screenshots, when generated this way, arrays start with 1, not with 0. Just be a bit careful.

Target Unreachable, identifier resolved to null in JSF 2.2

I solved this problem.

My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.

Thanks @PM77-1


Parcelable encountered IOException writing serializable object getactivity()

Need to change all arraylist to Serializable wif in bean class :

public static class PremiumListBean  implements Serializable {
    private List<AddOnValueBean> AddOnValue;

    public List<AddOnValueBean> getAddOnValue() {
        return AddOnValue;
     }

    public void setAddOnValue(List<AddOnValueBean> AddOnValue) {
        this.AddOnValue = AddOnValue;
    }


    public static class AddOnValueBean  implements Serializable{

        @SerializedName("Premium")
        private String Premium;

        public String getPremium() {
            return Premium;
        }

        public void setPremium(String Premium) {
            this.Premium = Premium;
        }
    }
 }

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

What does the ^ (XOR) operator do?

The (^) XOR operator generates 1 when it is applied on two different bits (0 and 1). It generates 0 when it is applied on two same bits (0 and 0 or 1 and 1).

Python strptime() and timezones?

Ran into this exact problem.

What I ended up doing:

# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'

# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)

# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))

# set timezone
import pendulum
tz = pendulum.timezone('utc')

dt_tz = datetime(*dt_vals,tzinfo=tz)

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

If you have downloaded Github Desktop Client 1.0.9 then the path for git.exe will be

C:\Users\Username\AppData\Local\GitHubDesktop\app-1.0.9\resources\app\git\cmd\git.exe

How to ignore HTML element from tabindex?

Just add the attribute disabled to the element (or use jQuery to do it for you). Disabled prevents the input from being focused or selected at all.

Converting between datetime, Timestamp and datetime64

indeed, all of these datetime types can be difficult, and potentially problematic (must keep careful track of timezone information). here's what i have done, though i admit that i am concerned that at least part of it is "not by design". also, this can be made a bit more compact as needed. starting with a numpy.datetime64 dt_a:

dt_a

numpy.datetime64('2015-04-24T23:11:26.270000-0700')

dt_a1 = dt_a.tolist() # yields a datetime object in UTC, but without tzinfo

dt_a1

datetime.datetime(2015, 4, 25, 6, 11, 26, 270000)

# now, make your "aware" datetime:

dt_a2=datetime.datetime(*list(dt_a1.timetuple()[:6]) + [dt_a1.microsecond], tzinfo=pytz.timezone('UTC'))

... and of course, that can be compressed into one line as needed.

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

Check if a path represents a file or a folder

There is no way for the system to tell you if a String represent a file or directory, if it does not exist in the file system. For example:

Path path = Paths.get("/some/path/to/dir");
System.out.println(Files.isDirectory(path)); // return false
System.out.println(Files.isRegularFile(path)); // return false

And for the following example:

Path path = Paths.get("/some/path/to/dir/file.txt");
System.out.println(Files.isDirectory(path));  //return false
System.out.println(Files.isRegularFile(path));  // return false

So we see that in both case system return false. This is true for both java.io.File and java.nio.file.Path

Task<> does not contain a definition for 'GetAwaiter'

GetAwaiter(), that is used by await, is implemented as an extension method in the Async CTP. I'm not sure what exactly are you using (you mention both the Async CTP and VS 2012 RC in your question), but it's possible the Async targeting pack uses the same technique.

The problem then is that extension methods don't work with dynamic. What you can do is to explicitly specify that you're working with a Task, which means the extension method will work, and then switch back to dynamic:

private async void MyButtonClick(object sender, RoutedEventArgs e)
{
    dynamic request = new SerializableDynamicObject();
    request.Operation = "test";

    Task<SerializableDynamicObject> task = Client(request);
    dynamic result = await task;

    // use result here
}

Or, since the Client() method is actually not dynamic, you could call it with SerializableDynamicObject, not dynamic, and so limit using dynamic as much as possible:

private async void MyButtonClick(object sender, RoutedEventArgs e)
{
    var request = new SerializableDynamicObject();
    dynamic dynamicRequest = request;
    dynamicRequest.Operation = "test";

    var task = Client(request);
    dynamic result = await task;

    // use result here
}

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Full examples of using pySerial package

Blog post Serial RS232 connections in Python

import time
import serial

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
    port='/dev/ttyUSB1',
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

ser.isOpen()

print 'Enter your commands below.\r\nInsert "exit" to leave the application.'

input=1
while 1 :
    # get keyboard input
    input = raw_input(">> ")
        # Python 3 users
        # input = input(">> ")
    if input == 'exit':
        ser.close()
        exit()
    else:
        # send the character to the device
        # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
        ser.write(input + '\r\n')
        out = ''
        # let's wait one second before reading output (let's give device time to answer)
        time.sleep(1)
        while ser.inWaiting() > 0:
            out += ser.read(1)

        if out != '':
            print ">>" + out

TypeError: can't use a string pattern on a bytes-like object in re.findall()

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

See Convert bytes to a Python String

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

jQuery click event not working in mobile browsers

I had the same problem and fixed it by adding "mousedown touchstart"

$(document).on("mousedown touchstart", ".className", function() { // your code here });

inested of others

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

A simpler version of your code would be:

dict(zip(names, d.values()))

If you want to keep the same structure, you can change it to:

vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}

(You can just as easily put list(d.values()) inside the comprehension instead of vlst; it's just wasteful to do so since it would be re-generating the list every time).

How to enable TLS 1.2 in Java 7

Add following option for java application:

-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2  

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

In short: Replace badge-important with either alert-danger or progress-bar-danger.

It looks like this: Bootply Demo.


You might combine the CSS class badge with alert-* or progess-bar-* to color them:

With class="badges alert-*"

  <span class="badge alert-info">badge</span> Info
  <span class="badge alert-success">badge</span> Success 
  <span class="badge alert-danger">badge</span> Danger   
  <span class="badge alert-warning">badge</span> Warning

Alerts Docu: http://getbootstrap.com/components/#alerts

With class="badges progress-bar-*" (as suggested by @clami219)

  <span class="badge progress-bar-info">badge</span> Info
  <span class="badge progress-bar-success">badge</span> Success
  <span class="badge progress-bar-danger">badge</span> Danger
  <span class="badge progress-bar-warning">badge</span> Warning

Progress-Bar Docu: http://getbootstrap.com/components/#progress-alternatives

How to use Visual Studio Code as Default Editor for Git

Just want to add these back slashes to previous answers, I am on Windows 10 CMD, and it doesn't work without back slashes before the spaces.

git config --global core.editor "C:\\Users\\your_user_name\\AppData\\Local\\Programs\\Microsoft\ VS\ Code\\Code.exe"

Why is the minidlna database not being refreshed?

There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF

Regards Gerry

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

How to stop a JavaScript for loop?

Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

let arr = [1,2,3,4,5];
for (let ele of arr) {
  if (ele > 3) break;
  console.log(ele);
}

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

how to configuring a xampp web server for different root directory

You can change the port while you open your XAMP control panel, follow the steps:

  1. click on config net to the start button, and
  2. select httpd.conf, a text file will open
  3. check the file and file listen:80,
  4. once got listen:80 replace with listen:8080 and
  5. save in the same folder.

Once done that, you will be able to start your local server.

Remove Datepicker Function dynamically

You can try the enable/disable methods instead of using the option method:

$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");

This disables the entire textbox. So may be you can use datepicker.destroy() instead:

$(document).ready(function() {
    $("#ddlSearchType").change(function() {
        if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
            $("#txtSearch").datepicker();
        }
        else {
            $("#txtSearch").datepicker("destroy");
        }
    }).change();
});

Demo here.

How to retrieve available RAM from Windows command line?

Here is a pure Java solution actually:

public static long getFreePhysicalMemory()
{
    com.sun.management.OperatingSystemMXBean bean =
            (com.sun.management.OperatingSystemMXBean)
                    java.lang.management.ManagementFactory.getOperatingSystemMXBean();
    return bean.getFreePhysicalMemorySize();
}

Use LINQ to get items in one List<>, that are not in another List<>

first, extract ids from the collection where condition

List<int> indexes_Yes = this.Contenido.Where(x => x.key == 'TEST').Select(x => x.Id).ToList();

second, use "compare" estament to select ids diffent to the selection

List<int> indexes_No = this.Contenido.Where(x => !indexes_Yes.Contains(x.Id)).Select(x => x.Id).ToList();

Obviously you can use x.key != "TEST", but is only a example

How to start IIS Express Manually

Once you have IIS Express installed (the easiest way is through Microsoft Web Platform Installer), you will find the executable file in %PROGRAMFILES%\IIS Express (%PROGRAMFILES(x86)%\IIS Express on x64 architectures) and its called iisexpress.exe.

To see all the possible command-line options, just run:

iisexpress /?

and the program detailed help will show up.

If executed without parameters, all the sites defined in the configuration file and marked to run at startup will be launched. An icon in the system tray will show which sites are running.

There are a couple of useful options once you have some sites created in the configuration file (found in %USERPROFILE%\Documents\IISExpress\config\applicationhost.config): the /site and /siteId.

With the first one, you can launch a specific site by name:

iisexpress /site:SiteName

And with the latter, you can launch by specifying the ID:

iisexpress /siteId:SiteId

With this, if IISExpress is launched from the command-line, a list of all the requests made to the server will be shown, which can be quite useful when debugging.

Finally, a site can be launched by specifying the full directory path. IIS Express will create a virtual configuration file and launch the site (remember to quote the path if it contains spaces):

iisexpress /path:FullSitePath

This covers the basic IISExpress usage from the command line.

How to escape double quotes in JSON

if you want to escape double quote in JSON use \\ to escape it.

example if you want to create json of following javascript object

{time: '7 "o" clock'}

then you must write in following way

'{"time":"7 \\"o\\" clock"}'

if we parse it using JSON.parse()

JSON.parse('{"time":"7 \\"o\\" clock"}')

result will be

{time: "7 "o" clock"}

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

Creating a range of dates in Python

Matplotlib related

from matplotlib.dates import drange
import datetime

base = datetime.date.today()
end  = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)

How to change package name of an Android Application

Alternative:

  1. Open AndroidManifest.xml
  2. Change package="NEW NAME" within manifest tag.

Insert results of a stored procedure into a temporary table

After searching around I found a way to create a temp table dynamically for any stored procedure without using OPENROWSET or OPENQUERY using a generic schema of Stored Procedure's result definition especially when you are not database Administrator.

Sql server has a buit-in proc sp_describe_first_result_set that can provide you with schema of any procedures resultset. I created a schema table from results of this procedure and manually set all the field to NULLABLE.

declare @procname varchar(100) = 'PROCEDURENAME' -- your procedure name
declare @param varchar(max) = '''2019-06-06''' -- your parameters 
declare @execstr nvarchar(max) = N'exec ' + @procname
declare @qry nvarchar(max)

-- Schema table to store the result from sp_describe_first_result_set.
create table #d
(is_hidden  bit  NULL, column_ordinal   int  NULL, name sysname NULL, is_nullable   bit  NULL, system_type_id   int  NULL, system_type_name nvarchar(256) NULL,
max_length  smallint  NULL, precision   tinyint  NULL,  scale   tinyint  NULL,  collation_name  sysname NULL, user_type_id  int NULL, user_type_database    sysname NULL,
user_type_schema    sysname NULL,user_type_name sysname NULL,assembly_qualified_type_name   nvarchar(4000),xml_collection_id    int NULL,xml_collection_database    sysname NULL,
xml_collection_schema   sysname NULL,xml_collection_name    sysname NULL,is_xml_document    bit  NULL,is_case_sensitive bit  NULL,is_fixed_length_clr_type  bit  NULL,
source_server   sysname NULL,source_database    sysname NULL,source_schema  sysname NULL,source_table   sysname NULL,source_column  sysname NULL,is_identity_column bit NULL,
is_part_of_unique_key   bit NULL,is_updateable  bit NULL,is_computed_column bit NULL,is_sparse_column_set   bit NULL,ordinal_in_order_by_list   smallint NULL,
order_by_list_length    smallint NULL,order_by_is_descending    smallint NULL,tds_type_id   int  NULL,tds_length    int  NULL,tds_collation_id  int NULL,
tds_collation_sort_id   tinyint NULL)


-- Get result set definition of your procedure
insert into #d
EXEC sp_describe_first_result_set @exestr, NULL, 0

-- Create a query to generate and populate a global temp table from above results
select 
@qry = 'Create table ##t(' +
stuff(  
    (select ',' + name + ' '+ system_type_name + ' NULL'
    from #d d For XML Path, TYPE)
    .value(N'.[1]', N'nvarchar(max)')
, 1,1,'')
+ ')

insert into ##t 
Exec '+@procname+' ' + @param

Exec sp_executesql @qry

-- Use below global temp table to query the data as you may
select * from ##t

-- **WARNING** Don't forget to drop the global temp table ##t.
--drop table ##t
drop table #d 

Developed and tested on Sql Server version - Microsoft SQL Server 2016 (RTM) - 13.0.1601.5(Build 17134:)

You can tweak the schema for your SQL server version that you are using (if needed).

How to run crontab job every week on Sunday

I think you would like this interactive website, which often helps me build complex Crontab directives: https://crontab.guru/

How are parameters sent in an HTTP POST request?

Some of the webservices require you to place request data and metadata separately. For example a remote function may expect that the signed metadata string is included in a URI, while the data is posted in a HTTP-body.

The POST request may semantically look like this:

POST /?AuthId=YOURKEY&Action=WebServiceAction&Signature=rcLXfkPldrYm04 HTTP/1.1
Content-Type: text/tab-separated-values; charset=iso-8859-1
Content-Length: []
Host: webservices.domain.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)

name    id
John    G12N
Sarah   J87M
Bob     N33Y

This approach logically combines QueryString and Body-Post using a single Content-Type which is a "parsing-instruction" for a web-server.

Please note: HTTP/1.1 is wrapped with the #32 (space) on the left and with #10 (Line feed) on the right.

How to change a <select> value from JavaScript

You can use the selectedIndex property to set it to the first option:

document.getElementById("select").selectedIndex = 0;

How do I order my SQLITE database in descending order, for an android app?

you can do it with this

Cursor cursor = database.query(
            TABLE_NAME,
            YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");

How to test if JSON object is empty in Java

if (jsonObj != null && jsonObj.length > 0)

To check if a nested JSON object is empty within a JSONObject:

if (!jsonObject.isNull("key") && jsonObject.getJSONObject("key").length() > 0)

Testing HTML email rendering

Campaign Monitor is quite popular and offers previews for many popular email clients.

How to remove undefined and null values from an object using lodash?

The correct answer is:

_.omitBy({ a: null, b: 1, c: undefined, d: false }, _.isNil)

That results in:

{b: 1, d: false}

The alternative given here by other people:

_.pickBy({ a: null, b: 1, c: undefined, d: false }, _.identity);

Will remove also false values which is not desired here.

Can I use conditional statements with EJS templates (in JMVC)?

EJS seems to behave differently depending on whether you use { } notation or not:

I have checked and the following condition is evaluated as you would expect:

<%if (3==3) {%>  TEXT PRINTED  <%}%>
<%if (3==4) {%>  TEXT NOT PRINTED  <%}%>

while this one doesn't:

<%if (3==3) %>  TEXT PRINTED  <% %>
<%if (3==4) %>  TEXT PRINTED  <% %>  

Does Django scale?

Not sure about the number of daily visits but here are a few examples of large Django sites:

Here is a link to list of high traffic Django sites on Quora.

How to format numbers by prepending 0 to single-digit numbers?

Here is a very simple solution that worked well for me.

First declare a variable to hold your number.

var number;

Now convert the number to a string and hold it in another variable;

var numberStr = number.toString();

Now you can test the length of this string , if it is less than desired you can append a 'zero' at the beginning.

if(numberStr.length < 2){
      number = '0' + number;
}

Now use the number as desired

console.log(number);

How to use basic authorization in PHP curl

Try the following code :

$username='ABC';
$password='XYZ';
$URL='<URL>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

Calling Javascript from a html form

In this bit of code:

getRadioButtonValue(this["whichThing"]))

you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.

EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:

  $('input[name=whichThing]:checked').val() 

Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:

var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
     if (document.myform.whichThing[i].checked==true) {
         t = t + document.myform.whichThing[i].value;
     }
}

or, basically, modify the original line of code to read thusly:

getRadioButtonValue(document.myform.whichThing))

Edit 3 Here's your homework:

      function handleClick() {
        alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
        //event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
<form name="aye" onSubmit="return handleClick()">
     <input name="Submit"  type="submit" value="Update" />
     Which of the following do you like best?
     <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
     <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
     <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>

Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.

In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.

The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.

EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.

See the difference in this method:

function handleClick() {
   alert("Direct Access: " + document.aye["whichThing"]);
   alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
   return false; // prevent further bubbling of event
}

How to set cursor to input box in Javascript?

You have not provided enough code to help You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.

Here is the canonical plain javascript method of validating a form It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point DEMO

function validate(formObj) {
  document.getElementById("errorMsg").innerHTML = "";    
  var quantity = formObj.quantity;
  if (isNaN(quantity)) {
    quantity.value="";
    quantity.focus();
    document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
    return false;
  }
  return true; // allow submit
}   

Here is the HTML

<form onsubmit="return validate(this)">
    <input type="text" name="quantity" value="" />
    <input type="submit" />
</form>    
<span id="errorMsg"></span>

Can I run Keras model on gpu?

See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already.

Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from here and put the DLL (e.g., cudnn64_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).

How to parse JSON Array (Not Json Object) in Android

My case Load From Server Example..

int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
            if (jsonLength != 1) {
                for (int i = 0; i < jsonLength; i++) {
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
                    JSONObject resJson = (JSONObject) jsonArray.get(i);
                    //addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
                }

Hope it help

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Difference between timestamps with/without time zone in PostgreSQL

I try to explain it more understandably than the referred PostgreSQL documentation.

Neither TIMESTAMP variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:

  • TIMESTAMP WITHOUT TIME ZONE stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30', then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00' and '2011-07-01 06:30:30+05' are the same as just '2011-07-01 06:30:30'. For Java developers: it's analogous to java.time.LocalDateTime.

  • TIMESTAMP WITH TIME ZONE stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30') it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'). The output is displayed converted to the current time zone of the PostgreSQL session. For Java developers: It's analogous to java.time.Instant (with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime (or to java.util.Date or java.sql.Timestamp of course).

Some say that both TIMESTAMP variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE is stored like a TIMESTAMP WITH TIME ZONE, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)

Oracle TNS names not showing when adding new connection to SQL Developer

Open SQL Developer. Go to Tools -> Preferences -> Databases -> Advanced Then explicitly set the Tnsnames Directory

My TNSNAMES was set up correctly and I could connect to Toad, SQL*Plus etc. but I needed to do this to get SQL Developer to work. Perhaps it was a Win 7 issue as it was a pain to install too.

Rollback to last git commit

Caveat Emptor - Destructive commands ahead.

Mitigation - git reflog can save you if you need it.


1) UNDO local file changes and KEEP your last commit

git reset --hard

2) UNDO local file changes and REMOVE your last commit

git reset --hard HEAD^

3) KEEP local file changes and REMOVE your last commit

git reset --soft HEAD^

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.


You can indeed use filters inside a boolean query.

Preview an image before it is uploaded

Default Iamge

                @Html.TextBoxFor(x => x.productModels.DefaultImage, new {@type = "file", @class = "form-control", onchange = "openFile(event)", @name = "DefaultImage", @id = "DefaultImage" })
                @Html.ValidationMessageFor(model => model.productModels.DefaultImage, "", new { @class = "text-danger" })
                    <img src="~/img/ApHandler.png"  style="height:125px; width:125px" id="DefaultImagePreview"/>
            </div>

 <script>
    var openFile = function (event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function () {
            var dataURL = reader.result;
            var output = document.getElementById('DefaultImagePreview');
            output.src = dataURL;
        };
        reader.readAsDataURL(input.files[0]);
    };
</script>

How to access the elements of a 2D array?

a[1][1] does work as expected. Do you mean a11 as the first element of the first row? Cause that would be a[0][0].

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

Call a REST API in PHP

CURL is the simplest way to go. Here is a simple call

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "THE URL TO THE SERVICE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);


print_r($result);
curl_close($ch);

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff

Intellij JAVA_HOME variable

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

To directly answer your question, you can add launchctl line in your ~/.bash_profile

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

Run jar file in command prompt

If you dont have an entry point defined in your manifest invoking java -jar foo.jar will not work.

Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:

java -cp foo.jar full.package.name.ClassName

See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

From MYSQL I solved the problem like this:

SUM(CASE WHEN used = 1 THEN 1 ELSE 0 END) as amount_one,

Hope this helps :D

Escape double quote character in XML

Others have answered in terms of how to handle the specific escaping in this case.

A broader answer is not to try to do it yourself. Use an XML API - there are plenty available for just about every modern programming platform in existence.

XML APIs will handle things like this for you automatically, making it a lot harder to go wrong. Unless you're writing an XML API yourself, you should rarely need to worry about the details like this.

Get multiple elements by Id

With querySelectorAll you can select the elements you want without the same id using css selector:

var elems = document.querySelectorAll("#id1, #id1, #id3");

count number of lines in terminal output

Pipe the result to wc using the -l (line count) switch:

grep -Rl "curl" ./ | wc -l

Scroll to bottom of div?

Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:

//get the div that contains all the messages
let div = document.getElementById('message-container');

//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });

Foreach with JSONArray and JSONObject

Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:

for(Object o: arr){
    if ( o instanceof JSONObject ) {
        parse((JSONObject)o);
    }
}

This is how things were done back in Java 1.4 and earlier.

JOptionPane - input dialog box program

Why to annoy the user with three different Dialog Boxes to enter things, why not do all this in one go in a single Dialog and save time, instead of testing the patience of the USER ?

You can add everything in a single Dialog, by putting all the fields on your JPanel and then adding this JPanel to your JOptionPane. Below code can clarify a bit more :

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class AverageExample
{
    private double[] marks;
    private JTextField[] marksField;
    private JLabel resultLabel;

    public AverageExample()
    {
        marks = new double[3];
        marksField = new JTextField[3];
        marksField[0] = new JTextField(10);
        marksField[1] = new JTextField(10);
        marksField[2] = new JTextField(10);
    }

    private void displayGUI()
    {
        int selection = JOptionPane.showConfirmDialog(
                null, getPanel(), "Input Form : "
                                , JOptionPane.OK_CANCEL_OPTION
                                , JOptionPane.PLAIN_MESSAGE);

        if (selection == JOptionPane.OK_OPTION) 
        {
            for ( int i = 0; i < 3; i++)
            {
                marks[i] = Double.valueOf(marksField[i].getText());             
            }
            Arrays.sort(marks);
            double average = (marks[1] + marks[2]) / 2.0;
            JOptionPane.showMessageDialog(null
                    , "Average is : " + Double.toString(average)
                    , "Average : "
                    , JOptionPane.PLAIN_MESSAGE);
        }
        else if (selection == JOptionPane.CANCEL_OPTION)
        {
            // Do something here.
        }
    }

    private JPanel getPanel()
    {
        JPanel basePanel = new JPanel();
        //basePanel.setLayout(new BorderLayout(5, 5));
        basePanel.setOpaque(true);
        basePanel.setBackground(Color.BLUE.darker());

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
        centerPanel.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        centerPanel.setOpaque(true);
        centerPanel.setBackground(Color.WHITE);

        JLabel mLabel1 = new JLabel("Enter Marks 1 : ");
        JLabel mLabel2 = new JLabel("Enter Marks 2 : ");
        JLabel mLabel3 = new JLabel("Enter Marks 3 : ");

        centerPanel.add(mLabel1);
        centerPanel.add(marksField[0]);
        centerPanel.add(mLabel2);
        centerPanel.add(marksField[1]);
        centerPanel.add(mLabel3);
        centerPanel.add(marksField[2]);

        basePanel.add(centerPanel);

        return basePanel;
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new AverageExample().displayGUI();
            }
        });
    }
}

How do you send a Firebase Notification to all devices via CURL?

EDIT: It appears that this method is not supported anymore (thx to @FernandoZamperin). Please take a look at the other answers!

Instead of subscribing to a topic you could instead make use of the condition key and send messages to instances, that are not in a group. Your data might look something like this:

{
    "data": {
        "foo": "bar"
    },
    "condition": "!('anytopicyoudontwanttouse' in topics)"
}

See https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics_2

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

$(document).ready(function() is not working

If you have a js file that references the jquery, it could be because the js file is in the body and not in the head section (that was my problem). You should move your js file to the head section AFTER the jquery.js reference.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
    <script src="myfile.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>

Where do I find the Instagram media ID of a image

If you add ?__a=1 at the end of Instagram public URLs, you get the data of the public URL in JSON.

For the media ID of an image from post URL, simply add the JSON request code at the post URL:

http://instagram.com/p/Y7GF-5vftL/?__a=1

The response will look like this below. You can easily recover the image ID from the "id" parameter in the reply...

{
"graphql": {
"shortcode_media": {
"__typename": "GraphImage",
"id": "448979387270691659",
"shortcode": "Y7GF-5vftL",
"dimensions": {
"height": 612,
"width": 612
},
"gating_info": null,
"fact_check_information": null,
"media_preview": null,
"display_url": "https://scontent-cdt1-1.cdninstagram.com/vp/6d4156d11e92ea1731377ef53324ce28/5E4D451A/t51.2885-15/e15/11324452_400723196800905_116356150_n.jpg?_nc_ht=scontent-cdt1-1.cdninstagram.com&_nc_cat=109",
"display_resources": [

Rails has_many with alias name

You could also use alias_attribute if you still want to be able to refer to them as tasks as well:

class User < ActiveRecord::Base
  alias_attribute :jobs, :tasks

  has_many :tasks
end

How to send HTML email using linux command line

Try with :

echo "To: [email protected]" > /var/www/report.csv
echo "Subject: Subject" >> /var/www/report.csv
echo "MIME-Version: 1.0" >> /var/www/report.csv
echo "Content-Type: text/html; charset=\"us-ascii\"" >> /var/www/report.csv
echo "Content-Disposition: inline" >> /var/www/report.csv

echo "<html>" >> /var/www/report.csv
mysql -u ***** -p***** -H -e "select * from users LIMIT 20" dev >> /var/www/report.csv
echo "</html>" >> /var/www/report.csv

mail -s "Built notification" [email protected] < /var/www/report.csv

How to put sshpass command inside a bash script?

Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.

sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

Android difference between Two Dates

This works and convert to String as a Bonus ;)

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

    setContentView(R.layout.activity_main);

    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);

    } catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}

What is the difference between a static method and a non-static method?

Generally

static: no need to create object we can directly call using

ClassName.methodname()

Non Static: we need to create a object like

ClassName obj=new ClassName()
obj.methodname();

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

Is there a way to set background-image as a base64 encoded image?

Had the same problem with base64. For anyone in the future with the same problem:

url = "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";

This would work executed from console, but not from within a script:

$img.css("background-image", "url('" + url + "')");

But after playing with it a bit, I came up with this:

var img = new Image();
img.src = url;
$img.css("background-image", "url('" + img.src + "')");

No idea why it works with a proxy image, but it does. Tested on Firefox Dev 37 and Chrome 40.

Hope it helps someone.

EDIT

Investigated a little bit further. It appears that sometimes base64 encoding (at least in my case) breaks with CSS because of line breaks present in the encoded value (in my case value was generated dynamically by ActionScript).

Simply using e.g.:

$img.css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");

works too, and even seems to be faster by a few ms than using a proxy image.

Random number in range [min - max] using PHP

In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.

int random_int ( int $min , int $max )

random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

I had this error message:

Error: Can't open display: localhost:13.0

This fixed it for me:

export DISPLAY="localhost:10.0"

You can use this too:

export DISPLAY="127.0.0.1:10.0"

Refused to load the script because it violates the following Content Security Policy directive

The probable reason why you get this error is likely because you've added the /build folder to your .gitignore file or generally haven't checked it into Git.

So when you Git push Heroku master, the build folder you're referencing don't get pushed to Heroku. And that's why it shows this error.

That's the reason it works properly locally, but not when you deployed to Heroku.

How to wrap text around an image using HTML/CSS

you have to float your image container as follows:

HTML

<div id="container">
    <div id="floated">...some other random text</div>
    ...
    some random text
    ...
</div>

CSS

#container{
    width: 400px;
    background: yellow;
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

FIDDLE

http://jsfiddle.net/kYDgL/

Mocking Logger and LoggerFactory with PowerMock and Mockito

I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.

Calculating distance between two geographic locations

Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.

Location selected_location = new Location("locationA");
            selected_location.setLatitude(17.372102);
            selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
            near_locations.setLatitude(17.375775);
            near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);

here "distance" is distance between locationA & locationB (in Meters)

Scroll to the top of the page after render in react.js

None of the above answers is currently working for me. It turns out that .scrollTo is not as widely compatible as .scrollIntoView.

In our App.js, in componentWillMount() we added

this.props.history.listen((location, action) => {
        setTimeout(() => { document.getElementById('root').scrollIntoView({ behavior: "smooth" }) }, 777)
    })

This is the only solution that is working universally for us. root is the ID of our App. The "smooth" behavior doesn't work on every browser / device. The 777 timeout is a bit conservative, but we load a lot of data on every page, so through testing this was necessary. A shorter 237 might work for most applications.

How to save Excel Workbook to Desktop regardless of user?

You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.

Public Sub SaveToDesktop()
    ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _ 
    FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

I'm not sure whether this would be a requirement, but may help!

C error: undefined reference to function, but it IS defined

How are you doing the compiling and linking? You'll need to specify both files, something like:

gcc testpoint.c point.c

...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main. You'll need/want to eliminate one (undoubtedly the one in point.c).

In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make to do the work. In this case you'd have something like this:

OBJS=testpoint.o point.o

testpoint.exe: $(OBJS)
    gcc $(OJBS)

The first is just a macro for the names of the object files. You get it expanded with $(OBJS). The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.

Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:

.c.o:
    $(CC) -c $(CFLAGS) $<

This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc) and allows you to specify any flags you care about in a macro named CFLAGS (e.g., CFLAGS=-O3 to turn on optimization) and $< is a special macro that expands to the name of the source file.

You typically store this in a file named Makefile, and to build your program, you just type make at the command line. It implicitly looks for a file named Makefile, and runs whatever rules it contains.

The good point of this is that make automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).

Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

Why is &#65279; appearing in my HTML?

Just use notepad ++ with encoding UTF-8 without BOM.

C++: Where to initialize variables in constructor

In short, always prefer initialization lists when possible. 2 reasons:

  • If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.

  • Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.

Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.