Programs & Examples On #Thread dump

When debugging it becomes necessary to dump the thread state of the application, this is usually to find a deadlock, lock contention or leaking connections.

How to get a thread and heap dump of a Java process on Windows that's not running in a console

If you are using JDK 1.6 or above, You can use jmap command to take a heap Dump of a Java process, condition is you should known ProcessID.

If you are on Windows Machine, you can use Task Manager to get PID. For Linux machine you can use varieties of command like ps -A | grep java or netstat -tupln | grep java or top | grep java, depends on your application.

Then you can use the command like jmap -dump:format=b,file=sample_heap_dump.hprof 1234 where 1234 is PID.

There are varieties of tool available to interpret the hprof file. I will recommend Oracle's visualvm tool, which is simple to use.

What value could I insert into a bit type column?

Generally speaking, for boolean or bit data types, you would use 0 or 1 like so:

UPDATE tbl SET bitCol = 1 WHERE bitCol = 0

See also:

Differences between strong and weak in Objective-C

A dummy answer :-

I think explanation is given in above answer, so i am just gonna tell you where to use STRONG and where to use WEAK :

Use of Weak :- 1. Delegates 2. Outlets 3. Subviews 4. Controls, etc.

Use of Strong :- Remaining everywhere which is not included in WEAK.

How do I set a fixed background image for a PHP file?

It's not a good coding to put PHP code into CSS

body
{
    background-image:url('bg.png');
}

that's it

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

How to make primary key as autoincrement for Room Persistence lib

You need to use the autoGenerate property

Your primary key annotation should be like this:

@PrimaryKey(autoGenerate = true)

Reference for PrimaryKey.

Bootstrap full-width text-input within inline-form

The bootstrap docs says about this:

Requires custom widths Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.

The default width of 100% as all form elements gets when they got the class form-control didn't apply if you use the form-inline class on your form.

You could take a look at the bootstrap.css (or .less, whatever you prefer) where you will find this part:

.form-inline {

  // Kick in the inline
  @media (min-width: @screen-sm-min) {
    // Inline-block all the things for "inline"
    .form-group {
      display: inline-block;
      margin-bottom: 0;
      vertical-align: middle;
    }

    // In navbar-form, allow folks to *not* use `.form-group`
    .form-control {
      display: inline-block;
      width: auto; // Prevent labels from stacking above inputs in `.form-group`
      vertical-align: middle;
    }
    // Input groups need that 100% width though
    .input-group > .form-control {
      width: 100%;
    }

    [...]
  }
}

Maybe you should take a look at input-groups, since I guess they have exactly the markup you want to use (working fiddle here):

<div class="row">
   <div class="col-lg-12">
    <div class="input-group input-group-lg">
      <input type="text" class="form-control input-lg" id="search-church" placeholder="Your location (City, State, ZIP)">
      <span class="input-group-btn">
        <button class="btn btn-default btn-lg" type="submit">Search</button>
      </span>
    </div>
  </div>
</div>

$ is not a function - jQuery error

In Wordpress jQuery.noConflict() is called on the jQuery file it includes (scroll to the bottom of the file it's including for jQuery to see this), which means $ doesn't work, but jQuery does, so your code should look like this:

<script type="text/javascript">
  jQuery(function($) {
    for(var i=0; i <= 20; i++) 
      $("ol li:nth-child(" + i + ")").addClass('olli' + i);
  });
</script>

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

android View not attached to window manager

Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.

Change DIV content using ajax, php and jQuery

This works for me and you don't need the inline script:

Javascript:

    $(document).ready(function() {
    $('.showme').bind('click', function() {

        var id=$(this).attr("id");
        var num=$(this).attr("class");
        var poststr="request="+num+"&moreinfo="+id;
        $.ajax({
              url:"testme.php",
              cache:0,
              data:poststr,
              success:function(result){
                     document.getElementById("stuff").innerHTML=result;
               }
        }); 
    });
 });

HTML:

    <div class='request_1 showme' id='rating_1'>More stuff 1</div>
    <div class='request_2 showme' id='rating_2'>More stuff 2</div>
    <div class='request_3 showme' id='rating_3'>More stuff 3</div>

    <div id="stuff">Here is some stuff that will update when the links above are clicked</div>

The request is sent to testme.php:

    header("Cache-Control: no-cache");
    header("Pragma: nocache");

    $request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
    $request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);

    if($request_id=="1")
    {
        echo "show 1";
    }
    elseif($request_id=="2")
    {
        echo "show 2";
    }
    else
    {
        echo "show 3";
    }

Getting the textarea value of a ckeditor textarea with javascript

var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

Getting a machine's external IP address with Python

import requests
import re


def getMyExtIp():
    try:
        res = requests.get("http://whatismyip.org")
        myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group()
        if myIp != "":
            return myIp
    except:
        pass
    return "n/a"

Docker command can't connect to Docker daemon

Perhaps this will help someone, as the error message is extremely unhelpful, and I had gone through all of the standard permission steps numerous times to no avail.

Docker occasionally leaves ghost environment variables in place that block access, despite your system otherwise being correctly set up. The following shell commands may make it accessible again, if you have had it running at one point and it just stopped cooperating after a reboot:

unset DOCKER_HOST
unset DOCKER_TLS_VERIFY
unset DOCKER_TLS_PATH
docker ps

I had a previously working docker install, and after rebooting my laptop it simply refused to work. Was correctly added to the docker user group, had the correct permissions on the socket, etc, but could still not run docker login, docker run ..., etc. This fixed it for me. Unfortunately I have to run this on each reboot. This is mentioned on a couple of github issues also as a workaround, although it seems like a bug that this is a persistent barrier to correct operation of Docker (note: I am on Arch Linux, not OSX, but this was the same issue for me).

the MySQL service on local computer started and then stopped

Nothing was working for me but then I checked here. I ran that command qc sc mysql57 and copied the value of BINARY_PATH_NAME from it. After that I checked this and changed the value of lower_case_table_names from 0 to 2 in my.ini file. Then in the command prompt, I ran this command - << BINARY_PATH_NAME >> --install-manual. After that, I started the MySQL57 service and it worked.

Unique constraint on multiple columns

This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.

  1. Under the table, right click Indexes->Click/hover New Index->Click Non-Clustered Index...

enter image description here

  1. A default Index name will be given but you may want to change it. Check the Unique checkbox and click Add... button

enter image description here

  1. Check the columns you want included

enter image description here

Click OK in each window and you're done.

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Based on Jakub's answer you can configure the following git aliases for convenience:

accept-ours = "!f() { git checkout --ours -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"
accept-theirs = "!f() { git checkout --theirs -- \"${@:-.}\"; git add -u \"${@:-.}\"; }; f"

They optionally take one or several paths of files to resolve and default to resolving everything under the current directory if none are given.

Add them to the [alias] section of your ~/.gitconfig or run

git config --global alias.accept-ours '!f() { git checkout --ours -- "${@:-.}"; git add -u "${@:-.}"; }; f'
git config --global alias.accept-theirs '!f() { git checkout --theirs -- "${@:-.}"; git add -u "${@:-.}"; }; f'

How does lock work exactly?

According to Microsoft's MSDN, the lock is equivalent to:

object __lockObj = x;
bool __lockWasTaken = false;
try
{
    System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
    // Your code...
}
finally
{
    if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);
}

If you need to create locks in runtime, you can use open source DynaLock. You can create new locks in run-time and specify boundaries to the locks with context concept.

DynaLock is open-source and source code is available at GitHub

Cross field validation with Hibernate Validator (JSR 303)

I like the idea from Jakub Jirutka to use Spring Expression Language. If you don't want to add another library/dependency (assuming that you already use Spring), here is a simplified implementation of his idea.

The constraint:

@Constraint(validatedBy=ExpressionAssertValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExpressionAssert {
    String message() default "expression must evaluate to true";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    String value();
}

The validator:

public class ExpressionAssertValidator implements ConstraintValidator<ExpressionAssert, Object> {
    private Expression exp;

    public void initialize(ExpressionAssert annotation) {
        ExpressionParser parser = new SpelExpressionParser();
        exp = parser.parseExpression(annotation.value());
    }

    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return exp.getValue(value, Boolean.class);
    }
}

Apply like this:

@ExpressionAssert(value="pass == passVerify", message="passwords must be same")
public class MyBean {
    @Size(min=6, max=50)
    private String pass;
    private String passVerify;
}

QR Code encoding and decoding using zxing

So, for future reference for anybody who doesn't want to spend two days searching the internet to figure this out, when you encode byte arrays into QR Codes, you have to use the ISO-8859-1character set, not UTF-8.

Detect a finger swipe through JavaScript on the iPhone and Android

I wanted to detect left and right swipe only, but trigger the action only when the touch event ends, so I slightly modified the @givanse's great answer to do that.

Why to do that? If for example, while swiping, the user notices he finally doesn't want to swipe, he can move his finger at the original position (a very popular "dating" phone application does this ;)), and then the "swipe right" event is cancelled.

So in order to avoid a "swipe right" event just because there is a 3px difference horizontally, I added a threshold under which an event is discarded: in order to have a "swipe right" event, the user has to swipe of at least 1/3 of the browser width (of course you can modify this).

All these small details enhance the user experience.

Note that currently, a "touch pinch zoom" might be detected as a swipe if one of the two fingers does a big horizontal move during the pinch zoom.

Here is the (Vanilla JS) code:

var xDown = null, yDown = null, xUp = null, yUp = null;
document.addEventListener('touchstart', touchstart, false);        
document.addEventListener('touchmove', touchmove, false);
document.addEventListener('touchend', touchend, false);
function touchstart(evt) { const firstTouch = (evt.touches || evt.originalEvent.touches)[0]; xDown = firstTouch.clientX; yDown = firstTouch.clientY; }
function touchmove(evt) { if (!xDown || !yDown ) return; xUp = evt.touches[0].clientX; yUp = evt.touches[0].clientY; }
function touchend(evt) { 
    var xDiff = xUp - xDown, yDiff = yUp - yDown;
    if ((Math.abs(xDiff) > Math.abs(yDiff)) && (Math.abs(xDiff) > 0.33 * document.body.clientWidth)) { 
        if (xDiff < 0) 
            document.getElementById('leftnav').click();
        else
            document.getElementById('rightnav').click();
    } 
    xDown = null, yDown = null;
}

How to parse unix timestamp to time.Time

Sharing a few functions which I created for dates:

Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.

func GetTimeStamp() string {
     loc, _ := time.LoadLocation("America/Los_Angeles")
     t := time.Now().In(loc)
     return t.Format("20060102150405")
}
func GetTodaysDate() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02")
}

func GetTodaysDateTime() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02 15:04:05")
}

func GetTodaysDateTimeFormatted() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("Jan 2, 2006 at 3:04 PM")
}

func GetTimeStampFromDate(dtformat string) string {
    form := "Jan 2, 2006 at 3:04 PM"
    t2, _ := time.Parse(form, dtformat)
    return t2.Format("20060102150405")
}

Polymorphism vs Overriding vs Overloading

Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)

anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved statically, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:

class animal {
    public void makeRumor(){
        print("thump");
    }
}
class dog extends animal {
    public void makeRumor(){
        print("woff");
    }
}

animal a = new dog();
dog b = new dog();

a.makeRumor() -> prints thump
b.makeRumor() -> prints woff

(supposing that makeRumor is NOT virtual)

java doesn't truly offer this level of polymorphism (called also object slicing).

animal a = new dog(); dog b = new dog();

a.makeRumor() -> prints thump
b.makeRumor() -> prints woff

on both case it will only print woff.. since a and b is refering to class dog

Joining Multiple Tables - Oracle

I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, and CROSS JOIN elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM clause and all the join conditions are put in the the WHERE clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.

I'd rewrite your query as:

SELECT bc.firstname,
       bc.lastname,
       b.title,
       TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
       p.publishername
FROM BOOK_CUSTOMER bc
INNER JOIN books b
  ON b.BOOK_ID = bc.BOOK_ID
INNER JOIN  book_order bo
  ON bo.BOOK_ID = b.BOOK_ID
INNER JOIN publisher p
  ON p.PUBLISHER_ID = b.PUBLISHER_ID
WHERE p.publishername = 'PRINTING IS US';

Share and enjoy.

How can I insert new line/carriage returns into an element.textContent?

Change the h1.textContent to h1.innerHTML and use <br> to go to the new line.

Chart.js - Formatting Y axis

Here you can find a good example of how to format Y-Axis value.

Also, you can use scaleLabel : "<%=value%>" that you mentioned, It basically means that everything between <%= and %> tags will be treated as javascript code (i.e you can use if statments...)

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

jquery clear input default value

$('.input').on('focus', function(){
    $(this).val('');
});

$('[type="submit"]').on('click', function(){
    $('.input').val('');
});

What do multiple arrow functions mean in javascript?

A general tip , if you get confused by any of new JS syntax and how it will compile , you can check babel. For example copying your code in babel and selecting the es2015 preset will give an output like this

handleChange = function handleChange(field) {
 return function (e) {
 e.preventDefault();
  // Do something here
   };
 };

babel

access key and value of object using *ngFor

None of the answers here worked for me out of the box, here is what worked for me:

Create pipes/keys.ts with contents:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform
{
    transform(value:any, args:string[]): any {
        let keys:any[] = [];
        for (let key in value) {
            keys.push({key: key, value: value[key]});
        }
        return keys;
    }
}

Add to app.module.ts (Your main module):

import { KeysPipe } from './pipes/keys';

and then add to your module declarations array something like this:

@NgModule({
    declarations: [
        KeysPipe
    ]
})
export class AppModule {}

Then in your view template you can use something like this:

<option *ngFor="let entry of (myData | keys)" value="{{ entry.key }}">{{ entry.value }}</option>

Here is a good reference I found if you want to read more.

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

I had the same problem: the error was File not found, while opening HTML files in chrome, but I resolved it as follows:

BEFORE:

1) I saved a html file abc.html in a folder name C#.

2) When I was opening the abc.html in Google Chrome, it was showing error as "file not found". But it was working fine on Firefox and Internet Explorer.

AFTER:

3) What I did then is, I simply changed the folder name C# to csharp without space and re opened it in Chrome. It worked.

4) The moral is: Make sure you don't give any space in a folder name as some browsers don't support it.

How to properly stop the Thread in Java?

Sometime I will try 1000 times in my onDestroy()/contextDestroyed()

      @Override
    protected void onDestroy() {
        boolean retry = true;
        int counter = 0;
        while(retry && counter<1000)
        {
            counter++;
            try{thread.setRunnung(false);
                thread.join();
                retry = false;
                thread = null; //garbage can coll
            }catch(InterruptedException e){e.printStackTrace();}
        }

    }

Get single listView SelectedItem

Usually SelectedItems returns either a collection, an array or an IQueryable.

Either way you can access items via the index as with an array:

String text = listView1.SelectedItems[0].Text; 

By the way, you can save an item you want to look at into a variable, and check its structure in the locals after setting a breakpoint.

Check that a variable is a number in UNIX shell

a=123
if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]
then
    echo numeric
else
    echo ng
fi

numeric

a=12s3
if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]
then
    echo numeric
else
    echo ng
fi

ng

HTML5 video won't play in Chrome only

I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.

The only thing that worked for me was updating my video drivers.

I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.

jquery function setInterval

// simple example using the concept of setInterval

$(document).ready(function(){
var g = $('.jumping');
function blink(){
  g.animate({ 'left':'50px' 
  }).animate({
     'left':'20px'
        },1000)
}
setInterval(blink,1500);
});

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

PostgreSQL 'NOT IN' and subquery

When using NOT IN you should ensure that none of the values are NULL:

SELECT mac, creation_date 
FROM logs 
WHERE logs_type_id=11
AND mac NOT IN (
    SELECT mac
    FROM consols
    WHERE mac IS NOT NULL -- add this
)

How can getContentResolver() be called in Android?

import android.content.Context;
import android.content.ContentResolver;

context = (Context)this;
ContentResolver result = (ContentResolver)context.getContentResolver();

WAMP won't turn green. And the VCRUNTIME140.dll error

After lots and lots of installing and uninstalling for a whole day and trying every packages for every answers in here, the only thing that worked for me was:

  1. Uninstall Wamp and reboot
  2. installing Visual Studio 2017 Community edition and choose "Web development" and check all of the options in the right site. Here's a screenshot: enter image description here

This somehow install something that is needed for Wamp as well.

  1. install Wamp, and you should be all good.

Link to visual studio 2017 Community edition

How to properly use unit-testing's assertRaises() with NoneType objects?

The usual way to use assertRaises is to call a function:

self.assertRaises(TypeError, test_function, args)

to test that the function call test_function(args) raises a TypeError.

The problem with self.testListNone[:1] is that Python evaluates the expression immediately, before the assertRaises method is called. The whole reason why test_function and args is passed as separate arguments to self.assertRaises is to allow assertRaises to call test_function(args) from within a try...except block, allowing assertRaises to catch the exception.

Since you've defined self.testListNone = None, and you need a function to call, you might use operator.itemgetter like this:

import operator
self.assertRaises(TypeError, operator.itemgetter, (self.testListNone,slice(None,1)))

since

operator.itemgetter(self.testListNone,slice(None,1))

is a long-winded way of saying self.testListNone[:1], but which separates the function (operator.itemgetter) from the arguments.

What's the best practice for primary keys in tables?

I suspect Steven A. Lowe's rolled up newspaper therapy is required for the designer of the original data structure.

As an aside, GUIDs as a primary key can be a performance hog. I wouldn't recommend it.

How to do a GitHub pull request

I followed tim peterson's instructions but I created a local branch for my changes. However, after pushing I was not seeing the new branch in GitHub. The solution was to add -u to the push command:

git push -u origin <branch>

Shell Script — Get all files modified after <date>

as simple as:

find . -mtime -1 | xargs tar --no-recursion -czf myfile.tgz

where find . -mtime -1 will select all the files in (recursively) current directory modified day before. you can use fractions, for example:

find . -mtime -1.5 | xargs tar --no-recursion -czf myfile.tgz

fastest way to export blobs from table into individual files

For me what worked by combining all the posts I have read is:

1.Enable OLE automation - if not enabled

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

2.Create a folder where the generated files will be stored:

C:\GREGTESTING

3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
enter image description here

CREATE TABLE [dbo].[Document](
    [Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [Extension] [varchar](50) NULL,
    [FileName] [varchar](200) NULL,
    [Doc_Content] [varbinary](max) NULL   
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
    SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)

Important note!

Don't forget to add in Doc_Content column the varbinary of file you want to generate!

4.Run the below script

DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max) 
, @fPath varchar(max)  
, @folderPath  varchar(max)

--Get Data into temp Table variable so that we can iterate over it 
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num]  varchar(100) , [FileName]  varchar(100), [Doc_Content] varBinary(max) )



INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM  [dbo].[Document]



SELECT @i = COUNT(1) FROM @Doctable   

WHILE @i >= 1   

BEGIN    

SELECT 
    @data = [Doc_Content],
    @fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
    @folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;  
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+  @fPath   

--Reset the variables for next use
SELECT @data = NULL  
, @init = NULL
, @fPath = NULL  
, @folderPath = NULL
SET @i -= 1
END   

5.The results is shown below: enter image description here

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

Access key value from Web.config in Razor View-MVC3 ASP.NET

The preferred method is actually:

@System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"]

It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.

Start ssh-agent on login

Tried couple solutions from many sources but all seemed like too much trouble. Finally I found the easiest one :)

If you're not yet familiar with zsh and oh-my-zsh then install it. You will love it :)

Then edit .zshrc

vim ~/.zshrc

find plugins section and update it to use ssh-agent like so:

plugins=(ssh-agent git)

And that's all! You'll have ssh-agent up and running every time you start your shell

How can I add new keys to a dictionary?

The conventional syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could also do:

d.__setitem__(key, value)

In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php

How does one use glide to download an image into a bitmap?

This is what worked for me: https://github.com/bumptech/glide/wiki/Custom-targets#overriding-default-behavior

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

...

Glide.with(yourFragment)
  .load("yourUrl")
  .asBitmap()
  .into(new BitmapImageViewTarget(yourImageView) {
    @Override
    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> anim) {
        super.onResourceReady(bitmap, anim);
        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {  
            @Override
            public void onGenerated(Palette palette) {
                // Here's your generated palette
                Palette.Swatch swatch = palette.getDarkVibrantSwatch();
                int color = palette.getDarkVibrantColor(swatch.getTitleTextColor());
            }
        });
    }
});

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

How do I make curl ignore the proxy?

Add your proxy preferences into .curlrc

proxy = 1.2.3.4
noproxy = .dev,localhost,127.0.0.1

This make all dev domains and local machine request ignore the proxy.

How can I get session id in php and show it?

In the PHP file first you need to register the session

 <? session_start();
     $_SESSION['id'] = $userData['user_id'];?>

And in each page of your php application you can retrive the session id

 <? session_start()
    id =  $_SESSION['id'];
   ?>

How do I install Python libraries in wheel format?

To install wheel packages in python 2.7x:

  1. Install python 2.7x (i would recommend python 2.78) - download the appropriate python binary for your version of windows . You can download python 2.78 at this site https://www.python.org/download/releases/2.7.8/ -I would recommend installing the graphical Tk module, and including python 2.78 in the windows path (environment variables) during installation.

  2. Install get-pip.py and setuptools Download the installer at https://bootstrap.pypa.io/get-pip.py Double click the above file to run it. It will install pip and setuptools [or update them, if you have an earlier version of either]

-Double click the above file and wait - it will open a black window and print will scroll across the screen as it downloads and installs [or updates] pip and setuptools --->when it finishes the window will close.

  1. Open an elevated command prompt - click on windows start icon, enter cmd in the search field (but do not press enter), then press ctrl+shift+. Click 'yes' when the uac box appears.

A-type cd c:\python27\scripts [or cd \scripts ]

B-type pip install -u Eg to install pyside, type pip install -u pyside

Wait - it will state 'downloading PySide or -->it will download and install the appropriate version of the python package [the one that corresponds to your version of python and windows.]

Note - if you have downloaded the .whl file and saved it locally on your hard drive, type in
pip install --no-index --find-links=localpathtowheelfile packagename

**to install a previously downloaded wheel package you need to type in the following command pip install --no-index --find-links=localpathtowheelfile packagename

Markdown open a new window link

Using sed

If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:

sed -i 's|href="http|target="_blank" href="http|g' index.html

This can be further automated in a single workflow when a Makefile with build instructions is employed.

PS: This answer was written at a time when extension link_attributes was not yet available in Pandoc.

How to convert char* to wchar_t*?

You're returning the address of a local variable allocated on the stack. When your function returns, the storage for all local variables (such as wc) is deallocated and is subject to being immediately overwritten by something else.

To fix this, you can pass the size of the buffer to GetWC, but then you've got pretty much the same interface as mbstowcs itself. Or, you could allocate a new buffer inside GetWC and return a pointer to that, leaving it up to the caller to deallocate the buffer.

Check if element found in array c++

You can use old C-style programming to do the job. This will require little knowledge about C++. Good for beginners.

For modern C++ language you usually accomplish this through lambda, function objects, ... or algorithm: find, find_if, any_of, for_each, or the new for (auto& v : container) { } syntax. find class algorithm takes more lines of code. You may also write you own template find function for your particular need.

Here is my sample code

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>

using namespace std;

/**
 * This is old C-like style.  It is mostly gong from 
 * modern C++ programming.  You can still use this
 * since you need to know very little about C++.
 * @param storeSize you have to know the size of store
 *    How many elements are in the array.
 * @return the index of the element in the array,
 *   if not found return -1
 */
int in_array(const int store[], const int storeSize, const int query) {
   for (size_t i=0; i<storeSize; ++i) {
      if (store[i] == query) {
         return i;
      }
   }
   return -1;
}

void testfind() {
   int iarr[] = { 3, 6, 8, 33, 77, 63, 7, 11 };

   // for beginners, it is good to practice a looping method
   int query = 7;
   if (in_array(iarr, 8, query) != -1) {
      cout << query << " is in the array\n";
   }

   // using vector or list, ... any container in C++
   vector<int> vecint{ 3, 6, 8, 33, 77, 63, 7, 11 };
   auto it=find(vecint.begin(), vecint.end(), query);
   cout << "using find()\n";
   if (it != vecint.end()) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }

   using namespace std::placeholders;
   // here the query variable is bound to the `equal_to` function 
   // object (defined in std)
   cout << "using any_of\n";
   if (any_of(vecint.begin(), vecint.end(), bind(equal_to<int>(), _1, query))) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }

   // using lambda, here I am capturing the query variable
   // into the lambda function
   cout << "using any_of with lambda:\n";
   if (any_of(vecint.begin(), vecint.end(),
            [query](int val)->bool{ return val==query; })) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }
}

int main(int argc, char* argv[]) {
   testfind();

   return 0;
}

Say this file is named 'testalgorithm.cpp' you need to compile it with

g++ -std=c++11 -o testalgorithm testalgorithm.cpp

Hope this will help. Please update or add if I have made any mistake.

String to byte array in php

@Sparr is right, but I guess you expected byte array like byte[] in C#. It's the same solution as Sparr did but instead of HEX you expected int presentation (range from 0 to 255) of each char. You can do as follows:

$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array);  // $byte_array should be int[] which can be converted
                        // to byte[] in C# since values are range of 0 - 255

By using var_dump you can see that elements are int (not string).

   array(44) {  [1]=>  int(84)  [2]=>  int(104) [3]=>  int(101) [4]=>  int(32)
[5]=> int(113)  [6]=>  int(117) [7]=>  int(105) [8]=>  int(99)  [9]=>  int(107)
[10]=> int(32)  [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32)
[15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101)
[20]=> int(100) [21]=> int(32)  [22]=> int(111) [23]=> int(118) [24]=> int(101)
[25]=> int(114) [26]=> int(32)  [27]=> int(116) [28]=> int(104) [29]=> int(101)
[30]=> int(32)  [31]=> int(108) [32]=> int(97)  [33]=> int(122) [34]=> int(121)
[35]=> int(32)  [36]=> int(98)  [37]=> int(114) [38]=> int(111) [39]=> int(119)
[40]=> int(110) [41]=> int(32)  [42]=> int(100) [43]=> int(111) [44]=> int(103) }

Be careful: the output array is of 1-based index (as it was pointed out in the comment)

'invalid value encountered in double_scalars' warning, possibly numpy

Sometimes NaNs or null values in data will generate this error with Numpy. If you are ingesting data from say, a CSV file or something like that, and then operating on the data using numpy arrays, the problem could have originated with your data ingest. You could try feeding your code a small set of data with known values, and see if you get the same result.

How do I put double quotes in a string in vba?

I find the easiest way is to double up on the quotes to handle a quote.

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)" 

Some people like to use CHR(34)*:

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)" 

*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.

How to change background color in android app

  1. go to Activity_Main.xml
  2. there are design view / and text view .
  3. choose Text view
  4. write this code up:

    android:background="@color/colorAccent"
    

How do I combine 2 select statements into one?

I think that's what you're looking for:

SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*
FROM WorkItems t1
WHERE (TextField01, TimeStamp) IN(
  SELECT TextField01, MAX(TimeStamp)
  FROM WorkItems t2
  GROUP BY t2.TextField01
  )
AND TimeStamp > '2009-02-12 18:00:00'

If you're in Oracle or in MS SQL 2005 and above, then you could do:

SELECT *
FROM (
  SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*,
     ROW_NUMBER() OVER (PARTITION BY TextField01 ORDER BY TimeStamp DESC) AS rn
  FROM WorkItems t1
) to
WHERE rn = 1

, it's more efficient.

Grant SELECT on multiple tables oracle

If you want to grant to both tables and views try:

SELECT DISTINCT
    || OWNER
    || '.'
    || TABLE_NAME
    || ' to db_user;'
FROM
    ALL_TAB_COLS 
WHERE
    TABLE_NAME LIKE 'TABLE_NAME_%';

For just views try:

SELECT
    'grant select on '
    || OWNER
    || '.'
    || VIEW_NAME
    || ' to REPORT_DW;'
FROM
    ALL_VIEWS
WHERE
    VIEW_NAME LIKE 'VIEW_NAME_%';

Copy results and execute.

How can I mock an ES6 module import using Jest?

I've been able to solve this by using a hack involving import *. It even works for both named and default exports!

For a named export:

// dependency.js
export const doSomething = (y) => console.log(y)

// myModule.js
import { doSomething } from './dependency';

export default (x) => {
  doSomething(x * 2);
}

// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.doSomething = jest.fn(); // Mutate the named export

    myModule(2);

    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

Or for a default export:

// dependency.js
export default (y) => console.log(y)

// myModule.js
import dependency from './dependency'; // Note lack of curlies

export default (x) => {
  dependency(x * 2);
}

// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.default = jest.fn(); // Mutate the default export

    myModule(2);

    expect(dependency.default).toBeCalledWith(4); // Assert against the default
  });
});

As Mihai Damian quite rightly pointed out below, this is mutating the module object of dependency, and so it will 'leak' across to other tests. So if you use this approach you should store the original value and then set it back again after each test.

To do this easily with Jest, use the spyOn() method instead of jest.fn(), because it supports easily restoring its original value, therefore avoiding before mentioned 'leaking'.

How to test if JSON object is empty in Java

If JSON returned with following structure when records is an ArrayNode:

{}client 
  records[]

and you want to check if records node has something in it then you can do it using a method size();

if (recordNodes.get(i).size() != 0) {}

WPF Check box: Check changed handling

As a checkbox click = a checkbox change the following will also work:

<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    // ... do some stuff
}

It has the additional advantage of working when IsThreeState="True" whereas just handling Checked and Unchecked does not.

Maven dependencies are failing with a 501 error

I have the same issue, but I use GitLab instead of Jenkins. The steps I had to do to get over the issue:

  1. My project is in GitLab so it uses the .yml file which points to a Docker image I have to do continuous integration, and the image it uses has the http://maven URLs. So I changed that to https://maven.
  2. That same Dockerfile image had an older version of Maven 3.0.1 that gave me issues just overnight. I updated the Dockerfile to get the latest version 3.6.3
  3. I then deployed that image to my online repository, and updated my Maven project ymlfile to use that new image.
  4. And lastly, I updated my main projects POM file to reference https://maven... instead of http://maven

I realize that is more specific to my setup. But without doing all of the steps above I would still continue to get this error message Return code is: 501 , ReasonPhrase:HTTPS Required

Select Multiple Fields from List in Linq

public class Student
{
    public string Name { set; get; }
    public int ID { set; get; }
}

class Program
{
  static void Main(string[] args)
    {
        Student[] students =
        {
        new Student { Name="zoyeb" , ID=1},
        new Student { Name="Siddiq" , ID=2},
        new Student { Name="sam" , ID=3},
        new Student { Name="james" , ID=4},
        new Student { Name="sonia" , ID=5}
        };

        var studentCollection = from s in students select new { s.ID , s.Name};

        foreach (var student in studentCollection)
        {
            Console.WriteLine(student.Name);
            Console.WriteLine(student.ID);
        }
    }
}

SQL, How to Concatenate results?

With MSSQL you can do something like this:

declare @result varchar(500)
set @result = ''
select @result = @result + ModuleValue + ', ' 
from TableX where ModuleId = @ModuleId

Convert Datetime column from UTC to local time in select statement

First function: configured for italian time zone (+1, +2), switch dates: last sunday of march and october, return the difference between the current time zone and the datetime as parameter.

Returns:
current timezone < parameter timezone ==> +1
current timezone > parameter timezone ==> -1
else 0

The code is:

CREATE FUNCTION [dbo].[UF_ADJUST_OFFSET]
(
    @dt_utc datetime2(7)
)
RETURNS INT
AS
BEGIN


declare @month int,
        @year int,
        @current_offset int,
        @offset_since int,
        @offset int,
        @yearmonth varchar(8),
        @changeoffsetdate datetime2(7)

declare @lastweek table(giorno datetime2(7))

select @current_offset = DATEDIFF(hh, GETUTCDATE(), GETDATE())

select @month = datepart(month, @dt_utc)

if @month < 3 or @month > 10 Begin Set @offset_since = 1 Goto JMP End

if @month > 3 and @month < 10 Begin Set @offset_since = 2 Goto JMP End

--If i'm here is march or october
select @year = datepart(yyyy, @dt_utc)

if @month = 3
Begin

Set @yearmonth = cast(@year as varchar) + '-03-'

Insert Into @lastweek Values(@yearmonth + '31 03:00:00.000000'),(@yearmonth + '30 03:00:00.000000'),(@yearmonth + '29 03:00:00.000000'),(@yearmonth + '28 03:00:00.000000'),
                         (@yearmonth + '27 03:00:00.000000'),(@yearmonth + '26 03:00:00.000000'),(@yearmonth + '25 03:00:00.000000')

--Last week of march
Select @changeoffsetdate = giorno From @lastweek Where  datepart(weekday, giorno) = 1

    if @dt_utc < @changeoffsetdate 
    Begin 
        Set @offset_since = 1 
    End Else Begin
        Set @offset_since = 2
    End
End

if @month = 10
Begin

Set @yearmonth = cast(@year as varchar) + '-10-'

Insert Into @lastweek Values(@yearmonth + '31 03:00:00.000000'),(@yearmonth + '30 03:00:00.000000'),(@yearmonth + '29 03:00:00.000000'),(@yearmonth + '28 03:00:00.000000'),
                         (@yearmonth + '27 03:00:00.000000'),(@yearmonth + '26 03:00:00.000000'),(@yearmonth + '25 03:00:00.000000')

--Last week of october
Select @changeoffsetdate = giorno From @lastweek Where  datepart(weekday, giorno) = 1

    if @dt_utc > @changeoffsetdate 
    Begin 
        Set @offset_since = 1 
    End Else Begin
        Set @offset_since = 2
    End
End

JMP:

if @current_offset < @offset_since Begin
    Set @offset = 1
End Else if @current_offset > @offset_since Set @offset = -1 Else Set @offset = 0

Return @offset

END

Then the function that convert date

CREATE FUNCTION [dbo].[UF_CONVERT]
(
    @dt_utc datetime2(7)
)
RETURNS datetime
AS
BEGIN

    declare @offset int


    Select @offset = dbo.UF_ADJUST_OFFSET(@dt_utc)

    if @dt_utc >= '9999-12-31 22:59:59.9999999'
        set @dt_utc = '9999-12-31 23:59:59.9999999'
    Else
        set @dt_utc = (SELECT DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), GETDATE()), @dt_utc) )

    if @offset <> 0
        Set @dt_utc = dateadd(hh, @offset, @dt_utc)

    RETURN @dt_utc

END

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

Creating a simple XML file using python

For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

For a Jinja example, see my answer to a similar question.

Here is an example of generating your xml with string templates.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

Output:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

I recently had this issue and I ran 'depends.exe' on the dll in question. It showed me that the dll was compiled in x86 while some of the dependencys were compiled in x64.

If you are still having troubles I would recommend using depends.exe.

How to create a bash script to check the SSH connection?

You can check this with the return-value ssh gives you:

$ ssh -q user@downhost exit
$ echo $?
255

$ ssh -q user@uphost exit
$ echo $?
0

EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):

$ a=`nmap uphost -PN -p ssh | grep open`
$ b=`nmap downhost -PN -p ssh | grep open`

$ echo $a
22/tcp open ssh
$ echo $b
(empty string)

But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).

EDIT2:

If you're interested in the actual state of the ssh-port, you can substitute grep open with egrep 'open|closed|filtered':

$ nmap host -PN -p ssh | egrep 'open|closed|filtered'

Just to be complete.

Why is NULL undeclared?

Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib

#include <stdlib.h>

or

#include <cstdlib>  // This is preferrable for c++

How to check if a service is running via batch file and start it, if it is not running?

That should do it:

FOR %%a IN (%Svcs%) DO (SC query %%a | FIND /i "RUNNING"
IF ERRORLEVEL 1 SC start %%a)

sort dict by value python

You could created sorted list from Values and rebuild the dictionary:

myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}

newDictionary={}

sortedList=sorted(myDictionary.values())

for sortedKey in sortedList:
    for key, value in myDictionary.items():
        if value==sortedKey:
            newDictionary[key]=value

Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}

Delete entire row if cell contains the string X

Ok I know this for VBA but if you need to do this for a once off bulk delete you can use the following Excel functionality: http://blog.contextures.com/archives/2010/06/21/fast-way-to-find-and-delete-excel-rows/ Hope this helps anyone

Example looking for the string "paper":

  1. In the Find and Replace dialog box, type "paper" in the Find What box.
  2. Click Find All, to see a list of cells with "paper"
  3. Select an item in the list, and press Ctrl+A, to select the entire list, and to select all the "paper" cells on the worksheet.
  4. On the Ribbon's Home tab, click Delete, and then click Delete Sheet Rows.

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>

In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.

// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];   
for (i=0; i < cacheBust.length; i++){
     var el = document.createElement('script');
     el.src = cacheBust[i]+"?v=" + Math.random();
     document.getElementsByTagName('head')[0].appendChild(el);
}

How to make multiple divs display in one line but still retain width?

You can use float:left in DIV or use SPAN tag, like

<div style="width:100px;float:left"> First </div> 
<div> Second </div> 
<br/>

or

<span style="width:100px;"> First </span> 
<span> Second </span> 
<br/>

How to add elements of a string array to a string array list?

In Java 8, the syntax for this simplifies greatly and can be used to accomplish this transformation succinctly.

Do note, you will need to change your field from a concrete implementation to the List interface for this to work smoothly.

public class Wetland {
    private String name;
    private List<String> species;
    public Wetland(String name, String[] speciesArr) {
        this.name = name;
        species = Arrays.stream(speciesArr)
                        .collect(Collectors.toList());
    }
}

How to write JUnit test with Spring Autowire?

Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;

Also this looks wierd to me :

@ContextConfiguration("classpath*:conf/components.xml")

Here is an example that works fine for me :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {

    @Autowired
    OwnerService ownerService;

    @Before
    public void setup() {

        ownerService.cleanList();

    }

    @Test
    public void testOwners() {

        Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
        owner = ownerService.createOwner(owner);
        assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
        assertTrue("Check that Id exist: ", owner.getId() > 0);

        owner.setLastName("Larsson");
        ownerService.updateOwner(owner);
        owner = ownerService.getOwner(owner.getId());
        assertEquals("Name is changed", "Larsson", owner.getLastName());

    }

SQL query for getting data for last 3 months

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE()) 

Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column.

or you can check against last 90 days.

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE()) 

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Here's a good post that shows how to do it.

If you want to read the values from a file other than the app.config, you need to load it into the ConfigurationManager.

Try this method: ConfigurationManager.OpenMappedExeConfiguration()

There's an example of how to use it in the MSDN article.

c# datatable insert column at position 0

Just to improve Wael's answer and put it on a single line:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

When does System.gc() do something?

Normally, the VM would do a garbage collection automatically before throwing an OutOfMemoryException, so adding an explicit call shouldn't help except in that it perhaps moves the performance hit to an earlier moment in time.

However, I think I encountered a case where it might be relevant. I'm not sure though, as I have yet to test whether it has any effect:

When you memory-map a file, I believe the map() call throws an IOException when a large enough block of memory is not available. A garbage collection just before the map() file might help prevent that, I think. What do you think?

How to Display Multiple Google Maps per page with API V3

Take a Look at this Bundle for Laravel that I Made Recently !


https://github.com/Maghrooni/googlemap

it helps you to create one or multiple maps in your page !

you can find the class on

src/googlemap.php

Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page

Re-doing a reverted merge in Git

You have to "revert the revert". Depending on you how did the original revert, it may not be as easy as it sounds. Look at the official document on this topic.

---o---o---o---M---x---x---W---x---Y
              /
      ---A---B-------------------C---D

to allow:

---o---o---o---M---x---x-------x-------*
              /                       /
      ---A---B-------------------C---D

But does it all work? Sure it does. You can revert a merge, and from a purely technical angle, git did it very naturally and had no real troubles.
It just considered it a change from "state before merge" to "state after merge", and that was it.
Nothing complicated, nothing odd, nothing really dangerous. Git will do it without even thinking about it.

So from a technical angle, there's nothing wrong with reverting a merge, but from a workflow angle it's something that you generally should try to avoid.

If at all possible, for example, if you find a problem that got merged into the main tree, rather than revert the merge, try really hard to:

  • bisect the problem down into the branch you merged, and just fix it,
  • or try to revert the individual commit that caused it.

Yes, it's more complex, and no, it's not always going to work (sometimes the answer is: "oops, I really shouldn't have merged it, because it wasn't ready yet, and I really need to undo all of the merge"). So then you really should revert the merge, but when you want to re-do the merge, you now need to do it by reverting the revert.

How to increase font size in the Xcode editor?

Easisest solution:

  1. Close any open projects.

  2. Xcode > Preferences > Font & Colors

  3. Make sure to press CMD+A to select all possible text types. Then change the font size from the picker.

enter image description here

Pass array to ajax request in $.ajax()

Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:

$.ajax({
    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){
        $('.answer').html(msg);
    }
});

You just need to make sure you include the JSON2.js file in your page...

"static const" vs "#define" vs "enum"

It depends on what you need the value for. You (and everyone else so far) omitted the third alternative:

  1. static const int var = 5;
  2. #define var 5
  3. enum { var = 5 };

Ignoring issues about the choice of name, then:

  • If you need to pass a pointer around, you must use (1).
  • Since (2) is apparently an option, you don't need to pass pointers around.
  • Both (1) and (3) have a symbol in the debugger's symbol table - that makes debugging easier. It is more likely that (2) will not have a symbol, leaving you wondering what it is.
  • (1) cannot be used as a dimension for arrays at global scope; both (2) and (3) can.
  • (1) cannot be used as a dimension for static arrays at function scope; both (2) and (3) can.
  • Under C99, all of these can be used for local arrays. Technically, using (1) would imply the use of a VLA (variable-length array), though the dimension referenced by 'var' would of course be fixed at size 5.
  • (1) cannot be used in places like switch statements; both (2) and (3) can.
  • (1) cannot be used to initialize static variables; both (2) and (3) can.
  • (2) can change code that you didn't want changed because it is used by the preprocessor; both (1) and (3) will not have unexpected side-effects like that.
  • You can detect whether (2) has been set in the preprocessor; neither (1) nor (3) allows that.

So, in most contexts, prefer the 'enum' over the alternatives. Otherwise, the first and last bullet points are likely to be the controlling factors — and you have to think harder if you need to satisfy both at once.

If you were asking about C++, then you'd use option (1) — the static const — every time.

How to get milliseconds from LocalDateTime in Java 8

To get the current time in milliseconds (since the epoch), use System.currentTimeMillis().

How do I find the current machine's full hostname in C (hostname and domain information)?

The easy way, try uname()

If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()

The h_name of hostent{} should be your FQDN

String to HtmlDocument

Using Html Agility Pack as suggested by SLaks, this becomes very easy:

string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);

HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");

AlertDialog styling - how to change style (color) of title, message, etc

I changed color programmatically in this way :

var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);

as alertTitle, you can change other data by this way (next example is for titleDivider):

int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);

this is in C#, but in java it is the same.

Pandas get the most frequent values of a column

To get the top five most common names:

dataframe['name'].value_counts().head()

Create mysql table directly from CSV file using the CSV Storage engine?

I'm recommended use MySQL Workbench where is import data. Workbench allows the user to create a new table from a file in CSV or JSON format. It handles table schema and data import in just a few clicks through the wizard.

In MySQL Workbench, use the context menu on table list and click Table Data Import Wizard.

MySQL Workbench image

More from the MySQL Workbench 6.5.1 Table Data Export and Import Wizard documentation. Download MySQL Workbench here.

Python variables as keys to dict

Not the most elegant solution, and only works 90% of the time:

def vardict(*args):
    ns = inspect.stack()[1][0].f_locals
    retval = {}
    for a in args:
        found = False
        for k, v in ns.items():
            if a is v:
                retval[k] = v
                if found:
                    raise ValueError("Value found in more than one local variable: " + str(a))
                found = True
        if found:
            continue
        if 'self' in ns:
            for k, v in ns['self'].__dict__.items():
                if a is v:
                    retval[k] = v
                    if found:
                        raise ValueError("Value found in more than one instance attribute: " + str(a))
                    found = True
        if found:
            continue
        for k, v in globals().items():
            if a is v:
                retval[k] = v
                if found:
                    raise ValueError("Value found in more than one global variable: " + str(a))
                found = True
        assert found, "Couldn't find one of the parameters."
    return retval

You'll run into problems if you store the same reference in multiple variables, but also if multiple variables store the same small int, since these get interned.

Angular no provider for NameService

add your service to providers[] array in app.module.ts file. Like below

// here my service is CarService

app.module.ts

import {CarsService} from './cars.service';

providers: [CarsService] // you can include as many services you have 

How do I return a proper success/error message for JQuery .ajax() using PHP?

In order to build an AJAX webservice, you need TWO files :

  • A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
  • A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)

So, first you call your webservice using this JQuery syntax, in the JavaScript file :

$.ajax({
     url : 'mywebservice.php',
     type : 'POST',
     data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
     dataType : 'json',
     success: function (data) {
          alert("The file is "+data.fichierZIP);
     },
     error: function(data) {
          //console.log(data);
          var responseText=JSON.parse(data.responseText);
          alert("Error(s) while building the ZIP file:\n"+responseText.messages);
     }
});

Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:

<?php
    //...
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
    //$errors is a string that may contain an error message while preparing the ZIP file
    //In the end, I check if there has been an error, and if so, I return an error object
    //...

    if ($errors==''){
        //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['ZIPFILENAME'] = basename($filename); 
        print json_encode($result);
    } else {
        //if there is an error, you should return a special header, followed by another JSON object
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['messages'] = $errors;
        //feel free to add other information like $result['errorcode']
        die(json_encode($result));
    }
?>

When do I have to use interfaces instead of abstract classes?

From Java How to Program about abstract classes:

Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.

To answer your question "What is the reason to use interfaces?":

An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.

As opposed to an interface:

An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.

So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)

Jest spyOn function called

In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:

1) Where the click handler calls a function passed as a prop, e.g.

class App extends Component {

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.props.someCallback();
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now pass in a spy function as a prop to the component, and assert that it is called:

describe('my sweet test', () => {
 it('clicks it', () => {
    const spy = jest.fn();
    const app = shallow(<App someCallback={spy} />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

2) Where the click handler sets some state on the component, e.g.

class App extends Component {
  state = {
      aProperty: 'first'
  }

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.setState({
          aProperty: 'second'
      });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now make assertions about the state of the component, i.e.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(app.state('aProperty')).toEqual('second');
 })
})

How to run a makefile in Windows?

With Visual Studio 2017 I had to add this folder to my Windows 10 path env variable:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.10.25017\bin\HostX64\x64

There's also HostX86

How to delete last item in list?

list.pop() removes and returns the last element of the list.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

For all that you add xmlbeans-2.3.0.jar and it is not working,you must use HSSFWorkbook instead of XSSFWorkbook after add jar.For instance;

    Workbook workbook = new HSSFWorkbook();
    Sheet listSheet = workbook.createSheet("Kisi Listesi");

    int rowIndex = 0;
    for (KayitParam kp : kayitList) {
        Row row = listSheet.createRow(rowIndex++);
        int cellIndex = 0;
        row.createCell(cellIndex++).setCellValue(kp.getAd());
        row.createCell(cellIndex++).setCellValue(kp.getSoyad());
        row.createCell(cellIndex++).setCellValue(kp.getEposta());
        row.createCell(cellIndex++).setCellValue(kp.getCinsiyet());
        row.createCell(cellIndex++).setCellValue(kp.getDogumtarihi());
        row.createCell(cellIndex++).setCellValue(kp.getTahsil());
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        AMedia amedia = new AMedia("Kisiler.xls", "xls",
                "application/file", baos.toByteArray());
        Filedownload.save(amedia);
        baos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

How to use Utilities.sleep() function

Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.

Here is an example :

function delsheets(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
  for (pa=numbofsheet-1;pa>0;--pa){ 
    ss.setActiveSheet(ss.getSheets()[pa]);
    var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
    Utilities.sleep(200);// pause in the loop for 200 milliseconds
  }
  ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

For a div-Element you could just set the opacity via a class to enable or disable the effect.

.mute-all {
   opacity: 0.4;
}

C# Generics and Type Checking

How about this :

            // Checks to see if the value passed is valid. 
            if (!TypeDescriptor.GetConverter(typeof(T)).IsValid(value))
            {
                throw new ArgumentException();
            }

WPF Button with Image

This should do the job, no?

<Button Content="Test">
    <Button.Background>
        <ImageBrush ImageSource="folder/file.PNG"/>
    </Button.Background>
</Button>

Change navbar text color Bootstrap

Try this in your css:

#ntext{
 color: #000000;
  }

Then the following in all your navigation bar list codes:

<li><a href="#" id="ntext"><span class="glyphicon glyphicon-user"></span> About</a></li>

Creating folders inside a GitHub repository without using Git

When creating a file, use slashes to specify the directory. For example:

Name the file:

repositoryname/newfoldername/filename

GitHub will automatically create a folder with the name newfoldername.

Print string to text file

With using pathlib module, indentation isn't needed.

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

As of python 3.6, f-strings is available.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")

Javascript - How to show escape characters in a string?

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

Using SimpleXML to create an XML object from scratch

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());

move_uploaded_file gives "failed to open stream: Permission denied" error

If you have Mac OS X, go to the file root or the folder of your website.

Then right-hand click on it, go to get information, go to the very bottom (Sharing & Permissions), open that, change all read-only to read and write. Make sure to open padlock, go to setting icon, and choose Apply to the enclosed items...

Spring Boot not serving static content

using spring boot 2.*, i have a controller that maps to routes GetMapping({"/{var}", "/{var1}/{var2}", "/{var1}/{var2}/{var3}"}) and boom my app stop serving resources.

i know it is not advisable to have such routes but it all depends on the app you are building (in my case, i have no choice but to have such routes)

so here is my hack to make sure my app serve resources again. I simply have a controller that maps to my resources. since spring will match a direct route first before any that has variable, i decided to add a controller method that maps to /imgaes/{name} and repeated same for other resources

@GetMapping(value = "/images/{image}", produces = {MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public @ResponseBody
    byte[] getImage(@PathVariable String image) {
        ClassPathResource file = new ClassPathResource("static/images/" + image);
        byte[] bytes;
        try {
            bytes = StreamUtils.copyToByteArray(file.getInputStream());
        } catch (IOException e) {
            throw new ResourceNotFoundException("file not found: " + image);
        }
        return bytes;
    }

and this solved my issue

How do I install ASP.NET MVC 5 in Visual Studio 2012?

You can use Visual Studio 2012.

Simply update your NuGet package in Visual Studio to Microsoft.AspNet.Mvc 5.0.

You may have to search pre-release.

Also the default project comes with Entity Framework 6.0, and ASP.NET Razor 3.0.

You may also need ASP.NET Identity Core and OWIN.

All of these can be downloaded/updated through menu Tools ? Library package manager ? Manage NuGet Packages for Solution....

If you don't yet have NuGet, follow this tutorial:

http://docs.nuget.org/docs/start-here/installing-nuget

How to include *.so library in Android Studio?

Current Solution

Create the folder project/app/src/main/jniLibs, and then put your *.so files within their abi folders in that location. E.g.,

project/
+--libs/
|  +-- *.jar       <-- if your library has jar files, they go here
+--src/
   +-- main/
       +-- AndroidManifest.xml
       +-- java/
       +-- jniLibs/ 
           +-- arm64-v8a/                       <-- ARM 64bit
           ¦   +-- yourlib.so
           +-- armeabi-v7a/                     <-- ARM 32bit
           ¦   +-- yourlib.so
           +-- x86/                             <-- Intel 32bit
               +-- yourlib.so

Deprecated solution

Add both code snippets in your module gradle.build file as a dependency:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

How to create this custom jar:

task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

Same answer can also be found in related question: Include .so library in apk in android studio

How do I get a reference to the app delegate in Swift?

  1. Make sure you import UIKit

  2. let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate

Save image from url with curl PHP

try this:

function grab_image($url,$saveto){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $raw=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($saveto)){
        unlink($saveto);
    }
    $fp = fopen($saveto,'x');
    fwrite($fp, $raw);
    fclose($fp);
}

and ensure that in php.ini allow_url_fopen is enable

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

How to get resources directory path programmatically

import org.springframework.core.io.ClassPathResource;

...

File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();

It is worth noting that this will limit your deployment options, ClassPathResource.getFile() only works if the container has exploded (unzipped) your war file.

How to serve .html files with Spring

I faced the same issue and tried various solutions to load the html page from Spring MVC, following solution worked for me

Step-1 in server's web.xml comment these two lines

<!--     <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>--> 
<!--     <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
 -->

Step-2 enter following code in application's web xml

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

Step-3 create a static controller class

@Controller 
public class FrontController {
     @RequestMapping("/landingPage") 
    public String getIndexPage() { 
    return "CompanyInfo"; 

    }

}

Step-4 in the Spring configuration file change the suffix to .htm .htm

Step-5 Rename page as .htm file and store it in WEB-INF and build/start the server

localhost:8080/.../landingPage

How do you use a variable in a regular expression?

"ABABAB".replace(/B/g, "A");

As always: don't use regex unless you have to. For a simple string replace, the idiom is:

'ABABAB'.split('B').join('A')

Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.

Best lightweight web server (only static content) for Windows

Consider thttpd. It can run under windows.

Quoting wikipedia:

"it is uniquely suited to service high volume requests for static data"

A version of thttpd-2.25b compiled under cygwin with cygwin dll's is available. It is single threaded and particularly good for servicing images.

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.

mysql  Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using  EditLine wrapper

Connection id:      12
Current database:   xxx
Current user:       yo@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/run/mysqld/mysqld.sock
Uptime:         42 min 49 sec

Threads: 1  Questions: 372  Slow queries: 0  Opens: 166  Flush tables: 1  Open tables: 30  Queries per second avg: 0.144

so, I look up the column charset in every table

show create table company;

It turns out the column charset is latin. That's why, I can not insert Chinese into database.

 ALTER TABLE company CONVERT TO CHARACTER SET utf8;

That might help you. :)

How to delete row in gridview using rowdeleting event?

If I remember from your previous questions, you're binding to a DataTable. Try this:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    DataTable sourceData = (DataTable)GridView1.DataSource;

    sourceData.Rows[e.RowIndex].Delete();

    GridVie1.DataSource = sourceData;
    GridView1.DataBind();
}

Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.

SFTP in Python? (platform independent)

PyFilesystem with its sshfs is one option. It uses Paramiko under the hood and provides a nicer paltform independent interface on top.

import fs

sf = fs.open_fs("sftp://[user[:password]@]host[:port]/[directory]")
sf.makedir('my_dir')

or

from fs.sshfs import SSHFS
sf = SSHFS(...

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

My solution was to insert <packaging>pom</packaging> between artifactId and version

<groupId>com.onlinechat</groupId>
<artifactId>chat-online</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
    <module>server</module>
    <module>client</module>
    <module>network</module>
</modules>

Asyncio.gather vs asyncio.wait

A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.


I'll use this example to simulate a coroutine that will raise exceptions, sometimes -

import asyncio
import random


async def a_flaky_tsk(i):
    await asyncio.sleep(i)  # bit of fuzz to simulate a real-world example

    if i % 2 == 0:
        print(i, "ok")
    else:
        print(i, "crashed!")
        raise ValueError

coros = [a_flaky_tsk(i) for i in range(10)]

await asyncio.gather(*coros) outputs -

0 ok
1 crashed!
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
    asyncio.run(main())
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
    await asyncio.gather(*coros)
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

As you can see, the coros after index 1 never got to execute.


But await asyncio.wait(coros) continues to execute tasks, even if some of them fail -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

Ofcourse, this behavior can be changed for both by using -

asyncio.gather(..., return_exceptions=True)

or,

asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)


But it doesn't end here!

Notice: Task exception was never retrieved in the logs above.

asyncio.wait() won't re-raise exceptions from the child tasks until you await them individually. (The stacktrace in the logs are just messages, they cannot be caught!)

done, pending = await asyncio.wait(coros)
for tsk in done:
    try:
        await tsk
    except Exception as e:
        print("I caught:", repr(e))

Output -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()

On the other hand, to catch exceptions with asyncio.gather(), you must -

results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
    if isinstance(result_or_exc, Exception):
        print("I caught:", repr(result_or_exc))

(Same output as before)

Pushing empty commits to remote

As long as you clearly reference the other commit from the empty commit it should be fine. Something like:

Commit message errata for [commit sha1]

[new commit message]

As others have pointed out, this is often preferable to force pushing a corrected commit.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I had the same problem just with switching the background images with reasonable sizes. I got better results with setting the ImageView to null before putting in a new picture.

ImageView ivBg = (ImageView) findViewById(R.id.main_backgroundImage);
ivBg.setImageDrawable(null);
ivBg.setImageDrawable(getResources().getDrawable(R.drawable.new_picture));

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

Sending an Intent to browser to open specific URL

Use following snippet in your code

Intent newIntent = new Intent(Intent.ACTION_VIEW, 
Uri.parse("https://www.google.co.in/?gws_rd=cr"));
startActivity(newIntent);

Use This link

http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

The final solution to your assembly redirect errors

Okay, hopefully this should help resolve any (sane) assembly reference discrepancies ...

  1. Check the error.

Surf to the website

  1. Check web.config after the assembly redirect. Create one if not exists.

Existing web.config assembly redirect

  1. Right-click the reference for the assembly and choose Properties.

Assembly in the Reference list, in the relevant project

  1. Check the Version (not Runtime version) in the Properties table. Copy that.

Properties table showing Version of assembly

  1. Paste into the newVersion attribute.

web.config assembly redirect with updated newVersion

  1. For convenience, change the last part of the oldVersion to something high, round and imaginary.

web.config assembly redirect with updated oldVersion

Rejoice.

Removing elements with Array.map in JavaScript

Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend checking that out if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece, and also give a JSperf comparison at the end, going over speed considerations.

That said, The tl;dr is this: To accomplish what you're asking for (filtering and mapping within one function call), you would use Array.reduce().

However, the more readable and (less importantly) usually significantly faster2 approach is to just use filter and map chained together:

[1,2,3].filter(num => num > 2).map(num => num * 2)

What follows is a description of how Array.reduce() works, and how it can be used to accomplish filter and map in one iteration. Again, if this is too condensed, I highly recommend seeing the blog post linked above, which is a much more friendly intro with clear examples and progression.


You give reduce an argument that is a (usually anonymous) function.

That anonymous function takes two parameters--one (like the anonymous functions passed in to map/filter/forEach) is the iteratee to be operated on. There is another argument for the anonymous function passed to reduce, however, that those functions do not accept, and that is the value that will be passed along between function calls, often referred to as the memo.

Note that while Array.filter() takes only one argument (a function), Array.reduce() also takes an important (though optional) second argument: an initial value for 'memo' that will be passed into that anonymous function as its first argument, and subsequently can be mutated and passed along between function calls. (If it is not supplied, then 'memo' in the first anonymous function call will by default be the first iteratee, and the 'iteratee' argument will actually be the second value in the array)

In our case, we'll pass in an empty array to start, and then choose whether to inject our iteratee into our array or not based on our function--this is the filtering process.

Finally, we'll return our 'array in progress' on each anonymous function call, and reduce will take that return value and pass it as an argument (called memo) to its next function call.

This allows filter and map to happen in one iteration, cutting down our number of required iterations in half--just doing twice as much work each iteration, though, so nothing is really saved other than function calls, which are not so expensive in javascript.

For a more complete explanation, refer to MDN docs (or to my post referenced at the beginning of this answer).

Basic example of a Reduce call:

let array = [1,2,3];
const initialMemo = [];

array = array.reduce((memo, iteratee) => {
    // if condition is our filter
    if (iteratee > 1) {
        // what happens inside the filter is the map
        memo.push(iteratee * 2); 
    }

    // this return value will be passed in as the 'memo' argument
    // to the next call of this function, and this function will have
    // every element passed into it at some point.
    return memo; 
}, initialMemo)

console.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)]

more succinct version:

[1,2,3].reduce((memo, value) => value > 1 ? memo.concat(value * 2) : memo, [])

Notice that the first iteratee was not greater than one, and so was filtered. Also note the initialMemo, named just to make its existence clear and draw attention to it. Once again, it is passed in as 'memo' to the first anonymous function call, and then the returned value of the anonymous function is passed in as the 'memo' argument to the next function.

Another example of the classic use case for memo would be returning the smallest or largest number in an array. Example:

[7,4,1,99,57,2,1,100].reduce((memo, val) => memo > val ? memo : val)
// ^this would return the largest number in the list.

An example of how to write your own reduce function (this often helps understanding functions like these, I find):

test_arr = [];

// we accept an anonymous function, and an optional 'initial memo' value.
test_arr.my_reducer = function(reduceFunc, initialMemo) {
    // if we did not pass in a second argument, then our first memo value 
    // will be whatever is in index zero. (Otherwise, it will 
    // be that second argument.)
    const initialMemoIsIndexZero = arguments.length < 2;

    // here we use that logic to set the memo value accordingly.
    let memo = initialMemoIsIndexZero ? this[0] : initialMemo;

    // here we use that same boolean to decide whether the first
    // value we pass in as iteratee is either the first or second
    // element
    const initialIteratee = initialMemoIsIndexZero ? 1 : 0;

    for (var i = initialIteratee; i < this.length; i++) {
        // memo is either the argument passed in above, or the 
        // first item in the list. initialIteratee is either the
        // first item in the list, or the second item in the list.
           memo = reduceFunc(memo, this[i]);
        // or, more technically complete, give access to base array
        // and index to the reducer as well:
        // memo = reduceFunc(memo, this[i], i, this);
    }

    // after we've compressed the array into a single value,
    // we return it.
    return memo;
}

The real implementation allows access to things like the index, for example, but I hope this helps you get an uncomplicated feel for the gist of it.

How can I make my own event in C#?

Here's an example of creating and using an event with C#

using System;

namespace Event_Example
{
    //First we have to define a delegate that acts as a signature for the
    //function that is ultimately called when the event is triggered.
    //You will notice that the second parameter is of MyEventArgs type.
    //This object will contain information about the triggered event.
    public delegate void MyEventHandler(object source, MyEventArgs e);

    //This is a class which describes the event to the class that recieves it.
    //An EventArgs class must always derive from System.EventArgs.
    public class MyEventArgs : EventArgs
    {
        private string EventInfo;
        public MyEventArgs(string Text)
        {
            EventInfo = Text;
        }
        public string GetInfo()
        {
            return EventInfo;
        }
    }

    //This next class is the one which contains an event and triggers it
    //once an action is performed. For example, lets trigger this event
    //once a variable is incremented over a particular value. Notice the
    //event uses the MyEventHandler delegate to create a signature
    //for the called function.
    public class MyClass
    {
        public event MyEventHandler OnMaximum;
        private int i;
        private int Maximum = 10;
        public int MyValue
        {
            get
            {
                return i;
            }
            set
            {
                if(value <= Maximum)
                {
                    i = value;
                }
                else
                {
                    //To make sure we only trigger the event if a handler is present
                    //we check the event to make sure it's not null.
                    if(OnMaximum != null)
                    {
                        OnMaximum(this, new MyEventArgs("You've entered " +
                            value.ToString() +
                            ", but the maximum is " +
                            Maximum.ToString()));
                    }
                }
            }
        }
    }

    class Program
    {
        //This is the actual method that will be assigned to the event handler
        //within the above class. This is where we perform an action once the
        //event has been triggered.
        static void MaximumReached(object source, MyEventArgs e)
        {
            Console.WriteLine(e.GetInfo());
        }

        static void Main(string[] args)
        {
            //Now lets test the event contained in the above class.
            MyClass MyObject = new MyClass();
            MyObject.OnMaximum += new MyEventHandler(MaximumReached);

            for(int x = 0; x <= 15; x++)
            {
                MyObject.MyValue = x;
            }

            Console.ReadLine();
        }
    }
}

How to auto-remove trailing whitespace in Eclipse?

I am not aware of any solution for the second part of your question. The reason is that it is not clear how to define I changed. Changed when? Just between 2 saves or between commits... Basically - forget it.

I assume you would like to stick to some guideline, but do not touch the rest of the code. But the guideline should be used overall, and not for bites and pieces. So my suggestion is - change all the code to the guideline: it is once-off operation, but make sure that all your developers have the same plugin (AnyEdit) with the same settings for the project.

Javascript ajax call on page onload

It's even easier to do without a library

window.onload = function() {
    // code
};

Preferred way of getting the selected item of a JComboBox

String x = JComboBox.getSelectedItem().toString();

will convert any value weather it is Integer, Double, Long, Short into text on the other hand,

String x = String.valueOf(JComboBox.getSelectedItem());

will avoid null values, and convert the selected item from object to string

make: *** [ ] Error 1 error

From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.

‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.

So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.

Intellij IDEA Java classes not auto compiling on save

You can keymap ctrl+s to save AND compile in one step. Go to the keymap settings and search for Compile.

Difference between Return and Break statements

break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.

error: cast from 'void*' to 'int' loses precision

You can cast it to an intptr_t type. It's an int type guaranteed to be big enough to contain a pointer. Use #include <cstdint> to define it.

How to use OpenSSL to encrypt/decrypt files?

To Encrypt:

$ openssl bf < arquivo.txt > arquivo.txt.bf

To Decrypt:

$ openssl bf -d < arquivo.txt.bf > arquivo.txt

bf === Blowfish in CBC mode

Vertical divider CSS

<div class="headerdivider"></div>

and

.headerdivider {
    border-left: 1px solid #38546d;
    background: #16222c;
    width: 1px;
    height: 80px;
    position: absolute;
    right: 250px;
    top: 10px;
}

Check if a JavaScript string is a URL

If you can change the input type, I think this solution would be much easier:

You can simple use type="url" in your input and the check it with checkValidity() in js

E.g:

your.html

<input id="foo" type="url">

your.js

// The selector is JQuery, but the function is plain JS
$("#foo").on("keyup", function() {
    if (this.checkValidity()) {
        // The url is valid
    } else {
        // The url is invalid
    }
});

npm WARN package.json: No repository field

Have you run npm init? That command runs you through everything...

Using Apache httpclient for https

This is what worked for me:

    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
    try {
        keyStore.load(instream, "password".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, "password".toCharArray())
        //.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
        .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
    CloseableHttpClient httpclient = HttpClients.custom()
        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
        .setSSLSocketFactory(sslsf)
        .build();
    try {

        HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

C# Remove object from list of objects

There are two problems with this code:

  • Capacity represents the number of items the list can contain before resizing is required, not the actual count; you need to use Count instead, and
  • When you remove from the list, you should go backwards, otherwise you could skip the second item when two identical items are next to each other.

Parse an HTML string with JS

EDIT: The solution below is only for HTML "fragments" since html,head and body are removed. I guess the solution for this question is DOMParser's parseFromString() method.


For HTML fragments, the solutions listed here works for most HTML, however for certain cases it won't work.

For example try parsing <td>Test</td>. This one won't work on the div.innerHTML solution nor DOMParser.prototype.parseFromString nor range.createContextualFragment solution. The td tag goes missing and only the text remains.

Only jQuery handles that case well.

So the future solution (MS Edge 13+) is to use template tag:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content.cloneNode(true);
}

var documentFragment = parseHTML('<td>Test</td>');

For older browsers I have extracted jQuery's parseHTML() method into an independent gist - https://gist.github.com/Munawwar/6e6362dbdf77c7865a99

How can I replace the deprecated set_magic_quotes_runtime in php?

add these code into the top of your script to solve problem

@set_magic_quotes_runtime(false);
ini_set('magic_quotes_runtime', 0);

Create Table from View

INSERT INTO table 2
SELECT * FROM table1/view1

How do I set cell value to Date and apply default Excel date format?

http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

How to make MySQL handle UTF-8 properly

The charset is a property of the database (default) and the table. You can have a look (MySQL commands):

show create database foo; 
> CREATE DATABASE  `foo`.`foo` /*!40100 DEFAULT CHARACTER SET latin1 */

show create table foo.bar;
> lots of stuff ending with
> ) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1

In other words; it's quite easy to check your database charset or change it:

ALTER TABLE `foo`.`bar` CHARACTER SET utf8;

How do I redirect with JavaScript?

To redirect to another page, you can use:

window.location = "http://www.yoururl.com";

What is the difference between Collection and List in Java?

First off: a List is a Collection. It is a specialized Collection, however.

A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.

There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

Two divs side by side - Fluid display

This is easy with a flexbox:

_x000D_
_x000D_
#wrapper {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
#left {_x000D_
  flex: 0 0 65%;_x000D_
}_x000D_
_x000D_
#right {_x000D_
  flex: 1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="left">Left side div</div>_x000D_
  <div id="right">Right side div</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Connect to mysql on Amazon EC2 from a remote server

A helpful step in tracking down this problem is to identify which bind-address MySQL is actually set to. You can do this with netstat:

netstat -nat |grep :3306

This helped me zero in on my problem, because there are multiple mysql config files, and I had edited the wrong one. Netstat showed mysql was still using the wrong config:

ubuntu@myhost:~$  netstat -nat |grep :3306
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN

So I grepped the config directories for any other files which might be overriding my setting and found:

ubuntu@myhost:~$  sudo grep -R bind /etc/mysql
/etc/mysql/mysql.conf.d/mysqld.cnf:bind-address         = 127.0.0.1
/etc/mysql/mysql.cnf:bind-address = 0.0.0.0
/etc/mysql/my.cnf:bind-address = 0.0.0.0

D'oh! This showed me the setting I had adjusted was the wrong config file, so I edited the RIGHT file this time, confirmed it with netstat, and was in business.

WPF popup window

In WPF there is a control named Popup.

Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;

Node/Express file upload

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

npm install --save multer


in app.js

    var multer  =   require('multer');
    var storage = multer.diskStorage({
      destination: function (req, file, callback) {
        callback(null, './public/uploads');
      },
      filename: function (req, file, callback) {
        console.log(file);
        callback(null, Date.now()+'-'+file.originalname)
      }
    });

    var upload = multer({storage: storage}).single('photo');

    router.route("/storedata").post(function(req, res, next){

        upload(req, res, function(err) {
          if(err) {
            console.log('Error Occured');
            return;
          }
          var userDetail = new mongoOp.User({
            'name':req.body.name,
            'email':req.body.email,
            'mobile':req.body.mobile,
            'address':req.body.address
          });

          console.log(req.file);

          res.end('Your File Uploaded');
          console.log('Photo Uploaded');

          userDetail.save(function(err,result){
          if (err) {
            return console.log(err)
          }
          console.log('saved to database') 
        })
      })

      res.redirect('/')

    });

Is there a <meta> tag to turn off caching in all browsers?

Try using

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">

PHP Change Array Keys

Use array array_flip in php

$array = array ( [1] => Sell [2] => Buy [3] => Rent [4] => Jobs )
print_r(array_flip($array));
Array ( [Sell] => 1 [Buy] => 2 [Rent] => 3 [Jobs] => 4 ) 

Tomcat is not deploying my web project from Eclipse

SOLVED: I faced this error and i cant understand, it took 5 hours.

Solution: project properties/Project faced/Dynamic web-module version set to 3.0

after one week ,I got same error

FIXED2 gwt-project-external-mode-main-main-nocache-js-not-found

How to post data to specific URL using WebClient in C#

Using WebClient.UploadString or WebClient.UploadData you can POST data to the server easily. I’ll show an example using UploadData, since UploadString is used in the same manner as DownloadString.

byte[] bret = client.UploadData("http://www.website.com/post.php", "POST",
                System.Text.Encoding.ASCII.GetBytes("field1=value1&amp;field2=value2") );
 
string sret = System.Text.Encoding.ASCII.GetString(bret);

More: http://www.daveamenta.com/2008-05/c-webclient-usage/

Opening a folder in explorer and selecting a file

Just my 2 cents worth, if your filename contains spaces, ie "c:\My File Contains Spaces.txt", you'll need to surround the filename with quotes otherwise explorer will assume that the othe words are different arguments...

string argument = "/select, \"" + filePath +"\"";

How to Upload Image file in Retrofit 2

Using Retrofit 2.0 you may use this:

@Multipart
    @POST("uploadImage")
    Call<ResponseBody> uploadImage(@Part("file\"; fileName=\"myFile.png\" ")RequestBody requestBodyFile, @Part("image") RequestBody requestBodyJson);

Make a request:

File imgFile = new File("YOUR IMAGE FILE PATH");
RequestBody requestBodyFile = RequestBody.create(MediaType.parse("image/*"), imgFile);
RequestBody requestBodyJson = RequestBody.create(MediaType.parse("text/plain"),
                    retrofitClient.getJsonObject(uploadRequest));



//make sync call
Call<ResponseBody> uploadBundle = uploadImpl.uploadImage(requestBodyFile, requestBodyJson);
Response<BaseResponse> response = uploadBundle.execute();

please refer https://square.github.io/retrofit/

How to make correct date format when writing data to Excel

This worked for me:

hoja_trabajo.Cells[i + 2, j + 1] = fecha.ToString("dd-MMM-yyyy").Replace(".", "");

In Node.js, how do I "include" functions from my other files?

Here is a plain and simple explanation:

Server.js content:

// Include the public functions from 'helpers.js'
var helpers = require('./helpers');

// Let's assume this is the data which comes from the database or somewhere else
var databaseName = 'Walter';
var databaseSurname = 'Heisenberg';

// Use the function from 'helpers.js' in the main file, which is server.js
var fullname = helpers.concatenateNames(databaseName, databaseSurname);

Helpers.js content:

// 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
module.exports = 
{
  // This is the function which will be called in the main file, which is server.js
  // The parameters 'name' and 'surname' will be provided inside the function
  // when the function is called in the main file.
  // Example: concatenameNames('John,'Doe');
  concatenateNames: function (name, surname) 
  {
     var wholeName = name + " " + surname;

     return wholeName;
  },

  sampleFunctionTwo: function () 
  {

  }
};

// Private variables and functions which will not be accessible outside this file
var privateFunction = function () 
{
};

Is it possible to clone html element objects in JavaScript / JQuery?

Using your code you can do something like this in plain JavaScript using the cloneNode() method:

// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );

// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );

// Append the newly created element on element p 
document.querySelector('p').appendChild( clone );

Or using jQuery clone() method (not the most efficient):

$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want

How to count the number of occurrences of a character in an Oracle varchar value?

SELECT {FN LENGTH('123-345-566')} - {FN LENGTH({FN REPLACE('123-345-566', '#', '')})} FROM DUAL

Remove multiple items from a Python list in just one statement

In Python, creating a new object is often better than modifying an existing one:

item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]

Which is equivalent to:

item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
    if e not in ('item', 5):
        new_list.append(e)
item_list = new_list

In case of a big list of filtered out values (here, ('item', 5) is a small set of elements), using a set is faster as the in operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:

unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]

A bloom filter is also a good solution if memory is not cheap.

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

I use an Android Studio plug-in called "adb idea" -- has a drop down menu for various functions (Uninstall, Kill, Start, etc) that you can target at any connected or simulated device. One could argue it takes me a step away from having a deeper understanding of the power of adb commands and I'd probably agree....though I'm really operating at a lower level of understanding anyway so for me it helps to have a helper. ADB Idea enter image description here

Convert a byte array to integer in Java and vice versa

/** length should be less than 4 (for int) **/
public long byteToInt(byte[] bytes, int length) {
        int val = 0;
        if(length>4) throw new RuntimeException("Too big to fit in int");
        for (int i = 0; i < length; i++) {
            val=val<<8;
            val=val|(bytes[i] & 0xFF);
        }
        return val;
    }

Copy values from one column to another in the same table

you can do it with Procedure also so i have a procedure for this

 DELIMITER $$
 CREATE PROCEDURE copyTo()
       BEGIN
               DECLARE x  INT;
            DECLARE str varchar(45);
              SET x = 1;
            set str = '';
              WHILE x < 5 DO
                set  str = (select source_col from emp where id=x);
            update emp set target_col =str where id=x;      
            SET  x = x + 1;
                END WHILE;

       END$$
   DELIMITER ;

Imported a csv-dataset to R but the values becomes factors

None of these answers mention the colClasses argument which is another way to specify the variable classes in read.csv.

 stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "numeric") # all variables to numeric

or you can specify which columns to convert:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = c("PTS" = "numeric", "MP" = "numeric") # specific columns to numeric

Note that if a variable can't be converted to numeric then it will be converted to factor as default which makes it more difficult to convert to number. Therefore, it can be advisable just to read all variables in as 'character' colClasses = "character" and then convert the specific columns to numeric once the csv is read in:

stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "character")
point <- as.numeric(stuckey$PTS)
time <- as.numeric(stuckey$MP)

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

Is string in array?

Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.

If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something> rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).

Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.

PHP - Redirect and send data via POST

It would involve the cURL PHP extension.

$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);  // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);

Fully backup a git repo?

git bundle

I like that method, as it results in only one file, easier to copy around.
See ProGit: little bundle of joy.
See also "How can I email someone a git repository?", where the command

git bundle create /tmp/foo-all --all

is detailed:

git bundle will only package references that are shown by git show-ref: this includes heads, tags, and remote heads.
It is very important that the basis used be held by the destination.
It is okay to err on the side of caution, causing the bundle file to contain objects already in the destination, as these are ignored when unpacking at the destination.


For using that bundle, you can clone it, specifying a non-existent folder (outside of any git repo):

git clone /tmp/foo-all newFolder

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

WPF Image Dynamically changing Image source during runtime

Try Stretch="UniformToFill" on the Image

What does the CSS rule "clear: both" do?

The clear property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:

clear: none; Element remains adjacent to floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-none {_x000D_
  clear: none;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-none">clear: none;</div>
_x000D_
_x000D_
_x000D_

clear: left; Element pushed below left floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-left {_x000D_
  clear: left;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-left">clear: left;</div>
_x000D_
_x000D_
_x000D_

clear: right; Element pushed below right floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-right {_x000D_
  clear: right;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-right">clear: right;</div>
_x000D_
_x000D_
_x000D_

clear: both; Element pushed below all floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-both">clear: both;</div>
_x000D_
_x000D_
_x000D_

clear does not affect floats outside the current block formatting context

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.inline-block {_x000D_
  display: inline-block;_x000D_
  background: #BDF;_x000D_
}_x000D_
.inline-block .float-left {_x000D_
  height: 60px;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="inline-block">_x000D_
  <div>display: inline-block;</div>_x000D_
  <div class="float-left">float: left;</div>_x000D_
  <div class="clear-both">clear: both;</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When 1 px border is added to div, Div size increases, Don't want to do that

Having used many of these solutions, I find using the trick of setting border-color: transparent to be the most flexible and widely-supported:

.some-element {
    border: solid 1px transparent;
}

.some-element-selected {
    border: solid 1px black;
}

Why it's better:

  • No need to to hard-code the element's width
  • Great cross-browser support (only IE6 missed)
  • Unlike with outline, you can still specify, e.g., top and bottom borders separately
  • Unlike setting border color to be that of the background, you don't need to update this if you change the background, and it's compatible with non-solid colored backgrounds.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How do I convert a decimal to an int in C#?

A neat trick for fast rounding is to add .5 before you cast your decimal to an int.

decimal d = 10.1m;
d += .5m;
int i = (int)d;

Still leaves i=10, but

decimal d = 10.5m;
d += .5m;
int i = (int)d;

Would round up so that i=11.

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

How to loop through a plain JavaScript object with the objects as members?

forEach2

( found here) :

var lunch = {
    sandwich: 'ham',
    age: 48,
};
lunch.forEach2(function (item, key) {
    console.log(key);
    console.log(item);
});

Code:

if (!Object.prototype.forEach2) {
    Object.defineProperty(Object.prototype, 'forEach2', {
        value: function (callback, thisArg) {
            if (this == null) {
                throw new TypeError('Not an object');
            }
            thisArg = thisArg || window;
            for (var key in this) {
                if (this.hasOwnProperty(key)) {
                    callback.call(thisArg, this[key], key, this);
                }
            }
        }
    });
}

python selenium click on button

open a website https://adviserinfo.sec.gov/compilation and click on button to download the file and even i want to close the pop up if it comes using python selenium

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.chrome.options import Options 

#For Mac - If you use windows change the chromedriver location
chrome_path = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_path)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-popup-blocking")

driver.maximize_window()
driver.get("https://adviserinfo.sec.gov/compilation")

# driver.get("https://adviserinfo.sec.gov/")
# tabName = driver.find_element_by_link_text("Investment Adviser Data")
# tabName.click()

time.sleep(3)

# report1 = driver.find_element_by_xpath("//div[@class='compilation-container ng-scope layout-column flex']//div[1]//div[1]//div[1]//div[2]//button[1]")

report1 = driver.find_element_by_xpath("//button[@analytics-label='IAPD - SEC Investment Adviser Report (GZIP)']")

# print(report1)
report1.click()

time.sleep(5)

driver.close()

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Are list-comprehensions and functional functions faster than "for loops"?

I modified @Alisa's code and used cProfile to show why list comprehension is faster:

from functools import reduce
import datetime

def reduce_(numbers):
    return reduce(lambda sum, next: sum + next * next, numbers, 0)

def for_loop(numbers):
    a = []
    for i in numbers:
        a.append(i*2)
    a = sum(a)
    return a

def map_(numbers):
    sqrt = lambda x: x*x
    return sum(map(sqrt, numbers))

def list_comp(numbers):
    return(sum([i*i for i in numbers]))

funcs = [
        reduce_,
        for_loop,
        map_,
        list_comp
        ]

if __name__ == "__main__":
    # [1, 2, 5, 3, 1, 2, 5, 3]
    import cProfile
    for f in funcs:
        print('=' * 25)
        print("Profiling:", f.__name__)
        print('=' * 25)
        pr = cProfile.Profile()
        for i in range(10**6):
            pr.runcall(f, [1, 2, 5, 3, 1, 2, 5, 3])
        pr.create_stats()
        pr.print_stats()

Here's the results:

=========================
Profiling: reduce_
=========================
         11000000 function calls in 1.501 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.162    0.000    1.473    0.000 profiling.py:4(reduce_)
  8000000    0.461    0.000    0.461    0.000 profiling.py:5(<lambda>)
  1000000    0.850    0.000    1.311    0.000 {built-in method _functools.reduce}
  1000000    0.028    0.000    0.028    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: for_loop
=========================
         11000000 function calls in 1.372 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.879    0.000    1.344    0.000 profiling.py:7(for_loop)
  1000000    0.145    0.000    0.145    0.000 {built-in method builtins.sum}
  8000000    0.320    0.000    0.320    0.000 {method 'append' of 'list' objects}
  1000000    0.027    0.000    0.027    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: map_
=========================
         11000000 function calls in 1.470 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.264    0.000    1.442    0.000 profiling.py:14(map_)
  8000000    0.387    0.000    0.387    0.000 profiling.py:15(<lambda>)
  1000000    0.791    0.000    1.178    0.000 {built-in method builtins.sum}
  1000000    0.028    0.000    0.028    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: list_comp
=========================
         4000000 function calls in 0.737 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.318    0.000    0.709    0.000 profiling.py:18(list_comp)
  1000000    0.261    0.000    0.261    0.000 profiling.py:19(<listcomp>)
  1000000    0.131    0.000    0.131    0.000 {built-in method builtins.sum}
  1000000    0.027    0.000    0.027    0.000 {method 'disable' of '_lsprof.Profiler' objects}

IMHO:

  • reduce and map are in general pretty slow. Not only that, using sum on the iterators that map returned is slow, compared to suming a list
  • for_loop uses append, which is of course slow to some extent
  • list-comprehension not only spent the least time building the list, it also makes sum much quicker, in contrast to map

Export DataTable to Excel File

Working code for Excel Export

 try
        {
            DataTable dt = DS.Tables[0];
            string attachment = "attachment; filename=log.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dc in dt.Columns)
            {
                Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }
        catch (Exception Ex)
        { }

length and length() in Java

A bit simplified you can think of it as arrays being a special case and not ordinary classes (a bit like primitives, but not). String and all the collections are classes, hence the methods to get size, length or similar things.

I guess the reason at the time of the design was performance. If they created it today they had probably come up with something like array-backed collection classes instead.

If anyone is interested, here is a small snippet of code to illustrate the difference between the two in generated code, first the source:

public class LengthTest {
  public static void main(String[] args) {
    int[] array = {12,1,4};
    String string = "Hoo";
    System.out.println(array.length);
    System.out.println(string.length());
  }
}

Cutting a way the not so important part of the byte code, running javap -c on the class results in the following for the two last lines:

20: getstatic   #3; //Field java/lang/System.out:Ljava/io/PrintStream;
23: aload_1
24: arraylength
25: invokevirtual   #4; //Method java/io/PrintStream.println:(I)V
28: getstatic   #3; //Field java/lang/System.out:Ljava/io/PrintStream;
31: aload_2
32: invokevirtual   #5; //Method java/lang/String.length:()I
35: invokevirtual   #4; //Method java/io/PrintStream.println:(I)V

In the first case (20-25) the code just asks the JVM for the size of the array (in JNI this would have been a call to GetArrayLength()) whereas in the String case (28-35) it needs to do a method call to get the length.

In the mid 1990s, without good JITs and stuff, it would have killed performance totally to only have the java.util.Vector (or something similar) and not a language construct which didn't really behave like a class but was fast. They could of course have masked the property as a method call and handled it in the compiler but I think it would have been even more confusing to have a method on something that isn't a real class.