Programs & Examples On #Name clash

Difference between PCDATA and CDATA in DTD

PCDATA - Parsed Character Data

XML parsers normally parse all the text in an XML document.

CDATA - (Unparsed) Character Data

The term CDATA is used about text data that should not be parsed by the XML parser.

Characters like "<" and "&" are illegal in XML elements.

How to make the division of 2 ints produce a float instead of another int?

Just cast one of the two operands to a float first.

v = (float)s / t;

The cast has higher precedence than the division, so happens before the division.

The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17

How to use "like" and "not like" in SQL MSAccess for the same field?

what's the problem with:

field like "*AA*" and field not like "*BB*"

it should be working.

Could you post some example of your data?

VMware Workstation and Device/Credential Guard are not compatible

QUICK SOLUTION EVERY STEP:

Fixed error in VMware Workstation on Windows 10 host Transport (VMDB) error -14: Pipe connection has been broken.

Today we will be fixing VMWare error on a windows 10 computer.

  1. In RUN box type "gpedit" then Goto [ERROR SEE POINT 3]

1- Computer Configuration

2- Administrative Templates

3- System - Device Guard : IF NO DEVICE GUARD : (DOWNLOAD https://www.microsoft.com/en-us/download/100591 install this "c:\Program Files (x86)\Microsoft Group Policy\Windows 10 November 2019 Update (1909)\PolicyDefinitions" COPY to c:\windows\PolicyDefinitions )

4- Turn on Virtualization Based Security. Now Double click that and "Disable"

  1. Open Command Prompt as Administrator and type the following gpupdate /force [DONT DO IF YOU DONT HAVE DEVICE GUARD ELSE IT WILL GO AGAIN]

  2. Open Registry Editor, now Go to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\DeviceGuard. Add a new DWORD value named EnableVirtualizationBasedSecurity and set it to 0 to disable it. Next Go to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA. Add a new DWORD value named LsaCfgFlags and set it to 0 to disable it.

  3. In RUN box, type Turn Windows features on or off, now uncheck Hyper-V and restart system.

  4. Open command prompt as a administrator and type the following commands

    bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"

    bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}
    
    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO,DISABLE-VBS

    bcdedit /set hypervisorlaunchtype off

Now, Restart your system

Can we open pdf file using UIWebView on iOS?

Swift version:

if let docPath = NSBundle.mainBundle().pathForResource("sample", ofType: "pdf") {
    let docURL = NSURL(fileURLWithPath: docPath)
    webView.loadRequest(NSURLRequest(URL: docURL))
}

How do I merge changes to a single file, rather than merging commits?

The following command will (1) compare the file of the correct branch, to master (2) interactively ask you which modifications to apply.

git checkout --patch master

Is there any way to install Composer globally on Windows?

This may be useful to someone:

On Windows 7, if you've installed Composer using curl, it can be found in similar path:

C:\Users\<username>\AppData\Roaming\Composer

SQLAlchemy: What's the difference between flush() and commit()?

This does not strictly answer the original question but some people have mentioned that with session.autoflush = True you don't have to use session.flush()... And this is not always true.

If you want to use the id of a newly created object in the middle of a transaction, you must call session.flush().

# Given a model with at least this id
class AModel(Base):
   id = Column(Integer, primary_key=True)  # autoincrement by default on integer primary key

session.autoflush = True

a = AModel()
session.add(a)
a.id  # None
session.flush()
a.id  # autoincremented integer

This is because autoflush does NOT auto fill the id (although a query of the object will, which sometimes can cause confusion as in "why this works here but not there?" But snapshoe already covered this part).


One related aspect that seems pretty important to me and wasn't really mentioned:

Why would you not commit all the time? - The answer is atomicity.

A fancy word to say: an ensemble of operations have to all be executed successfully OR none of them will take effect.

For example, if you want to create/update/delete some object (A) and then create/update/delete another (B), but if (B) fails you want to revert (A). This means those 2 operations are atomic.

Therefore, if (B) needs a result of (A), you want to call flush after (A) and commit after (B).

Also, if session.autoflush is True, except for the case that I mentioned above or others in Jimbo's answer, you will not need to call flush manually.

Abstract Class vs Interface in C++

Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.

class IInterface() 
{ 
   Public: 
   Virtual ~IInterface(){}; 
   … 
} 

Class ClassImpl : public IInterface 
{ 
    … 
} 

Int main() 
{ 

  IInterface* pInterface = new ClassImpl(); 
  … 
  delete pInterface; // Wrong in OO Programming, correct in C++.
}

turn typescript object into json string

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');

fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

Javascript return number of days,hours,minutes,seconds between two dates

Easy Way

function diff_hours(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60 * 60);
  return Math.abs(Math.round(diff));

 }


function diff_minutes(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60);
  return Math.abs(Math.round(diff));

 }

function diff_seconds(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  return Math.abs(Math.round(diff));

 }

function diff_miliseconds(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime());
  return Math.abs(Math.round(diff));

 }


dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,3);
console.log(diff_hours(dt1, dt2));


dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 14, 2014 11:13:00");
console.log(diff_hours(dt1, dt2));

console.log(diff_minutes(dt1, dt2));

console.log(diff_seconds(dt1, dt2));

console.log(diff_miliseconds(dt1, dt2));

What are XAND and XOR

Have a look

x   y      A    B   C   D   E   F   G   H   I   J   K   L   M   N

·   ·      T    ·   T   ·   T   ·   T   ·   T   ·   T   ·   T   ·
·   T      ·    T   T   ·   ·   T   T   ·   ·   T   T   ·   ·   T
T   ·      ·    ·   ·   T   T   T   T   ·   ·   ·   ·   T   T   T
T   T      ·    ·   ·   ·   ·   ·   ·   T   T   T   T   T   T   T

A) !(x OR y)    
B) !(x) AND y   
C) !(x) 
D) x AND !(y)   
E) !(y) 
F) x XOR y  
G) !(x AND y)   
H) x AND y  
I) !(x XOR y)   
J) y    
K) !(x) OR y    
L) x    
M) x OR !(y)    
N) x OR y

In PowerShell, how do I test whether or not a specific variable exists in global scope?

Test the existence of variavle MyVariable. Returns boolean true or false.

Test-Path variable:\MyVariable

Programmatically trigger "select file" dialog box

Most answers here are lacking a useful information:

Yes, you can programmatically click the input element using jQuery/JavaScript, but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER!

So, for example, nothing will happen if you, the script, programmatically click the button in an ajax callback, but if you put the same line of code in an event handler that was raised by the user, it will work.

P.S. The debugger; keyword disrupts the browse window if it is before the programmatical click ...at least in chrome 33...

how to make label visible/invisible?

You can set display attribute as none to hide a label.

<label id="excel-data-div" style="display: none;"></label>

How to open select file dialog via js?

JS only - no need for jquery

Simply create an input element and trigger the click.

var input = document.createElement('input');
input.type = 'file';
input.click();

This is the most basic, pop a select-a-file dialog, but its no use for anything without handling the selected file...

Handling the files

Adding an onchange event to the newly created input would allow us to do stuff once the user has selected the file.

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 
   var file = e.target.files[0]; 
}

input.click();

At the moment we have the file variable storing various information :

file.name // the file's name including extension
file.size // the size in bytes
file.type // file type ex. 'application/pdf'

Great!

But, what if we need the content of the file?

In order to get to the actual content of the file, for various reasons. place an image, load into canvas, create a window with Base64 data url, etc. we would need to use the FileReader API

We would create an instance of the FileReader, and load our user selected file reference to it.

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 

   // getting a hold of the file reference
   var file = e.target.files[0]; 

   // setting up the reader
   var reader = new FileReader();
   reader.readAsText(file,'UTF-8');

   // here we tell the reader what to do when it's done reading...
   reader.onload = readerEvent => {
      var content = readerEvent.target.result; // this is the content!
      console.log( content );
   }

}

input.click();

Trying pasting the above code into your devtool's console window, it should produce a select-a-file dialog, after selecting the file, the console should now print the contents of the file.

Example - "Stackoverflow's new background image!"

Let's try to create a file select dialog to change stackoverflows background image to something more spicy...

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 

   // getting a hold of the file reference
   var file = e.target.files[0]; 

   // setting up the reader
   var reader = new FileReader();
   reader.readAsDataURL(file); // this is reading as data url

   // here we tell the reader what to do when it's done reading...
   reader.onload = readerEvent => {
      var content = readerEvent.target.result; // this is the content!
      document.querySelector('#content').style.backgroundImage = 'url('+ content +')';
   }

}

input.click();

open devtools, and paste the above code into console window, this should pop a select-a-file dialog, upon selecting an image, stackoverflows content box background should change to the image selected.

Cheers!

Get my phone number in android

Method 1:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Method 2:

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Hope this helps, Thanks!

Rotating a point about another point (2D)

I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.

def rotate(origin, point, angle):
    """
    Rotate a point counter-clockwise by a given angle around a given origin.
    """
    # Convert negative angles to positive
    angle = normalise_angle(angle)

    # Convert to radians
    angle = math.radians(angle)

    # Convert to radians
    ox, oy = origin
    px, py = point
    
    # Move point 'p' to origin (0,0)
    _px = px - ox
    _py = py - oy
    
    # Rotate the point 'p' 
    qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
    qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
    
    # Move point 'p' back to origin (ox, oy)
    qx = ox + qx
    qy = oy + qy
    
    return [qx, qy]


def normalise_angle(angle):
    """ If angle is negative then convert it to positive. """
    if (angle != 0) & (abs(angle) == (angle * -1)):
        angle = 360 + angle
    return angle

What is a "slug" in Django?

It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)

HTML5 Video Stop onClose

The problem may be with jquery selector you've chosen $("video") is not a selector

The right selector may be putting an id element for video tag i.e.
Let's say your video element looks like this:

<video id="vid1" width="480" height="267" oster="example.jpg" durationHint="33"> 
    <source src="video1.ogv" /> 
    <source src="video2.ogv" /> 
</video> 

Then you can select it via $("#vid1") with hash mark (#), id selector in jquery. If a video element is exposed in function,then you have access to HtmlVideoElement (HtmlMediaElement).This elements has control over video element,in your case you can use pause() method for your video element.

Check reference for VideoElement here.
Also check that there is a fallback reference here.

ngFor with index as value in attribute

Adding this late answer to show a case most people will come across. If you only need to see what is the last item in the list, use the last key word:

<div *ngFor="let item of devcaseFeedback.reviewItems; let last = last">
  <divider *ngIf="!last"></divider>
</div>

This will add the divider component to every item except the last.

Because of the comment below, I will add the rest of the ngFor exported values that can be aliased to local variables (As are shown in the docs):

  • $implicit: T: The value of the individual items in the iterable (ngForOf).
  • ngForOf: NgIterable: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (userStreams | async).
  • index: number: The index of the current item in the iterable.
  • count: number: The length of the iterable.
  • count: number: The length of the iterable.
  • first: boolean: True when the item is the first item in the iterable.
  • last: boolean: True when the item is the last item in the iterable.
  • even: boolean: True when the item has an even index in the iterable.
  • odd: boolean: True when the item has an odd index in the iterable.

How do I programmatically click on an element in JavaScript?

I used KooiInc's function listed above but I had to use two different input types one 'button' for IE and one 'submit' for FireFox. I am not exactly sure why but it works.

// HTML

<input type="button" id="btnEmailHidden" style="display:none" />
<input type="submit" id="btnEmailHidden2" style="display:none" />

// in JavaScript

var hiddenBtn = document.getElementById("btnEmailHidden");

if (hiddenBtn.fireEvent) {
    hiddenBtn.fireEvent('onclick');
    hiddenBtn[eType]();
}
else {
    // dispatch for firefox + others
    var evObj = document.createEvent('MouseEvent');
    evObj.initEvent(eType, true, true);
    var hiddenBtn2 = document.getElementById("btnEmailHidden2");
    hiddenBtn2.dispatchEvent(evObj);
}

I have search and tried many suggestions but this is what ended up working. If I had some more time I would have liked to investigate why submit works with FF and button with IE but that would be a luxury right now so on to the next problem.

Socket transport "ssl" in PHP not enabled

I was having problem in Windows 7 with PHP 5.4.0 in command line, using Xampp 1.8.1 server. This is what i did:

  1. Rename php.ini-production to php.ini (in C:\xampp\php\ folder)
  2. Edit php.ini and uncomment extension_dir=ext.
  3. Also uncomment extension=php_openssl.dll.

After that it worked fine.

angular js unknown provider

At the end of the JS file to close the factory function I had

});

instead of

}());

TLS 1.2 not working in cURL

Replace following

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');

With

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);

Should work flawlessly.

Measure the time it takes to execute a t-sql query

If you want a more accurate measurement than the answer above:

set statistics time on 

-- Query 1 goes here

-- Query 2 goes here

set statistics time off

The results will be in the Messages window.

Update (2015-07-29):

By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats that may also be of value:

-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.

-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';

SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0)) 
       AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
      (OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
      (DB_NAME(database_id)=@DbName OR @DbName IS NULL)

How to Maximize a firefox browser window using Selenium WebDriver with node.js

As of 2020, the correct answer is :

driver.maximize_window()

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

How to remove border from specific PrimeFaces p:panelGrid?

Nowdays, Primefaces 5.x have a attribute in panelGrid named "columnClasses".

.no-border {
    border-style: hidden !important ; /* or none */
}

So, to a panelGrid with 2 columns, repeat two times the css class.

<p:panelGrid columns="2" columnClasses="no-border, no-border">

To other elements, the ugly " !important " is not necessary, but to the border just with it work fine to me.

How to set locale in DatePipe in Angular 2?

For those having problems with AOT, you need to do it a little differently with a useFactory:

export function getCulture() {
    return 'fr-CA';
}

@NgModule({
  providers: [
    { provide: LOCALE_ID, useFactory: getCulture },
    //otherProviders...
  ]
})

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

Capture keyboardinterrupt in Python without try-except

If someone is in search for a quick minimal solution,

import signal

# The code which crashes program on interruption

signal.signal(signal.SIGINT, call_this_function_if_interrupted)

# The code skipped if interrupted

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Node.js: Gzip compression?

Generally speaking, for a production web application, you will want to put your node.js app behind a lightweight reverse proxy such as nginx or lighttpd. Among the many benefits of this setup, you can configure the reverse proxy to do http compression or even tls compression, without having to change your application source code.

Load Image from javascript

If you are loading the image via AJAX you could use a callback to check if the image is loaded and do the hiding and src attribute assigning. Something like this:

$.ajax({ 
  url: [image source],
  success: function() {
  // Do the hiding here and the attribute setting
  }
});

For more reading refer to this JQuery AJAX

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

INSERTING

enter image description here

REFRESHING THE TABLE

enter image description here

Entity Framework: There is already an open DataReader associated with this Command

I had originally decided to use a static field in my API class to reference an instance of MyDataContext object (Where MyDataContext is an EF5 Context object), but that is what seemed to create the problem. I added code something like the following to every one of my API methods and that fixed the problem.

using(MyDBContext db = new MyDBContext())
{
    //Do some linq queries
}

As other people have stated, the EF Data Context objects are NOT thread safe. So placing them in the static object will eventually cause the "data reader" error under the right conditions.

My original assumption was that creating only one instance of the object would be more efficient, and afford better memory management. From what I have gathered researching this issue, that is not the case. In fact, it seems to be more efficient to treat each call to your API as an isolated, thread safe event. Ensuring that all resources are properly released, as the object goes out of scope.

This makes sense especially if you take your API to the next natural progression which would be to expose it as a WebService or REST API.

Disclosure

  • OS: Windows Server 2012
  • .NET: Installed 4.5, Project using 4.0
  • Data Source: MySQL
  • Application Framework: MVC3
  • Authentication: Forms

Multiple Where clauses in Lambda expressions

The lambda you pass to Where can include any normal C# code, for example the && operator:

.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)

How can I start PostgreSQL on Windows?

After a lot of search and tests i found the solution : if you are in windows :

1 - first you must found the PG databases directory execute the command as sql command in pgAdmin query tools

$ show data_directory;

result :

------------------------
- D:/PG_DATA/data      -
------------------------

2 - go to the bin directory of postgres in my case it's located "c:/programms/postgresSql/bin"

and open a command prompt (CMD) and execute this command :

pg_ctl -D "D:\PSG_SQL\data" restart

This should do it.

Execute curl command within a Python script

You could use urllib as @roippi said:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

await is only valid in async function

async/await is the mechanism of handling promise, two ways we can do it

functionWhichReturnsPromise()
            .then(result => {
                console.log(result);
            })
            .cathc(err => {
                console.log(result);

            });

or we can use await to wait for the promise to full-filed it first, which means either it is rejected or resolved.

Now if we want to use await (waiting for a promise to fulfil) inside a function, it's mandatory that the container function must be an async function because we are waiting for a promise to fulfiled asynchronously || make sense right?.

async function getRecipesAw(){
            const IDs = await getIds; // returns promise
            const recipe = await getRecipe(IDs[2]); // returns promise
            return recipe; // returning a promise
        }

        getRecipesAw().then(result=>{
            console.log(result);
        }).catch(error=>{
            console.log(error);
        });

Cannot uninstall angular-cli

Check if you have the hidden folder ".npm" in your Home directory and delete the old angular-cli folder.

Using C# to read/write Excel files (.xls/.xlsx)

If you are doing simple manipulation and can tie yourself to xlsx then you can look into manipulating the XML yourself. I have done it and found it to be faster than grokking the excel libs.

There are also 3rd party libs that can be easier to use... and can be used on the server which MS's can't.

The request was aborted: Could not create SSL/TLS secure channel

I had to enable other security protocol versions to resolve the issue:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
        | SecurityProtocolType.Tls11
        | SecurityProtocolType.Tls12
        | SecurityProtocolType.Ssl3;

How do I sort a VARCHAR column in SQL server that contains numbers?

One possible solution is to pad the numeric values with a character in front so that all are of the same string length.

Here is an example using that approach:

select MyColumn
from MyTable
order by 
    case IsNumeric(MyColumn) 
        when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
        else MyColumn
    end

The 100 should be replaced with the actual length of that column.

Controlling number of decimal digits in print output in R

If you are producing the entire output yourself, you can use sprintf(), e.g.

> sprintf("%.10f",0.25)
[1] "0.2500000000"

specifies that you want to format a floating point number with ten decimal points (in %.10f the f is for float and the .10 specifies ten decimal points).

I don't know of any way of forcing R's higher level functions to print an exact number of digits.

Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.

Replace input type=file by an image

_x000D_
_x000D_
        form input[type="file"] {_x000D_
          display: none;_x000D_
        }
_x000D_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Simple File Upload</title>_x000D_
  <meta name="" content="">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <form action="upload.php" method="post" enctype="multipart/form-data">_x000D_
    Select image to upload:_x000D_
    <label for="fileToUpload">_x000D_
      <img src="http://s3.postimg.org/mjzvuzi5b/uploader_image.png" />_x000D_
    </label>_x000D_
    <input type="File" name="fileToUpload" id="fileToUpload">_x000D_
    <input type="submit" value="Upload Image" name="submit">_x000D_
  </form>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

RUN SNIPPET or Just copy the above code and execute. You will get what you wanted. Very simple and effective without javascript. Enjoy!!!

Cursor inside cursor

Do you do any more fetches? You should show those as well. You're only showing us half the code.

It should look like:

FETCH NEXT FROM @Outer INTO ...
WHILE @@FETCH_STATUS = 0
BEGIN
  DECLARE @Inner...
  OPEN @Inner
  FETCH NEXT FROM @Inner INTO ...
  WHILE @@FETCH_STATUS = 0
  BEGIN
  ...
    FETCH NEXT FROM @Inner INTO ...
  END
  CLOSE @Inner
  DEALLOCATE @Inner
  FETCH NEXT FROM @Outer INTO ...
END
CLOSE @Outer
DEALLOCATE @Outer

Also, make sure you do not name the cursors the same... and any code (check your triggers) that gets called does not use a cursor that is named the same. I've seen odd behavior from people using 'theCursor' in multiple layers of the stack.

How to stretch div height to fill parent div - CSS

If you're gonna use B2 for styling purposes you can try this "hack"

#B { overflow: hidden;}
#B2 {padding-bottom: 9999px; margin-bottom: -9999px}

jsFiddle

How to generate the JPA entity Metamodel?

Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath element of the compiler plugin.

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

Removing all script tags from html with JS Regular Expression

Try this:

var text = text.replace(/<script[^>]*>(?:(?!<\/script>)[^])*<\/script>/g, "")

How to close a Java Swing application from the code

In response to other comments, DISPOSE_ON_CLOSE does not seem to properly exit the application - it only destroys the window, but the application will continue running. If you want to terminate the application use EXIT_ON_CLOSE.

"google is not defined" when using Google Maps V3 in Firefox remotely

I had the same error "google is not defined" while using Gmap3. The problem was that I was including 'gmap3' before including 'google', so I reversed the order:

<script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="/assets/gmap3.js?body=1" type="text/javascript"></script>

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

C++ "was not declared in this scope" compile error

As the compiler says, grid was not declared in the scope of your function :) "Scope" basically means a set of curly braces. Every variable is limited to the scope in which it is declared (it cannot be accessed outside that scope). In your case, you're declaring the grid variable in your main() function and trying to use it in nonrecursivecountcells(). You seem to be passing it as the argument colors however, so I suggest you just rename your uses of grid in nonrecursivecountcells() to colors. I think there may be something wrong with trying to pass the array that way, too, so you should probably investigate passing it as a pointer (unless someone else says something to the contrary).

How to install pip in CentOS 7?

Figure out what version of python3 you have installed:

yum search pip

and then install the best match. Use reqoquery to find name of resulting pip3.e.g

repoquery -l python36u-pip

tells me to use pip3.6 instead of pip3

How to retrieve current workspace using Jenkins Pipeline Groovy script?

I think you can also execute the pwd() function on the particular node:

node {
    def PWD = pwd();
    ...
}

Corrupt jar file

Try use the command jar -xvf fileName.jar and then do export the content of the decompressed file into a new Java project into Eclipse.

CSS Styling for a Button: Using <input type="button> instead of <button>

In your .button CSS, try display:inline-block. See this JSFiddle

If/else else if in Jquery for a condition

Change the less-than operator to a greater-than-or-equal-to operator:

}elseif($("#seats").val() >= 99999){

How to check if a process id (PID) exists

The best way is:

if ps -p $PID > /dev/null
then
   echo "$PID is running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
fi

The problem with:

kill -0 $PID

is the exit code will be non-zero even if the pid is running and you dont have permission to kill it. For example:

kill -0 1

and

kill -0 $non-running-pid

have an indistinguishable (non-zero) exit code for a normal user, but the init process (PID 1) is certainly running.

DISCUSSION

The answers discussing kill and race conditions are exactly right if the body of the test is a "kill". I came looking for the general "how do you test for a PID existence in bash".

The /proc method is interesting, but in some sense breaks the spirit of the "ps" command abstraction, i.e. you dont need to go looking in /proc because what if Linus decides to call the "exe" file something else?

How to compare two vectors for equality element by element in C++?

Check std::mismatch method of C++.

comparing vectors has been discussed on DaniWeb forum and also answered.

C++: Comparing two vectors

Check the below SO post. will helpful for you. they have achieved the same with different-2 method.

Compare two vectors C++

Is there a Public FTP server to test upload and download?

I have found an FTP server and its working. I was successfully able to upload a file to this FTP server and then see file created by hitting same url. Visit here and read properly before use. Good luck...!

Edit: link is now dead, but the FTP server is still up! Connect with the username "anonymous" and an email address as a password: ftp://ftp.swfwmd.state.fl.us

BUT FIRST read this before using it

How to make a simple modal pop up form using jquery and html?

I have placed here complete bins for above query. you can check demo link too.

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

HTML

<div id="panel">
  <input type="button" class="button" value="1" id="btn1">
  <input type="button" class="button" value="2" id="btn2">
  <input type="button" class="button" value="3" id="btn3">
  <br>
  <input type="text" id="valueFromMyModal">
  <!-- Dialog Box-->
  <div class="dialog" id="myform">
    <form>
      <label id="valueFromMyButton">
      </label>
      <input type="text" id="name">
      <div align="center">
        <input type="button" value="Ok" id="btnOK">
      </div>
    </form>
  </div>
</div>

JQuery

$(function() {
    $(".button").click(function() {
        $("#myform #valueFromMyButton").text($(this).val().trim());
        $("#myform input[type=text]").val('');
        $("#myform").show(500);
    });
    $("#btnOK").click(function() {
        $("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
        $("#myform").hide(400);
    });
});

CSS

.button{
  border:1px solid #333;
  background:#6479fd;
}
.button:hover{
  background:#a4a9fd;
}
.dialog{
  border:5px solid #666;
  padding:10px;
  background:#3A3A3A;
  position:absolute;
  display:none;
}
.dialog label{
  display:inline-block;
  color:#cecece;
}
input[type=text]{
  border:1px solid #333;
  display:inline-block;
  margin:5px;
}
#btnOK{
  border:1px solid #000;
  background:#ff9999;
  margin:5px;
}

#btnOK:hover{
  border:1px solid #000;
  background:#ffacac;
}

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

PowerShell: Format-Table without headers

Try the -HideTableHeaders parameter to Format-Table:

gci | ft -HideTableHeaders

(I'm using PowerShell v2. I don't know if this was in v1.)

Can you do greater than comparison on a date in a Rails 3 search?

If you aren't a fan of passing in a string, I prefer how @sesperanto has done it, except to make it even more concise, you could drop Float::INFINITY in the date range and instead simply use created_at: p[:date]..

Note.where(
    user_id: current_user.id,
    notetype: p[:note_type],
    created_at: p[:date]..
).order(:date, :created_at)

Take note that this will change the query to be >= instead of >. If that's a concern, you could always add a unit of time to the date by running something like p[:date] + 1.day..

How to remove "disabled" attribute using jQuery?

<input type="text" disabled="disabled" class="inputDisabled" value="">
?<button id="edit">Edit</button>????????????????????????????????

$("#edit").click(function(event){
    event.preventDefault();
    $('.inputDisabled').removeAttr("disabled")
});?

http://jsfiddle.net/ZwHfY/

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

This is how a browser interprets and empty href. It assumes you want to link back to the page that you are on. This is the same as if you dont assign an action to a <form> element.

If you add any word in the href it will append it to the current page unless you:

  • Add a slash / to the front of it telling it to append it to your base url e.g. http://www.whatever.com/something
  • add a # sign in which case it is an in-page anchor
  • or a valid URL

EDIT: It was suggested that I add a link to help clarify the situation. I found the following site that I think does a really good job explaining the href attribute of anchor tags and how it interprets URL paths. It is not incredibly technical and very human-readable. It uses lots of examples to illustrate the differences between the path types: http://www.mediacollege.com/internet/html/hyperlinks.html

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

/*
    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
            login_function();
        } 
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;
*/

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
    }
// If $multi is boolean return $hash
} else return $hash;

}

What does ^M character mean in Vim?

In Unix it is probably easier to use 'tr' command.

cat file1.txt | tr "\r" "\n" > file2.txt

jQuery Show-Hide DIV based on Checkbox Value

You might consider using the :checked selector, provided by jQuery. Something like this:

$('.pChk').click(function() {
    if( $('.pChk:checked').length > 0 ) {
        $("#ProjectListButton").show();
    } else {
        $("#ProjectListButton").hide();
    }
}); 

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

Python, how to check if a result set is empty?

if you're connecting to a postgres database, the following works:

result = cursor.execute(query)

if result.returns_rows:
    # we got rows!
    return [{k:v for k,v in zip(result.keys(), r)} for r in result.rows]
else:
    return None

How to convert a Collection to List?

What you request is quite a costy operation, make sure you don't need to do it often (e.g in a cycle).

If you need it to stay sorted and you update it frequently, you can create a custom collection. For example, I came up with one that has your TreeBidiMap and TreeMultiset under the hood. Implement only what you need and care about data integrity.

class MyCustomCollection implements Map<K, V> {
    TreeBidiMap<K, V> map;
    TreeMultiset<V> multiset;
    public V put(K key, V value) {
        removeValue(map.put(key, value));
        multiset.add(value);
    }
    public boolean remove(K key) {
        removeValue(map.remove(key));
    }
    /** removes value that was removed/replaced in map */
    private removeValue(V value) {
        if (value != null) {
            multiset.remove(value);
        }
    }
    public Set<K> keySet() {
        return Collections.unmodifiableSet(map.keySet());
    }
    public Collection<V> values() {
        return Collections.unmodifiableCollection(multiset);
    }
    // many more methods to be implemented, e.g. count, isEmpty etc.
    // but these are fairly simple
}

This way, you have a sorted Multiset returned from values(). However, if you need it to be a list (e.g. you need the array-like get(index) method), you'd need something more complex.

For brevity, I only return unmodifiable collections. What @Lino mentioned is correct, and modifying the keySet or values collection as it is would make it inconsistent. I don't know any consistent way to make the values mutable, but the keySet could support remove if it uses the remove method from the MyCustomCollection class above.

What is the difference between active and passive FTP?

Redacted version of my article FTP Connection Modes (Active vs. Passive):

FTP connection mode (active or passive), determines how a data connection is established. In both cases, a client creates a TCP control connection to an FTP server command port 21. This is a standard outgoing connection, as with any other file transfer protocol (SFTP, SCP, WebDAV) or any other TCP client application (e.g. web browser). So, usually there are no problems when opening the control connection.

Where FTP protocol is more complicated comparing to the other file transfer protocols are file transfers. While the other protocols use the same connection for both session control and file (data) transfers, the FTP protocol uses a separate connection for the file transfers and directory listings.

In the active mode, the client starts listening on a random port for incoming data connections from the server (the client sends the FTP command PORT to inform the server on which port it is listening). Nowadays, it is typical that the client is behind a firewall (e.g. built-in Windows firewall) or NAT router (e.g. ADSL modem), unable to accept incoming TCP connections.

For this reason the passive mode was introduced and is mostly used nowadays. Using the passive mode is preferable because most of the complex configuration is done only once on the server side, by experienced administrator, rather than individually on a client side, by (possibly) inexperienced users.

In the passive mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection to the server IP address and server port number received.

Network Configuration for Passive Mode

With the passive mode, most of the configuration burden is on the server side. The server administrator should setup the server as described below.

The firewall and NAT on the FTP server side have to be configured not only to allow/route the incoming connections on FTP port 21 but also a range of ports for the incoming data connections. Typically, the FTP server software has a configuration option to setup a range of the ports, the server will use. And the same range has to be opened/routed on the firewall/NAT.

When the FTP server is behind a NAT, it needs to know it's external IP address, so it can provide it to the client in a response to PASV command.

Network Configuration for Active Mode

With the active mode, most of the configuration burden is on the client side.

The firewall (e.g. Windows firewall) and NAT (e.g. ADSL modem routing rules) on the client side have to be configured to allow/route a range of ports for the incoming data connections. To open the ports in Windows, go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules > New Rule. For routing the ports on the NAT (if any), refer to its documentation.

When there's NAT in your network, the FTP client needs to know its external IP address that the WinSCP needs to provide to the FTP server using PORT command. So that the server can correctly connect back to the client to open the data connection. Some FTP clients are capable of autodetecting the external IP address, some have to be manually configured.

Smart Firewalls/NATs

Some firewalls/NATs try to automatically open/close data ports by inspecting FTP control connection and/or translate the data connection IP addresses in control connection traffic.

With such a firewall/NAT, the above configuration is not necessary for a plain unencrypted FTP. But this cannot work with FTPS, as the control connection traffic is encrypted and the firewall/NAT cannot inspect nor modify it.

How to truncate a foreign key constrained table?

Tested on MYSQL Database

Solution 1:

SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table1;

Solution 2:

DELETE FROM table1;
ALTER TABLE table1 AUTO_INCREMENT = 1;
TRUNCATE table1;

This works for me. I hope, this will help you also. Thanks for asking this question.

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Why does the 260 character path length limit exist in Windows?

This is not strictly true as the NTFS filesystem supports paths up to 32k characters. You can use the win32 api and "\\?\" prefix the path to use greater than 260 characters.

A detailed explanation of long path from the .Net BCL team blog.
A small excerpt highlights the issue with long paths

Another concern is inconsistent behavior that would result by exposing long path support. Long paths with the \\?\ prefix can be used in most of the file-related Windows APIs, but not all Windows APIs. For example, LoadLibrary, which maps a module into the address of the calling process, fails if the file name is longer than MAX_PATH. So this means MoveFile will let you move a DLL to a location such that its path is longer than 260 characters, but when you try to load the DLL, it would fail. There are similar examples throughout the Windows APIs; some workarounds exist, but they are on a case-by-case basis.

How can we print line numbers to the log in java

This is exactly the feature I implemented in this lib XDDLib. (But, it's for android)

Lg.d("int array:", intArrayOf(1, 2, 3), "int list:", listOf(4, 5, 6))

enter image description here

One click on the underlined text to navigate to where the log command is

That StackTraceElement is determined by the first element outside this library. Thus, anywhere outside this lib will be legal, including lambda expression, static initialization block, etc.

What is an idempotent operation?

Idempotence means that applying an operation once or applying it multiple times has the same effect.

Examples:

  • Multiplication by zero. No matter how many times you do it, the result is still zero.
  • Setting a boolean flag. No matter how many times you do it, the flag stays set.
  • Deleting a row from a database with a given ID. If you try it again, the row is still gone.

For pure functions (functions with no side effects) then idempotency implies that f(x) = f(f(x)) = f(f(f(x))) = f(f(f(f(x)))) = ...... for all values of x

For functions with side effects, idempotency furthermore implies that no additional side effects will be caused after the first application. You can consider the state of the world to be an additional "hidden" parameter to the function if you like.

Note that in a world where you have concurrent actions going on, you may find that operations you thought were idempotent cease to be so (for example, another thread could unset the value of the boolean flag in the example above). Basically whenever you have concurrency and mutable state, you need to think much more carefully about idempotency.

Idempotency is often a useful property in building robust systems. For example, if there is a risk that you may receive a duplicate message from a third party, it is helpful to have the message handler act as an idempotent operation so that the message effect only happens once.

How to get the Development/Staging/production Hosting Environment in ConfigureServices

If you need to test this somewhere in your codebase that doesn't have easy access to the IHostingEnvironment, another easy way to do it is like this:

bool isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";

AngularJS : When to use service instead of factory

Both the factory and the service result in singleton objects which are able to be configured by providers and injected into controllers and run blocks. From the point of view of the injectee, there is absolutely no difference whether the object came from a factory or a service.

So, when to use a factory, and when to use a service? It boils down to your coding preference, and nothing else. If you like the modular JS pattern then go for the factory. If you like the constructor function ("class") style then go for the service. Note that both styles support private members.

The advantage of the service might be that it's more intuitive from the OOP point of view: create a "class", and, in conjunction with a provider, reuse the same code across modules, and vary the behavior of the instantiated objects simply by supplying different parameters to the constructor in a config block.

Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

jQuery - determine if input element is textbox or select list

You could do this:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

or this, which is slower, but shorter and cleaner:

if( ctrl.is('input') ) {
    // it was an input
}

If you want to be more specific, you can test the type:

if( ctrl.is('input:text') ) {
    // it was an input
}

SQL: IF clause within WHERE clause

There isn't a good way to do this in SQL. Some approaches I have seen:

1) Use CASE combined with boolean operators:

WHERE
    OrderNumber = CASE 
        WHEN (IsNumeric(@OrderNumber) = 1)
        THEN CONVERT(INT, @OrderNumber)
        ELSE -9999 -- Some numeric value that just cannot exist in the column
    END
    OR 
    FirstName LIKE CASE
        WHEN (IsNumeric(@OrderNumber) = 0)
        THEN '%' + @OrderNumber
        ELSE ''
    END

2) Use IF's outside the SELECT

IF (IsNumeric(@OrderNumber)) = 1
BEGIN
    SELECT * FROM Table
    WHERE @OrderNumber = OrderNumber
END ELSE BEGIN
    SELECT * FROM Table
    WHERE OrderNumber LIKE '%' + @OrderNumber
END

3) Using a long string, compose your SQL statement conditionally, and then use EXEC

The 3rd approach is hideous, but it's almost the only think that works if you have a number of variable conditions like that.

How to make a submit out of a <a href...>...</a> link?

We replace the submit button with this all the time on forms:

<form method="post" action="whatever.asp">
<input type=...n

<input type="image" name="Submit" src="/graphics/continue.gif" align="middle" border="0" alt="Continue">
</form>

Clicking the image submits the form. Hope that helps!

Password Protect a SQLite DB. Is it possible?

You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.

Quoting SQLite documentation:

The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.

You can find more info about this addon in this link.

How to install JDK 11 under Ubuntu?

I came here looking for the answer and since no one put the command for the oracle Java 11 but only openjava 11 I figured out how to do it on Ubuntu, the syntax is as following:

sudo add-apt-repository ppa:linuxuprising/java
sudo apt update
sudo apt install oracle-java11-installer

Enter export password to generate a P12 certificate

MacOS High Sierra is very crazy to update openssl command suddenly.

Possible in last month:

$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts
MAC verified OK

But now:

$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts -password pass:
MAC verified OK

How to write files to assets folder or raw folder in android?

Why not update the files on the local file system instead? You can read/write files into your applications sandboxed area.

http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Other alternatives you may want to look into are Shared Perferences and using Cache Files (all described at the link above)

What does the regex \S mean in JavaScript?

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

How can I tell which button was clicked in a PHP form submit?

In HTML:

<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />

In PHP:

if (isset($_POST["btnSubmit"])){
  // "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
  // "Delete" clicked
}

How can I add a PHP page to WordPress?

Try this:

/**
 * The template for displaying demo page
 *
 * template name: demo template
 *
 */

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

You are running the Command Prompt as an admin. You have only defined PYTHON for your user. You need to define it in the bottom "System variables" section.

Also, you should only point the variable to the folder, not directly to the executable.

How do I access properties of a javascript object if I don't know the names?

Old versions of JavaScript (< ES5) require using a for..in loop:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 introduces Object.keys and Array#forEach which makes this a little easier:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017 introduces Object.values and Object.entries.

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]

Java Calendar, getting current month value, clarification needed

Months in Java Calendar are 0-indexed. Calendar.JANUARY isn't a field so you shouldn't be passing it in to the get method.

Delete empty lines using sed

sed '/^$/d' should be fine, are you expecting to modify the file in place? If so you should use the -i flag.

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.

Dynamically allocating an array of objects

Using the placement feature of new operator, you can create the object in place and avoid copying:

placement (3) :void* operator new (std::size_t size, void* ptr) noexcept;

Simply returns ptr (no storage is allocated). Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor).

I suggest the following:

A* arrayOfAs = new A[5]; //Allocate a block of memory for 5 objects
for (int i = 0; i < 5; ++i)
{
    //Do not allocate memory,
    //initialize an object in memory address provided by the pointer
    new (&arrayOfAs[i]) A(3);
}

MySQL: Large VARCHAR vs. TEXT?

Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.

I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.

Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.

Combining two sorted lists in Python

Well, the naive approach (combine 2 lists into large one and sort) will be O(N*log(N)) complexity. On the other hand, if you implement the merge manually (i do not know about any ready code in python libs for this, but i'm no expert) the complexity will be O(N), which is clearly faster. The idea is described wery well in post by Barry Kelly.

Trying to add adb to PATH variable OSX

If anyone can't seem to get there .bash_profile file to take any new Paths AND you have other commands in that file (like alias commands) then try moving the PATH statements to the top of the file.

That is the only thing that worked for me. The reason it worked was because I had some typos in my alias commands and apparently this file throws an error and exits if it runs into a problem. So that is why my PATH statements weren't being run. Moving it to the top just let it run first.

Importing large sql file to MySql via command line

The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.

Here is the script https://github.com/kedarvj/mysqldumpsplitter

And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully

make div's height expand with its content

Before to do anything check for css rules with:

{ position:absolute }

Remove if exist and don't need them.

Rails 4 - Strong Parameters - Nested Objects

As odd as it sound when you want to permit nested attributes you do specify the attributes of nested object within an array. In your case it would be

Update as suggested by @RafaelOliveira

params.require(:measurement)
      .permit(:name, :groundtruth => [:type, :coordinates => []])

On the other hand if you want nested of multiple objects then you wrap it inside a hash… like this

params.require(:foo).permit(:bar, {:baz => [:x, :y]})


Rails actually have pretty good documentation on this: http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

For further clarification, you could look at the implementation of permit and strong_parameters itself: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

ADD instruction copies files or folders from a local or remote source and adds them to the container's file system. It used to copy local files, those must be in the working directory. ADD instruction unpacks local .tar files to the destination image directory.

Example

ADD http://someserver.com/filename.pdf /var/www/html

COPY copies files from the working directory and adds them to the container's file system. It is not possible to copy a remote file using its URL with this Dockerfile instruction.

Example

COPY Gemfile Gemfile.lock ./
COPY ./src/ /var/www/html/

PHP - cannot use a scalar as an array warning

The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:

$data = [
"rs" => null
]

this above will work absolutely fine when used like:

$data["rs"] =  5;

But the below will throw a warning ::

$data = [
    "rs" => [
       "rs1" => null;
       ]
    ]
..

$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

The following should fix it for every client.

//Gather output (if it is not already in a variable, use ob_start() and ob_get_clean() )    

// Before sending output:
header('Content-length: ' . strlen($output));

But in my case the following was a better option and fixed it as well:

.htaccess:

php_value opcache.enable 0

How to call a JavaScript function from PHP?

I don't accept the naysayers' answers.

If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.

onClick is a kludge that involves the end-user, hence not acceptable.

@umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):

<script type="text/javascript">
function JSFunction() {
    alert('In test Function');   // This demonstrates that the function was called
}
</script>

<?php
// Call a JS function "from" php

if (true) {   // This if() is to point out that you might
              // want to call JSFunction conditionally
    // An echo like this is how you implant the 'call' in a way
    // that it will be invoked in the client.
    echo '<script type="text/javascript">
         JSFunction();
    </script>';
}

Disable time in bootstrap date time picker

This is for: Eonasdan's Bootstrap Datetimepicker

First of all I would provide an id attribute for the <input> and then initialize the datetimepicker directly for that <input> (and not for the parent container):

<div class="container">
  <input data-format="yyyy-MM-dd" type="text" id="datetimepicker"/>
</div>
<script type="text/javascript">
  $(function() {
    // Bootstrap DateTimePicker v3
    $('#datetimepicker').datetimepicker({
      pickTime: false
    });
    // Bootstrap DateTimePicker v4
    $('#datetimepicker').datetimepicker({
      format: 'DD/MM/YYYY'
    });
  });
</script>

For v3: Contrary to Ck Maurya's answer:

  • pickDate: false will disable the date and only allow to pick a time
  • pickTime: false will disable the time and only allow to pick a date (which is what you want).

For v4: Bootstrap Datetimepicker now uses the format to determine if a time-component is present. If no time component is present, it won't let you choose a time (and hide the clock icon).

Forms authentication timeout vs sessionState timeout

The difference is that one (forms time-out) has to do authenticating the user and the other( session timeout) has to do with how long cached data is stored on the server. So they are very independent things so one doesn't take precedence over the other.

An attempt was made to access a socket in a way forbidden by its access permissions

I had a similar issue with Docker for Windows and Hyper-V having reserved ports for its own use- in my case, it was port 3001 that couldn't be accessed.

  • The port wasn't be used by another process- running netstat -ano | findstr 3001 in an Administrator Powershell prompt showed nothing.
  • However, netsh interface ipv4 show excludedportrange protocol=tcp showed that the port was in one of the exclusion ranges.

I was able to follow the solution described in Docker for Windows issue #3171 (Unable to bind ports: Docker-for-Windows & Hyper-V excluding but not using important port ranges):

  1. Disable Hyper-V:

    dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
    
  2. After the required restarts, reserve the port you want so Hyper-V doesn't reserve it back:

    netsh int ipv4 add excludedportrange protocol=tcp startport=3001 numberofports=1
    
  3. Reenable Hyper-V:

    dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
    

After this, I was able to start my docker container.

Hyphen, underscore, or camelCase as word delimiter in URIs?

The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.

This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.

In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris

As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

modify list of host names for your system:

C:\Windows\System32\drivers\etc\hosts

Make sure that you have the following entry:

127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem

(you may need to change modify permission to modify this file)

This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

What is a non-capturing group in regular expressions?

Well I am a JavaScript developer and will try to explain its significance pertaining to JavaScript.

Consider a scenario where you want to match cat is animal when you would like match cat and animal and both should have a is in between them.

 // this will ignore "is" as that's is what we want
"cat is animal".match(/(cat)(?: is )(animal)/) ;
result ["cat is animal", "cat", "animal"]

 // using lookahead pattern it will match only "cat" we can
 // use lookahead but the problem is we can not give anything
 // at the back of lookahead pattern
"cat is animal".match(/cat(?= is animal)/) ;
result ["cat"]

 //so I gave another grouping parenthesis for animal
 // in lookahead pattern to match animal as well
"cat is animal".match(/(cat)(?= is (animal))/) ;
result ["cat", "cat", "animal"]

 // we got extra cat in above example so removing another grouping
"cat is animal".match(/cat(?= is (animal))/) ;
result ["cat", "animal"]

How to merge many PDF files into a single one?

You can use http://www.mergepdf.net/ for example

Or:

PDFTK http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/

If you are NOT on Ubuntu and you have the same problem (and you wanted to start a new topic on SO and SO suggested to have a look at this question) you can also do it like this:

Things You'll Need:

* Full Version of Adobe Acrobat
  1. Open all the .pdf files you wish to merge. These can be minimized on your desktop as individual tabs.

  2. Pull up what you wish to be the first page of your merged document.

  3. Click the 'Combine Files' icon on the top left portion of the screen.

  4. The 'Combine Files' window that pops up is divided into three sections. The first section is titled, 'Choose the files you wish to combine'. Select the 'Add Open Files' option.

  5. Select the other open .pdf documents on your desktop when prompted.

  6. Rearrange the documents as you wish in the second window, titled, 'Arrange the files in the order you want them to appear in the new PDF'

  7. The final window, titled, 'Choose a file size and conversion setting' allows you to control the size of your merged PDF document. Consider the purpose of your new document. If its to be sent as an e-mail attachment, use a low size setting. If the PDF contains images or is to be used for presentation, choose a high setting. When finished, select 'Next'.

  8. A final choice: choose between either a single PDF document, or a PDF package, which comes with the option of creating a specialized cover sheet. When finished, hit 'Create', and save to your preferred location.

    • Tips & Warnings

Double check the PDF documents prior to merging to make sure all pertinent information is included. Its much easier to re-create a single PDF page than a multi-page document.

HTTP Headers for File Downloads

You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:

<?php

$filename = $_GET['file'];

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
  exit;
};
switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

OrderBy descending in Lambda expression?

Use System.Linq.Enumerable.OrderByDescending()?

For example:

var items = someEnumerable.OrderByDescending();

git: 'credential-cache' is not a git command

I fixed this issue by removing the credential section from the config of specific project:

  • Just typed: git config -e
  • Inside the editor I removed the whole section [credential] helper = cache.

This removed the annoying message :

git: 'credential-cache' is not a git command. See 'git --help'.

How to import Angular Material in project?

Install & Add Material to Angular Projects

There is an automatic/easy way of adding Material to Angular Projects. Use the Angular CLI's install schematic to set up your Angular Material project by running the following command:

ng add @angular/material

The ng add command will additionally perform the following configurations:

  • Add project dependencies to package.json
  • Add the Roboto font to your index.html
  • Add the Material Design icon font to your index.html
  • Add a few global CSS styles to:
    • Remove margins from body
    • Set height: 100% on html and body
    • Set Roboto as the default application font

You're done! Angular Material is now configured to be used in your application.

Read more about this here

How to return a value from __init__ in Python?

Sample Usage of the matter in question can be like:

class SampleObject(object):

    def __new__(cls, item):
        if cls.IsValid(item):
            return super(SampleObject, cls).__new__(cls)
        else:
            return None

    def __init__(self, item):
        self.InitData(item) #large amount of data and very complex calculations

...

ValidObjects = []
for i in data:
    item = SampleObject(i)
    if item:             # in case the i data is valid for the sample object
        ValidObjects.append(item)

I do not have enough reputation so I can not write a comment, it is crazy! I wish I could post it as a comment to weronika

Getting the encoding of a Postgres database

From the command line:

psql my_database -c 'SHOW SERVER_ENCODING'

From within psql, an SQL IDE or an API:

SHOW SERVER_ENCODING

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

For Tomcat running on Ubuntu server, to find out which Java is being used, use "ps -ef | grep tomcat" command:

Sample:

/home/mcp01$ **ps -ef |grep tomcat**
tomcat7  28477     1  0 10:59 ?        00:00:18 **/usr/local/java/jdk1.7.0_15/bin/java** -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -Djava.awt.headless=true -Xmx512m -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/share/tomcat7/endorsed -classpath /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/var/lib/tomcat7 -Dcatalina.home=/usr/share/tomcat7 -Djava.io.tmpdir=/tmp/tomcat7-tomcat7-tmp org.apache.catalina.startup.Bootstrap start
1005     28567 28131  0 11:34 pts/1    00:00:00 grep --color=auto tomcat

Then, we can go in to: cd /usr/local/java/jdk1.7.0_15/jre/lib/security

Default cacerts file is located in here. Insert the untrusted certificate into it.

No Main class found in NetBeans

If the advice to add the closing braces work, I suggest adding indentation to your code so every closing brace is on a spaced separately, i.e.:

public class LuisRp3 {

    public static void main(String[] args) throws FileNotFoundException  {

    // stuff

    }
}

This just helps with readability.

If, on the other hand, you just forgot to copy the closing braces in your code, or the above suggestion doesn't work: open up the configuration and see if you can manually set the main class. I'm afraid I haven't used NetBeans much, so I can't help you with where that option is. My best guess is under "Run Configuration", or something like that.

Edit: See peeskillet's answer if adding closing braces doesn't work.

How can I create a blank/hardcoded column in a sql query?

The answers above are correct, and what I'd consider the "best" answers. But just to be as complete as possible, you can also do this directly in CF using queryAddColumn.

See http://www.cfquickdocs.com/cf9/#queryaddcolumn

Again, it's more efficient to do it at the database level... but it's good to be aware of as many alternatives as possible (IMO, of course) :)

Constructor overloading in Java - best practice

Well, here's an example for overloaded constructors.

public class Employee
{
   private String name;
   private int age;

   public Employee()
   {
      System.out.println("We are inside Employee() constructor");
   }

   public Employee(String name)
   {
      System.out.println("We are inside Employee(String name) constructor");
      this.name = name;
   }

   public Employee(String name, int age)
   {
      System.out.println("We are inside Employee(String name, int age) constructor");
      this.name = name;
      this.age = age;
   }

   public Employee(int age)
   {
      System.out.println("We are inside Employee(int age) constructor");
      this.age = age; 
   }

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public int getAge()
   {
      return age;
   }

   public void setAge(int age)
   {
      this.age = age;
   }
}

In the above example you can see overloaded constructors. Name of the constructors is same but each constructors has different parameters.

Here are some resources which throw more light on constructor overloading in java,

Constructors.

Constructor explanation.

Getting the Facebook like/share count for a given URL

UPDATE: This solution is no longer valid. FQLs are deprecated since August 7th, 2016.


https://api.facebook.com/method/fql.query?query=select%20%20like_count%20from%20link_stat%20where%20url=%22http://www.techlila.com%22

Also http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.techlila.com will show you all the data like 'Share Count', 'Like Count' and 'Comment Count' and total of all these.

Change the URL (i.e. http://www.techlila.com) as per your need.

This is the correct URL, I'm getting right results.

EDIT (May 2017): as of v2.9 you can make a graph API call where ID is the URL and select the 'engagement' field, below is a link with the example from the graph explorer.

https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%3A%2F%2Fcomunidade.edp.pt%26fields%3Dengagement&version=v2.9

How to define the css :hover state in a jQuery selector?

You can try this:

$(".myclass").mouseover(function() {
    $(this).find(" > div").css("background-color","red");
}).mouseout(function() {
    $(this).find(" > div").css("background-color","transparent");
});

DEMO

How to read an external local JSON file in JavaScript?

So, if you are planning to go with "Apache Tomcat" for hosting your JSON file,

1> After starting up the server, verify that your Apache Tomcat is up and running by going to this url: "localhost:8080" -

enter image description here



2> Next, go to the "webapps" folder - "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps". And, create a project folder or copy your project folder.

enter image description here


3> Paste your json file over there. enter image description here



4> And that's it. You are done! Just go to - "http://localhost:8080/$project_name$/$jsonFile_name$.json"enter image description here

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Create an ISO date object in javascript

This worked for me:

_x000D_
_x000D_
var start = new Date("2020-10-15T00:00:00.000+0000");
 //or
start = new date("2020-10-15T00:00:00.000Z");

collection.find({
    start_date:{
        $gte: start
    }
})...etc
_x000D_
_x000D_
_x000D_ new Date(2020,9,15,0,0,0,0) may lead to wrong date: i mean non ISO format (remember javascript count months from 0 to 11 so it's 9 for october)

For..In loops in JavaScript - key value pairs

ES6 will provide Map.prototype.forEach(callback) which can be used like this

myMap.forEach(function(value, key, myMap) {
                        // Do something
                    });

Rendering HTML in a WebView with custom CSS

I assume that your style-sheet "style.css" is already located in the assets-folder

  1. load the web-page with jsoup:

    doc = Jsoup.connect("http://....").get();
    
  2. remove links to external style-sheets:

    // remove links to external style-sheets
    doc.head().getElementsByTag("link").remove();
    
  3. set link to local style-sheet:

    // set link to local stylesheet
    // <link rel="stylesheet" type="text/css" href="style.css" />
    doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
    
  4. make string from jsoup-doc/web-page:

    String htmldata = doc.outerHtml();
    
  5. display web-page in webview:

    WebView webview = new WebView(this);
    setContentView(webview);
    webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
    

Convert a date format in PHP

function dateFormat($date)
{
    $m = preg_replace('/[^0-9]/', '', $date);
    if (preg_match_all('/\d{2}+/', $m, $r)) {
        $r = reset($r);
        if (count($r) == 4) {
            if ($r[2] <= 12 && $r[3] <= 31) return "$r[0]$r[1]-$r[2]-$r[3]"; // Y-m-d
            if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$r[2]$r[3]-$r[1]-$r[0]"; // d-m-Y
            if ($r[0] <= 12 && $r[1] <= 31) return "$r[2]$r[3]-$r[0]-$r[1]"; // m-d-Y
            if ($r[2] <= 31 && $r[3] <= 12) return "$r[0]$r[1]-$r[3]-$r[2]"; //Y-m-d
        }

        $y = $r[2] >= 0 && $r[2] <= date('y') ? date('y') . $r[2] : (date('y') - 1) . $r[2];
        if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$y-$r[1]-$r[0]"; // d-m-y
    }
}

var_dump(dateFormat('31/01/00')); // return 2000-01-31
var_dump(dateFormat('31/01/2000')); // return 2000-01-31
var_dump(dateFormat('01-31-2000')); // return 2000-01-31
var_dump(dateFormat('2000-31-01')); // return 2000-01-31
var_dump(dateFormat('20003101')); // return 2000-01-31

How to create a new branch from a tag?

If you simply want to create a new branch without immediately changing to it, you could do the following:

git branch newbranch v1.0

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

If you got the error in your IDE(compile-time error), you need to add your mysql-connector jar file to your libs and add this to your referenced library of project too.

If you get this error when you are running it, then probably its because you have not included mysql-connector JAR file to your webserver's lib folder.

Add mysql-connector-java-5.1.25-bin.jar to your classpath and also to your webserver's lib directory. Tomcat lib path is given as an example Tomcat 6.0\lib

How do I force "git pull" to overwrite local files?

An easier way would be to:

git checkout --theirs /path/to/file.extension
git pull origin master

This will override your local file with the file on git

How to avoid soft keyboard pushing up my layout?

For future readers.

I wanted specific control over this issue, so this is what I did:

From a fragment or activity, hide your other views (that aren't needed while the keyboard is up), then restore them to solve this problem:

rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
     @Override
     public void onGlobalLayout() {
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);

        if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
           //ok now we know the keyboard is up...
           view_one.setVisibility(View.GONE);
           view_two.setVisibility(View.GONE);

        } else {
           //ok now we know the keyboard is down...
           view_one.setVisibility(View.VISIBLE);
           view_two.setVisibility(View.VISIBLE);       
        }
     }
});

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
{
    return ViewComponent("AddURL");
}

You can load it using JQuery load method.

$(document).ready (function(){
    $("#LoadSignIn").click(function(){
        $('#UserControl').load("/Home/AddURLTest");
    });
});

source code link

"Could not find a valid gem in any repository" (rubygame and others)

You can also add the source you want on the command whenever you have troubles using https, like this:

gem install GEMNAME --source http://rubygems.org

It's better to fix the SSL problem though.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

What is the difference between VFAT and FAT32 file systems?

Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx

What's FAT?

FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.

The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.

What About VFAT?

Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.

When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.

An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.

You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.

FAT32

FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.

The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.

This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.

Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.

Note: This section of the quote/ article (1999) is out of date. Updated info quote below.

As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.

The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.

Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.

Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):

I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.

The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.

The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.

How do I share variables between different .c files?

The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.

That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

How can I divide two integers to get a double?

Complementing the @NoahD's answer

To have a greater precision you can cast to decimal:

(decimal)100/863
//0.1158748551564310544611819235

Or:

Decimal.Divide(100, 863)
//0.1158748551564310544611819235

Double are represented allocating 64 bits while decimal uses 128

(double)100/863
//0.11587485515643106

In depth explanation of "precision"

For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats and doubles and this one where he talks about decimals.

Java generics: multiple generic parameters?

a and b must both be sets of the same type. But nothing prevents you from writing

myfunction(Set<X> a, Set<Y> b)

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

The name 'ViewBag' does not exist in the current context

For MVC5, in case you are building an application from scratch. You need to add a web.config file to the Views folder and paste the following code in it.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</configuration>

Note that for MVC 3 you will have to change version to 3.0.0.0 at

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

You may have to close and open the *.cshtml page again to see the changes.

Find unused code

I have come across AXTools CODESMART..Try that once. Use code analyzer in reviews section.It will list dead local and global functions along with other issues.

What is the difference between single-quoted and double-quoted strings in PHP?

In PHP, single quote text is considered as string value and double quote text will parse the variables by replacing and processing their value.

$test = "variable";
echo "Hello Mr $test"; // the output would be: Hello Mr variable
echo 'Hello Mr $test'; // the output would be: Hello Mr $test

Here, double quote parse the value and single quote is considered as string value (without parsing the $test variable.)

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Deleting records before a certain date

To show result till yesterday

WHERE DATE(date_time) < CURDATE()

To show results of 10 days

WHERE date_time < NOW() - INTERVAL 10 DAY

To show results before 10 days

WHERE DATE(date_time) < DATE(NOW() - INTERVAL 10 DAY)

These will work for you

You can find dates like this

SELECT DATE(NOW() - INTERVAL 11 DAY)

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Invalidating JSON Web Tokens

If you want to be able to revoke user tokens, you can keep track of all issued tokens on your DB and check if they're valid (exist) on a session-like table. The downside is that you'll hit the DB on every request.

I haven't tried it, but i suggest the following method to allow token revocation while keeping DB hits to a minimum -

To lower the database checks rate, divide all issued JWT tokens into X groups according to some deterministic association (e.g., 10 groups by first digit of the user id).

Each JWT token will hold the group id and a timestamp created upon token creation. e.g., { "group_id": 1, "timestamp": 1551861473716 }

The server will hold all group ids in memory and each group will have a timestamp that indicates when was the last log-out event of a user belonging to that group. e.g., { "group1": 1551861473714, "group2": 1551861487293, ... }

Requests with a JWT token that have an older group timestamp, will be checked for validity (DB hit) and if valid, a new JWT token with a fresh timestamp will be issued for client's future use. If the token's group timestamp is newer, we trust the JWT (No DB hit).

So -

  1. We only validate a JWT token using the DB if the token has an old group timestamp, while future requests won't get validated until someone in the user's group will log-out.
  2. We use groups to limit the number of timestamp changes (say there's a user logging in and out like there's no tomorrow - will only affect limited number of users instead of everyone)
  3. We limit the number of groups to limit the amount of timestamps held in memory
  4. Invalidating a token is a breeze - just remove it from the session table and generate a new timestamp for the user's group.

Replace CRLF using powershell

The following will be able to process very large files quickly.

$file = New-Object System.IO.StreamReader -Arg "file1.txt"
$outstream = [System.IO.StreamWriter] "file2.txt"
$count = 0 

while ($line = $file.ReadLine()) {
      $count += 1
      $s = $line -replace "`n", "`r`n"
      $outstream.WriteLine($s)
  }

$file.close()
$outstream.close()

Write-Host ([string] $count + ' lines have been processed.')

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

How to align text below an image in CSS?

Since the default for block elements is to order one on top of the other you should also be able to do this:

<div>
    <img src="path/to/img">
    <div>Text Under Image</div>
</div

img {
    display: block;
}

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I got this issue after migration to Gradle 3.3, on Windows (with gradle-2.14.1 everything was fine).

The problem was in the path to the Gradle build-cache, which contains Cyrillic characters, like

C:\Users\????\.android\build-cache

So I renamed the user's folder to "Ivan", and the problem was gone.

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Simply use This:

driver.find_elements_by_xpath('//*[text() = "My Button"]')

VSCode regex find & replace submatch math?

For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.

So, in case this is your first contact with either:

To find and modify text,

  1. In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2), using parentheses. This would find the same text as I want to find group1 and group2, but with the difference that you can then reference group1 and group2 in the next step:

  2. In the "Replace" step, you can refer to the capturing groups via $1, $2 etc, so you could change the sentence to I found $1 and $2 having a picnic, which would output I found group1 and group2 having a picnic.

Notes:

  • Instead of just a string, anything inside or outside the () can be a regular expression.

  • $0 refers to the whole match

http://localhost/phpMyAdmin/ unable to connect

You dont start phpmyadmin from your webbrowser. When you want to start PHPMyAdmin you have to do so from the XAMPP control-panel. When you've started phpmyadmin from your control-panel you can access it from the web-browser.

How do I remove blank elements from an array?

Here is one more approach to achieve this

we can use presence with select

cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]

cities.select(&:presence)

["Kathmandu", "Pokhara", "Dharan", "Butwal"]

How to set placeholder value using CSS?

I recently had to do this with google's search box, this is an extreme hack reserved for extreme situations (the resulting selector was slightly different, but I made it work in this example)

_x000D_
_x000D_
/*_x000D_
 this is just used to calculate the resulting svg data url and need not be included in the final page_x000D_
*/_x000D_
_x000D_
var text = placeholder.outerHTML;_x000D_
 var url = "data:image/svg+xml;,"+text.replace(/id="placeholder"/g," ").replace(/\n|([ ] )/g,"");//.replace(/" /g,"\"");_x000D_
img.src = url;_x000D_
result.value = url;_x000D_
overlay.style.backgroundImage = "url('"+url+"')";
_x000D_
svg,img{_x000D_
  border: 3px dashed black;_x000D_
}_x000D_
textarea{_x000D_
width:50%;_x000D_
height:300px;_x000D_
vertical-align: top;_x000D_
}_x000D_
.wrapper{_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}_x000D_
#overlay{_x000D_
  position:absolute;_x000D_
  left:0;_x000D_
  top:0;_x000D_
  right:0;_x000D_
  bottom:0;_x000D_
  pointer-events: none;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center left;_x000D_
}_x000D_
#my_input:focus + #overlay{_x000D_
  display: none;_x000D_
}
_x000D_
As SVG <svg id="placeholder"xmlns="http://www.w3.org/2000/svg"width="235"height="13"><text x="0"y="10"font-family="Verdana"font-size="12" fill ="green">Some New Rad Placeholder</text></svg>_x000D_
<br>_x000D_
As IMG <img id="img">_x000D_
<br>_x000D_
As Data URI <textarea id="result"></textarea><br>_x000D_
_x000D_
As "Placeholder" <div class="wrapper">_x000D_
  <input id="my_input" />_x000D_
  <div id="overlay">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to change navbar/container width? Bootstrap 3

The .navbar-static-top you are using forces your navbar to become full-width. Remove that class and you will get a resizable navbar. Then, you can wrap it in a span# of the size you want.

<div class="container">
<div class="row">
    <div class="span6 offset3">
        <div class="navbar">
            ...
        </div>
    </div>
</div>

Check if a String contains a special character

Use java.util.regex.Pattern class's static method matches(regex, String obj)
regex : characters in lower and upper case & digits between 0-9
String obj : String object you want to check either it contain special character or not.

It returns boolean value true if only contain characters and numbers, otherwise returns boolean value false

Example.

String isin = "12GBIU34RT12";<br>
if(Pattern.matches("[a-zA-Z0-9]+", isin)<br>{<br>
   &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Valid isin");<br>
}else{<br>
   &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Invalid isin");<br>
}

How to set focus on input field?

It's easy.. try this

html

<select id="ddl00">  
 <option>"test 01"</option>  
</select>

javascript

document.getElementById("ddl00").focus();

How to generate unique ID with node.js

node-uuid is deprecated so please use uuid

npm install uuid --save
// Generate a v1 UUID (time-based) 
const uuidV1 = require('uuid/v1');
uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

// Generate a v4 UUID (random) 
const uuidV4 = require('uuid/v4');
uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

Npm link

Try catch statements in C

C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

static jmp_buf s_jumpBuffer;

void Example() { 
  if (setjmp(s_jumpBuffer)) {
    // The longjmp was executed and returned control here
    printf("Exception happened here\n");
  } else {
    // Normal code execution starts here
    Test();
  }
}

void Test() {
  // Rough equivalent of `throw`
  longjmp(s_jumpBuffer, 42);
}

This website has a nice tutorial on how to simulate exceptions with setjmp and longjmp

Artisan migrate could not find driver

whilst sometimes you might have multiple php versions, you might also have a held-back version of php-mysql.. do a sudo dpkg -l | grep mysql | grep php and compare what you get from php -v

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

Show div #id on click with jQuery

This is simple way to Display Div using:-

$("#musicinfo").show();  //or
$("#musicinfo").css({'display':'block'});  //or
$("#musicinfo").toggle("slow");   //or
$("#musicinfo").fadeToggle();    //or

Is there a .NET/C# wrapper for SQLite?

A barebones wrapper of the functions as provided by the sqlite library. Latest version supports functions provided sqlite library 3.7.10

SQLiteWrapper project

How can I get the nth character of a string?

Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:

char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];

...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:

str = str + 1; // makes it point to 'E' now
char myChar =  *str;

I hope this helps.

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

In this case, first of all you need to check the java version using below command:

java -version

after running this command you get something like this:

java version "1.7.0_51" OpenJDK Runtime Environment (rhel-2.4.5.5.el7-x86_64 u51-b31) OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

then use this command:

update-alternatives --config java

and select the below version

*+ 1 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.51-2.4.5.5.el7.x86_64/jre/bin/java 2 /usr/java/jdk1.8.0_73/jre/bin/java

Enter to keep the current selection[+], or type selection number: 2

curl -XGET http://127.0.0.1:9200

How to replace list item in best way

Why not use the extension methods?

Consider the following code:

        var intArray = new int[] { 0, 1, 1, 2, 3, 4 };
        // Replaces the first occurance and returns the index
        var index = intArray.Replace(1, 0);
        // {0, 0, 1, 2, 3, 4}; index=1

        var stringList = new List<string> { "a", "a", "c", "d"};
        stringList.ReplaceAll("a", "b");
        // {"b", "b", "c", "d"};

        var intEnum = intArray.Select(x => x);
        intEnum = intEnum.Replace(0, 1);
        // {0, 0, 1, 2, 3, 4} => {1, 1, 1, 2, 3, 4}
  • No code duplication
  • There is no need to type long linq expressions
  • There is no need for additional usings

The source code:

namespace System.Collections.Generic
{
    public static class Extensions
    {
        public static int Replace<T>(this IList<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            var index = source.IndexOf(oldValue);
            if (index != -1)
                source[index] = newValue;
            return index;
        }

        public static void ReplaceAll<T>(this IList<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            int index = -1;
            do
            {
                index = source.IndexOf(oldValue);
                if (index != -1)
                    source[index] = newValue;
            } while (index != -1);
        }


        public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            return source.Select(x => EqualityComparer<T>.Default.Equals(x, oldValue) ? newValue : x);
        }
    }
}

The first two methods have been added to change the objects of reference types in place. Of course, you can use just the third method for all types.

P.S. Thanks to mike's observation, I've added the ReplaceAll method.

PHP date yesterday

date() itself is only for formatting, but it accepts a second parameter.

date("F j, Y", time() - 60 * 60 * 24);

To keep it simple I just subtract 24 hours from the unix timestamp.

A modern oop-approach is using DateTime

$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";

Or in your case (more readable/obvious)

$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";

(Because DateInterval is negative here, we must add() it here)

See also: DateTime::sub() and DateInterval

SELECT INTO USING UNION QUERY

INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2

Confused about Service vs Factory

I had this confusion for a while and I'm trying my best to provide a simple explanation here. Hope this will help!

angular .factory and angular .service both are used to initialize a service and work in the same way.

The only difference is, how you want to initialize your service.

Both are Singletons


var app = angular.module('app', []);


Factory

app.factory(<service name>, <function with a return value>)

If you would like to initialize your service from a function that you have with a return value, you have to use this factory method.

e.g.

function myService() {
  //return what you want
  var service = {
    myfunc: function (param) { /* do stuff */ }
  }
  return service;
}

app.factory('myService', myService);

When injecting this service (e.g. to your controller):

  • Angular will call your given function (as myService()) to return the object
  • Singleton - called only once, stored, and pass the same object.


Service

app.service(<service name>, <constructor function>)

If you would like to initialize your service from a constructor function (using this keyword), you have to use this service method.

e.g.

function myService() {
  this.myfunc: function (param) { /* do stuff */ }
}

app.service('myService', myService);

When injecting this service (e.g. to your controller):

  • Angular will newing your given function (as new myService()) to return the object
  • Singleton - called only once, stored, and pass the same object.


NOTE: If you use factory with <constructor function> or service with <function with a return value>, it will not work.


Examples - DEMOs

Problems with a PHP shell script: "Could not open input file"

I know its stupid but in my case i was outside of my project folder i didn't have spark file.

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

Seeing if data is normally distributed in R

The Anderson-Darling test is also be useful.

library(nortest)
ad.test(data)

CSS Auto hide elements after 5 seconds

Why not try fadeOut?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#plsme').fadeOut(5000); // 5 seconds x 1000 milisec = 5000 milisec_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='plsme'>Loading... Please Wait</div>
_x000D_
_x000D_
_x000D_

fadeOut (Javascript Pure):

How to make fadeOut effect with pure JavaScript

Limitations of SQL Server Express

You can't install Integration Services with it. Express does not support Integration Services. So if you want build say SSIS-packages you'll need at least Standard Edition.

See more here.

How do I import modules or install extensions in PostgreSQL 9.1+?

How to download and install if you have SUSE. As an example I am downloading the tablefunc module so I can use crosstab. I have PostgreSQL 9.6.1.

right-click desktop, terminal, type:

sudo zypper in postgreql-contrib

Enter credentials, continue by typing:

y

Run query (I ran mine from pgAdminIII):

CREATE EXTENSION tablefunc;

You should now have the crosstab function.

I did not have to restart.

How can I convert my Java program to an .exe file?

UPDATE: GCJ is dead. It was officially removed from the GCC project in 2016. Even before that, it was practically abandoned for seven years, and in any case it was never sufficiently complete to serve as a viable alternative Java implementation.

Go find another Java AOT compiler.

GCJ: The GNU Compiler for Java can compile Java source code into native machine code, including Windows executables.

Although not everything in Java is supported under GCJ, especially the GUI components (see What Java API's are supported? How complete is the support? question from the FAQ). I haven't used GCJ much, but from the limited testing I've done with console applications, it seems fine.

One downside of using GCJ to create an standalone executable is that the size of the resulting EXE can be quite large. One time I compiled a trivial console application in GCJ and the result was an executable about 1 MB. (There may be ways around this that I am not aware of. Another option would be executable compression programs.)

In terms of open-source installers, the Nullsoft Scriptable Install System is a scriptable installer. If you're curious, there are user contributed examples on how to detect the presence of a JRE and install it automatically if the required JRE is not installed. (Just to let you know, I haven't used NSIS before.)

For more information on using NSIS for installing Java applications, please take a look at my response for the question "What's the best way to distribute Java applications?"

Import existing source code to GitHub

As JB quite rightly points out, it's made incredibly easy on GitHub by simply following the instructions.

Here's an example of the instructions displayed after setting up a new repository on GitHub using http://github.com/new when you're logged in.

Global setup:

 Set up Git:
  git config --global user.name "Name"
  git config --global user.email [email protected]


Next steps:

  mkdir audioscripts
  cd audioscripts
  git init
  touch README
  git add README
  git commit -m 'first commit'
  git remote add origin [email protected]:ktec/audioscripts.git
  git push -u origin master


Existing Git repository?

  cd existing_git_repo
  git remote add origin [email protected]:ktec/audioscripts.git
  git push -u origin master


Importing a Subversion repository?

  Check out the guide for step-by-step instructions.

It couldn't be easier!!

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

Delete the java.exe process in Task Manager and re-execute.It worked for me.

What is the difference between supervised learning and unsupervised learning?

Supervised learning

Applications in which the training data comprises examples of the input vectors along with their corresponding target vectors are known as supervised learning problems.

Unsupervised learning

In other pattern recognition problems, the training data consists of a set of input vectors x without any corresponding target values. The goal in such unsupervised learning problems may be to discover groups of similar examples within the data, where it is called clustering

Pattern Recognition and Machine Learning (Bishop, 2006)

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

Gson library in Android Studio

Read Google-gson

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Add the following line to your MODULE LEVEL build.gradle configuration:

dependencies {
     implementation 'com.google.code.gson:gson:2.8.5' // Old 2.8.2
}

Efficient way to insert a number into a sorted array of numbers?

function insertOrdered(array, elem) {
    let _array = array;
    let i = 0;
    while ( i < array.length && array[i] < elem ) {i ++};
    _array.splice(i, 0, elem);
    return _array;
}

Download files from server php

Here is a simpler solution to list all files in a directory and to download it.

In your index.php file

<?php
$dir = "./";

$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..')); // To remove . and .. 

foreach($files as $file){
     echo "<a href='download.php?file=".$file."'>".$file."</a><br>";
}

The scandir() function list all files and directories inside the specified path. It works with both PHP 5 and PHP 7.

Now in the download.php

<?php
$filename = basename($_GET['file']);
// Specify file path.
$path = ''; // '/uplods/'
$download_file =  $path.$filename;

if(!empty($filename)){
    // Check file is exists on given path.
    if(file_exists($download_file))
    {
      header('Content-Disposition: attachment; filename=' . $filename);  
      readfile($download_file); 
      exit;
    }
    else
    {
      echo 'File does not exists on given path';
    }
 }

Get yesterday's date in bash on Linux, DST-safe

As this question is tagged "DST safe"

And using fork to date command implie delay, there is a simple and more efficient way using pure bash built-in:

printf -v tznow '%(%z %s)T' -1
TZ=${tznow% *} printf -v yesterday '%(%Y-%m-%d)T' $(( ${tznow#* } - 86400 ))
echo $yesterday

This is a lot quicker on more system friendly than having to fork to date.

From V>=5.0, there is a new variable $EPOCHSECONDS

printf -v tz '%(%z)T' -1
TZ=$tz printf -v yesterday '%(%Y-%m-%d)T' $(( EPOCHSECONDS - 86400 ))
echo $yesterday