Programs & Examples On #Iscsi

The Internet Small Computer System Interface (iSCSI) is a transport protocol designed to communicate SCSI commands over IP networks. It is described by Internet RFC 3720 (http://tools.ietf.org/html/rfc3720), though it has been amended and corrected by later RFCs.

HTML checkbox onclick called in Javascript

How about putting the checkbox into the label, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange event?

<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....> 

function toggleCheckbox(element)
 {
   element.checked = !element.checked;
 }

This will additionally catch users using a keyboard to toggle the check box, something onclick would not.

Shell script - remove first and last quote (") from a variable

There is another way to do it. Like:

echo ${opt:1:-1}

Is there a function to round a float in C or do I need to write my own?

Sure, you can use roundf(). If you want to round to one decimal, then you could do something like: roundf(10 * x) / 10

How can I set the initial value of Select2 when using AJAX?

For a simple and semantic solution i prefer to define the initial value in HTML, example:

<select name="myfield" data-placeholder="Select an option">
    <option value="initial-value" selected>Initial text</option>
</select>

So when i call $('select').select2({ ajax: {...}}); the initial value is initial-value and its option text is Initial text.

My current Select2 version is 4.0.3, but i think it has a great compatibility with other versions.

Error: Cannot find module html

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

Check which element has been clicked with jQuery

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

http://api.jquery.com/category/selectors/

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.

HTML5 Canvas and Anti-aliasing

It's now 2018, and we finally have cheap ways to do something around it...

Indeed, since the 2d context API now has a filter property, and that this filter property can accept SVGFilters, we can build an SVGFilter that will keep only fully opaque pixels from our drawings, and thus eliminate the default anti-aliasing.

So it won't deactivate antialiasing per se, but provides a cheap way both in term of implementation and of performances to remove all semi-transparent pixels while drawing.

I am not really a specialist of SVGFilters, so there might be a better way of doing it, but for the example, I'll use a <feComponentTransfer> node to grab only fully opaque pixels.

_x000D_
_x000D_
var ctx = canvas.getContext('2d');_x000D_
ctx.fillStyle = '#ABEDBE';_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.font = '14px sans-serif';_x000D_
ctx.textAlign = 'center';_x000D_
_x000D_
// first without filter_x000D_
ctx.fillText('no filter', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
// then with filter_x000D_
ctx.setTransform(1, 0, 0, 1, 120, 0);_x000D_
ctx.filter = 'url(#remove-alpha)';_x000D_
// and do the same ops_x000D_
ctx.fillText('no alpha', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
_x000D_
// to remove the filter_x000D_
ctx.filter = 'none';_x000D_
_x000D_
_x000D_
function drawArc() {_x000D_
  ctx.beginPath();_x000D_
  ctx.arc(60, 80, 50, 0, Math.PI * 2);_x000D_
  ctx.stroke();_x000D_
}_x000D_
_x000D_
function drawTriangle() {_x000D_
  ctx.beginPath();_x000D_
  ctx.moveTo(60, 150);_x000D_
  ctx.lineTo(110, 230);_x000D_
  ctx.lineTo(10, 230);_x000D_
  ctx.closePath();_x000D_
  ctx.stroke();_x000D_
}_x000D_
// unrelated_x000D_
// simply to show a zoomed-in version_x000D_
var zCtx = zoomed.getContext('2d');_x000D_
zCtx.imageSmoothingEnabled = false;_x000D_
canvas.onmousemove = function drawToZoommed(e) {_x000D_
  var x = e.pageX - this.offsetLeft,_x000D_
    y = e.pageY - this.offsetTop,_x000D_
    w = this.width,_x000D_
    h = this.height;_x000D_
    _x000D_
  zCtx.clearRect(0,0,w,h);_x000D_
  zCtx.drawImage(this, x-w/6,y-h/6,w, h, 0,0,w*3, h*3);_x000D_
}
_x000D_
<svg width="0" height="0" style="position:absolute;z-index:-1;">_x000D_
  <defs>_x000D_
    <filter id="remove-alpha" x="0" y="0" width="100%" height="100%">_x000D_
      <feComponentTransfer>_x000D_
        <feFuncA type="discrete" tableValues="0 1"></feFuncA>_x000D_
      </feComponentTransfer>_x000D_
      </filter>_x000D_
  </defs>_x000D_
</svg>_x000D_
_x000D_
<canvas id="canvas" width="250" height="250" ></canvas>_x000D_
<canvas id="zoomed" width="250" height="250" ></canvas>
_x000D_
_x000D_
_x000D_

And for the ones that don't like to append an <svg> element in their DOM, you can also save it as an external svg file and set the filter property to path/to/svg_file.svg#remove-alpha.

How to programmatically set style attribute in a view

You can do style attributes like so:

Button myButton = new Button(this, null,android.R.attr.buttonBarButtonStyle);

in place of:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    style="?android:attr/buttonBarButtonStyle"

    />

How to export DataTable to Excel

Old thread - but thought i would throw my code in here. I wrote a little function to write a data table to a new excel sheet at a specified path (location). Also you will need to add a reference to microsoft excel 14.0 library.

I pulled from this thread on writing anything to excel - How to write some data to excel file(.xlsx)

i used that to extrapolate how to write a datatable

*note in catch statements i have an errorhandler static class reference (you can ignore those)

 using excel = Microsoft.Office.Interop.Excel;
 using System.IO;
 using System.Data;
 using System.Runtime.InteropServices;

 //class and namespace wrapper is not shown in this example 

 private void WriteToExcel(System.Data.DataTable dt, string location)
    {
        //instantiate excel objects (application, workbook, worksheets)
        excel.Application XlObj = new excel.Application();
        XlObj.Visible = false;
        excel._Workbook WbObj = (excel.Workbook)(XlObj.Workbooks.Add(""));
        excel._Worksheet WsObj = (excel.Worksheet)WbObj.ActiveSheet;

        //run through datatable and assign cells to values of datatable
        try
        {
            int row = 1; int col = 1;
            foreach (DataColumn column in dt.Columns)
            {
                //adding columns
                WsObj.Cells[row, col] = column.ColumnName;
                col++;
            }
            //reset column and row variables
            col = 1;
            row++;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //adding data
                foreach (var cell in dt.Rows[i].ItemArray)
                {
                    WsObj.Cells[row, col] = cell;
                    col++;
                }
                col = 1;
                row++;
            }
            WbObj.SaveAs(location);
        }
        catch (COMException x)
        {                
            ErrorHandler.Handle(x);
        }
        catch (Exception ex)
        {               
            ErrorHandler.Handle(ex);
        }
        finally
        {
            WbObj.Close();                
        }
    }

How to Automatically Close Alerts using Twitter Bootstrap

try this one

$(function () {

 setTimeout(function () {
            if ($(".alert").is(":visible")){
                 //you may add animate.css class for fancy fadeout
                $(".alert").fadeOut("fast");
            }

        }, 3000)

});

ssh script returns 255 error

If there's a problem with authentication or connection, such as not being able to read a password from the terminal, ssh will exit with 255 without being able to run your actual script. Verify to make sure you can run 'true' instead, to see if the ssh connection is established successfully.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Check your system clock,

$ date

If it's not correct the certificate check will fail. To correct the system clock,

$ apt-get install ntp

The clock should synchronise itself.

Finally enter the clone command again.

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

vb.net get file names in directory?

System.IO.Directory.GetFiles() 

could help

How to change column datatype from character to numeric in PostgreSQL 8.4

You can try using USING:

The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

So this might work (depending on your data):

alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);

This will fail if you have anything in code that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

Check if registry key exists using VBScript

See the Scripting Guy! Blog:

How Can I Tell Whether a Value Exists in the Registry?

They discuss doing the check on a remote computer and show that if you read a string value from the key, and if the value is Null (as opposed to Empty), the key does not exist.

With respect to using the RegRead method, if the term "key" refers to the path (or folder) where registry values are kept, and if the leaf items in that key are called "values", using WshShell.RegRead(strKey) to detect key existence (as opposed to value existance) consider the following (as observed on Windows XP):

If strKey name is not the name of an existing registry path, Err.Description reads "Invalid root in registry key"... with an Err.Number of 0x80070002.

If strKey names a registry path that exists but does not include a trailing "\" the RegRead method appears to interpret strKey as a path\value reference rather than as a simple path reference, and returns the same Err.Number but with an Err.Description of "Unable to open registry key". The term "key" in the error message appears to mean "value". This is the same result obtained when strKey references a path\value where the path exists, but the value does not exist.

Matrix multiplication using arrays

You can try this code:

public class MyMatrix {
    Double[][] A = { { 4.00, 3.00 }, { 2.00, 1.00 } };
    Double[][] B = { { -0.500, 1.500 }, { 1.000, -2.0000 } };

    public static Double[][] multiplicar(Double[][] A, Double[][] B) {

        int aRows = A.length;
        int aColumns = A[0].length;
        int bRows = B.length;
        int bColumns = B[0].length;

        if (aColumns != bRows) {
            throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
        }

        Double[][] C = new Double[aRows][bColumns];
        for (int i = 0; i < aRows; i++) {
            for (int j = 0; j < bColumns; j++) {
                C[i][j] = 0.00000;
            }
        }

        for (int i = 0; i < aRows; i++) { // aRow
            for (int j = 0; j < bColumns; j++) { // bColumn
                for (int k = 0; k < aColumns; k++) { // aColumn
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }

        return C;
    }

    public static void main(String[] args) {

        MyMatrix matrix = new MyMatrix();
        Double[][] result = multiplicar(matrix.A, matrix.B);

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++)
                System.out.print(result[i][j] + " ");
            System.out.println();
        }
    }
}

Mutex example / tutorial?

While a mutex may be used to solve other problems, the primary reason they exist is to provide mutual exclusion and thereby solve what is known as a race condition. When two (or more) threads or processes are attempting to access the same variable concurrently, we have potential for a race condition. Consider the following code

//somewhere long ago, we have i declared as int
void my_concurrently_called_function()
{
  i++;
}

The internals of this function look so simple. It's only one statement. However, a typical pseudo-assembly language equivalent might be:

load i from memory into a register
add 1 to i
store i back into memory

Because the equivalent assembly-language instructions are all required to perform the increment operation on i, we say that incrementing i is a non-atmoic operation. An atomic operation is one that can be completed on the hardware with a gurantee of not being interrupted once the instruction execution has begun. Incrementing i consists of a chain of 3 atomic instructions. In a concurrent system where several threads are calling the function, problems arise when a thread reads or writes at the wrong time. Imagine we have two threads running simultaneoulsy and one calls the function immediately after the other. Let's also say that we have i initialized to 0. Also assume that we have plenty of registers and that the two threads are using completely different registers, so there will be no collisions. The actual timing of these events may be:

thread 1 load 0 into register from memory corresponding to i //register is currently 0
thread 1 add 1 to a register //register is now 1, but not memory is 0
thread 2 load 0 into register from memory corresponding to i
thread 2 add 1 to a register //register is now 1, but not memory is 0
thread 1 write register to memory //memory is now 1
thread 2 write register to memory //memory is now 1

What's happened is that we have two threads incrementing i concurrently, our function gets called twice, but the outcome is inconsistent with that fact. It looks like the function was only called once. This is because the atomicity is "broken" at the machine level, meaning threads can interrupt each other or work together at the wrong times.

We need a mechanism to solve this. We need to impose some ordering to the instructions above. One common mechanism is to block all threads except one. Pthread mutex uses this mechanism.

Any thread which has to execute some lines of code which may unsafely modify shared values by other threads at the same time (using the phone to talk to his wife), should first be made acquire a lock on a mutex. In this way, any thread that requires access to the shared data must pass through the mutex lock. Only then will a thread be able to execute the code. This section of code is called a critical section.

Once the thread has executed the critical section, it should release the lock on the mutex so that another thread can acquire a lock on the mutex.

The concept of having a mutex seems a bit odd when considering humans seeking exclusive access to real, physical objects but when programming, we must be intentional. Concurrent threads and processes don't have the social and cultural upbringing that we do, so we must force them to share data nicely.

So technically speaking, how does a mutex work? Doesn't it suffer from the same race conditions that we mentioned earlier? Isn't pthread_mutex_lock() a bit more complex that a simple increment of a variable?

Technically speaking, we need some hardware support to help us out. The hardware designers give us machine instructions that do more than one thing but are guranteed to be atomic. A classic example of such an instruction is the test-and-set (TAS). When trying to acquire a lock on a resource, we might use the TAS might check to see if a value in memory is 0. If it is, that would be our signal that the resource is in use and we do nothing (or more accurately, we wait by some mechanism. A pthreads mutex will put us into a special queue in the operating system and will notify us when the resource becomes available. Dumber systems may require us to do a tight spin loop, testing the condition over and over). If the value in memory is not 0, the TAS sets the location to something other than 0 without using any other instructions. It's like combining two assembly instructions into 1 to give us atomicity. Thus, testing and changing the value (if changing is appropriate) cannot be interrupted once it has begun. We can build mutexes on top of such an instruction.

Note: some sections may appear similar to an earlier answer. I accepted his invite to edit, he preferred the original way it was, so I'm keeping what I had which is infused with a little bit of his verbiage.

Storing sex (gender) in database

An Int (or TinyInt) aligned to an Enum field would be my methodology.

First, if you have a single bit field in a database, the row will still use a full byte, so as far as space savings, it only pays off if you have multiple bit fields.

Second, strings/chars have a "magic value" feel to them, regardless of how obvious they may seem at design time. Not to mention, it lets people store just about any value they would not necessarily map to anything obvious.

Third, a numeric value is much easier (and better practice) to create a lookup table for, in order to enforce referential integrity, and can correlate 1-to-1 with an enum, so there is parity in storing the value in memory within the application or in the database.

How can I pass parameters to a partial view in mvc 4

One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.

In your Partial calling side

@Html.Partial("ParitalAction", "String data to pass to partial")

And then binding the model with Partial View like this

@model string

and the using its value in Partial View like this

@Model

You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.

Hope it helps,

Read connection string from web.config

using System.Configuration;


string connString = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();

Remember don't Use ConnectionStrings[index] because you might of Global machine Config and Portability

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

PHP Fatal error: Cannot access empty property

Interesting:

  1. You declared an array var $my_value = array();
  2. Pushed value into it $a->my_value[] = 'b';
  3. Assigned a string to variable. (so it is no more array) $a->set_value ('c');
  4. Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');

And your foreach wont work anymore.

Multiple radio button groups in one form

To create a group of inputs you can create a custom html element

window.customElements.define('radio-group', RadioGroup);

https://gist.github.com/robdodson/85deb2f821f9beb2ed1ce049f6a6ed47

to keep selected option in each group, you need to add name attribute to inputs in group, if you not add it then all is one group.

JS how to cache a variable

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

Cookie *Create and Store a Cookie:*

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

The function which will return the specified cookie:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Display a welcome message if the cookie is set

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.

Jquery

Set a value to the session storage.

Javascript:

$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:
{data:'bar'}

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);

//...
var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

Adding to Sesion

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.

Usage of \b and \r in C

I have experimented many of the backslash escape characters. \n which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.

Code:

#include <stdio.h>
int main(void){
    printf("Hello World!");
    printf("Goodbye \a");
    printf("Hi \b");
    printf("Yo\f");
    printf("What? \t");
    printf("pewpew");
    return 0;
}

c#: getter/setter

These are called auto properties.

http://msdn.microsoft.com/en-us/library/bb384054.aspx

Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.

Documentation for using JavaScript code inside a PDF file

I'm pretty sure it's an Adobe standard, bearing in mind the whole PDF standard is theirs to begin with; despite being open now.

My guess would be no for all PDF viewers supporting it, as some definitely will not have a JS engine. I doubt you can rely on full support outside the most recent versions of Acrobat (Reader). So I guess it depends on how you imagine it being used, if mainly via a browser display, then the majority of the market is catered for by Acrobat (Reader) and Chrome's built-in viewer - dare say there is documentation on whether Chrome's PDF viewer supports JS fully.

Align contents inside a div

Honestly, I hate all the solutions I've seen so far, and I'll tell you why: They just don't seem to ever align it right...so here's what I usually do:

I know what pixel values each div and their respective margins hold...so I do the following.

I'll create a wrapper div that has an absolute position and a left value of 50%...so this div now starts in the middle of the screen, and then I subtract half of all the content of the div's width...and I get BEAUTIFULLY scaling content...and I think this works across all browsers, too. Try it for yourself (this example assumes all content on your site is wrapped in a div tag that uses this wrapper class and all content in it is 200px in width):

.wrapper {
    position: absolute;
    left: 50%;
    margin-left: -100px;
}

EDIT: I forgot to add...you may also want to set width: 0px; on this wrapper div for some browsers to not show the scrollbars, and then you may use absolute positioning for all inner divs.

This also works AMAZING for vertically aligning your content as well using top: 50% and margin-top. Cheers!

Copy a file in a sane, safe and efficient way

Too many!

The "ANSI C" way buffer is redundant, since a FILE is already buffered. (The size of this internal buffer is what BUFSIZ actually defines.)

The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator class bypasses the stream layer.)

I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream, just create bare std::filebuf instances when no actual formatting is needed.

For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.

The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.

EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.

How to form tuple column from two columns in Pandas

In [10]: df
Out[10]:
          A         B       lat      long
0  1.428987  0.614405  0.484370 -0.628298
1 -0.485747  0.275096  0.497116  1.047605
2  0.822527  0.340689  2.120676 -2.436831
3  0.384719 -0.042070  1.426703 -0.634355
4 -0.937442  2.520756 -1.662615 -1.377490
5 -0.154816  0.617671 -0.090484 -0.191906
6 -0.705177 -1.086138 -0.629708  1.332853
7  0.637496 -0.643773 -0.492668 -0.777344
8  1.109497 -0.610165  0.260325  2.533383
9 -1.224584  0.117668  1.304369 -0.152561

In [11]: df['lat_long'] = df[['lat', 'long']].apply(tuple, axis=1)

In [12]: df
Out[12]:
          A         B       lat      long                             lat_long
0  1.428987  0.614405  0.484370 -0.628298      (0.484370195967, -0.6282975278)
1 -0.485747  0.275096  0.497116  1.047605      (0.497115615839, 1.04760475074)
2  0.822527  0.340689  2.120676 -2.436831      (2.12067574274, -2.43683074367)
3  0.384719 -0.042070  1.426703 -0.634355      (1.42670326172, -0.63435462504)
4 -0.937442  2.520756 -1.662615 -1.377490     (-1.66261469102, -1.37749004179)
5 -0.154816  0.617671 -0.090484 -0.191906  (-0.0904840623396, -0.191905582481)
6 -0.705177 -1.086138 -0.629708  1.332853     (-0.629707821728, 1.33285348929)
7  0.637496 -0.643773 -0.492668 -0.777344   (-0.492667604075, -0.777344111021)
8  1.109497 -0.610165  0.260325  2.533383        (0.26032456699, 2.5333825651)
9 -1.224584  0.117668  1.304369 -0.152561     (1.30436900612, -0.152560909725)

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You need to start the Apache Tomcat services.

Win+R --> sevices.msc

Then, search for Apache Tomcat and right click on it and click on Start. This will start the service and then you'll be able to see Apache Tomcat homepage on the localhost .

What is the most efficient/quickest way to loop through rows in VBA (excel)?

EDIT Summary and reccomendations

Using a for each cell in range construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).

What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.

So, some general advice:

  1. keep it simple at first. If the result is too slow for your needs, then optimise
  2. focus on optimisation of the content of the loop
  3. don't just assume a loop is needed. There are sometime alternatives
  4. if you need to use cell values (a lot) inside the loop, load them into a variant array outside the loop.
  5. a good way to avoid complexity with inserts is to loop the range from the bottom up
    (for index = max to min step -1)
  6. if you can't do that and your 'insert a row here and there' is not too many, consider reloading the array after each insert
  7. If you need to access cell properties other than value, you are stuck with cell references
  8. To delete a number of rows consider building a range reference to a multi area range in the loop, then delete that range in one go after the loop

eg (not tested!)

Dim rngToDelete as range
for each rw in rng.rows
    if need to delete rw then

        if rngToDelete is nothing then
            set rngToDelete = rw
        else
            set rngToDelete = Union(rngToDelete, rw)
        end if

    endif
next
rngToDelete.EntireRow.Delete

Original post

Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:

test data set: a simple list in cells A1 .. A1000000 (thats 1,000,000 rows)

Test case 1: loop an array

Dim v As Variant
Dim n As Long

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    'i = i + 1
    'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")

Result:

Array Time = 0.249 sec
Array Count = 1,000,001

Test Case 2: loop the range

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 0.296 sec
Range Count = 1,000,000

So,looping an array is faster but only by 19% - much less than I expected.

Test 3: loop an array with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")

Result:

Array Time = 5.897 sec
Array Count = 1,000,000

Test case 4: loop range with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
    i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 2.356 sec
Range Count = 1,000,000

So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!

So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options

FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with

  • ScreenUpdating off,
  • Calulation manual,
  • Events disabled.

VBA macro that search for file in multiple subfolders

Just for fun, here's a sample with a recursive function which (I hope) should be a bit simpler to understand and to use with your code:

Function Recurse(sPath As String) As String

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim mySubFolder As Folder

    Set myFolder = FSO.GetFolder(sPath)
    For Each mySubFolder In myFolder.SubFolders
        Call TestSub(mySubFolder.Path)
        Recurse = Recurse(mySubFolder.Path)
    Next

End Function

Sub TestR()

    Call Recurse("D:\Projets\")

End Sub

Sub TestSub(ByVal s As String)

    Debug.Print s

End Sub

Edit: Here's how you can implement this code in your workbook to achieve your objective.

Sub TestSub(ByVal s As String)

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim myFile As File

    Set myFolder = FSO.GetFolder(s)
    For Each myFile In myFolder.Files
        If myFile.Name = Range("E1").Value Then
            Debug.Print myFile.Name 'Or do whatever you want with the file
        End If
    Next

End Sub

Here, I just debug the name of the found file, the rest is up to you. ;)

Of course, some would say it's a bit clumsy to call twice the FileSystemObject so you could simply write your code like this (depends on wether you want to compartmentalize or not):

Function Recurse(sPath As String) As String

    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim mySubFolder As Folder
    Dim myFile As File

    Set myFolder = FSO.GetFolder(sPath)

    For Each mySubFolder In myFolder.SubFolders
        For Each myFile In mySubFolder.Files
            If myFile.Name = Range("E1").Value Then
                Debug.Print myFile.Name & " in " & myFile.Path 'Or do whatever you want with the file
                Exit For
            End If
        Next
        Recurse = Recurse(mySubFolder.Path)
    Next

End Function

Sub TestR()

    Call Recurse("D:\Projets\")

End Sub

Request format is unrecognized for URL unexpectedly ending in

I also got this error with apache mod-mono. It looks like the documentation page for webservice is not implemented yet in linux. But the webservice is working despite this error. You should see it by adding ?WSDL at the end of url, i.e http://localhost/WebService1.asmx?WSDL

change cursor to finger pointer

 <! ––  add this code in your class called menu_links -->
<style> 
.menu_links{
cursor: pointer;
}
</style>

In the above code [cursor:pointer] is used to access the hand like cursor that appears when you hover over a link.

And if you use [cursor: default] it will show the usual arrow cursor that appears.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

Date format in dd/MM/yyyy hh:mm:ss

This will be varchar but should format as you need.

RIGHT('0' + LTRIM(DAY(d)), 2) + '/'
+ RIGHT('0' + LTRIM(MONTH(d)), 2) + '/'
+ LTRIM(YEAR(d)) + ' '
+ RIGHT('0' + LTRIM(DATEPART(HOUR, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(MINUTE, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(SECOND, d)), 2)

Where d is your datetime field or variable.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

For me this problem still exists with SSMS version 2016 (13.0.16100.1).

A decent workaround is to not use the 'Right click' -> 'Add table...' dialog, but simply drag the table you want to add from the Object Explorer, onto the Diagram surface. While dragging the mouse icon changes into an 'add' symbol and the table is added when you release the mouse.

Beats having to close SSMS every time.

How do ports work with IPv6?

The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.

Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793

List<T> OrderBy Alphabetical Order

This is a generic sorter. Called with the switch below.

dvm.PagePermissions is a property on my ViewModel of type List T in this case T is a EF6 model class called page_permission.

dvm.UserNameSortDir is a string property on the viewmodel that holds the next sort direction. The one that is actaully used in the view.

switch (sortColumn)
{
    case "user_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);
        dvm.UserNameSortDir = sortDir;
        break;
    case "role_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);
        dvm.RoleNameSortDir = sortDir;
        break;
    case "page_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);
        dvm.PageNameSortDir = sortDir;
        break;
}                 


public List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)
    {
        if (direction == "asc")
        {
            list = list.OrderBy(sorter).ToList();
            direction = "desc";
        }
        else
        {
            list = list.OrderByDescending(sorter).ToList();
            direction = "asc";
        }
        return list;
    }

Using Keras & Tensorflow with AMD GPU

Theano does have support for OpenCL but it is still in its early stages. Theano itself is not interested in OpenCL and relies on community support.

Most of the operations are already implemented and it is mostly a matter of tuning and optimizing the given operations.

To use the OpenCL backend you have to build libgpuarray yourself.

From personal experience I can tell you that you will get CPU performance if you are lucky. The memory allocation seems to be very naively implemented (therefore computation will be slow) and will crash when it runs out of memory. But I encourage you to try and maybe even optimize the code or help reporting bugs.

Relative imports - ModuleNotFoundError: No module named x

Declare correct sys.path list before you call module:

import os, sys

#'/home/user/example/parent/child'
current_path = os.path.abspath('.')

#'/home/user/example/parent'
parent_path = os.path.dirname(current_path)

sys.path.append(parent_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'child.settings')

In Python, how do I split a string and keep the separators?

I found this generator based approach more satisfying:

def split_keep(string, sep):
    """Usage:
    >>> list(split_keep("a.b.c.d", "."))
    ['a.', 'b.', 'c.', 'd']
    """
    start = 0
    while True:
        end = string.find(sep, start) + 1
        if end == 0:
            break
        yield string[start:end]
        start = end
    yield string[start:]

It avoids the need to figure out the correct regex, while in theory should be fairly cheap. It doesn't create new string objects and, delegates most of the iteration work to the efficient find method.

... and in Python 3.8 it can be as short as:

def split_keep(string, sep):
    start = 0
    while (end := string.find(sep, start) + 1) > 0:
        yield string[start:end]
        start = end
    yield string[start:]

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

From the data you gathered, I would tend to say that encoded "/" in an uri are meant to be seen as "/" again at application/cgi level.

That's to say, that if you're using apache with mod_rewrite for instance, it will not match pattern expecting slashes against URI with encoded slashes in it. However, once the appropriate module/cgi/... is called to handle the request, it's up to it to do the decoding and, for instance, retrieve a parameter including slashes as the first component of the URI.

If your application is then using this data to retrieve a file (whose filename contains a slash), that's probably a bad thing.

To sum up, I find it perfectly normal to see a difference of behaviour in "/" or "%2F" as their interpretation will be done at different levels.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

Select rows which are not present in other table

SELECT * FROM testcases1 t WHERE NOT EXISTS ( SELECT 1
FROM executions1 i WHERE t.tc_id = i.tc_id and t.pro_id=i.pro_id and pro_id=7 and version_id=5 ) and pro_id=7 ;

Here testcases1 table contains all datas and executions1 table contains some data among testcases1 table. I am retrieving only the datas which are not present in exections1 table. ( and even I am giving some conditions inside that you can also give.) specify condition which should not be there in retrieving data should be inside brackets.

How do I concatenate or merge arrays in Swift?

Swift 3.0

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array's type is inferred from the type of the two array you add together,

let arr0 = Array(repeating: 1, count: 3) // [1, 1, 1]
let arr1 = Array(repeating: 2, count: 6)//[2, 2, 2, 2, 2, 2]
let arr2 = arr0 + arr1 //[1, 1, 1, 2, 2, 2, 2, 2, 2]

this is the right results of above codes.

How to wait until an element exists?

You can do

$('#yourelement').ready(function() {

});

Please note that this will only work if the element is present in the DOM when being requested from the server. If the element is being dynamically added via JavaScript, it will not work and you may need to look at the other answers.

Drop shadow on a div container?

You can try using the PNG drop shadows. IE6 doesn't support it, however it will degrade nicely.

http://www.positioniseverything.net/articles/dropshadows.html

Reflection: How to Invoke Method with parameters

I'am posting this answer because many visitors enter here from google for this problem.


string result = this.GetType().GetMethod("Print").Invoke(this, new object[]{"firstParam", 157, "third_Parammmm" } );

when external .dll -instead of this.GetType(), you might use typeof(YourClass).

How to trigger a build only if changes happen on particular set of files

If the logic for choosing the files is not trivial, I would trigger script execution on each change and then write a script to check if indeed a build is required, then triggering a build if it is.

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

How to get a unique device ID in Swift?

I've tried with

let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString

instead

let UUID = NSUUID().UUIDString

and it works.

Clear text area

I believe the problem is simply a spelling error when writing bbcode as bbocde:

$("#vinanghinguyen_images_bbocde").val('')

should be:

$("#vinanghinguyen_images_bbcode").val('')

What is the difference between char s[] and char *s?

Given the declarations

char *s0 = "hello world";
char s1[] = "hello world";

assume the following hypothetical memory map:

                    0x01  0x02  0x03  0x04
        0x00008000: 'h'   'e'   'l'   'l'
        0x00008004: 'o'   ' '   'w'   'o'
        0x00008008: 'r'   'l'   'd'   0x00
        ...
s0:     0x00010000: 0x00  0x00  0x80  0x00
s1:     0x00010004: 'h'   'e'   'l'   'l'
        0x00010008: 'o'   ' '   'w'   'o'
        0x0001000C: 'r'   'l'   'd'   0x00

The string literal "hello world" is a 12-element array of char (const char in C++) with static storage duration, meaning that the memory for it is allocated when the program starts up and remains allocated until the program terminates. Attempting to modify the contents of a string literal invokes undefined behavior.

The line

char *s0 = "hello world";

defines s0 as a pointer to char with auto storage duration (meaning the variable s0 only exists for the scope in which it is declared) and copies the address of the string literal (0x00008000 in this example) to it. Note that since s0 points to a string literal, it should not be used as an argument to any function that would try to modify it (e.g., strtok(), strcat(), strcpy(), etc.).

The line

char s1[] = "hello world";

defines s1 as a 12-element array of char (length is taken from the string literal) with auto storage duration and copies the contents of the literal to the array. As you can see from the memory map, we have two copies of the string "hello world"; the difference is that you can modify the string contained in s1.

s0 and s1 are interchangeable in most contexts; here are the exceptions:

sizeof s0 == sizeof (char*)
sizeof s1 == 12

type of &s0 == char **
type of &s1 == char (*)[12] // pointer to a 12-element array of char

You can reassign the variable s0 to point to a different string literal or to another variable. You cannot reassign the variable s1 to point to a different array.

CSS Animation and Display None

CSS (or jQuery, for that matter) can't animate between display: none; and display: block;. Worse yet: it can't animate between height: 0 and height: auto. So you need to hard code the height (if you can't hard code the values then you need to use javascript, but this is an entirely different question);

#main-image{
    height: 0;
    overflow: hidden;
    background: red;
   -prefix-animation: slide 1s ease 3.5s forwards;
}

@-prefix-keyframes slide {
  from {height: 0;}
  to {height: 300px;}
}

You mention that you're using Animate.css, which I'm not familiar with, so this is a vanilla CSS.

You can see a demo here: http://jsfiddle.net/duopixel/qD5XX/

How can I exclude a directory from Visual Studio Code "Explore" tab?

In version 1.28 of Visual Studio Code "files.exclude" must be placed within a settings node.

Resulting in a workspace file that looks like:

{
    "settings": {
        "files.exclude": {
            "**/node_modules": true
        }
    }
}

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.

<?php

if (!isset($_SESSION)) {
    session_start();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['postdata'] = $_POST;
    unset($_POST);
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}
?>

The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.

6 digits regular expression

^[0-9]{1,6}$ should do it. I don't know VB.NET good enough to know if it's the same there.

For examples, have a look at the Wikipedia.

How to put labels over geom_bar for each bar in R with ggplot2

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)

passing 2 $index values within nested ng-repeat

Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope.

So what you need to do is reach up to the parent scope, and use that $index.

See http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview

<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials">
    {{tutorial.name}}
</li>

Message Queue vs. Web Services?

There's been a fair amount of recent research in considering how REST HTTP calls could replace the message queue concept.

If you introduce the concept of a process and a task as a resource, the need for middle messaging layer starts to evaporate.

Ex:

POST /task/name
    - Returns a 202 accepted status immediately
    - Returns a resource url for the created task: /task/name/X
    - Returns a resource url for the started process: /process/Y

GET /process/Y
    - Returns status of ongoing process

A task can have multiple steps for initialization, and a process can return status when polled or POST to a callback URL when complete.

This is dead simple, and becomes quite powerful when you realize that you can now subscribe to an rss/atom feed of all running processes and tasks without any middle layer. Any queuing system is going to require some sort of web front end anyway, and this concept has it built in without another layer of custom code.

Your resources exist until you delete them, which means you can view historical information long after the process and task complete.

You have built in service discovery, even for a task that has multiple steps, without any extra complicated protocols.

GET /task/name
    - returns form with required fields

POST (URL provided form's "action" attribute)

Your service discovery is an HTML form - a universal and human readable format.

The entire flow can be used programmatically or by a human, using universally accepted tools. It's a client driven, and therefore RESTful. Every tool created for the web can drive your business processes. You still have alternate message channels by POSTing asynchronously to a separate array of log servers.

After you consider it for a while, you sit back and start to realize that REST may just eliminate the need for a messaging queue and an ESB altogether.

http://www.infoq.com/presentations/BPM-with-REST

Convert string to title case with JavaScript

I think the simplest is using css.

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}

swift 3.0 Data to String?

I found the way to do it. You need to convert Data to NSData:

let characterSet = CharacterSet(charactersIn: "<>")
let nsdataStr = NSData.init(data: deviceToken)
let deviceStr = nsdataStr.description.trimmingCharacters(in: characterSet).replacingOccurrences(of: " ", with: "")
print(deviceStr)

How do you connect to a MySQL database using Oracle SQL Developer?

My experience with windows client and linux/mysql server:

When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.

Assuming mysql is already up and running and the databases to be accessed are up and functional:

• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.

a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “

 i. “PE  d” it is 64.

ii. “PE  L” it is 32.

b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.

• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.

a. Driver name = mysql-connector-java-x.x.xx

b. Copy it into someplace related to your sqldeveloper directory.

c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)

• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for

bind-address = 127.0.0.1 (this linux localhost)

and change to

bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)

• Enter to linux mysql and grant needed access for example

# mysql –u root -p

GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';

flush privileges;

restart mysql - sudo /etc/init.d/mysql restart

• Start sqldev and create a new connection

a. user = root

b. pass = (your mysql pass)

c. Choose MySql tab

 i.   Hostname = the linux IP hostname

 ii.  Port     = 3306 (default for mysql)

 iii. Choose Database = (from pull down the mysql database you want to use)

 iv.  save and connect

That is all I had to do in my case.

Thank you,

Ale

ArrayList vs List<> in C#

To add to the above points. Using ArrayList in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T> will use much low memory than the ArrayList.

for example if we use a ArrayList of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int> of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.

Source: ArrayList’s vs. generic List for primitive types and 64-bits

Downloading images with node.js

You can use Axios (a promise-based HTTP client for Node.js) to download images in the order of your choosing in an asynchronous environment:

npm i axios

Then, you can use the following basic example to begin downloading images:

const fs = require('fs');
const axios = require('axios');

/* ============================================================
  Function: Download Image
============================================================ */

const download_image = (url, image_path) =>
  axios({
    url,
    responseType: 'stream',
  }).then(
    response =>
      new Promise((resolve, reject) => {
        response.data
          .pipe(fs.createWriteStream(image_path))
          .on('finish', () => resolve())
          .on('error', e => reject(e));
      }),
  );

/* ============================================================
  Download Images in Order
============================================================ */

(async () => {
  let example_image_1 = await download_image('https://example.com/test-1.png', 'example-1.png');

  console.log(example_image_1.status); // true
  console.log(example_image_1.error); // ''

  let example_image_2 = await download_image('https://example.com/does-not-exist.png', 'example-2.png');

  console.log(example_image_2.status); // false
  console.log(example_image_2.error); // 'Error: Request failed with status code 404'

  let example_image_3 = await download_image('https://example.com/test-3.png', 'example-3.png');

  console.log(example_image_3.status); // true
  console.log(example_image_3.error); // ''
})();

ASP.NET - How to write some html in the page? With Response.Write?

You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.

_x000D_
_x000D_
 [WebMethod]_x000D_
    public static string showTxtbox(string name)_x000D_
    {_x000D_
         return showResult(name);_x000D_
    }_x000D_
      _x000D_
    public static string showResult(string name)_x000D_
    {_x000D_
        Database databaseObj = new Database();_x000D_
        DataTable dtObj = databaseObj.getMatches(name);_x000D_
_x000D_
        string result = "<table  border='1' cellspacing='2' cellpadding='2' >" +_x000D_
                                            "<tr>" +_x000D_
                                                "<td><b>Name</b></td>" +_x000D_
                                                "<td><b>Company Name</b></td>" +_x000D_
                                                "<td><b>Phone</b></td>"+_x000D_
                                             "</tr>";_x000D_
_x000D_
        for (int i = 0; i < dtObj.Rows.Count; i++)_x000D_
        {_x000D_
            result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +_x000D_
             dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +_x000D_
                "<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +_x000D_
                "<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+_x000D_
             "</tr>";_x000D_
        }_x000D_
_x000D_
        result += "</table>";_x000D_
        return result;_x000D_
    }
_x000D_
_x000D_
_x000D_

Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function. Result is displayed in the form of table.

Pick any kind of file via an Intent in Android

Not for camera but for other files..

In my device I have ES File Explorer installed and This simply thing works in my case..

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);

Removing html5 required attribute with jQuery

_x000D_
_x000D_
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How do you kill all current connections to a SQL Server 2005 database?

Another "kill it with fire" approach is to just restart the MSSQLSERVER service. I like to do stuff from the commandline. Pasting this exactly into CMD will do it: NET STOP MSSQLSERVER & NET START MSSQLSERVER

Or open "services.msc" and find "SQL Server (MSSQLSERVER)" and right-click, select "restart".

This will "for sure, for sure" kill ALL connections to ALL databases running on that instance.

(I like this better than many approaches that change and change back the configuration on the server/database)

Eclipse C++: Symbol 'std' could not be resolved

I do not know whether you have solved this problem but I want to post my solution for those might ran into the same problem.

  1. First, make sure that you have the "Includes" folder in your Project Explorer. If you do not have it, go to second step. If you have it, go to third step.

  2. Second, Window -> Preferences-> C/C++- > Build >Environment: Create two environment variables:

    a) Name: C_INCLUDE_PATH Value: /usr/include

    b) Name: CPLUS_INCLUDE_PATH Value: /usr/include/c++

Go to Cygwin/usr/include/, if you cannot find folder "c++", copy it from \cygwin\lib\gcc\i686-pc-cygwin\X.X.X\include and Then restart your Eclipse.

  1. Third, Right Click your project in Project Explorer -> Properties -> C/C++ General -> Paths and Symbols -> Includes -> Languages:GNU C++ If you can find some C++ folders in the "Include directories" then click Apply and OK. Change a bit your codes, and save it.

You will find there will be not symbol could not be resolved problems.

I documented my solution, hoping someone might get benefits.

Python circular importing?

When you import a module (or a member of it) for the first time, the code inside the module is executed sequentially like any other code; e.g., it is not treated any differently that the body of a function. An import is just a command like any other (assignment, a function call, def, class). Assuming your imports occur at the top of the script, then here's what's happening:

  • When you try to import World from world, the world script gets executed.
  • The world script imports Field, which causes the entities.field script to get executed.
  • This process continues until you reach the entities.post script because you tried to import Post
  • The entities.post script causes physics module to be executed because it tries to import PostBody
  • Finally, physics tries to import Post from entities.post
  • I'm not sure whether the entities.post module exists in memory yet, but it really doesn't matter. Either the module is not in memory, or the module doesn't yet have a Post member because it hasn't finished executing to define Post
  • Either way, an error occurs because Post is not there to be imported

So no, it's not "working further up in the call stack". This is a stack trace of where the error occurred, which means it errored out trying to import Post in that class. You shouldn't use circular imports. At best, it has negligible benefit (typically, no benefit), and it causes problems like this. It burdens any developer maintaining it, forcing them to walk on egg shells to avoid breaking it. Refactor your module organization.

Android Layout Animations from bottom to top and top to bottom on ImageView click

create directory in /res/anim and create bottom_to_original.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="1500"
        android:fromYDelta="100%"
        android:toYDelta="1%" />
</set>

JAVA:

    LinearLayout ll = findViewById(R.id.ll);

    Animation animation;
    animation = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.sample_animation);
    ll .setAnimation(animation);

Type Checking: typeof, GetType, or is?

Use typeof when you want to get the type at compilation time. Use GetType when you want to get the type at execution time. There are rarely any cases to use is as it does a cast and, in most cases, you end up casting the variable anyway.

There is a fourth option that you haven't considered (especially if you are going to cast an object to the type you find as well); that is to use as.

Foo foo = obj as Foo;

if (foo != null)
    // your code here

This only uses one cast whereas this approach:

if (obj is Foo)
    Foo foo = (Foo)obj;

requires two.

Update (Jan 2020):

  • As of C# 7+, you can now cast inline, so the 'is' approach can now be done in one cast as well.

Example:

if(obj is Foo newLocalFoo)
{
    // For example, you can now reference 'newLocalFoo' in this local scope
    Console.WriteLine(newLocalFoo);
}

Why is Tkinter Entry's get function returning nothing?

A simple example without classes:

from tkinter import *    
master = Tk()

# Create this method before you create the entry
def return_entry(en):
    """Gets and prints the content of the entry"""
    content = entry.get()
    print(content)  

Label(master, text="Input: ").grid(row=0, sticky=W)

entry = Entry(master)
entry.grid(row=0, column=1)

# Connect the entry with the return button
entry.bind('<Return>', return_entry) 

mainloop()

What is causing "Unable to allocate memory for pool" in PHP?

solution for me:

  • apc.ttl=0
  • apc.shm_size=anything you want

edit start

warning!

@bokan indicated me that i should add a warning here.

if you have a ttl of 0 this means the every cached item can be purged immediately. so if you have a small cache size like 2mb and a ttl of 0 this would render the apc useless, because the data in the cache gets always overwritten.

lowering the ttl means only that the cache cannot become full, only with items which can't be replaced.

so you have to choose a good balance between ttl and cache size.

in my case i had a cache size of 1gb, so it was more than enough for me.

edit end

had the same issue on centos 5 with php 5.2.17 and noticed that if the cache size is small and the ttl parameter is "high" (like 7200) while having a lot of php files to cache, then the cache fills up quite fast and apc doesn't find anything which it can remove because all files in the cache still fit in the ttl.

increasing the memory size is only a part solution, you still run in this error if you cache fills up and all files are within the ttl.

so my solution was to set the ttl to 0, so apc fills up the cache an there is allways the possibility for apc to clear some memory for new data.

hope that helps

edit: see also: http://pecl.php.net/bugs/bug.php?id=16966

download http://pecl.php.net/get/APC extract and run the apc.php, there you have a nice diagram how your cache usage look like

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

SQL Server - transactions roll back on error?

You are correct in that the entire transaction will be rolled back. You should issue the command to roll it back.

You can wrap this in a TRY CATCH block as follows

BEGIN TRY
    BEGIN TRANSACTION

        INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
        INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
        INSERT INTO myTable (myColumns ...) VALUES (myValues ...);

    COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    -- you can Raise ERROR with RAISEERROR() Statement including the details of the exception
    RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1)
END CATCH

How can I select all options of multi-select select box on click?

If you are using JQuery 1.9+ then above answers will not work in Firefox.

So here is a code for latest jquery which will work in all browsers.

See live demo

Here is the code

var select_ids = [];
$(document).ready(function(e) {
    $('select#myselect option').each(function(index, element) {
        select_ids.push($(this).val());
    })
});

function selectAll()
{
    $('select#myselect').val(select_ids);
}

function deSelectAll()
{
    $('select#myselect').val('');
}

Hope this will help you... :)

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.

android {
   ...
   defaultConfig {
      multiDexEnabled true
      ...
   }
}

dependencies {
  // add dependency 
  implementation 'com.android.support:multidex:1.0.1'
}

2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        .
        .
        .
        .
        .
    </application>

3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.

    public class MyApplication extends Application {

    @Override 
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    } 

If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]

Hopefully, It works for you.

Cannot read property 'map' of undefined

First of all, set more safe initial data:

getInitialState : function() {
    return {data: {comments:[]}};
},

And ensure your ajax data.

It should work if you follow above two instructions like Demo.

Updated: you can just wrap the .map block with conditional statement.

if (this.props.data) {
  var commentNodes = this.props.data.map(function (comment){
      return (
        <div>
          <h1>{comment.author}</h1>
        </div>
      );
  });
}

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

Combining the results of two SQL queries as separate columns

You could also use a CTE to grab groups of information you want and join them together, if you wanted them in the same row. Example, depending on which SQL syntax you use, here:

WITH group1 AS (
  SELECT testA
    FROM tableA
),
group2 AS (
  SELECT testB
    FROM tableB 
)
SELECT *
  FROM group1
  JOIN group2 ON group1.testA = group2.testB --your choice of join
;

You decide what kind of JOIN you want based on the data you are pulling, and make sure to have the same fields in the groups you are getting information from in order to put it all into a single row. If you have multiple columns, make sure to name them all properly so you know which is which. Also, for performance sake, CTE's are the way to go, instead of inline SELECT's and such. Hope this helps.

Convert AM/PM time to 24 hours format?

using System;

class Solution
{
    static string timeConversion(string s)
    {
        return DateTime.Parse(s).ToString("HH:mm");
    }

    static void Main(string[] args)
    {
        Console.WriteLine(timeConversion("01:00 PM"));
        Console.Read();
    }
}

#1071 - Specified key was too long; max key length is 767 bytes

Here is my original answer:

I just drop database and recreate like this, and the error is gone:

drop database if exists rhodes; create database rhodes default CHARACTER set utf8 default COLLATE utf8_general_ci;

However, it doesn't work for all the cases.

It is actually a problem of using indexes on VARCHAR columns with the character set utf8 (or utf8mb4), with VARCHAR columns that have more than a certain length of characters. In the case of utf8mb4, that certain length is 191.

Please refer to the Long Index section in this article for more information how to use long indexes in MySQL database: http://hanoian.com/content/index.php/24-automate-the-converting-a-mysql-database-character-set-to-utf8mb4

Replace characters from a column of a data frame R

If your variable data1$c is a factor, it's more efficient to change the labels of the factor levels than to create a new vector of characters:

levels(data1$c) <- sub("_", "-", levels(data1$c))


            a b   c
1  0.73945260 a A-B
2  0.75998815 b A-B
3  0.19576725 c A-B
4  0.85932140 d A-B
5  0.80717115 e A-C
6  0.09101492 f A-C
7  0.10183586 g A-C
8  0.97742424 h A-C
9  0.21364521 i A-C
10 0.02389782 j A-C

How to pass arguments and redirect stdin from a file to program run in gdb?

Pass the arguments to the run command from within gdb.

$ gdb ./a.out
(gdb) r < t
Starting program: /dir/a.out < t

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

I was also getting the same issue I tried multiple IPs like my public IP and localhost default IP 127.0.0.1 in windows and default gateway but same response. but I forget to check by

C:> ipconfig

ipconfig cleanly say what is my actual IP address of that adapter with which I have connected like I was connected with Wifi adapter my IP address will show me as:

Wireless LAN adapter Wireless Network Connection:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::69fa:9475:431e:fad7%11
   IPv4 Address. . . . . . . . . . . : 192.168.15.92

I hope this will help you.

Center a DIV horizontally and vertically

You want to set style

margin: auto;

And remove the positioning styles (top, left, position)

I know this will center horrizontaly but I'm not sure about vertical!

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:

<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
    <div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
        <div class="uil-default-css">
            <img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
        </div>
        <div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;">&nbsp;</div>
    </div>
    <div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>

Finally, replace .loader-text element's content on the fly on every navigation event and turn on the #resultloading div, note that it is initially hidden.

var showLoader = function (text) {
    $('#resultLoading').show();
    $('#resultLoading').find('.loader-text').html(text);
};

jQuery(document).ready(function () {
    jQuery(window).on("beforeunload ", function () {
        showLoader('Loading, please wait...');
    });
});

This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.

The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.

Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.

Secure random token in Node.js

0. Using nanoid third party library [NEW!]

A tiny, secure, URL-friendly, unique string ID generator for JavaScript

https://github.com/ai/nanoid

import { nanoid } from "nanoid";
const id = nanoid(48);


1. Base 64 Encoding with URL and Filename Safe Alphabet

Page 7 of RCF 4648 describes how to encode in base 64 with URL safety. You can use an existing library like base64url to do the job.

The function will be:

var crypto = require('crypto');
var base64url = require('base64url');

/** Sync */
function randomStringAsBase64Url(size) {
  return base64url(crypto.randomBytes(size));
}

Usage example:

randomStringAsBase64Url(20);
// Returns 'AXSGpLVjne_f7w5Xg-fWdoBwbfs' which is 27 characters length.

Note that the returned string length will not match with the size argument (size != final length).


2. Crypto random values from limited set of characters

Beware that with this solution the generated random string is not uniformly distributed.

You can also build a strong random string from a limited set of characters like that:

var crypto = require('crypto');

/** Sync */
function randomString(length, chars) {
  if (!chars) {
    throw new Error('Argument \'chars\' is undefined');
  }

  var charsLength = chars.length;
  if (charsLength > 256) {
    throw new Error('Argument \'chars\' should not have more than 256 characters'
      + ', otherwise unpredictability will be broken');
  }

  var randomBytes = crypto.randomBytes(length);
  var result = new Array(length);

  var cursor = 0;
  for (var i = 0; i < length; i++) {
    cursor += randomBytes[i];
    result[i] = chars[cursor % charsLength];
  }

  return result.join('');
}

/** Sync */
function randomAsciiString(length) {
  return randomString(length,
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
}

Usage example:

randomAsciiString(20);
// Returns 'rmRptK5niTSey7NlDk5y' which is 20 characters length.

randomString(20, 'ABCDEFG');
// Returns 'CCBAAGDGBBEGBDBECDCE' which is 20 characters length.

Moment js get first and last day of current month

Assuming you are using a Date range Picker to retrieve the dates. You could do something like to to get what you want.

$('#daterange-btn').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            startDate: moment().subtract(29, 'days'),
            endDate: moment()
        }, function (start, end) {
      alert( 'Date is between' + start.format('YYYY-MM-DD h:m') + 'and' + end.format('YYYY-MM-DD h:m')}

How does ifstream's eof() work?

iostream doesn't know it's at the end of the file until it tries to read that first character past the end of the file.

The sample code at cplusplus.com says to do it like this: (But you shouldn't actually do it this way)

  while (is.good())     // loop while extraction from file is possible
  {
    c = is.get();       // get character from file
    if (is.good())
      cout << c;
  }

A better idiom is to move the read into the loop condition, like so: (You can do this with all istream read operations that return *this, including the >> operator)

  char c;
  while(is.get(c))
    cout << c;

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Most likely the socket is held by some process. Use netstat -o to find which one.

Extracting specific columns from a data frame

You can also use the sqldf package which performs selects on R data frames as :

df1 <- sqldf("select A, B, E from df")

This gives as the output a data frame df1 with columns: A, B ,E.

Transactions in .net

if you just need it for db-related stuff, some OR Mappers (e.g. NHibernate) support transactinos out of the box per default.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Limiting only to Swagger related resources:

.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/springfox-swagger-ui/**");

Get the current first responder without using a private API

Peter Steinberger just tweeted about the private notification UIWindowFirstResponderDidChangeNotification, which you can observe if you want to watch the firstResponder change.

Get all photos from Instagram which have a specific hashtag with PHP

To get more than 20 you can use a load more button.

index.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Instagram more button example</title>
  <!--
    Instagram PHP API class @ Github
    https://github.com/cosenary/Instagram-PHP-API
  -->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
    ul {
      width: 950px;
    }
    ul > li {
      float: left;
      list-style: none;
      padding: 4px;
    }
    #more {
      bottom: 8px;
      margin-left: 80px;
      position: fixed;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#more').click(function() {
        var tag   = $(this).data('tag'),
            maxid = $(this).data('maxid');

        $.ajax({
          type: 'GET',
          url: 'ajax.php',
          data: {
            tag: tag,
            max_id: maxid
          },
          dataType: 'json',
          cache: false,
          success: function(data) {
            // Output data
            $.each(data.images, function(i, src) {
              $('ul#photos').append('<li><img src="' + src + '"></li>');
            });

            // Store new maxid
            $('#more').data('maxid', data.next_id);
          }
        });
      });
    });
  </script>
</head>
<body>

<?php
  /**
   * Instagram PHP API
   */

   require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('ENTER CLIENT ID HERE');

    // Get latest photos according to geolocation for Växjö
    // $geo = $instagram->searchMedia(56.8770413, 14.8092744);

    $tag = 'sweden';

    // Get recently tagged media
    $media = $instagram->getTagMedia($tag);

    // Display first results in a <ul>
    echo '<ul id="photos">';

    foreach ($media->data as $data) 
    {
        echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
    }
    echo '</ul>';

    // Show 'load more' button
    echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>

</body>
</html>

ajax.php

<?php
    /**
     * Instagram PHP API
     */

     require_once 'instagram.class.php';

      // Initialize class for public requests
      $instagram = new Instagram('ENTER CLIENT ID HERE');

      // Receive AJAX request and create call object
      $tag = $_GET['tag'];
      $maxID = $_GET['max_id'];
      $clientID = $instagram->getApiKey();

      $call = new stdClass;
      $call->pagination->next_max_id = $maxID;
      $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

      // Receive new data
      $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

      // Collect everything for json output
      $images = array();
      foreach ($media->data as $data) {
        $images[] = $data->images->thumbnail->url;
      }

      echo json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images'  => $images
      ));
?>

instagram.class.php

Find the function getTagMedia() and replace with:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}

Display JSON as HTML

For the syntax highlighting, use code prettify. I believe this is what StackOverflow uses for its code highlighting.

  1. Wrap your formatted JSON in code blocks and give them the "prettyprint" class.
  2. Include prettify.js in your page.
  3. Make sure your document's body tag calls prettyPrint() when it loads

You will have syntax highlighted JSON in the format you have laid out in your page. See here for an example. So if you had a code block like this:

<code class="prettyprint">
    var jsonObj = {
        "height" : 6.2,
        "width" : 7.3,
        "length" : 9.1,
        "color" : {
            "r" : 255,
            "g" : 200,
            "b" : 10
        }
    }
</code>

It would look like this:

var jsonObj = {
    "height" : 6.2,
    "width" : 7.3,
    "length" : 9.1,
    "color" : {
        "r" : 255,
        "g" : 200,
        "b" : 10
    }
}

This doesn't help with the indenting, but the other answers seem to be addressing that.

iOS - UIImageView - how to handle UIImage image orientation

I converted the code in Anomie's answer here (copy-pasted above by suvish valsan) into Swift:

func fixOrientation() -> UIImage {
    if self.imageOrientation == UIImageOrientation.Up {
        return self
    }

    var transform = CGAffineTransformIdentity

    switch self.imageOrientation {
    case .Down, .DownMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
        transform = CGAffineTransformRotate(transform, CGFloat(M_PI));

    case .Left, .LeftMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.width, 0);
        transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2));

    case .Right, .RightMirrored:
        transform = CGAffineTransformTranslate(transform, 0, self.size.height);
        transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2));

    case .Up, .UpMirrored:
        break
    }

    switch self.imageOrientation {

    case .UpMirrored, .DownMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.width, 0)
        transform = CGAffineTransformScale(transform, -1, 1)

    case .LeftMirrored, .RightMirrored:
        transform = CGAffineTransformTranslate(transform, self.size.height, 0)
        transform = CGAffineTransformScale(transform, -1, 1);

    default:
        break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    let ctx = CGBitmapContextCreate(
        nil,
        Int(self.size.width),
        Int(self.size.height),
        CGImageGetBitsPerComponent(self.CGImage),
        0,
        CGImageGetColorSpace(self.CGImage),
        UInt32(CGImageGetBitmapInfo(self.CGImage).rawValue)
    )

    CGContextConcatCTM(ctx, transform);

    switch self.imageOrientation {
    case .Left, .LeftMirrored, .Right, .RightMirrored:
        // Grr...
        CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.height,self.size.width), self.CGImage);

    default:
        CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.width,self.size.height), self.CGImage);
        break;
    }

    // And now we just create a new UIImage from the drawing context
    let cgimg = CGBitmapContextCreateImage(ctx)

    let img = UIImage(CGImage: cgimg!)

    return img;
}

(I replaced all occurencies of the parameter image with self, because my code is an extension on UIImage).


EDIT: Swift 3 version.

The method returns an optional, because many of the intermediate calls can fail and I don't like to use !.

func fixOrientation() -> UIImage? {

    guard let cgImage = self.cgImage else {
        return nil
    }

    if self.imageOrientation == UIImageOrientation.up {
        return self
    }

    let width  = self.size.width
    let height = self.size.height

    var transform = CGAffineTransform.identity

    switch self.imageOrientation {
    case .down, .downMirrored:
        transform = transform.translatedBy(x: width, y: height)
        transform = transform.rotated(by: CGFloat.pi)

    case .left, .leftMirrored:
        transform = transform.translatedBy(x: width, y: 0)
        transform = transform.rotated(by: 0.5*CGFloat.pi)

    case .right, .rightMirrored:
        transform = transform.translatedBy(x: 0, y: height)
        transform = transform.rotated(by: -0.5*CGFloat.pi)

    case .up, .upMirrored:
        break
    }

    switch self.imageOrientation {
    case .upMirrored, .downMirrored:
        transform = transform.translatedBy(x: width, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)

    case .leftMirrored, .rightMirrored:
        transform = transform.translatedBy(x: height, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)

    default:
        break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    guard let colorSpace = cgImage.colorSpace else {
        return nil
    }

    guard let context = CGContext(
        data: nil,
        width: Int(width),
        height: Int(height),
        bitsPerComponent: cgImage.bitsPerComponent,
        bytesPerRow: 0,
        space: colorSpace,
        bitmapInfo: UInt32(cgImage.bitmapInfo.rawValue)
        ) else {
            return nil
    }

    context.concatenate(transform);

    switch self.imageOrientation {

    case .left, .leftMirrored, .right, .rightMirrored:
        // Grr...
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width))

    default:
        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
    }

    // And now we just create a new UIImage from the drawing context
    guard let newCGImg = context.makeImage() else {
        return nil
    }

    let img = UIImage(cgImage: newCGImg)

    return img;
}

(Note: Swift 3 version odes compile under Xcode 8.1, but haven't tested it actually works. There might be a typo somewhere, mixed up width/height, etc. Feel free to point/fix any errors).

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

The variable mean_data is a nested list, in Python accessing a nested list cannot be done by multi-dimensional slicing, i.e.: mean_data[1,2], instead one would write mean_data[1][2].

This is becausemean_data[2] is a list. Further indexing is done recursively - since mean_data[2] is a list, mean_data[2][0] is the first index of that list.

Additionally, mean_data[:][0] does not work because mean_data[:] returns mean_data.

The solution is to replace the array ,or import the original data, as follows:

mean_data = np.array(mean_data)

numpy arrays (like MATLAB arrays and unlike nested lists) support multi-dimensional slicing with tuples.

What is an unsigned char?

If you like using various types of specific length and signedness, you're probably better off with uint8_t, int8_t, uint16_t, etc simply because they do exactly what they say.

Can a PDF file's print dialog be opened with Javascript?

If you know how PDF files are structured (or are willing to spend a little while reading the spec), you can do it this way.

Use the Named Action "Print" in the OpenAction field of the Catalog object; the "Print" action is undocumented, but Acrobat Reader and most of the other major readers understand it. A nice benefit of this approach is that you don't get any JavaScript warnings. See here for details: http://www.gnostice.com/nl_article.asp?id=157

To make it even shinier, I added a second Action, URI, directing the reader to go back to the page that originated the request. Then I attached this Action to the first Named action using its Next field. With content disposition set to "inline", this makes it so that when the user clicks on the print link:

  1. It opens up Adobe Reader in the same tab and loads the file
  2. It immediately shows the print dialog
  3. As soon as the Print dialog is closed (whether they hit "OK" or "cancel"), the browser tab goes back to the webpage

I was able to do all these changes in Ruby easily enough using only the File and IO modules; I opened the PDF I had generated with an external tool, followed the xref to the existing Catalog section, then appended a new section onto the PDF with an updated Catalog object containing my special OpenAction line, and also the new Action objects.

Because of PDF's incremental revision features, you don't have to make any changes to the existing data to do this, just append an additional section to the end.

ToString() function in Go

Another example with a struct :

package types

import "fmt"

type MyType struct {
    Id   int    
    Name string
}

func (t MyType) String() string {
    return fmt.Sprintf(
    "[%d : %s]",
    t.Id, 
    t.Name)
}

Be careful when using it,
concatenation with '+' doesn't compile :

t := types.MyType{ 12, "Blabla" }

fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly

Android Studio - How to Change Android SDK Path

Though many of the above answers serve the purpose, there is one straight forward thing we can do in project itself.

In Eclipse, go to Window->Preferences, select "Android" from left side menu. On the right panel you will see "SDK Location". Provide the path here.

Good luck.

Java to Jackson JSON serialization: Money fields

Inspired by Steve, and as the updates for Java 11. Here's how we did the BigDecimal reformatting to avoid scientific notation.

public class PriceSerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        // Using writNumber and removing toString make sure the output is number but not String.
        jgen.writeNumber(value.setScale(2, RoundingMode.HALF_UP));
    }
}

Length of a JavaScript object

I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:

var element_count = 0;
for (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; }

@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".

'router-outlet' is not a known element

In your app.module.ts file

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
    component: DashboardComponent
},  
{
    path: 'dashboard',
    component: DashboardComponent
}
];

@NgModule({
imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    FormsModule               
],
declarations: [
    AppComponent,  
    DashboardComponent      
],
bootstrap: [AppComponent]
})
export class AppModule {

}

Add this code. Happy Coding.

Regex date format validation on Java

Putting it all together:

  • REGEX doesn't validate values (like "2010-19-19")
  • SimpleDateFormat does not check format ("2010-1-2", "1-0002-003" are accepted)

it's necessary to use both to validate format and value:

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    df.setLenient(false);
    try {
        df.parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}



A ThreadLocal can be used to avoid the creation of a new SimpleDateFormat for each call.
It is needed in a multithread context since the SimpleDateFormat is not thread safe:

private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        System.out.println("created");
        return df;
    }
};

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    try {
        format.get().parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

(same can be done for a Matcher, that also is not thread safe)

What is the equivalent of Java's System.out.println() in Javascript?

console.log().

Chrome, Safari, and IE 8+ come with built-in consoles (as part of a larger set of development tools). If you're using Firefox, getfirebug.com.

What's the difference between next() and nextLine() methods from Scanner class?

From javadocs

next() Returns the next token if it matches the pattern constructed from the specified string. nextLine() Advances this scanner past the current line and returns the input that was skipped.

Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.

How to automatically crop and center an image

One solution is to use a background image centered within an element sized to the cropped dimensions.


Basic example

_x000D_
_x000D_
.center-cropped {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-position: center center;_x000D_
  background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="center-cropped" _x000D_
     style="background-image: url('http://placehold.it/200x200');">_x000D_
</div>
_x000D_
_x000D_
_x000D_


Example with img tag

This version retains the img tag so that we do not lose the ability to drag or right-click to save the image. Credit to Parker Bennett for the opacity trick.

_x000D_
_x000D_
.center-cropped {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-position: center center;_x000D_
  background-repeat: no-repeat;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
/* Set the image to fill its parent and make transparent */_x000D_
.center-cropped img {_x000D_
  min-height: 100%;_x000D_
  min-width: 100%;_x000D_
  /* IE 8 */_x000D_
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
  /* IE 5-7 */_x000D_
  filter: alpha(opacity=0);_x000D_
  /* modern browsers */_x000D_
  opacity: 0;_x000D_
}
_x000D_
<div class="center-cropped" _x000D_
     style="background-image: url('http://placehold.it/200x200');">_x000D_
  <img src="http://placehold.it/200x200" />_x000D_
</div>
_x000D_
_x000D_
_x000D_


object-fit/-position

See supported browsers.

The CSS3 Images specification defines the object-fit and object-position properties which together allow for greater control over the scale and position of the image content of an img element. With these, it will be possible to achieve the desired effect:

_x000D_
_x000D_
.center-cropped {_x000D_
  object-fit: none; /* Do not scale the image */_x000D_
  object-position: center; /* Center the image within the element */_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<img class="center-cropped" src="http://placehold.it/200x200" />
_x000D_
_x000D_
_x000D_

Spring Boot Program cannot find main class

start-class doesn't work for me, I fixed it by adding build plugins to pom.xml, and executions is necessary.

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

PHP file_get_contents() and setting request headers

If you don't need HTTPS and curl is not available on your system you could use fsockopen

This function opens a connection from which you can both read and write like you would do with a normal file handle.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.

OK, the answer is easy, but read on:

col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px

The pixel numbers are the breakpoints, so for example col-xs is targeting the element when the window is smaller than 768px(likely mobile devices)...

I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6 to show you how the grid system work in the page, look at how lg, md and xs are responsive to the window size:

Bootstrap grid system, col-*-6

Where does this come from: -*- coding: utf-8 -*-

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

Python - Check If Word Is In A String

You can split string to the words and check the result list.

if word in string.split():
    print 'success'

Suppress Scientific Notation in Numpy When Creating Array From Nested List

I guess what you need is np.set_printoptions(suppress=True), for details see here: http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html

For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html

How to change ViewPager's page?

Without checking your code, I think what you are describing is that your pages are out of sync and you have stale data.

You say you are changing the number of pages, then crashing because you are accessing the old set of pages. This sounds to me like you are not calling pageAdapter.notifyDataSetChanged() after changing your data.

When your viewPager is showing page 3 of a set of 10 pages, and you change to a set with only 5, then call notifyDataSetChanged(), what you'll find is you are now viewing page 3 of the new set. If you were previously viewing page 8 of the old set, after putting in the new set and calling notifyDataSetChanged() you will find you are now viewing the last page of the new set without crashing.

If you simply change your current page, you may just be masking the problem.

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

The other side has abruptly aborted the connection in midst of a transaction. That can have many causes which are not controllable from the server side on. E.g. the enduser decided to shutdown the client or change the server abruptly while still interacting with your server, or the client program has crashed, or the enduser's internet connection went down, or the enduser's machine crashed, etc, etc.

How to do a GitHub pull request

(In addition of the official "GitHub Help 'Using pull requests' page",
see also "Forking vs. Branching in GitHub", "What is the difference between origin and upstream in GitHub")

Couple tips on pull-requests:

Assuming that you have first forked a repo, here is what you should do in that fork that you own:

  • create a branch: isolate your modifications in a branch. Don't create a pull request from master, where you could be tempted to accumulate and mix several modifications at once.
  • rebase that branch: even if you already did a pull request from that branch, rebasing it on top of origin/master (making sure your patch is still working) will update the pull request automagically (no need to click on anything)
  • update that branch: if your pull request is rejected, you simply can add new commits, and/or redo your history completely: it will activate your existing pull request again.
  • "focus" that branch: i.e., make its topic "tight", don't modify thousands of class and the all app, only add or fix a well-defined feature, keeping the changes small.
  • delete that branch: once accepted, you can safely delete that branch on your fork (and git remote prune origin). The GitHub GUI will propose for you to delete your branch in your pull-request page.

Note: to write the Pull-Request itself, see "How to write the perfect pull request" (January 2015, GitHub)


March 2016: New PR merge button option: see "Github squash commits from web interface on pull request after review comments?".

squash

The maintainer of the repo can chose to merge --squash those PR commits.


After a Pull Request

Regarding the last point, since April, 10th 2013, "Redesigned merge button", the branch is deleted for you:

new merge button

Deleting branches after you merge has also been simplified.
Instead of confirming the delete with an extra step, we immediately remove the branch when you delete it and provide a convenient link to restore the branch in the event you need it again.

That confirms the best practice of deleting the branch after merging a pull request.


pull-request vs. request-pull


e-notes for "reposotory" (sic)

<humour>

That (pull request) isn't even defined properly by GitHub!

Fortunately, a true business news organization would know, and there is an e-note in order to replace pull-replace by 'e-note':

https://pbs.twimg.com/media/BT_5S-TCcAA-EF2.jpg:large

So if your reposotory needs a e-note... ask Fox Business. They are in the know.

</humour>

Call of overloaded function is ambiguous

Use

p.setval(static_cast<const char *>(0));

or

p.setval(static_cast<unsigned int>(0));

As indicated by the error, the type of 0 is int. This can just as easily be cast to an unsigned int or a const char *. By making the cast manually, you are telling the compiler which overload you want.

PostgreSQL - max number of parameters in "IN" clause?

You might want to consider refactoring that query instead of adding an arbitrarily long list of ids... You could use a range if the ids indeed follow the pattern in your example:

SELECT * FROM user WHERE id >= minValue AND id <= maxValue;

Another option is to add an inner select:

SELECT * 
FROM user 
WHERE id IN (
    SELECT userId
    FROM ForumThreads ft
    WHERE ft.id = X
);

Change the size of a JTextField inside a JBorderLayout

Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:

JPanel displayPanel = new JPanel(new GridLayout(4, 2)); 
JTextField titleText = new JTextField("title"); 
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper); 
//displayPanel.add(titleText); 

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

How to generate Javadoc from command line

Oracle provides some simple examples:

http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html#CHDJBGFC

Assuming you are in ~/ and the java source tree is in ./saxon_source/net and you want to recurse through the whole source tree net is both a directory and the top package name.

mkdir saxon_docs
javadoc -d saxon_docs -sourcepath saxon_source -subpackages net

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

Python Request Post with param data

params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

You could split out the URL parameters as well:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

then post your data with:

import requests

url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, json=data)

The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, data=json.dumps(data), headers=headers)

How to reset Android Studio

On MAC delete this folder:

~/Library/Application Support/Google/AndroidStudio4.1

How to solve ADB device unauthorized in Android ADB host device?

Delete the folder .android from C:/users/<user name>/.android. It solved the issue for me.

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

How to get numbers after decimal point?

You may want to try this:

your_num = 5.55
n = len(str(int(your_num)))
float('0' + str(your_num)[n:])

It will return 0.55.

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

NSAttributedString add text alignment

In swift 4:

    let paraStyle = NSMutableParagraphStyle.init()
    paraStyle.alignment = .left

    let str = "Test Message"
    let attribute = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]

    let attrMessage = NSMutableAttributedString(string: str, attributes: attribute)


    attrMessage.addAttribute(kCTParagraphStyleAttributeName as NSAttributedStringKey, value: paraStyle, range: NSMakeRange(0, str.count))

Java Convert GMT/UTC to Local time doesn't work as expected

I also recommend using Joda as mentioned before.

Solving your problem using standard Java Date objects only can be done as follows:

    // **** YOUR CODE **** BEGIN ****
    long ts = System.currentTimeMillis();
    Date localTime = new Date(ts);
    String format = "yyyy/MM/dd HH:mm:ss";
    SimpleDateFormat sdf = new SimpleDateFormat(format);

    // Convert Local Time to UTC (Works Fine)
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date gmtTime = new Date(sdf.format(localTime));
    System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:"
            + gmtTime.toString() + "," + gmtTime.getTime());

    // **** YOUR CODE **** END ****

    // Convert UTC to Local Time
    Date fromGmt = new Date(gmtTime.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
    System.out.println("UTC time:" + gmtTime.toString() + "," + gmtTime.getTime() + " --> Local:"
            + fromGmt.toString() + "-" + fromGmt.getTime());

Output:

Local:Tue Oct 15 12:19:40 CEST 2013,1381832380522 --> UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000
UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000 --> Local:Tue Oct 15 12:19:40 CEST 2013-1381832380000

SyntaxError: Unexpected Identifier in Chrome's Javascript console

Write it as below

<script language="javascript">
var visitorName = 'Chuck';
var myOldString = 'Hello username. I hope you enjoy your stay username.';

var myNewString = myOldString.replace('username', visitorName);

document.write('Old String = ' + myOldString);
document.write('<br/>New string = ' + myNewString);
</script>

http://jsfiddle.net/h6xc4/23/

What is "overhead"?

its anything other than the data itself, ie tcp flags, headers, crc, fcs etc..

How to upgrade safely php version in wamp server

One important step is missing in all answers. I successfully upgraded with following steps:

  • stop apache service with wamp stack manager.
  • rename your wampstack/php dir to wampstack/php_old
  • copy new php dir to wampstack/
  • replace wampstack/php/php.ini by wampstack/php_old/php.ini
  • test and fix any error with php -v (for example missing extensions)
  • [optional] update php version in wampstack/properties.ini
  • Replace wampstack/apache/bin/php7ts.dll by wampstack/php/php7ts.dll
    • This is not mentioned in the other answers but you need this to use the right php version in apache!
  • start apache service

Getting A File's Mime Type In Java

The JAF API is part of JDK 6. Look at javax.activation package.

Most interesting classes are javax.activation.MimeType - an actual MIME type holder - and javax.activation.MimetypesFileTypeMap - class whose instance can resolve MIME type as String for a file:

String fileName = "/path/to/file";
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

// only by file name
String mimeType = mimeTypesMap.getContentType(fileName);

// or by actual File instance
File file = new File(fileName);
mimeType = mimeTypesMap.getContentType(file);

How to remove margin space around body or clear default css styles

try to ad the following in your CSS:

body, html{
    padding:0;
    margin:0;
}

Comparing two NumPy arrays for equality, element-wise

(A==B).all()

test if all values of array (A==B) are True.

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

Special cases and alternatives (from dbaupp's answer and yoavram's comment)

It should be noted that:

  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don't have the same shape and aren't broadcastable, then this approach will raise an error.

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values

Convert interface{} to int

Best avoid casting by declaring f to be f the correct type to correspond to the JSON.

ggplot with 2 y axes on each side and different scales

The following incorporates Dag Hjermann's basic data and programming, improves upon user4786271's strategy to create a "transformation function" to optimally combine the plots and data axis, and responds to baptist's note that such a function can be created within R.

#Climatogram for Oslo (1961-1990)
climate <- tibble(
  Month = 1:12,
  Temp = c(-4,-4,0,5,11,15,16,15,11,6,1,-3),
  Precip = c(49,36,47,41,53,65,81,89,90,84,73,55))

#y1 identifies the position, relative to the y1 axis, 
#the locations of the minimum and maximum of the y2 graph.
#Usually this will be the min and max of y1.
#y1<-(c(max(climate$Precip), 0))
#y1<-(c(150, 55))
y1<-(c(max(climate$Precip), min(climate$Precip)))

#y2 is the Minimum and maximum of the secondary axis data.
y2<-(c(max(climate$Temp), min(climate$Temp)))

#axis combines y1 and y2 into a dataframe used for regressions.
axis<-cbind(y1,y2)
axis<-data.frame(axis)

#Regression of Temperature to Precipitation:
T2P<-lm(formula = y1 ~ y2, data = axis)
T2P_summary <- summary(lm(formula = y1 ~ y2, data = axis))
T2P_summary   

#Identifies the intercept and slope of regressing Temperature to Precipitation:
T2PInt<-T2P_summary$coefficients[1, 1] 
T2PSlope<-T2P_summary$coefficients[2, 1] 


#Regression of Precipitation to Temperature:
P2T<-lm(formula = y2 ~ y1, data = axis)
P2T_summary <- summary(lm(formula = y2 ~ y1, data = axis))
P2T_summary   

#Identifies the intercept and slope of regressing Precipitation to Temperature:
P2TInt<-P2T_summary$coefficients[1, 1] 
P2TSlope<-P2T_summary$coefficients[2, 1] 


#Create Plot:
ggplot(climate, aes(Month, Precip)) +
  geom_col() +
  geom_line(aes(y = T2PSlope*Temp + T2PInt), color = "red") +
  scale_y_continuous("Precipitation", sec.axis = sec_axis(~.*P2TSlope + P2TInt, name = "Temperature")) +
  scale_x_continuous("Month", breaks = 1:12) +
  theme(axis.line.y.right = element_line(color = "red"), 
        axis.ticks.y.right = element_line(color = "red"),
        axis.text.y.right = element_text(color = "red"), 
        axis.title.y.right = element_text(color = "red")) +
  ggtitle("Climatogram for Oslo (1961-1990)")

Most noteworthy is that a new "transformation function" works better with just two data points from the data set of each axes—usually the maximum and minimum values of each set. The resulting slopes and intercepts of the two regressions enable ggplot2 to exactly pair the plots of the minimums and maximums of each axis. As user4786271 pointed out, the two regressions transform each data set and plot to the other. One transforms the break points of the first y axis to the values of the second y axis. The second transforms the data of the secondary y axis to be "normalized" according to the first y axis. The following output shows how the axis align the minimums and maximums of each dataset:

enter image description here

Having the maximums and minimums match may be most appropriate; however, another benefit of this method is that the plot associated with the secondary axis can be easily shifted, if desired, by altering a programming line related to the primary axis data. The output below simply changes the minimum precipitation input in the programming line of y1 to "0", and thus aligns the minimum Temperature level with the "0" Precipitation level.

From: y1<-(c(max(climate$Precip), min(climate$Precip)))

To: y1<-(c(max(climate$Precip), 0))

enter image description here

Notice how the resulting new regressions and ggplot2 automatically adjusted the plot and axis to correctly align the minimum Temperature to the new "base" of the "0" Precipitation level. Likewise, one is easily able to elevate the Temperature plot so that it is more obvious. The following graph is created by simply changing the above-noted line to:

"y1<-(c(150, 55))"

The above line tells the maximum of the Temperature graph to coincide with the "150" Precipitation level, and the minimum of the temperature line to coincide with the "55" Precipitation level. Again, notice how ggplot2 and the resulting new regression outputs enable the graph to maintain correct alignment with the axis.

enter image description here

The above may not be a desirable output; however, it is an example of how the graph can be easily manipulated and still have correct relationships between the plots and the axis. The incorporation of Dag Hjermann's theme improves identification of the axis corresponding to the plot.

enter image description here

How to edit nginx.conf to increase file size upload

Add client_max_body_size

Now that you are editing the file you need to add the line into the server block, like so;

server {
    client_max_body_size 8M;

    //other lines...
}

If you are hosting multiple sites add it to the http context like so;

http {
    client_max_body_size 8M;

    //other lines...
}

And also update the upload_max_filesize in your php.ini file so that you can upload files of the same size.

Saving in Vi

Once you are done you need to save, this can be done in vi with pressing esc key and typing :wq and returning.

Restarting Nginx and PHP

Now you need to restart nginx and php to reload the configs. This can be done using the following commands;

sudo service nginx restart
sudo service php5-fpm restart

Or whatever your php service is called.

Write a file on iOS

Swift

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
}

func loadFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String = String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding, error: nil)!
    println(content)
}

Swift 2

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] 
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
       content = try String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding)
    }catch _{
        content=""
    }
    return content;
}

Swift 3

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.write(toFile: fileName, atomically: false, encoding: String.Encoding.utf8)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
        content = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8)
    } catch _{
        content=""
    }
    return content;
}

Using PowerShell credentials without being prompted for a password

I saw one example that uses Import/Export-CLIXML.

These are my favorite commands for the issue you're trying to resolve. And the simplest way to use them is.

$passwordPath = './password.txt'
if (-not (test-path $passwordPath)) {
    $cred = Get-Credential -Username domain\username -message 'Please login.'
    Export-CliXML -InputObject $cred -Path $passwordPath
}
$cred = Import-CliXML -path $passwordPath

So if the file doesn't locally exist it will prompt for the credentials and store them. This will take a [pscredential] object without issue and will hide the credentials as a secure string.

Finally just use the credential like you normally do.

Restart-Computer -ComputerName ... -Credentail $cred

Note on Securty:

Securely store credentials on disk

When reading the Solution, you might at first be wary of storing a password on disk. While it is natural (and prudent) to be cautious of littering your hard drive with sensitive information, the Export-CliXml cmdlet encrypts credential objects using the Windows standard Data Protection API. This ensures that only your user account can properly decrypt its contents. Similarly, the ConvertFrom-SecureString cmdlet also encrypts the password you provide.

Edit: Just reread the original question. The above will work so long as you've initialized the [pscredential] to the hard disk. That is if you drop that in your script and run the script once it will create that file and then running the script unattended will be simple.

checking if a number is divisible by 6 PHP

Simply run a while loop that will continue to loop (and increase the number) until the number is divisible by 6.

while ($number % 6 != 0) {
    $number++;
}

Using Pairs or 2-tuples in Java

Though the article is pretty old now, and though I understand that I'm not really very helpful, I think the work done here: http://www.pds.ewi.tudelft.nl/pubs/papers/cpe2005.pdf, would have been nice in mainstream Java.

You can do things like:

int a;
char b;
float c;
[a,b,c] = [3,'a',2.33];

or

[int,int,char] x = [1,2,'a'];

or

public [int,boolean] Find(int i)
{
  int idx = FindInArray(A,i);
  return [idx,idx>=0];
}

[idx, found] = Find(7);

Here tuples are:

  • Defined as primitive types - no templates/generics
  • Stack-allocated if declared locally
  • Assigned using pattern-matching

This approach increases

  • Performance
  • Readability
  • Expressiveness

Bootstrap 4 Center Vertical and Horizontal Alignment

Update 2019 - Bootstrap 4.3.1

There's no need for extra CSS. What's already included in Bootstrap will work. Make sure the container(s) of the form are full height. Bootstrap 4 now has a h-100 class for 100% height...

Vertical center:

<div class="container h-100">
  <div class="row h-100 justify-content-center align-items-center">
    <form class="col-12">
      <div class="form-group">
        <label for="formGroupExampleInput">Example label</label>
        <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
      </div>
      <div class="form-group">
        <label for="formGroupExampleInput2">Another label</label>
        <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
      </div>
    </form>   
  </div>
</div>

https://codeply.com/go/raCutAGHre

the height of the container with the item(s) to center should be 100% (or whatever the desired height is relative to the centered item)

Note: When using height:100% (percentage height) on any element, the element takes in the height of it's container. In modern browsers vh units height:100vh; can be used instead of % to get the desired height.

Therefore, you can set html, body {height: 100%}, or use the new min-vh-100 class on container instead of h-100.


Horizontal center:

  • text-center to center display:inline elements & column content
  • mx-auto for centering inside flex elements
  • offset-* or mx-auto can be used to center columns (.col-)
  • justify-content-center to center columns (col-*) inside row

Vertical Align Center in Bootstrap 4
Bootstrap 4 full-screen centered form
Bootstrap 4 center input group
Bootstrap 4 horizontal + vertical center full screen

Convert js Array() to JSon object for use with JQuery .ajax

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1

Get cookie by name

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

Pass the cookie name to getCookie() function to get it's value

Change WPF window background image in C# code

Here the XAML Version

<Window.Background>
    <ImageBrush>
        <ImageBrush.ImageSource>
            <BitmapImage UriSource="//your source .."/>
        </ImageBrush.ImageSource>
    </ImageBrush>
</Window.Background>

How to format date and time in Android?

This is my method, you can define and input and output format.

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

How to check if a URL exists or returns 404 with Java?

There is nothing wrong with your code. It's the NBC.com doing tricks on you. When NBC.com decides that your browser is not capable of displaying PDF, it simply sends back a webpage regardless what you are requesting, even if it doesn't exist.

You need to trick it back by telling it your browser is capable, something like,

conn.setRequestProperty("User-Agent",
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");

How do you decrease navbar height in Bootstrap 3?

 .navbar-nav > li > a {padding-top:7px !important; padding-bottom:7px !important;}
.navbar {min-height:32px !important;} 
.navbar-brand{padding-top:7px !important; max-height: 24px;  }
.navbar .navbar-toggle {  margin-top: 0px; margin-bottom: 0px; padding: 8px 9px; }

How to print a percentage value in python?

You are dividing integers then converting to float. Divide by floats instead.

As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language

To specify a percent conversion and precision.

>>> float(1) / float(3)
[Out] 0.33333333333333331

>>> 1.0/3.0
[Out] 0.33333333333333331

>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'

>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'

A great gem!

How do I set up a simple delegate to communicate between two view controllers?

This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.

First you need to declare a protocol:

Let's call it MyFirstControllerDelegate.h

@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end

Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate

#import "MyFirstControllerDelegate.h"

@interface FirstController : UIViewController<MyFirstControllerDelegate>
{

}

@end

In the implementation file, you need to implement both functions of protocol:

@implementation FirstController 


    - (void) FunctionOne: (MyDataOne*) dataOne
      {
          //Put your finction code here
      }
    - (void) FunctionTwo: (MyDatatwo*) dataTwo
      {
          //Put your finction code here
      }

     //Call below function from your code
    -(void) CreateSecondController
     {
             SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
           //..... push second controller into navigation stack 
            mySecondController.delegate = self ;
            [mySecondController release];
     }

@end

in your SecondController:

@interface SecondController:<UIViewController>
{
   id <MyFirstControllerDelegate> delegate;
}

@property (nonatomic,assign)  id <MyFirstControllerDelegate> delegate;

@end

In the implementation file of SecondController.

@implementation SecondController

@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
   [delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
   [delegate FunctionTwo:myDataSecond];
}

@end

Here is the wiki article on delegate.

How do you test a public/private DSA keypair?

I always compare an MD5 hash of the modulus using these commands:

Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5
Private Key: openssl rsa -noout -modulus -in server.key | openssl md5
CSR: openssl req -noout -modulus -in server.csr | openssl md5

If the hashes match, then those two files go together.

How can I pretty-print JSON using node.js?

If you don't want to store this anywhere, but just view the object for debugging purposes.

console.log(JSON.stringify(object, null, "  "));

You can change the third parameter to adjust the indentation.

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Assign value from successful promise resolve to external variable

This could be updated to ES6 with arrow functions and look like:

getFeed().then(data => vm.feed = data);

If you wish to use the async function, you could also do like that:

async function myFunction(){
    vm.feed = await getFeed();
    // do whatever you need with vm.feed below
 }

jQuery vs document.querySelectorAll

as the official site says: "jQuery: The Write Less, Do More, JavaScript Library"

try to translate the following jQuery code without any library

$("p.neat").addClass("ohmy").show("slow");

Android EditText view Floating Hint in Material Design

The Android support library can be imported within gradle in the dependencies :

    compile 'com.android.support:design:22.2.0'

It should be included within GradlePlease! And as an example to use it:

 <android.support.design.widget.TextInputLayout
    android:id="@+id/to_text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextViewTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="To"
        android:layout_marginTop="45dp"
        />
</android.support.design.widget.TextInputLayout>

Btw, the editor may not understand that AutoCompleteTextView is allowed within TextInputLayout.

System.Net.WebException HTTP status code

Maybe something like this...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

AddRange to a Collection

Agree with some guys above and Lipert's opinion. In my case, it's quite often to do like this:

ICollection<int> A;
var B = new List<int> {1,2,3,4,5};
B.ForEach(A.Add);

To have an extension method for such operation a bit redundant in my view.

Order by descending date - month, day and year

I'm guessing EventDate is a char or varchar and not a date otherwise your order by clause would be fine.

You can use CONVERT to change the values to a date and sort by that

SELECT * 
FROM 
     vw_view 
ORDER BY 
   CONVERT(DateTime, EventDate,101)  DESC

The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.

This means you should either exclude the bad rows or let the bad rows go to the bottom of the results

To exclude the bad rows just add WHERE IsDate(EventDate) = 1

To let let the bad dates go to the bottom you need to use CASE

e.g.

ORDER BY 
    CASE
       WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
       ELSE null
    END DESC

How to set Default Controller in asp.net MVC 4 & MVC 5

I didnt see this question answered:

How should I setup a default Area when the application starts?

So, here is how you can set up a default Area:

var route = routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    ).DataTokens = new RouteValueDictionary(new { area = "MyArea" });

LINQ to SQL Left Outer Join

Take care of performance:

I experienced that at least with EF Core the different answers given here might result in different performance. I'm aware that the OP asked about Linq to SQL, but it seems to me that the same questions occur also with EF Core.

In a specific case I had to handle, the (syntactically nicer) suggestion by Marc Gravell resulted in left joins inside a cross apply -- similarly to what Mike U described -- which had the result that the estimated costs for this specific query were two times as high compared to a query with no cross joins. The server execution times differed by a factor of 3. [1]

The solution by Marc Gravell resulted in a query without cross joins.

Context: I essentially needed to perform two left joins on two tables each of which again required a join to another table. Furthermore, there I had to specify other where-conditions on the tables on which I needed to apply the left join. In addition, I had two inner joins on the main table.

Estimated operator costs:

  • with cross apply: 0.2534
  • without cross apply: 0.0991.

Server execution times in ms (queries executed 10 times; measured using SET STATISTICS TIME ON):

  • with cross apply: 5, 6, 6, 6, 6, 6, 6, 6, 6, 6
  • without cross apply: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2

(The very first run was slower for both queries; seems that something is cached.)

Table sizes:

  • main table: 87 rows,
  • first table for left join: 179 rows;
  • second table for left join: 7 rows.

EF Core version: 2.2.1.

SQL Server version: MS SQL Server 2017 - 14... (on Windows 10).

All relevant tables had indexes on the primary keys only.

My conclusion: it's always recommended to look at the generated SQL since it can really differ.


[1] Interestingly enough, when setting the 'Client statistics' in MS SQL Server Management Studio on, I could see an opposite trend; namely that last run of the solution without cross apply took more than 1s. I suppose that something was going wrong here - maybe with my setup.

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

How to overcome the CORS issue in ReactJS

You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/" And add the following line to your package.json file

"proxy": "https://awww.api.com"

Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself This link will help you set that up Create React App Proxying API requests

How to use querySelectorAll only for elements that have a specific attribute set?

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Well, I can think of a CSS hack that will resolve this issue.

You could add the following line in your CSS file:

* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; } 

The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

How to write file in UTF-8 format?

Add BOM: UTF-8

file_put_contents($myFile, "\xEF\xBB\xBF".  $content); 

What is the parameter "next" used for in Express?

Next is used to pass control to the next middleware function. If not the request will be left hanging or open.

Query comparing dates in SQL

Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "

Ex:

 select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= #2013-04-12#

How to download fetch response in react as file

This worked for me.

const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};

fetch(`${url}`, requestOptions)
.then((res) => {
    return res.blob();
})
.then((blob) => {
    const href = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'config.json'); //or any other extension
    document.body.appendChild(link);
    link.click();
})
.catch((err) => {
    return Promise.reject({ Error: 'Something Went Wrong', err });
})

What is the difference between function and procedure in PL/SQL?

In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.

How to exit when back button is pressed?

First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.

Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.

Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html

But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:

@Override
 public void onBackPressed() {

// make sure you have this outcommented
// super.onBackPressed();
 Intent intent = new Intent(Intent.ACTION_MAIN);
 intent.addCategory(Intent.CATEGORY_HOME);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent);
}

How to detect if javascript files are loaded?

When they say "The bottom of the page" they don't literally mean the bottom: they mean just before the closing </body> tag. Place your scripts there and they will be loaded before the DOMReady event; place them afterwards and the DOM will be ready before they are loaded (because it's complete when the closing </html> tag is parsed), which as you have found will not work.

If you're wondering how I know that this is what they mean: I have worked at Yahoo! and we put our scripts just before the </body> tag :-)

EDIT: also, see T.J. Crowder's reply and make sure you have things in the correct order.

How to build and fill pandas dataframe from for loop?

The simplest answer is what Paul H said:

d = []
for p in game.players.passing():
    d.append(
        {
            'Player': p,
            'Team': p.team,
            'Passer Rating':  p.passer_rating()
        }
    )

pd.DataFrame(d)

But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do it.

d = pd.DataFrame()

for p in game.players.passing():
    temp = pd.DataFrame(
        {
            'Player': p,
            'Team': p.team,
            'Passer Rating': p.passer_rating()
        }
    )

    d = pd.concat([d, temp])

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Sending mail attachment using Java

Working code, I have used Java Mail 1.4.7 jar

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;

public class MailProjectClass {

public static void main(String[] args) {

    final String username = "[email protected]";
    final String password = "your.password";

    Properties props = new Properties();
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");
        message.setText("PFA");

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();
        
        String file = "path of file to be attached";
        String fileName = "attachmentName";
        DataSource source = new FileDataSource(file);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        System.out.println("Sending");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        e.printStackTrace();
    }
  }
}

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

How to create relationships in MySQL

One of the rules you have to know is that the table column you want to reference to has to be with the same data type as The referencing table . 2 if you decide to use mysql you have to use InnoDB Engine because according to your question that’s the engine which supports what you want to achieve in mysql .

Bellow is the code try it though the first people to answer this question they 100% provided great answers and please consider them all .

CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY (account_id)
)ENGINE=InnoDB;

CREATE TABLE customers(
    customer_id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    address VARCHAR(20) NOT NULL,
    city VARCHAR(20) NOT NULL,
    state VARCHAR(20) NOT NULL,
     PRIMARY KEY ( account_id ), 
FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 
)ENGINE=InnoDB; 

How to set table name in dynamic SQL query?

This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically

select @sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'

exec (@sql)

of course #tables is a dynamic table in the stored procedure

How can I add the sqlite3 module to Python?

I have python 2.7.3 and this solved my problem:

pip install pysqlite

Is it possible to auto-format your code in Dreamweaver?

Coding toolbar (Edit > Toolbars > Coding) and select Code Format Settings to set your preferred formatting.

You can also access the formatting option from Commands > Apply Source Formatting or only apply it to a select block of code by selecting the Apply Source Formatting to Selection option.

http://www.hongkiat.com/blog/10-useful-dreamweaver-tips-for-beginners/

How do I remove the title bar from my app?

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

works in onCreate() when put before setContentView() is invoked.

otherwise it crashes

Execute bash script from URL

For bash, Bourne shell and fish:

curl -s http://server/path/script.sh | bash -s arg1 arg2

Flag "-s" makes shell read from stdin.