Programs & Examples On #Cross language

jQuery return ajax result into outside variable

I solved it by doing like that:

var return_first = (function () {
        var tmp = $.ajax({
            'type': "POST",
            'dataType': 'html',
            'url': "ajax.php?first",
            'data': { 'request': "", 'target': arrange_url, 'method': 
                    method_target },
            'success': function (data) {
                tmp = data;
            }
        }).done(function(data){
                return data;
        });
      return tmp;
    });
  • Be careful 'async':fale javascript will be asynchronous.

Use jquery click to handle anchor onClick()

You can't have multiple time the same ID for elements. It is meant to be unique.

Use a class and make your IDs unique:

<div class="solTitle" id="solTitle1"> <a href = "#"  id = "solution0" onClick = "openSolution();">Solution0 </a></div>

And use the class selector:

$('.solTitle a').click(function(evt) {

    evt.preventDefault();
    alert('here in');
    var divId = 'summary' + this.id.substring(0, this.id.length-1);

    document.getElementById(divId).className = ''; 

});

Fixed header, footer with scrollable content

Approach 1 - flexbox

It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%; and reset the default margin on body. See the browser support tables.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  flex: 1;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 2 - CSS table

For both known and unknown height elements. It also works in legacy browsers including IE8.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
  display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.inner {_x000D_
  display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
  position: absolute;_x000D_
  left: 0; right: 0;_x000D_
  top: 0; bottom: 0;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">_x000D_
    <div class="inner">Header</div>_x000D_
  </div>_x000D_
  <div class="content">_x000D_
    <div class="inner">_x000D_
      <div class="scrollable">_x000D_
        <div style="height:1000px;">Content</div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="footer">_x000D_
    <div class="inner">Footer</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 3 - calc()

If header and footer are fixed height, you can use CSS calc().

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 50px;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: calc(100% - 100px);_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 4 - % for all

If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 10%;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: 80%;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

Pagination using MySQL LIMIT, OFFSET

A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.

It is better to remember where you left off.

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

HTML input field hint

If you mean like a text in the background, I'd say you use a label with the input field and position it on the input using CSS, of course. With JS, you fade out the label when the input receives values and fade it in when the input is empty. In this way, it is not possible for the user to submit the description, whether by accident or intent.

Printing Even and Odd using two Threads in Java

This code will also work fine.

class Thread1 implements Runnable {

    private static boolean evenFlag = true;

    public synchronized void run() {
        if (evenFlag == true) {
            printEven();
        } else {
           printOdd();
        }
    }

    public void printEven() {
        for (int i = 0; i <= 10; i += 2) {
            System.out.println(i+""+Thread.currentThread());
        }
        evenFlag = false;
    }

    public  void printOdd() {
        for (int i = 1; i <= 11; i += 2) {
            System.out.println(i+""+Thread.currentThread());
        }
        evenFlag = true;
    }
}

public class OddEvenDemo {

    public static void main(String[] args) {

        Thread1 t1 = new Thread1();
        Thread td1 = new Thread(t1);
        Thread td2 = new Thread(t1);
        td1.start();
        td2.start();

    }
}

Random numbers with Math.random() in Java

There's a small problem with the formula that you found on Google. It should be:
(int)(Math.random() * (max - min + 1) + min)
not
(int)(Math.random() * (max - min) + min) .

max - min + 1 is the range in which random numbers can be generated

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

How to Check whether Session is Expired or not in asp.net

this way many people detect session has expired or not. the below code may help u.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

How to remove duplicates from a list?

If the code in your question doesn't work, you probably have not implemented equals(Object) on the Customer class appropriately.

Presumably there is some key (let us call it customerId) that uniquely identifies a customer; e.g.

class Customer {
    private String customerId;
    ...

An appropriate definition of equals(Object) would look like this:

    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Customer)) {
            return false;
        }
        Customer other = (Customer) obj;
        return this.customerId.equals(other.customerId);
    }

For completeness, you should also implement hashCode so that two Customer objects that are equal will return the same hash value. A matching hashCode for the above definition of equals would be:

    public int hashCode() {
        return customerId.hashCode();
    }

It is also worth noting that this is not an efficient way to remove duplicates if the list is large. (For a list with N customers, you will need to perform N*(N-1)/2 comparisons in the worst case; i.e. when there are no duplicates.) For a more efficient solution you should use something like a HashSet to do the duplicate checking.

Copy files without overwrite

This is what has worked for me. I use this to "add" files over to the other drive, with no overwrites.

Batch file: robocopy-missingfiles.bat

@echo off
echo Copying 
echo      "%1"
echo   to "%2"
echo.
echo Press Cntr+C to abort
Pause
echo.
@echo on
robocopy %1 %2 /Xo /XN /XC /J /SL /S /MT:8 /R:1 /W:1 /V /DCOPY:DAT /ETA /COPY:DATO /FFT /A-:SH /XD $RECYCLE.BIN "System Volume Information"

Example:

robocopy-missingfiles.bat f:\Working-folder\ E:\Backup-folder\

Do test before implementation.

remove kernel on jupyter notebook

If you are doing this for virtualenv, the kernels in inactive environments might not be shown with jupyter kernelspec list, as suggested above. You can delete it from directory:

~/.local/share/jupyter/kernels/

Scroll back to the top of scrollable div

For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function.

Example:

$('#elem').show();
$('#elem').scrollTop(0);

Mysql: Select rows from a table that are not in another

If you have 300 columns as you mentioned in another comment, and you want to compare on all columns (assuming the columns are all the same name), you can use a NATURAL LEFT JOIN to implicitly join on all matching column names between the two tables so that you don't have to tediously type out all join conditions manually:

SELECT            a.*
FROM              tbl_1 a
NATURAL LEFT JOIN tbl_2 b
WHERE             b.FirstName IS NULL

How to add double quotes to a string that is inside a variable?

If I understand your question properly, maybe you can try this:

string title = string.Format("<div>\"{0}\"</div>", "some text");

Putting images with options in a dropdown list

You can't do that in plain HTML, but you can do it with jQuery:

JavaScript Image Dropdown

Are you tired with your old fashion dropdown? Try this new one. Image combo box. You can add an icon with each option. It works with your existing "select" element or you can create by JSON object.

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not really a COM dll (you can't register it).

What you need is comdlg32.ocx which contains the MSComDlg.CommonDialog COM class (and indeed relies on comdlg32.dll to work). Once you get ahold on a comdlg32.ocx, then you will be able to do regsvr32 comdlg32.ocx.

Adding a SVN repository in Eclipse

Necropost, but helpful: I came across this problem with an RA request failed since the files "already existed on the server" but wouldn't sync with my repository. I went to the source on my disk, deleted there, refreshed my Eclipse view, and updated the source. Error gone.

How does one parse XML files?

I'd use LINQ to XML if you're in .NET 3.5 or higher.

Writing/outputting HTML strings unescaped

Complete example for using template functions in RazorEngine (for email generation, for example):

@model SomeModel
@{
    Func<PropertyChangeInfo, object> PropInfo =
        @<tr class="property">
            <td>
                @item.PropertyName                
            </td>
            <td class="value">
                <small class="old">@item.OldValue</small>
                <small class="new">@item.CurrentValue</small>                
            </td>
        </tr>;
}

<body>

@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }

</body>

Can I use return value of INSERT...RETURNING in another INSERT?

You can use the lastval() function:

Return value most recently obtained with nextval for any sequence

So something like this:

INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val)  VALUES (lastval());

This will work fine as long as no one calls nextval() on any other sequence (in the current session) between your INSERTs.

As Denis noted below and I warned about above, using lastval() can get you into trouble if another sequence is accessed using nextval() between your INSERTs. This could happen if there was an INSERT trigger on Table1 that manually called nextval() on a sequence or, more likely, did an INSERT on a table with a SERIAL or BIGSERIAL primary key. If you want to be really paranoid (a good thing, they really are you to get you after all), then you could use currval() but you'd need to know the name of the relevant sequence:

INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val)  VALUES (currval('Table1_id_seq'::regclass));

The automatically generated sequence is usually named t_c_seq where t is the table name and c is the column name but you can always find out by going into psql and saying:

=> \d table_name;

and then looking at the default value for the column in question, for example:

id | integer | not null default nextval('people_id_seq'::regclass)

FYI: lastval() is, more or less, the PostgreSQL version of MySQL's LAST_INSERT_ID. I only mention this because a lot of people are more familiar with MySQL than PostgreSQL so linking lastval() to something familiar might clarify things.

Node.js on multi-core machines

It's also possible to design the web-service as several stand alone servers that listen to unix sockets, so that you can push functions like data processing into seperate processes.

This is similar to most scrpting/database web server architectures where a cgi process handles business logic and then pushes and pulls the data via a unix socket to a database.

the difference being that the data processing is written as a node webserver listening on a port.

it's more complex but ultimately its where multi-core development has to go. a multiprocess architecture using multiple components for each web request.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Difference in make_shared and normal shared_ptr in C++

Shared_ptr: Performs two heap allocation

  1. Control block(reference count)
  2. Object being managed

Make_shared: Performs only one heap allocation

  1. Control block and object data.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

apt-get install python-dev

...solved the problem for me.

What is __future__ in Python used for and how/when to use it, and how it works

It can be used to use features which will appear in newer versions while having an older release of Python.

For example

>>> from __future__ import print_function

will allow you to use print as a function:

>>> print('# of entries', len(dictionary), file=sys.stderr)

How can I close a login form and show the main form without my application closing?

It's simple.

Here is the code.

 private void button1_Click(object sender, EventArgs e)
 {  
        //creating instance of main form
        MainForm mainForm = new MainForm();

        // creating event handler to catch the main form closed event
        // this will fire when mainForm closed
        mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
        //showing the main form
        mainForm.Show();
        //hiding the current form
        this.Hide();
  }

  // this is the method block executes when main form is closed
  void mainForm_FormClosed(object sender, FormClosedEventArgs e)
  {
       // here you can do anything

       // we will close the application
       Application.Exit();
  }

Get specific object by id from array of objects in AngularJS

use $timeout and run a function to search in "results" array

app.controller("Search", function ($scope, $timeout) {
        var foo = { "results": [
          {
             "id": 12,
             "name": "Test"
          },
          {
             "id": 2,
             "name": "Beispiel"
          },
          {
             "id": 3,
            "name": "Sample"
          }
        ] };
        $timeout(function () {
            for (var i = 0; i < foo.results.length; i++) {
                if (foo.results[i].id=== 2) {
                    $scope.name = foo.results[i].name;
                }
            }
        }, 10);

    });

Regular Expression to match valid dates

This is not an appropriate use of regular expressions. You'd be better off using

[0-9]{2}/[0-9]{2}/[0-9]{4}

and then checking ranges in a higher-level language.

How to determine if .NET Core is installed

After all the other answers, this might prove useful.

Open your application in Visual Studio. In Solutions Explorer, right click your project. Click Properties. Click Application. Under "Target Framework" click the dropdown button and there you are, all of the installed frameworks.

BTW - you may now choose which framework you want.

angularjs getting previous route path

This alternative also provides a back function.

The template:

<a ng-click='back()'>Back</a>

The module:

myModule.run(function ($rootScope, $location) {

    var history = [];

    $rootScope.$on('$routeChangeSuccess', function() {
        history.push($location.$$path);
    });

    $rootScope.back = function () {
        var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
        $location.path(prevUrl);
    };

});

Custom height Bootstrap's navbar

For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..

<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
    <div class="navbar-collapse collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
        </ul>
    </div>
</nav>

Bootstrap 4 Navbar Height Demo

How to get all options of a select using jQuery?

I don't know jQuery, but I do know that if you get the select element, it contains an 'options' object.

var myOpts = document.getElementById('yourselect').options;
alert(myOpts[0].value) //=> Value of the first option

Redirect stderr and stdout in Bash

"Easiest" way (bash4 only): ls * 2>&- 1>&-.

Execute stored procedure with an Output parameter?

Here is the stored procedure

create procedure sp1
(
@id as int,
@name as nvarchar(20) out
)
as
begin
select @name=name from employee where id=@id
end

And here is the way to execute the procedure

 declare @name1 nvarchar(10)
    exec sp1 1,@name1 out
    print @name1

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Blocking device rotation on mobile web pages

seems weird that no one proposed the CSS media query solution:

@media screen and (orientation: portrait) {
  ...
}

and the option to use a specific style sheet:

<link rel="stylesheet" type="text/css" href="css/style_p.css" media="screen and (orientation: portrait)">

MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#orientation

Java FileWriter how to write to next Line

You can call the method newLine() provided by java, to insert the new line in to a file.

For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()

Change div width live with jQuery

There are two ways to do this:

CSS: Use width as %, like 75%, so the width of the div will change automatically when user resizes the browser.

Javascipt: Use resize event

$(window).bind('resize', function()
{
    if($(window).width() > 500)
        $('#divID').css('width', '300px');
    else
        $('divID').css('width', '200px');
});

Hope this will help you :)

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

How do you stylize a font in Swift?

Xamarin

Label.Font = UIFont.FromName("Copperplate", 10.0f);

Swift

text.font = UIFont.init(name: "Poppins-Regular", size: 14)

To get the list of font family Github/IOS-UIFont-Names

How to replace space with comma using sed?

Try the following command and it should work out for you.

sed "s/\s/,/g" orignalFive.csv > editedFinal.csv

MySQL query to get column names?

Try this one out I personally use it:

SHOW COLUMNS FROM $table where field REGEXP 'stock_id|drug_name' 

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

OS X Terminal shortcut: Jump to beginning/end of line

Here I found a tweak for this, without any third party tool. This will make the following shortcut to work:

 fn + right: to go to the end of the line.
 fn + left: to go to the beginning of the line.
  • Open terminal preferences.(cmd + ,).
  • Go to your selected theme and then to the keyboard tab.

enter image description here

  • And add a new entry as following. enter image description here enter image description here

  • That's all. Now close and check.

    Hope it helps.

EDIT: Refer to the comment by @Maurice Gilden below for more insights.

Connect multiple devices to one device via Bluetooth

I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
which allows one-to-many connections.

Bootstrap 3 select input form inline

Thanks to G_money and other suggestions for this excellent solution to input-text with inline dropdown... here's another great solution.

<form class="form-inline" role="form" id="yourformID-form" action="" method="post">
    <div class="input-group">
        <span class="input-group-addon"><i class="fa fa-male"></i></span>

        <div class="form-group">
            <input size="50" maxlength="50" class="form-control" name="q" type="text">          
        </div>

        <div class="form-group">
            <select class="form-control" name="category">
                <option value=""></option>
                <option value="0">select1</option>
                <option value="1">select2</option>
                <option value="2">select3</option>
            </select>           
        </div>
    </div>
</form>

This works with Bootstrap 3: allowing input-text inline with a select dropdown. Here's what it looks like below...

enter image description here

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

Live search through table rows

This one is Best in my case

https://www.w3schools.com/jquery/jquery_filters.asp

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

Download multiple files as a zip-file using php

You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

and to stream it:

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

How to declare array of zeros in python (or an array of a certain size)

Depending on what you're actually going to do with the data after it's collected, collections.defaultdict(int) might be useful.

Convert date to UTC using moment.js

Read this documentation of moment.js here. See below example and output where I convert GMT time to local time (my zone is IST) and then I convert local time to GMT.

// convert GMT to local time
console.log('Server time:' + data[i].locationServerTime)
let serv_utc = moment.utc(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment(serv_utc,"YYYY-MM-DD HH:mm:ss").tz(self.zone_name).format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to local time:' + data[i].locationServerTime)

// convert local time to GMT
console.log('local time:' + data[i].locationServerTime)
let serv_utc = moment(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment.utc(serv_utc,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to server time:' + data[i].locationServerTime)

Output is

Server time:2019-12-19 09:28:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to local time:2019-12-19 14:58:13
local time:2019-12-19 14:58:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to server time:2019-12-19 09:28:13

LINQ to SQL - Left Outer Join with multiple join conditions

this works too, ...if you have multiple column joins

from p in context.Periods
join f in context.Facts 
on new {
    id = p.periodid,
    p.otherid
} equals new {
    f.id,
    f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value

How to get the CUDA version?

First you should find where Cuda installed.

If it's a default installation like here the location should be:

for ubuntu:

/usr/local/cuda

in this folder you should have a file

version.txt

open this file with any text editor or run:

cat version.txt

from the folder

OR

 cat /usr/local/cuda/version.txt 

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

PUT

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H answer

DELETE

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

how to modify an existing check constraint?

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

I think you have 2 separate problems, 1. with restoring and 2. with creating

For 1. you could try checking to see if the file was transferred properly (one easy way would be to check the md5 of the file on the server and again on the local environment to see if they match).

MySQL Workbench not displaying query results

This is a known bug: link. Upcoming release 6.2.2 fixes this for OS X (Unfortunately, Linux version is still broken).

At least on my computer it's not dissapeared, just folded, and it's edge is almost merged with the edge of 'Action Output' block. When you move your mouse to that edge, the cursor starts looking like a dash with two arrows. Slowly move it couple of pixels higher until you catch the small 1px area where the cursor changes to a dash with a single arrow. Then catch it and pull : )

I've made a couple of photos to illustrate this.

Step 1 Step 2 Step 3

Anchor links in Angularjs?

There are a few ways to do this it seems.

Option 1: Native Angular

Angular provides an $anchorScroll service, but the documentation is severely lacking and I've not been able to get it to work.

Check out http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html for some insight into $anchorScroll.

Option 2: Custom Directive / Native JavaScript

Another way I tested out was creating a custom directive and using el.scrollIntoView(). This works pretty decently by basically doing the following in your directive link function:

var el = document.getElementById(attrs.href);
el.scrollIntoView();

However, it seems a bit overblown to do both of these when the browser natively supports this, right?

Option 3: Angular Override / Native Browser

If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:

Links that contain target element

Example: <a href="/ext/link?a=b" target="_self">link</a>

So, all you have to do is add the target attribute to your links, like so:

<a href="#anchorLinkID" target="_self">Go to inpage section</a>

Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.

I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.

Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.

OnChange event using React JS for drop down

import React, { PureComponent, Fragment } from 'react';
import ReactDOM from 'react-dom';

class Select extends PureComponent {
  state = {
    options: [
      {
        name: 'Select…',
        value: null,
      },
      {
        name: 'A',
        value: 'a',
      },
      {
        name: 'B',
        value: 'b',
      },
      {
        name: 'C',
        value: 'c',
      },
    ],
    value: '?',
  };

  handleChange = (event) => {
    this.setState({ value: event.target.value });
  };

  render() {
    const { options, value } = this.state;

    return (
      <Fragment>
        <select onChange={this.handleChange} value={value}>
          {options.map(item => (
            <option key={item.value} value={item.value}>
              {item.name}
            </option>
          ))}
        </select>
        <h1>Favorite letter: {value}</h1>
      </Fragment>
    );
  }
}

ReactDOM.render(<Select />, window.document.body);

Android: Clear Activity Stack

Intent intent = new Intent(LoginActivity.this, Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //It is use to finish current activity
startActivity(intent);
this.finish();

Web API optional parameters

you need only set default value to parameters(you do not need the Route attribute):

public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

How can I trim leading and trailing white space?

Another option is to use the stri_trim function from the stringi package which defaults to removing leading and trailing whitespace:

> x <- c("  leading space","trailing space   ")
> stri_trim(x)
[1] "leading space"  "trailing space"

For only removing leading whitespace, use stri_trim_left. For only removing trailing whitespace, use stri_trim_right. When you want to remove other leading or trailing characters, you have to specify that with pattern =.

See also ?stri_trim for more info.

optional parameters in SQL Server stored proc?

2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine

exec getlist 47,1,0

create procedure getlist
   @convId int,
   @SortOrder int,
   @contestantsOnly bit = 0
as

overlay two images in android to set an imageview

You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable dynamically in code.

Solution #1 (via XML):

Create a new Drawable XML file, let's call it layer.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/t" />
    <item android:drawable="@drawable/tt" />
</layer-list>

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));

Solution #2 (dynamic):

Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);

(I haven't tested this code so there may be a mistake, but this general outline should work.)

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

How can I disable a button on a jQuery UI dialog?

this code disable the button with 'YOUR_BUTTON_LABEL'. you can replace name in contains(). to disable

$(".ui-dialog-buttonpane button:contains('YOUR_BUTTON_LABEL')").button("disable");

replace 'YOUR_BUTTON_LABEL' with your button's label. to enable

$(".ui-dialog-buttonpane button:contains('YOUR_BUTTON_LABEL')").button("enable");

Creating an array from a text file in Bash

You can simply read each line from the file and assign it to an array.

#!/bin/bash
i=0
while read line 
do
        arr[$i]="$line"
        i=$((i+1))
done < file.txt

How to run a program in Atom Editor?

You can run specific lines of script by highlighting them and clicking shift + ctrl + b

You can also use command line by going to the root folder and writing: $ node nameOfFile.js

How much memory can a 32 bit process access on a 64 bit operating system?

The limit is not 2g or 3gb its 4gb for 32bit.

The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.

Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.

4Gig not 3 not 2 got it?

Use CASE statement to check if column exists in table - SQL Server

select case
         when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
         then 0
         else 1
       end

PHP cURL, extract an XML response

$sXML = download_page('http://alanstorm.com/atom');
// Comment This    
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
//  echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);

Comment out HTML and PHP together

PHP parser will search your entire code for <?php (or <? if short_open_tag = On), so HTML comment tags have no effect on PHP parser behavior & if you don't want to parse your PHP code, you have to use PHP commenting directives(/* */ or //).

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

Error: request entity too large

I had the same error recently, and all the solutions I've found did not work.

After some digging, I found that setting app.use(express.bodyParser({limit: '50mb'})); did set the limit correctly.

When adding a console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/lib/middleware/json.js:46 and restarting node, I get this output in the console:

Limit file size: 1048576
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
Limit file size: 52428800
Express server listening on port 3002

We can see that at first, when loading the connect module, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the console.log is called again and this time the limit is 52428800 (50mb). However, I still get a 413 Request entity too large.

Then I added console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10 and saw another line in the console when calling the route with a big request (before the error output) :

Limit file size: 1048576

This means that somehow, somewhere, connect resets the limit parameter and ignores what we specified. I tried specifying the bodyParser parameters in the route definition individually, but no luck either.

While I did not find any proper way to set it permanently, you can "patch" it in the module directly. If you are using Express 3.4.4, add this at line 46 of node_modules/express/node_modules/connect/lib/middleware/json.js :

limit = 52428800; // for 50mb, this corresponds to the size in bytes

The line number might differ if you don't run the same version of Express. Please note that this is bad practice and it will be overwritten if you update your module.

So this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.

I have opened an issue on their GitHub about this problem.

[edit - found the solution]

After some research and testing, I found that when debugging, I added app.use(express.bodyParser({limit: '50mb'}));, but after app.use(express.json());. Express would then set the global limit to 1mb because the first parser he encountered when running the script was express.json(). Moving bodyParser above it did the trick.

That said, the bodyParser() method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));

In case you need multipart (for file uploads) see this post.

[second edit]

Note that in Express 4, instead of express.json() and express.urlencoded(), you must require the body-parser module and use its json() and urlencoded() methods, like so:

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

If the extended option is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option). This is because this option will be required in the next version and will not be optional anymore. For more info on the extended option, you can refer to the readme of body-parser.

[third edit]

It seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));

How can I see the raw SQL queries Django is running?

If you make sure your settings.py file has:

  1. django.core.context_processors.debug listed in CONTEXT_PROCESSORS
  2. DEBUG=True
  3. your IP in the INTERNAL_IPS tuple

Then you should have access to the sql_queries variable. I append a footer to each page that looks like this:

{%if sql_queries %}
  <div class="footNav">
    <h2>Queries</h2>
    <p>
      {{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }}, {{sql_time_sum}} Time
    {% ifnotequal sql_queries|length 0 %}
      (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.disp\
lay=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
    {% endifnotequal %}
    </p>
    <table id="debugQueryTable" style="display: none;">
      <col width="1"></col>
      <col></col>
      <col width="1"></col>
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">SQL</th>
          <th scope="col">Time</th>
        </tr>
      </thead>
      <tbody>
        {% for query in sql_queries %}
          <tr class="{% cycle odd,even %}">
            <td>{{ forloop.counter }}</td>
            <td>{{ query.sql|escape }}</td>
            <td>{{ query.time }}</td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
{% endif %}

I got the variable sql_time_sum by adding the line

context_extras['sql_time_sum'] = sum([float(q['time']) for q in connection.queries])

to the debug function in django_src/django/core/context_processors.py.

postgres: upgrade a user to be a superuser?

Run this Command

alter user myuser with superuser;

If you want to see the permission to a user run following command

\du

How to get the employees with their managers

Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr) thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)

have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)

SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;

Is Fortran easier to optimize than C for heavy calculations?

The faster code is not really up to the language, is the compiler so you can see the ms-vb "compiler" that generates bloated, slower and redundant object code that is tied together inside an ".exe", but powerBasic generates too way better code. Object code made by a C and C++ compilers is generated in some phases (at least 2) but by design most Fortran compilers have at least 5 phases including high-level optimizations so by design Fortran will always have the capability to generate highly optimized code. So at the end is the compiler not the language you should ask for, the best compiler i know is the Intel Fortran Compiler because you can get it on LINUX and Windows and you can use VS as the IDE, if you're looking for a cheap tigh compiler you can always relay on OpenWatcom.

More info about this: http://ed-thelen.org/1401Project/1401-IBM-Systems-Journal-FORTRAN.html

Read XML file using javascript

The code below will convert any XMLObject or string to a native JavaScript object. Then you can walk on the object to extract any value you want.

/**
 * Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
 * If a string is given, it first tries to create an XMLDomElement from the given string.
 * 
 * @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
 * @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
 * @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
 */
Object.fromXML = function( source, includeRoot ) {
    if( typeof source == 'string' )
    {
        try
        {
            if ( window.DOMParser )
                source = ( new DOMParser() ).parseFromString( source, "application/xml" );
            else if( window.ActiveXObject )
            {
                var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" );
                xmlObject.async = false;
                xmlObject.loadXML( source );
                source = xmlObject;
                xmlObject = undefined;
            }
            else
                throw new Error( "Cannot find an XML parser!" );
        }
        catch( error )
        {
            return false;
        }
    }

    var result = {};

    if( source.nodeType == 9 )
        source = source.firstChild;
    if( !includeRoot )
        source = source.firstChild;

    while( source ) {
        if( source.childNodes.length ) {
            if( source.tagName in result ) {
                if( result[source.tagName].constructor != Array ) 
                    result[source.tagName] = [result[source.tagName]];
                result[source.tagName].push( Object.fromXML( source ) );
            }
            else 
                result[source.tagName] = Object.fromXML( source );
        } else if( source.tagName )
            result[source.tagName] = source.nodeValue;
        else if( !source.nextSibling ) {
            if( source.nodeValue.clean() != "" ) {
                result = source.nodeValue.clean();
            }
        }
        source = source.nextSibling;
    }
    return result;
};

String.prototype.clean = function() {
    var self = this;
    return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "");
}

Android - How to get application name? (Not package name)

Okay guys another sleek option is

Application.Context.ApplicationInfo.NonLocalizedLabel

verified for hard coded android label on application element.

<application android:label="Big App"></application>

Reference: http://developer.android.com/reference/android/content/pm/PackageItemInfo.html#nonLocalizedLabel

How do I get the total Json record count using JQuery?

If you have something like this:

var json = [ {a:b, c:d}, {e:f, g:h, ...}, {..}, ... ]

then, you can do:

alert(json.length)

How do I define a method in Razor?

It's very simple to define a function inside razor.

@functions {

    public static HtmlString OrderedList(IEnumerable<string> items)
    { }
}

So you can call a the function anywhere. Like

@Functions.OrderedList(new[] { "Blue", "Red", "Green" })

However, this same work can be done through helper too. As an example

@helper OrderedList(IEnumerable<string> items){
    <ol>
        @foreach(var item in items){
            <li>@item</li>
        }
    </ol>
}

So what is the difference?? According to this previous post both @helpers and @functions do share one thing in common - they make code reuse a possibility within Web Pages. They also share another thing in common - they look the same at first glance, which is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.

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

A simple answer would be (26 characters):

String.fromCharCode(97+n);

If space is precious you could do the following (20 characters):

(10+n).toString(36);

Think about what you could do with all those extra bytes!

How this works is you convert the number to base 36, so you have the following characters:

0123456789abcdefghijklmnopqrstuvwxyz
^         ^
n        n+10

By offsetting by 10 the characters start at a instead of 0.

Not entirely sure about how fast running the two different examples client-side would compare though.

How to use LogonUser properly to impersonate domain user from workgroup client

It's better to use a SecureString:

var password = new SecureString();
var phPassword phPassword = Marshal.SecureStringToGlobalAllocUnicode(password);
IntPtr phUserToken;
LogonUser(username, domain, phPassword, LOGON32_LOGON_INTERACTIVE,  LOGON32_PROVIDER_DEFAULT, out phUserToken);

And:

Marshal.ZeroFreeGlobalAllocUnicode(phPassword);
password.Dispose();

Function definition:

private static extern bool LogonUser(
  string pszUserName,
  string pszDomain,
  IntPtr pszPassword,
  int dwLogonType,
  int dwLogonProvider,
  out IntPtr phToken);

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.

How to delete a file from SD card?

Also you have to give permission if you are using >1.6 SDK

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

in AndroidManifest.xml file

Include PHP inside JavaScript (.js) files

A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:

PHP File (*.php)

First define an array with the values to be used into javascript files:

<?php
$phpToJsVars = [
  'value1' => 'foo1',
  'value2' => 'foo2'    
];
?>

Now write the php array values into a javascript object literal:

<script type="text/javascript">
var phpVars = { 
<?php 
  foreach ($phpToJsVars as $key => $value) {
    echo '  ' . $key . ': ' . '"' . $value . '",' . "\n";  
  }
?>
};
</script>

Javascript file (*.js)

Now we can access the javscript object literal from any other .js file with the notation:

phpVars["value1"]
phpVars["value2"]

Truncate to three decimals in Python

Okay, this is just another approach to solve this working on the number as a string and performing a simple slice of it. This gives you a truncated output of the number instead of a rounded one.

num = str(1324343032.324325235)
i = num.index(".")
truncated = num[:i + 4]
    
print(truncated)

Output:

'1324343032.324'

Of course then you can parse:

float(truncated)

REST URI convention - Singular or plural name of resource while creating it

Singular

Convenience Things can have irregular plural names. Sometimes they don't have one. But Singular names are always there.

e.g. CustomerAddress over CustomerAddresses

Consider this related resource.

This /order/12/orderdetail/12 is more readable and logical than /orders/12/orderdetails/4.

Database Tables

A resource represents an entity like a database table. It should have a logical singular name. Here's the answer over table names.

Class Mapping

Classes are always singular. ORM tools generate tables with the same names as class names. As more and more tools are being used, singular names are becoming a standard.

Read more about A REST API Developer's Dilemma

For things without singular names

In the case of trousers and sunglasses, they don't seem to have a singular counterpart. They are commonly known and they appear to be singular by use. Like a pair of shoes. Think about naming the class file Shoe or Shoes. Here these names must be considered as a singular entity by their use. You don't see anyone buying a single shoe to have the URL as

/shoe/23

We have to see Shoes as a singular entity.

Reference: Top 6 REST Naming Best Practices

What is Mocking?

Other answers explain what mocking is. Let me walk you through it with different examples. And believe me, it's actually far more simpler than you think.

tl;dr It's an instance of the original class. It has other data injected into so you avoid testing the injected parts and solely focus on testing the implementation details of your class/functions.

Simple example:

class Foo {
    func add (num1: Int, num2: Int) -> Int { // Line A 
        return num1 + num2 // Line B
    }
}

let unit = Foo() // unit under test
assertEqual(unit.add(1,5),6)

As you can see, I'm not testing LineA ie I'm not validating the input parameters. I'm not validating to see if num1, num2 are an Integer. I have no asserts against that.

I'm only testing to see if LineB (my implementation) given the mocked values 1 and 5 is doing as I expect.

Obviously in the real word this can become much more complex. The parameters can be a custom object like a Person, Address, or the implementation details can be more than a single +. But the logic of testing would be the same.

Non-coding Example:

Assume you're building a machine that identifies the type and brand name of electronic devices for an airport security. The machine does this by processing what it sees with its camera.

Now your manager walks in the door and asks you to unit-test it.

Then you as a developer you can either bring 1000 real objects, like a MacBook pro, Google Nexus, a banana, an iPad etc in front of it and test and see if it all works.

But you can also use mocked objects, like an identical looking MacBook pro (with no real internal parts) or a plastic banana in front of it. You can save yourself from investing in 1000 real laptops and rotting bananas.

The point is you're not trying to test if the banana is fake or not. Nor testing if the laptop is fake or not. All you're doing is testing if your machine once it sees a banana it would say not an electronic device and for a MacBook Pro it would say: Laptop, Apple. To the machine, the outcome of its detection should be the same for fake/mocked electronics and real electronics. If your machine also factored in the internals of a laptop (x-ray scan) or banana then your mocks' internals need to look the same as well. But you could also use a gadget with a friend motherboard. Had your machine tested whether or not devices can power on then well you'd need real devices.

The logic mentioned above applies to unit-testing of actual code as well. That is a function should work the same with real values you get from real input (and interactions) or mocked values you inject during unit-testing. And just as how you save yourself from using a real banana or MacBook, with unit-tests (and mocking) you save yourself from having to do something that causes your server to return a status code of 500, 403, 200, etc (forcing your server to trigger 500 is only when server is down, while 200 is when server is up. It gets difficult to run 100 network focused tests if you have to constantly wait 10 seconds between switching over server up and down). So instead you inject/mock a response with status code 500, 200, 403, etc and test your unit/function with a injected/mocked value.

Be aware:

Sometimes you don't correctly mock the actual object. Or you don't mock every possibility. E.g. your fake laptops are dark, and your machine accurately works with them, but then it doesn't work accurately with white fake laptops. Later when you ship this machine to customers they complain that it doesn't work all the time. You get random reports that it's not working. It takes you 3 months of time to finally figure out that the color of fake laptops need to be more varied so you can test your modules appropriately.

For a true coding example, your implementation may be different for status code 200 with image data returned vs 200 with image data not returned. For this reason it's good to use an IDE that provides code coverage e.g. the image below shows that your unit-tests don't ever go through the lines marked with brown.

enter image description here

image source

Real world coding Example:

Let's say you are writing an iOS application and have network calls.Your job is to test your application. To test/identify whether or not the network calls work as expected is NOT YOUR RESPONSIBILITY . It's another party's (server team) responsibility to test it. You must remove this (network) dependency and yet continue to test all your code that works around it.

A network call can return different status codes 404, 500, 200, 303, etc with a JSON response.

Your app is suppose to work for all of them (in case of errors, your app should throw its expected error). What you do with mocking is you create 'imaginary—similar to real' network responses (like a 200 code with a JSON file) and test your code without 'making the real network call and waiting for your network response'. You manually hardcode/return the network response for ALL kinds of network responses and see if your app is working as you expect. (you never assume/test a 200 with incorrect data, because that is not your responsibility, your responsibility is to test your app with a correct 200, or in case of a 400, 500, you test if your app throws the right error)

This creating imaginary—similar to real is known as mocking.

In order to do this, you can't use your original code (your original code doesn't have the pre-inserted responses, right?). You must add something to it, inject/insert that dummy data which isn't normally needed (or a part of your class).

So you create an instance the original class and add whatever (here being the network HTTPResponse, data OR in the case of failure, you pass the correct errorString, HTTPResponse) you need to it and then test the mocked class.

Long story short, mocking is to simplify and limit what you are testing and also make you feed what a class depends on. In this example you avoid testing the network calls themselves, and instead test whether or not your app works as you expect with the injected outputs/responses —— by mocking classes

Needless to say, you test each network response separately.


Now a question that I always had in my mind was: The contracts/end points and basically the JSON response of my APIs get updated constantly. How can I write unit tests which take this into consideration?

To elaborate more on this: let’s say model requires a key/field named username. You test this and your test passes. 2 weeks later backend changes the key's name to id. Your tests still passes. right? or not?

Is it the backend developer’s responsibility to update the mocks. Should it be part of our agreement that they provide updated mocks?

The answer to the above issue is that: unit tests + your development process as a client-side developer should/would catch outdated mocked response. If you ask me how? well the answer is:

Our actual app would fail (or not fail yet not have the desired behavior) without using updated APIs...hence if that fails...we will make changes on our development code. Which again leads to our tests failing....which we’ll have to correct it. (Actually if we are to do the TDD process correctly we are to not write any code about the field unless we write the test for it...and see it fail and then go and write the actual development code for it.)

This all means that backend doesn’t have to say: “hey we updated the mocks”...it eventually happens through your code development/debugging. ??Because it’s all part of the development process! Though if backend provides the mocked response for you then it's easier.

My whole point on this is that (if you can’t automate getting updated mocked API response then) some human interaction is required ie manual updates of JSONs and having short meetings to make sure their values are up to date will become part of your process

This section was written thanks to a slack discussion in our CocoaHead meetup group


For iOS devs only:

A very good example of mocking is this Practical Protocol-Oriented talk by Natasha Muraschev. Just skip to minute 18:30, though the slides may become out of sync with the actual video ???

I really like this part from the transcript:

Because this is testing...we do want to make sure that the get function from the Gettable is called, because it can return and the function could theoretically assign an array of food items from anywhere. We need to make sure that it is called;

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

How do I style (css) radio buttons and labels?

The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.

Getting the Label Near the Radio Button

I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory):

  • Use <br />s to split the options apart and some CSS to vertically align them:
<style type='text/css'>
    .input input
    {
        width: 20px;
    }
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

Applying a Style to the Currently Selected Label + Radio Button

Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this:

<style type='text/css'>
    .input label.focused
    {
        background-color: #EEEEEE;
        font-style: italic;
    }
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
    $(document).ready(function() {
        $('.input :radio').focus(updateSelectedStyle);
        $('.input :radio').blur(updateSelectedStyle);
        $('.input :radio').change(updateSelectedStyle);
    })

    function updateSelectedStyle() {
        $('.input :radio').removeClass('focused').next().removeClass('focused');
        $('.input :radio:checked').addClass('focused').next().addClass('focused');
    }
</script>

The focus and blur hooks are needed to make this work in IE.

How to detect Windows 64-bit platform with .NET?

Just see if the "C:\Program Files (x86)" exists. If not, then you are on a 32 bit OS. If it does, then the OS is 64 bit (Windows Vista or Windows 7). It seems simple enough...

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

Error: Could not find or load main class

This solved the issue for me today:

cd /path/to/project
cd build
rm -r classes

Then clean&build it and run the individual files you need.

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

ADB.exe is obsolete and has serious performance problems

First you need to check which SDK your Emulator is using and as @kuya suggested you need to follow those steps and install the latest version of that SDK Build Tool. Suppose your Emulator uses SDK 27 then you need to install latest in that series. For me it was 27.0.3. After that the error was gone.

How to add a footer in ListView?

you can use a stackLayout, inside of this layout you can put a list a frame, for example:

<StackLayout VerticalOptions="FillAndExpand">
            <ListView  ItemsSource="{Binding YourList}"
                       CachingStrategy="RecycleElement"
                       HasUnevenRows="True">

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell >
                            <StackLayout  Orientation="Horizontal">
                                <Label Text="{Binding Image, Mode=TwoWay}" />

                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <Frame BackgroundColor="AliceBlue" HorizontalOptions="FillAndExpand">
                <Button Text="More"></Button>
            </Frame>
        </StackLayout>

this is the result:

enter image description here

Reading string by char till end of line C/C++

If you are using C function fgetc then you should check a next character whether it is equal to the new line character or to EOF. For example

unsigned int count = 0;
while ( 1 )
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
      if ( c == EOF ) break;
   }
   else
   {
      ++count;
   }
}    

or maybe it would be better to rewrite the code using do-while loop. For example

unsigned int count = 0;
do
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
   }
   else
   {
      ++count;
   }
} while ( c != EOF );

Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc to read lines of a file.

But if the program is written in C++ then it would be much better if you would use std::ifstream and std::string classes and function std::getline to read a whole line.

Disabling contextual LOB creation as createClob() method threw error

For anyone who is facing this problem with Spring Boot 2

by default spring boot was using hibernate 5.3.x version, I have added following property in my pom.xml

<hibernate.version>5.4.2.Final</hibernate.version>

and error was gone. Reason for error is already explained in posts above

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

Klaus' answer was great, but ReSharper will ask you to "Simplify LINQ expression":

var result = peopleList2.Where(p => peopleList1.All(p2 => p2.ID != p.ID));

How to acces external json file objects in vue.js app

If your file looks like this:

[
    {
        "firstname": "toto",
        "lastname": "titi"
    },
    {
        "firstname": "toto2",
        "lastname": "titi2"
    },
]

You can do:

import json from './json/data.json';
// ....
json.forEach(x => { console.log(x.firstname, x.lastname); });

Difference between | and || or & and && for comparison

& and | are binary operators while || and && are boolean.

The big difference:
(1 & 2) is 0, false
(1 && 2) is true

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

I had the same problem and I resolved it like this:

  • Open MySQL my.ini file
  • In [mysqld] section, add the following line: innodb_force_recovery = 1
  • Save the file and try starting MySQL
  • Remove that line which you just added and Save

Java Long primitive type maximum limit

Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:

Long.MAX_VALUE + 1

you will notice that the result is the equivalent to Long.MIN_VALUE.

From here: java number exceeds long.max_value - how to detect?

SQL Server Operating system error 5: "5(Access is denied.)"

An old post, but here is a step by step that worked for SQL Server 2014 running under windows 7:

  • Control Panel ->
  • System and Security ->
  • Administrative Tools ->
  • Services ->
  • Double Click SQL Server (SQLEXPRESS) -> right click, Properties
  • Select Log On Tab
  • Select "Local System Account" (the default was some obtuse Windows System account)
  • -> OK
  • right click, Stop
  • right click, Start

Voilá !

I think setting the logon account may have been an option in the installation, but if so it was not the default, and was easy to miss if you were not already aware of this issue.

How to compare strings in sql ignoring case?

You could use the UPPER keyword:

SELECT *
FROM Customers
WHERE UPPER(LastName) = UPPER('AnGel')

How can I get just the first row in a result set AFTER ordering?

An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

Slide right to left Android Animations

Right to left new page animation

<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="false">
 <translate
    android:fromXDelta="0%" android:toXDelta="800%"
    android:fromYDelta="0%" android:toYDelta="0%"
    android:duration="600" />

Get button click inside UITableViewCell

The reason i like below technique because it also help me to identify the section of table.

Add Button in cell cellForRowAtIndexPath:

 UIButton *selectTaskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [selectTaskBtn setFrame:CGRectMake(15, 5, 30, 30.0)];
        [selectTaskBtn setTag:indexPath.section]; //Not required but may find useful if you need only section or row (indexpath.row) as suggested by MR.Tarun 
    [selectTaskBtn addTarget:self action:@selector(addTask:)   forControlEvents:UIControlEventTouchDown];
[cell addsubview: selectTaskBtn];

Event addTask:

-(void)addTask:(UIButton*)btn
{
    CGPoint buttonPosition = [btn convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
     int currentIndex = indexPath.row;
     int tableSection = indexPath.section;
    }
}

Hopes this help.

Current time formatting with Javascript

function formatTime(date){

  d = new Date(date);
  var h=d.getHours(),m=d.getMinutes(),l="AM";
  if(h > 12){
    h = h - 12;
  }
  if(h < 10){
    h = '0'+h;
  }
  if(m < 10){
    m = '0'+m;
  }
  if(d.getHours() >= 12){
    l="PM"
  }else{
    l="AM"
  }

  return h+':'+m+' '+l;

}

Usage & result:

var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"

Error message: "'chromedriver' executable needs to be available in the path"

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Program Files\Python38\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

I ran into a merge conflict. How can I abort the merge?

In this particular use case, you don't really want to abort the merge, just resolve the conflict in a particular way.

There is no particular need to reset and perform a merge with a different strategy, either. The conflicts have been correctly highlighted by git and the requirement to accept the other sides changes is only for this one file.

For an unmerged file in a conflict git makes available the common base, local and remote versions of the file in the index. (This is where they are read from for use in a 3-way diff tool by git mergetool.) You can use git show to view them.

# common base:
git show :1:_widget.html.erb

# 'ours'
git show :2:_widget.html.erb

# 'theirs'
git show :3:_widget.html.erb

The simplest way to resolve the conflict to use the remote version verbatim is:

git show :3:_widget.html.erb >_widget.html.erb
git add _widget.html.erb

Or, with git >= 1.6.1:

git checkout --theirs _widget.html.erb

node.js http 'get' request with query string parameters

Check out the request module.

It's more full featured than node's built-in http client.

var request = require('request');

var propertiesObject = { field1:'test1', field2:'test2' };

request({url:url, qs:propertiesObject}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});

updating table rows in postgres using subquery

update json_source_tabcol as d
set isnullable = a.is_Nullable
from information_schema.columns as a 
where a.table_name =d.table_name 
and a.table_schema = d.table_schema 
and a.column_name = d.column_name;

Convert Go map to json

Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal would work as expected.

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler 
type Num int

func (n *Num) UnmarshalText(text []byte) error {
    i, err := strconv.Atoi(string(text))
    if err != nil {
        return err
    }
    *n = Num(i)
    return nil
}

func (n Num) MarshalText() (text []byte, err error) {
    return []byte(strconv.Itoa(int(n))), nil
}

type Foo struct {
    Number Num    `json:"number"`
    Title  string `json:"title"`
}

func main() {
    datas := make(map[Num]Foo)

    for i := 0; i < 10; i++ {
        datas[Num(i)] = Foo{Number: 1, Title: "test"}
    }

    jsonString, err := json.Marshal(datas)
    if err != nil {
        panic(err)
    }

    fmt.Println(datas)
    fmt.Println(jsonString)

    m := make(map[Num]Foo)
    err = json.Unmarshal(jsonString, &m)
    if err != nil {
        panic(err)
    }

    fmt.Println(m)
}

Output:

map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]

Make Https call using HttpClient

You can try using the ModernHttpClient Nuget Package: After downloading the package, you can implement it like this:

 var handler = new ModernHttpClient.NativeMessageHandler()
 {
     UseProxy = true,
 };


 handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
 handler.PreAuthenticate = true;
 HttpClient client = new HttpClient(handler);

How can I recover the return value of a function passed to multiprocessing.Process?

This example shows how to use a list of multiprocessing.Pipe instances to return strings from an arbitrary number of processes:

import multiprocessing

def worker(procnum, send_end):
    '''worker function'''
    result = str(procnum) + ' represent!'
    print result
    send_end.send(result)

def main():
    jobs = []
    pipe_list = []
    for i in range(5):
        recv_end, send_end = multiprocessing.Pipe(False)
        p = multiprocessing.Process(target=worker, args=(i, send_end))
        jobs.append(p)
        pipe_list.append(recv_end)
        p.start()

    for proc in jobs:
        proc.join()
    result_list = [x.recv() for x in pipe_list]
    print result_list

if __name__ == '__main__':
    main()

Output:

0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
['0 represent!', '1 represent!', '2 represent!', '3 represent!', '4 represent!']

This solution uses fewer resources than a multiprocessing.Queue which uses

  • a Pipe
  • at least one Lock
  • a buffer
  • a thread

or a multiprocessing.SimpleQueue which uses

  • a Pipe
  • at least one Lock

It is very instructive to look at the source for each of these types.

How to concatenate strings in django templates?

Have a look at the add filter.

Edit: You can chain filters, so you could do "shop/"|add:shop_name|add:"/base.html". But that won't work because it is up to the template tag to evaluate filters in arguments, and extends doesn't.

I guess you can't do this within templates.

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

CSS text-decoration underline color

As far as I know it's not possible... but you can try something like this:

_x000D_
_x000D_
.underline _x000D_
{_x000D_
    color: blue;_x000D_
    border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <span class="underline">hello world</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Switch with if, else if, else, and loops inside case

In this case, I'd recommend using break labels.

http://www.java-examples.com/break-statement

This way you can specifically call it outside of the for loop.

SQL Statement using Where clause with multiple values

Select t1.SongName
From tablename t1
left join tablename t2
 on t1.SongName = t2.SongName
    and t1.PersonName <> t2.PersonName
    and t1.Status = 'Complete' -- my assumption that this is necessary
    and t2.Status = 'Complete' -- my assumption that this is necessary
    and t1.PersonName IN ('Holly', 'Ryan')
    and t2.PersonName IN ('Holly', 'Ryan')

Bat file to run a .exe at the command prompt

Well, the important point it seems here is that svcutil is not available by default from command line, you can run it from the vs xommand line shortcut but if you make a batch file normally that wont help unless you run the vcvarsall.bat file before the script. Below is a sample

"C:\Program Files\Microsoft Visual Studio *version*\VC\vcvarsall.bat"
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service

App not setup: This app is still in development mode

2021 UPDATE

I have done successfully Login with Facebook by doing below things. Now it is working fine.

As per described by George Mano

Visit Facebook Apps Page and select your application.

Go to Settings -> Basic.

Add a 1 Contact Email, 2 Privacy Policy URL, 3 User Data Deletion and choose 4 Category and Last 5. Live your application

The Privacy Policy URL should be a webpage where you have hosted the terms and conditions of your application and data used.

The General Data Protection Regulation (GDPR) requires developers to provide a way for people to request that their data be deleted. To be compliant with these requirements, you must provide either a data deletion request callback or instructions to inform people how to delete their data from your app or website

Toggle the button in the top of the screen, as seen below, in order to switch from Development to Live.

enter image description here

Set select option 'selected', by value

An issue I ran into when the value is an ID and the text is a code. You cannot set the value using the code but you don't have direct access to the ID.

var value;

$("#selectorId > option").each(function () {
  if ("SOMECODE" === $(this).text()) {
    value = $(this).val();
  }
});

//Do work here

Safe String to BigDecimal conversion

The code could be cleaner, but this seems to do the trick for different locales.

import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;


public class Main
{
    public static void main(String[] args)
    {
        final BigDecimal numberA;
        final BigDecimal numberB;

        numberA = stringToBigDecimal("1,000,000,000.999999999999999", Locale.CANADA);
        numberB = stringToBigDecimal("1.000.000.000,999999999999999", Locale.GERMANY);
        System.out.println(numberA);
        System.out.println(numberB);
    }

    private static BigDecimal stringToBigDecimal(final String formattedString,
                                                 final Locale locale)
    {
        final DecimalFormatSymbols symbols;
        final char                 groupSeparatorChar;
        final String               groupSeparator;
        final char                 decimalSeparatorChar;
        final String               decimalSeparator;
        String                     fixedString;
        final BigDecimal           number;

        symbols              = new DecimalFormatSymbols(locale);
        groupSeparatorChar   = symbols.getGroupingSeparator();
        decimalSeparatorChar = symbols.getDecimalSeparator();

        if(groupSeparatorChar == '.')
        {
            groupSeparator = "\\" + groupSeparatorChar;
        }
        else
        {
            groupSeparator = Character.toString(groupSeparatorChar);
        }

        if(decimalSeparatorChar == '.')
        {
            decimalSeparator = "\\" + decimalSeparatorChar;
        }
        else
        {
            decimalSeparator = Character.toString(decimalSeparatorChar);
        }

        fixedString = formattedString.replaceAll(groupSeparator , "");
        fixedString = fixedString.replaceAll(decimalSeparator , ".");
        number      = new BigDecimal(fixedString);

        return (number);
    }
}

Adding n hours to a date in Java?

Check Calendar class. It has add method (and some others) to allow time manipulation.

Something like this should work:

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date());               // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1);      // adds one hour
cal.getTime();                         // returns new date object plus one hour

Check API for more.

How to reference a method in javadoc?

You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the

{@link package.class#member label}

tag (that you are looking for). The corresponding example from the documentation is as follows

For example, here is a comment that refers to the getComponentAt(int, int) method:

Use the {@link #getComponentAt(int, int) getComponentAt} method.

The package.class part can be ommited if the referred method is in the current class.


Other useful links about JavaDoc are:

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};

Difference between CR LF, LF and CR line break types?

This is a good summary I found:

The Carriage Return (CR) character (0x0D, \r) moves the cursor to the beginning of the line without advancing to the next line. This character is used as a new line character in Commodore and Early Macintosh operating systems (OS-9 and earlier).

The Line Feed (LF) character (0x0A, \n) moves the cursor down to the next line without returning to the beginning of the line. This character is used as a new line character in UNIX based systems (Linux, Mac OSX, etc)

The End of Line (EOL) sequence (0x0D 0x0A, \r\n) is actually two ASCII characters, a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as a new line character in most other non-Unix operating systems including Microsoft Windows, Symbian OS and others.

Source

How can I use a carriage return in a HTML tooltip?

&#13; will work on all majors browsers (IE included)

Making an image act like a button

You could use an image submit button:

<input type="image"  id="saveform" src="logg.png " alt="Submit Form" />

Add an object to a python list

while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy

What does the "@" symbol do in SQL?

publish data where stoloc = 'AB143' 
|
[select prtnum where stoloc = @stoloc]

This is how the @ works.

How to run SQL in shell script

#!/bin/ksh
variable1=$( 
echo "set feed off
set pages 0
select count(*) from table;
exit
"  | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"

Getting request payload from POST request in Java servlet

If the contents of the body are a string in Java 8 you can do:

String body = request.getReader().lines().collect(Collectors.joining());

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

Disabling tab focus on form elements

You have to disable or enable the individual elements. This is how I did it:

$(':input').keydown(function(e){
     var allowTab = true; 
     var id = $(this).attr('name');

     // insert your form fields here -- (:'') is required after
     var inputArr = {username:'', email:'', password:'', address:''}

     // allow or disable the fields in inputArr by changing true / false
     if(id in inputArr) allowTab = false; 

     if(e.keyCode==9 && allowTab==false) e.preventDefault();
});

Git: How to commit a manually deleted file?

Use git add -A, this will include the deleted files.

Note: use git rm for certain files.

What's the best practice for putting multiple projects in a git repository?

While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.

Solution 1

A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.

git checkout --orphan BRANCHNAME

This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.

Now for whatever reason, git needs a bit of cleanup after an orphan checkout.

rm .git/index
rm -r *

Make sure everything is committed before deleting

Once the orphan branch is clean, you can use it normally.

Solution 2

Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.

# repo 1
git push origin master:master-1

# repo 2
git push origin master:master-2

Load an image from a url into a PictureBox

The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."

ByRef argument type mismatch in Excel VBA

I suspect you haven't set up last_name properly in the caller.

With the statement Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)

this will only work if last_name is a string, i.e.

Dim last_name as String

appears in the caller somewhere.

The reason for this is that VBA passes in variables by reference by default which means that the data types have to match exactly between caller and callee.

Two fixes:

1) Force ByVal -- Change your function to pass variable ByVal:
Public Function ProcessString(ByVal input_string As String) As String, or

2) Dim varname -- put Dim last_name As String in the caller before you use it.

(1) works because for ByVal, a copy of input_string is taken when passing to the function which will coerce it into the correct data type. It also leads to better program stability since the function cannot modify the variable in the caller.

Async/Await Class Constructor

You can definitely do this. Basically:

class AsyncConstructor {
    constructor() {
        return (async () => {

            // All async code here
            this.value = await asyncFunction();

            return this; // when done
        })();
    }
}

to create the class use:

let instance = await new AsyncConstructor();

This solution has a few short falls though:

super note: If you need to use super, you cannot call it within the async callback.

TypeScript note: this causes issues with TypeScript because the constructor returns type Promise<MyClass> instead of MyClass. There is no definitive way to resolve this that I know of. One potential way suggested by @blitter is to put /** @type {any} */ at the beginning of the constructor body— I do not know if this works in all situations however.

Creating a UITableView Programmatically

- (void)viewDidLoad {
     [super viewDidLoad];
     arr=[[NSArray alloc]initWithObjects:@"ABC",@"XYZ", nil];
     tableview = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];   
     tableview.delegate = self;
     tableview.dataSource = self;
     [self.view addSubview:tableview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
    }

    cell.textLabel.text=[arr objectAtIndex:indexPath.row];

    return cell;
}

Uncaught SyntaxError: Unexpected token with JSON.parse

[
  {
    "name": "Pizza",
    "price": "10",
    "quantity": "7"
  },
  {
    "name": "Cerveja",
    "price": "12",
    "quantity": "5"
  },
  {
    "name": "Hamburguer",
    "price": "10",
    "quantity": "2"
  },
  {
    "name": "Fraldas",
    "price": "6",
    "quantity": "2"
  }
]

Here is your perfect Json that you can parse.

Setting graph figure size

I managed to get a good result with the following sequence (run Matlab twice at the beginning):

h = gcf; % Current figure handle
set(h,'Resize','off');
set(h,'PaperPositionMode','manual');
set(h,'PaperPosition',[0 0 9 6]);
set(h,'PaperUnits','centimeters');
set(h,'PaperSize',[9 6]); % IEEE columnwidth = 9cm
set(h,'Position',[0 0 9 6]);
% xpos, ypos must be set
txlabel = text(xpos,ypos,'$$[\mathrm{min}]$$','Interpreter','latex','FontSize',9);

% Dump colored encapsulated PostScript
print('-depsc2','-loose', 'signals');

Iterate through a HashMap

If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).

Understanding __getitem__ method

__getitem__ can be used to implement "lazy" dict subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.

As a simple example, suppose you have two lists, keys and values, whereby {k:v for k,v in zip(keys, values)} is the dictionary that you need, which must be made lazy for speed or efficiency purposes:

class LazyDict(dict):
    
    def __init__(self, keys, values):
        self.keys = keys
        self.values = values
        super().__init__()
        
    def __getitem__(self, key):
        if key not in self:
            try:
                i = self.keys.index(key)
                self.__setitem__(self.keys.pop(i), self.values.pop(i))
            except ValueError, IndexError:
                raise KeyError("No such key-value pair!!")
        return super().__getitem__(key)

Usage:

>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])

How to update npm

To get the latest stable version just run

npm install npm@latest -g

It worked just fine for me!

Program to find prime numbers

I know this is quiet old question, but after reading here: Sieve of Eratosthenes Wiki

This is the way i wrote it from understanding the algorithm:

void SieveOfEratosthenes(int n)
{
    bool[] primes = new bool[n + 1];

    for (int i = 0; i < n; i++)
        primes[i] = true;

    for (int i = 2; i * i <= n; i++)
        if (primes[i])
            for (int j = i * 2; j <= n; j += i)
                primes[j] = false;

    for (int i = 2; i <= n; i++)
        if (primes[i]) Console.Write(i + " ");
}

In the first loop we fill the array of booleans with true.

Second for loop will start from 2 since 1 is not a prime number and will check if prime number is still not changed and then assign false to the index of j.

last loop we just printing when it is prime.

jQuery checkbox onChange

$('input[type=checkbox]').change(function () {
    alert('changed');
});

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

To hide static cells in UITable:

  1. Add this method:

In your UITableView controller delegate class:

Objective-C:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];

    if(cell == self.cellYouWantToHide)
        return 0; //set the hidden cell's height to 0

    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

Swift:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    var cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)

    if cell == self.cellYouWantToHide {
        return 0
    }

    return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}

This method will get called for each cell in the UITable. Once it calls it for the cell you want to hide, we set its height to 0. We identify the target cell by creating an outlet for it:

  1. In the designer, create an outlet for the cell(s) you want to hide. The outlet for one such cell is called "cellYouWantToHide" above.
  2. Check "Clip Subviews" in the IB for the cells you want to hide. The cells you are hiding need to have ClipToBounds = YES. Otherwise the text will pile up in the UITableView.

How to update Identity Column in SQL Server?

You can also use SET IDENTITY INSERT to allow you to insert values into an identity column.

Example:

SET IDENTITY_INSERT dbo.Tool ON
GO

And then you can insert into an identity column the values you need.

How to execute a shell script from C in Linux?

You can use system:

system("/usr/local/bin/foo.sh");

This will block while executing it using sh -c, then return the status code.

How do I use variables in Oracle SQL Developer?

Ok I know this a bit of a hack but this is a way to use a variable in a simple query, not a script:

WITH
    emplVar AS
    (SELECT 1234 AS id FROM dual)
SELECT
    *
FROM
    employees,
    emplVar
WHERE
    EmployId=emplVar.id;

You get to run it everywhere.

What's the easiest way to call a function every 5 seconds in jQuery?

A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function myTimer() {
    console.log(' each 1 second...');
}

var myVar = setInterval(myTimer, 1000);

call this line to stop the loop:

 clearInterval(myVar);

How to remove "onclick" with JQuery?

Try this if you unbind the onclick event by ID Then use:

$('#youLinkID').attr('onclick','').unbind('click');

Try this if you unbind the onclick event by Class Then use:

$('.className').attr('onclick','').unbind('click');

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

How to get scrollbar position with Javascript?

it's like this :)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

Full Page <iframe>

Put this in your CSS.

iframe {
  width: 100%;
  height: 100vh;
}

Scanner is skipping nextLine() after using next() or nextFoo()?

Use 2 scanner objects instead of one

Scanner input = new Scanner(System.in);
System.out.println("Enter numerical value");    
int option;
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();

jQuery Form Validation before Ajax submit

You need to trigger form validation before checking if it is valid. Field validation runs after you enter data in each field. Form validation is triggered by the submit event but at the document level. So your event handler is being triggered before jquery validates the whole form. But fret not, there's a simple solution to all of this.

You should validate the form:

if ($(this).validate().form()) {
  // do ajax stuff
}

https://jqueryvalidation.org/Validator.form/#validator-form()

How to display a gif fullscreen for a webpage background?

if it's background, use background-size: cover;

_x000D_
_x000D_
body{_x000D_
    background-image: url('http://i.stack.imgur.com/kx8MT.gif');_x000D_
    background-size: cover;_x000D_
    _x000D_
    _x000D_
    _x000D_
    height: 100vh;_x000D_
    padding:0;_x000D_
    margin:0;_x000D_
}
_x000D_
_x000D_
_x000D_

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

I don't yet have the rep needed to add a comment or I would have just added this to Bell's answer. I think Bell did a very good job of summing up the top level pros and cons of the two approaches. Just a few other factors that you might want to consider:

1) Do the requests between your clients and your service need to go through intermediaries that require access to the payload? If so then WS-Security might be a better fit.

2) It is actually possible to use SSL to provide the server with assurance as to the clients identity using a feature called mutual authentication. However, this doesn't get much use outside of some very specialized scenarios due to the complexity of configuring it. So Bell is right that WS-Sec is a much better fit here.

3) SSL in general can be a bit of a bear to setup and maintain (even in the simpler configuration) due largely to certificate management issues. Having someone who knows how to do this for your platform will be a big plus.

4) If you might need to do some form of credential mapping or identity federation then WS-Sec might be worth the overhead. Not that you can't do this with REST, you just have less structure to help you.

5) Getting all the WS-Security goop into the right places on the client side of things can be more of a pain than you would think it should.

In the end though it really does depend on a lot of things we're not likely to know. For most situations I would say that either approach will be "secure enough" and so that shouldn't be the main deciding factor.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.

If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.

req.body empty on posts

For express 4.16+, no need to install body-parser, use the following:

const express = require('express');
const app = express();
app.use(express.json());

app.post('/your/path', (req, res) => {
    const body = req.body;
    ...
}

Return empty cell from formula in Excel

I used the following work around to make my excel looks cleaner:

When you make any calculations the "" will give you error so you want to treat it as a number so I used a nested if statement to return 0 istead of "", and then if the result is 0 this equation will return ""

=IF((IF(A5="",0,A5)+IF(B5="",0,B5)) = 0, "",(IF(A5="",0,A5)+IF(B5="",0,B5)))

This way the excel sheet will look clean...

Algorithm to return all combinations of k elements from n

Lets say your array of letters looks like this: "ABCDEFGH". You have three indices (i, j, k) indicating which letters you are going to use for the current word, You start with:

A B C D E F G H
^ ^ ^
i j k

First you vary k, so the next step looks like that:

A B C D E F G H
^ ^   ^
i j   k

If you reached the end you go on and vary j and then k again.

A B C D E F G H
^   ^ ^
i   j k

A B C D E F G H
^   ^   ^
i   j   k

Once you j reached G you start also to vary i.

A B C D E F G H
  ^ ^ ^
  i j k

A B C D E F G H
  ^ ^   ^
  i j   k
...
function initializePointers($cnt) {
    $pointers = [];

    for($i=0; $i<$cnt; $i++) {
        $pointers[] = $i;
    }

    return $pointers;     
}

function incrementPointers(&$pointers, &$arrLength) {
    for($i=0; $i<count($pointers); $i++) {
        $currentPointerIndex = count($pointers) - $i - 1;
        $currentPointer = $pointers[$currentPointerIndex];

        if($currentPointer < $arrLength - $i - 1) {
           ++$pointers[$currentPointerIndex];

           for($j=1; ($currentPointerIndex+$j)<count($pointers); $j++) {
                $pointers[$currentPointerIndex+$j] = $pointers[$currentPointerIndex]+$j;
           }

           return true;
        }
    }

    return false;
}

function getDataByPointers(&$arr, &$pointers) {
    $data = [];

    for($i=0; $i<count($pointers); $i++) {
        $data[] = $arr[$pointers[$i]];
    }

    return $data;
}

function getCombinations($arr, $cnt)
{
    $len = count($arr);
    $result = [];
    $pointers = initializePointers($cnt);

    do {
        $result[] = getDataByPointers($arr, $pointers);
    } while(incrementPointers($pointers, count($arr)));

    return $result;
}

$result = getCombinations([0, 1, 2, 3, 4, 5], 3);
print_r($result);

Based on https://stackoverflow.com/a/127898/2628125, but more abstract, for any size of pointers.

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

How to clear form after submit in Angular 2?

Make a Call clearForm(); in your .ts file

Try like below example code snippet to clear your form data.

clearForm() {

this.addContactForm.reset({
      'first_name': '',
      'last_name': '',
      'mobile': '',
      'address': '',
      'city': '',
      'state': '',
      'country': '',
       'zip': ''
     });
}

How to check if element has any children in Javascript?

<script type="text/javascript">

function uwtPBSTree_NodeChecked(treeId, nodeId, bChecked) 
{
    //debugger;
    var selectedNode = igtree_getNodeById(nodeId);
    var ParentNodes = selectedNode.getChildNodes();

    var length = ParentNodes.length;

    if (bChecked) 
    {
/*                if (length != 0) {
                    for (i = 0; i < length; i++) {
                        ParentNodes[i].setChecked(true);
                    }
    }*/
    }
    else 
    {
        if (length != 0) 
        {
            for (i = 0; i < length; i++) 
            {
                ParentNodes[i].setChecked(false);
            }
        }
    }
}
</script>

<ignav:UltraWebTree ID="uwtPBSTree" runat="server"..........>
<ClientSideEvents NodeChecked="uwtPBSTree_NodeChecked"></ClientSideEvents>
</ignav:UltraWebTree>

How to convert View Model into JSON object in ASP.NET MVC?

I found it to be pretty nice to do it like this (usage in the view):

    @Html.HiddenJsonFor(m => m.TrackingTypes)

Here is the according helper method Extension class:

public static class DataHelpers
{
    public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return HiddenJsonFor(htmlHelper, expression, (IDictionary<string, object>) null);
    }

    public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        return HiddenJsonFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
    {
        var name = ExpressionHelper.GetExpressionText(expression);
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        var tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute("name", name);
        tagBuilder.MergeAttribute("type", "hidden");

        var json = JsonConvert.SerializeObject(metadata.Model);

        tagBuilder.MergeAttribute("value", json);

        return MvcHtmlString.Create(tagBuilder.ToString());
    }
}

It is not super-sofisticated, but it solves the problem of where to put it (in Controller or in view?) The answer is obviously: neither ;)

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

Instead of the EndsWith function, I would choose to use the Path.GetExtension() method instead. Here is the full example:

var filteredFiles = Directory.EnumerateFiles( path )
.Where(
    file => Path.GetExtension(file).Equals( ".aspx", StringComparison.OrdinalIgnoreCase ) ||
            Path.GetExtension(file).Equals( ".ascx", StringComparison.OrdinalIgnoreCase ) );

or:

var filteredFiles = Directory.EnumerateFiles(path)
.Where(
    file => string.Equals( Path.GetExtension(file), ".aspx", StringComparison.OrdinalIgnoreCase ) ||
            string.Equals( Path.GetExtension(file), ".ascx", StringComparison.OrdinalIgnoreCase ) );

(Use StringComparison.OrdinalIgnoreCase if you care about performance: MSDN string comparisons)

jQuery scrollTop not working in Chrome but working in Firefox

Testing on Chrome, Firefox and Edge, the only solution that worked fine for me is using setTimeout with the solution of Aaron in this way:

setTimeout( function () {
    $('body, html').stop().animate({ scrollTop: 0 }, 100);
}, 500);

No one of the other solutions resetted the previuos scrollTop, when I reloaded the page, in Chrome and Edge for me. Unfortunately there is still a little "flick" in Edge.

' << ' operator in verilog

<< is the left-shift operator, as it is in many other languages.

Here RAM_DEPTH will be 1 left-shifted by 8 bits, which is equivalent to 2^8, or 256.

How to convert a list of numbers to jsonarray in Python

Use the json module to produce JSON output:

import json

with open(outputfilename, 'wb') as outfile:
    json.dump(row, outfile)

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use json.dumps() (added s, for 'string'):

json_string = json.dumps(row)

The L is just Python syntax for a long integer value; the json library knows how to handle those values, no L will be written.

Demo string output:

>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'

Loading custom configuration files

The config file is just an XML file, you can open it by:

private static XmlDocument loadConfigDocument()
{
    XmlDocument doc = null;
    try
    {
        doc = new XmlDocument();
        doc.Load(getConfigFilePath());
        return doc;
    }
    catch (System.IO.FileNotFoundException e)
    {
        throw new Exception("No configuration file found.", e);
    }
    catch (Exception ex)
    {
        return null;
    }
}

and later retrieving values by:

    // retrieve appSettings node

    XmlNode node =  doc.SelectSingleNode("//appSettings");

ActiveX component can't create object

I've had the same issue in a VB6 program I'm writing, where a Form uses a ScriptControl object to run VBScripts selected by the User.

It worked fine until the other day, when it suddenly started displaying 'Runtime error 429' when the VBScript attempted to create a Scripting.FileSystemObject.

After going mad for an entire day, trying all the solutions proposed here, I began suspecting the problem was in my application.

Fortunately, I had a backup version of that form: I compared their codes, and discovered that inadvertently I had set UseSafeSubset property of my ScriptControl object to True.

It was the only difference in the form, and after restoring the backup copy it worked like a charm.

Hope this can be useful to someone. Up with VB6! :-)

Max - Italy

How do I temporarily disable triggers in PostgreSQL?

PostgreSQL knows the ALTER TABLE tblname DISABLE TRIGGER USER command, which seems to do what I need. See ALTER TABLE.

How can I pass a member function where a free function is expected?

A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be

void function1(void (aClass::*function)(int, int), aClass& a) {
    (a.*function)(1, 1);
}

and to call it:

aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);

How to get selected value of a dropdown menu in ReactJS

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}

And you can check it out on this site.

Getting unique values in Excel by using formulas only

Simple formula solution: Using dynamic array functions (UNIQUE function)

Since fall 2018, the subscription versions of Microsoft Excel (Office 365 / Microsoft 365 app) contain so called dynamic array functions (not yet available in Office 2016/2019 nonsubscription versions).

UNIQUE function

One of those functions is the UNIQUE function that will deliver an array of unique values for the selected range.

Example

In the following example, the input values are in range A1:A6. The UNIQUE function is typed into cell C1.

=UNIQUE(A1:A6)

Simple solution to show unique values in Excel using dynamic array functions

As you can see, the UNIQUE function will automatically spill over the necessary range of cells in order to show all unique values. This is indicated by the thin, blue frame around C1:C4.

Good to know

As the UNIQUE function automatically spills over the necessary number of rows, you should leave enough space under the C1. If there is not enough space, you will get a #SPILL error.

Dynamic array functions: Spill not possible because a value in C3 is blocking the spill range

If you want to reference the results of the UNIQUE function, you can just reference the cell containing the UNIQUE function and add a hash # sign.

=C1#

It is also possible to check unique values in several columns. In this case, the UNIQUE function will deliver all rows where the combination of the cells within the row are unique:

Applying the UNIQUE function over several columns

If you wish to show unique columns instead of unique rows, you have to set the [by_col] argument to TRUE (default is FALSE, meaning you will receive unique rows).

You can also show values that appear exactly once by setting the [exactly_once] argument to TRUE:

=UNIQUE(A1:A6;;TRUE)

Show unique values that appear exactly once

After updating Entity Framework model, Visual Studio does not see changes

Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.

Concatenate two PySpark dataframes

Above answers are very elegant. I have written this function long back where i was also struggling to concatenate two dataframe with distinct columns.

Suppose you have dataframe sdf1 and sdf2

from pyspark.sql import functions as F
from pyspark.sql.types import *

def unequal_union_sdf(sdf1, sdf2):
    s_df1_schema = set((x.name, x.dataType) for x in sdf1.schema)
    s_df2_schema = set((x.name, x.dataType) for x in sdf2.schema)

    for i,j in s_df2_schema.difference(s_df1_schema):
        sdf1 = sdf1.withColumn(i,F.lit(None).cast(j))

    for i,j in s_df1_schema.difference(s_df2_schema):
        sdf2 = sdf2.withColumn(i,F.lit(None).cast(j))

    common_schema_colnames = sdf1.columns
    sdk = \
        sdf1.select(common_schema_colnames).union(sdf2.select(common_schema_colnames))
    return sdk 

sdf_concat = unequal_union_sdf(sdf1, sdf2) 

How to make a vertical SeekBar in Android?

I tried in many different ways, but the one which worked for me was. Use Seekbar inside FrameLayout

<FrameLayout
    android:id="@+id/VolumeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/MuteButton"
    android:layout_below="@id/volumeText"
    android:layout_centerInParent="true">
        <SeekBar
        android:id="@+id/volume"
        android:layout_width="500dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:progress="50"
        android:secondaryProgress="40"
        android:progressDrawable="@drawable/seekbar_volume"
        android:secondaryProgressTint="@color/tint_neutral"
        android:thumbTint="@color/tint_neutral"
    />

And in Code.

Setup Pre Draw callback on Seekbar, Where you can change the Width and height of the Seekbar I did this part in c#, so Code i used was

            var volumeSlider = view.FindViewById<SeekBar>(Resource.Id.home_link_volume);

            var volumeFrameLayout = view.FindViewById<FrameLayout>(Resource.Id.linkVolumeFrameLayout);

            void OnPreDrawVolume(object sender, ViewTreeObserver.PreDrawEventArgs e)
            {
                volumeSlider.ViewTreeObserver.PreDraw -= OnPreDrawVolume;
                var h = volumeFrameLayout.Height;
                volumeSlider.Rotation = 270.0f;
                volumeSlider.LayoutParameters.Width = h;
                volumeSlider.RequestLayout();
            }

            volumeSlider.ViewTreeObserver.PreDraw += OnPreDrawVolume;

Here i Add listener to PreDraw Event and when its triggered, I remove the PreDraw so that it doesnt go into Infinite loop.

So when Pre Draw gets executed, I fetch the Height of FrameLayout and assign it to Seekbar. And set the rotation of seekbar to 270. As my seekbar is inside frame Layout and its Gravity is set as Center. I dont need to worry about the Translation. As Seekbar always stay in middle of Frame Layout.

Reason i remove EventHandler is because seekbar.RequestLayout(); Will make this event to be executed again.

ORDER BY the IN value list

I think this way is better :

SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
    ORDER BY  id=1 DESC, id=3 DESC, id=2 DESC, id=4 DESC

How to access random item in list?

Printing randomly country name from JSON file.
Model:

public class Country
    {
        public string Name { get; set; }
        public string Code { get; set; }
    }

Implementaton:

string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\")) + @"Data\Country.json";
            string _countryJson = File.ReadAllText(filePath);
            var _country = JsonConvert.DeserializeObject<List<Country>>(_countryJson);


            int index = random.Next(_country.Count);
            Console.WriteLine(_country[index].Name);

Multiple Java versions running concurrently under Windows

I use a simple script when starting jmeter with my own java versin

setlocal set JAVA_HOME="c:\java8" set PATH=%JAVA_HOME%\bin;%PATH%; java -version

to have a java "portable" you can use this method here:

https://www.whitebyte.info/programming/java/how-to-install-a-portable-jdk-in-windows-without-admin-rights

Truncate (not round off) decimal numbers in javascript

Here is simple but working function to truncate number upto 2 decimal places.

           function truncateNumber(num) {
                var num1 = "";
                var num2 = "";
                var num1 = num.split('.')[0];
                num2 = num.split('.')[1];
                var decimalNum = num2.substring(0, 2);
                var strNum = num1 +"."+ decimalNum;
                var finalNum = parseFloat(strNum);
                return finalNum;
            }

Equivalent of Math.Min & Math.Max for Dates?

How about a DateTime extension method?

public static DateTime MaxOf(this DateTime instance, DateTime dateTime)
{
    return instance > dateTime ? instance : dateTime;
}

Usage:

var maxDate = date1.MaxOf(date2);

Creating layout constraints programmatically

why can't I use a property like self.myView instead of a local variable like myView?

try using:

NSDictionaryOfVariableBindings(_view)

instead of self.view