Programs & Examples On #Kqueue

Kqueue is a scalable event notification interface introduced in FreeBSD 4.1,[1] also supported in NetBSD, OpenBSD, DragonflyBSD, and Mac OS X.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

HttpClientModule needs to be in the imports array, and remove it from providers. That section is for you to tell Angular which services the module has (written by you and not imported from a library).

Cannot find control with name: formControlName in angular reactive form

For me even with [formGroup] the error was popping up "Cannot find control with name:''".
It got fixed when I added ngModel Value to the input box along with formControlName="fileName"

  <form class="upload-form" [formGroup]="UploadForm">
  <div class="row">
    <div class="form-group col-sm-6">
      <label for="fileName">File Name</label>
      <!-- *** *** *** Adding [(ngModel)]="FileName" fixed the issue-->
      <input type="text" class="form-control" id="fileName" [(ngModel)]="FileName"
        placeholder="Enter file name" formControlName="fileName"> 
    </div>
    <div class="form-group col-sm-6">
      <label for="selectedType">File Type</label>
      <select class="form-control" formControlName="selectedType" id="selectedType" 
        (change)="TypeChanged(selectedType)" name="selectedType" disabled="true">
        <option>Type 1</option>
        <option>Type 2</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label for="fileUploader">Select {{selectedType}} file</label>
    <input type="file" class="form-control-file" id="fileUploader" (change)="onFileSelected($event)">
  </div>
  <div class="w-80 text-right mt-3">
    <button class="btn btn-primary mb-2 search-button cancel-button" (click)="cancelUpload()">Cancel</button>
    <button class="btn btn-primary mb-2 search-button" (click)="uploadFrmwrFile()">Upload</button>
  </div>
 </form>

And in the controller

ngOnInit() {
this.UploadForm= new FormGroup({
  fileName: new FormControl({value: this.FileName}),
  selectedType: new FormControl({value: this.selectedType, disabled: true}, Validators.required),
  frmwareFile: new FormControl({value: ['']})
});
}

Error: Unexpected value 'undefined' imported by the module

I had the same issue, I added the component in the index.ts of a=of the folder and did a export. Still the undefined error was popping. But the IDE pop our any red squiggly lines

Then as suggested changed from

import { SearchComponent } from './';

to

import { SearchComponent } from './search/search.component';

Spark - load CSV file as DataFrame?

There are a lot of challenges to parsing a CSV file, it keeps adding up if the file size is bigger, if there are non-english/escape/separator/other characters in the column values, that could cause parsing errors.

The magic then is in the options that are used. The ones that worked for me and hope should cover most of the edge cases are in code below:

### Create a Spark Session
spark = SparkSession.builder.master("local").appName("Classify Urls").getOrCreate()

### Note the options that are used. You may have to tweak these in case of error
html_df = spark.read.csv(html_csv_file_path, 
                         header=True, 
                         multiLine=True, 
                         ignoreLeadingWhiteSpace=True, 
                         ignoreTrailingWhiteSpace=True, 
                         encoding="UTF-8",
                         sep=',',
                         quote='"', 
                         escape='"',
                         maxColumns=2,
                         inferSchema=True)

Hope that helps. For more refer: Using PySpark 2 to read CSV having HTML source code

Note: The code above is from Spark 2 API, where the CSV file reading API comes bundled with built-in packages of Spark installable.

Note: PySpark is a Python wrapper for Spark and shares the same API as Scala/Java.

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

Oracle - Insert New Row with Auto Incremental ID

ELXAN@DB1> create table cedvel(id integer,ad varchar2(15));

Table created.

ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id);

Table altered.

ELXAN@DB1> create sequence test_seq start with 1 increment by 1;

Sequence created.

ELXAN@DB1> create or replace trigger ad_insert
before insert on cedvel
REFERENCING NEW AS NEW OLD AS OLD
for each row
begin
    select test_seq.nextval into :new.id from dual;
end;
/  2    3    4    5    6    7    8 

Trigger created.

ELXAN@DB1> insert into cedvel (ad) values ('nese');

1 row created.

ExecutorService that interrupts tasks after a timeout

You can use this implementation that ExecutorService provides

invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
as

executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);

However, in my case, I could not as Arrays.asList took extra 20ms.

How do I write a bash script to restart a process if it dies?

I've used the following script with great success on numerous servers:

pid=`jps -v | grep $INSTALLATION | awk '{print $1}'`
echo $INSTALLATION found at PID $pid 
while [ -e /proc/$pid ]; do sleep 0.1; done

notes:

  • It's looking for a java process, so I can use jps, this is much more consistent across distributions than ps
  • $INSTALLATION contains enough of the process path that's it's totally unambiguous
  • Use sleep while waiting for the process to die, avoid hogging resources :)

This script is actually used to shut down a running instance of tomcat, which I want to shut down (and wait for) at the command line, so launching it as a child process simply isn't an option for me.

How to 'insert if not exists' in MySQL?

Update or insert without known primary key

If you already have a unique or primary key, the other answers with either INSERT INTO ... ON DUPLICATE KEY UPDATE ... or REPLACE INTO ... should work fine (note that replace into deletes if exists and then inserts - thus does not partially update existing values).

But if you have the values for some_column_id and some_type, the combination of which are known to be unique. And you want to update some_value if exists, or insert if not exists. And you want to do it in just one query (to avoid using a transaction). This might be a solution:

INSERT INTO my_table (id, some_column_id, some_type, some_value)
SELECT t.id, t.some_column_id, t.some_type, t.some_value
FROM (
    SELECT id, some_column_id, some_type, some_value
    FROM my_table
    WHERE some_column_id = ? AND some_type = ?
    UNION ALL
    SELECT s.id, s.some_column_id, s.some_type, s.some_value
    FROM (SELECT NULL AS id, ? AS some_column_id, ? AS some_type, ? AS some_value) AS s
) AS t
LIMIT 1
ON DUPLICATE KEY UPDATE
some_value = ?

Basically, the query executes this way (less complicated than it may look):

  • Select an existing row via the WHERE clause match.
  • Union that result with a potential new row (table s), where the column values are explicitly given (s.id is NULL, so it will generate a new auto-increment identifier).
  • If an existing row is found, then the potential new row from table s is discarded (due to LIMIT 1 on table t), and it will always trigger an ON DUPLICATE KEY which will UPDATE the some_value column.
  • If an existing row is not found, then the potential new row is inserted (as given by table s).

Note: Every table in a relational database should have at least a primary auto-increment id column. If you don't have this, add it, even when you don't need it at first sight. It is definitely needed for this "trick".

Remove NA values from a vector

?max shows you that there is an extra parameter na.rm that you can set to TRUE.

Apart from that, if you really want to remove the NAs, just use something like:

myvec[!is.na(myvec)]

How can I split a text into sentences?

Also, be wary of additional top level domains that aren't included in some of the answers above.

For example .info, .biz, .ru, .online will throw some sentence parsers but aren't included above.

Here's some info on frequency of top level domains: https://www.westhost.com/blog/the-most-popular-top-level-domains-in-2017/

That could be addressed by editing the code above to read:

alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov|ai|edu|co.uk|ru|info|biz|online)"

HTML form do some "action" when hit submit button

Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems

Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:

For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:

<html>   
<head>
 <title>Test Page</title>
</head>   
<body>   
    <h2>Data Collection</h2><p>
    <form action="process.php" method="post">  
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="Name"/></td>
            </tr>   
            <tr>
                <td>Age:</td>
                <td><input type="text" name="Age"/></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                <input type="submit"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:

<?php   
    print "Your name is ". $Name;   
    print "<br />";   
    print "You are ". $Age . " years old";   
    print "<br />";   $old = 25 + $Age;
    print "In 25 years you will be " . $old . " years old";   
?>

As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.

Additional JavaScript Example

This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.

Note: document.getElementById("fname").value gets the object with the ID tag that equals fname and then pulls it's value - which in this case is the text in the First Name textbox.

 <html>
    <head>
     <script type="text/javascript">
     function ExampleJS(){
        var jFirst = document.getElementById("fname").value;
        var jLast = document.getElementById("lname").value;
        alert("Your name is: " + jFirst + " " + jLast);
     }
     </script>

    </head>
    <body>
        <FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">

             First name: <input type="text" id="fname" name="firstname" /><br />
             Last name:  <input type="text" id="lname" name="lastname" /><br />
            <input name="Submit"  type="submit" value="Update" />
        </FORM>
    </body>
</html>

CSS3 Spin Animation

You haven't specified any keyframes. I made it work here.

div {
    margin: 20px;
    width: 100px; 
    height: 100px;    
    background: #f00;
    -webkit-animation: spin 4s infinite linear;
}

@-webkit-keyframes spin {
    0%  {-webkit-transform: rotate(0deg);}
    100% {-webkit-transform: rotate(360deg);}   
}

You can actually do lots of really cool stuff with this. Here is one I made earlier.

:)

N.B. You can skip having to write out all the prefixes if you use -prefix-free.

Using BeautifulSoup to extract text without tags

Just loop through all the <strong> tags and use next_sibling to get what you want. Like this:

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

Demo:

from bs4 import BeautifulSoup

html = '''
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''

soup = BeautifulSoup(html)

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

This gives you:

YOB:  1987
RACE:  WHITE
GENDER:  FEMALE
HEIGHT:  5'05''
WEIGHT:  118
EYE COLOR:  GREEN
HAIR COLOR:  BROWN

How to tar certain file types in all subdirectories?

tar -cf my_archive `find ./ | grep '.php\|.html'`

Use "find" and "grep" to get all path of .php and .html files in all directory and its sub-directories. Then pass those path information to tar to compress.

Please be careful with those symbol ` and '. Note also that this will hit the limit of how many characters your shell will allow on the command line, unlike some of the other answers.

Opening a new tab to read a PDF file

As everyone else has pointed out, this can work:

<a href="newsletter_01.pdf" target="_blank">Read more</a> 

But what nobody has pointed out is that it's not guaranteed to work.

There is no way to force a user's browser to open a PDF file in a new tab. Depending on the user's browser settings, even with target="_blank" the browser may react the following ways:

  1. Ask for action
  2. Open it in Adobe Acrobat
  3. Simply download the file directly to their computer

Take a look at Firefox's settings, for example:

enter image description here

Chrome has a similar setting:

enter image description here

If the user has chosen to "Save File" in their browsers settings when encountering a PDF, there is no way you can override it.

Format date to MM/dd/yyyy in JavaScript

All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.

i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.

I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
  var year = date.getFullYear();_x000D_
_x000D_
  var month = (1 + date.getMonth()).toString();_x000D_
  month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
  var day = date.getDate().toString();_x000D_
  day = day.length > 1 ? day : '0' + day;_x000D_
  _x000D_
  return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_


Update for ES2017 using String.padStart(), supported by all major browsers except IE.

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
    let year = date.getFullYear();_x000D_
    let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
    let day = date.getDate().toString().padStart(2, '0');_x000D_
  _x000D_
    return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_

How to get all key in JSON object (javascript)

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "[email protected]" };

for (x in jsonData) {   
  console.log(x +" => "+ jsonData[x]);  
  alert(x +" => "+  jsonData[x]);  
  }

How do you auto format code in Visual Studio?

You can add the buttons to your toolbar by clicking the little drop down arrow to the right of the last toolbar button, select "Add or Remove Buttons" and then click the buttons you want to add a tick to them. The button(s) you select will appear on your toolbar ...

enter image description here

Then you just select text and click the Increase Indent or Decrease Indent buttons. I tested this on Visual Studio 2013 only.

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

"Class.forName()" returns the Class-Type for the given name. "newInstance()" does return an instance of this class.

On the type you can't call directly any instance methods but can only use reflection for the class. If you want to work with an object of the class you have to create an instance of it (same as calling "new MyClass()").

Example for "Class.forName()"

Class myClass = Class.forName("test.MyClass");
System.out.println("Number of public methods: " + myClass.getMethods().length);

Example for "Class.forName().newInstance()"

MyClass myClass = (MyClass) Class.forName("test.MyClass").newInstance();
System.out.println("String representation of MyClass instance: " + myClass.toString());

Postgres user does not exist?

OS X tends to prefix the system account names with "_"; you don't say what version of OS X you're using, but at least in 10.8 and 10.9 the _postgres user exists in a default install. Note that you won't be able to su to this account (except as root), since it doesn't have a password. sudo -u _postgres, on the other hand, should work fine.

How can I count all the lines of code in a directory recursively?

A straightforward one that will be fast, will use all the search/filtering power of find, not fail when there are too many files (number arguments overflow), work fine with files with funny symbols in their name, without using xargs, and will not launch a uselessly high number of external commands (thanks to + for find's -exec). Here you go:

find . -name '*.php' -type f -exec cat -- {} + | wc -l

How to get the wsdl file from a webservice's URL

to get the WSDL (Web Service Description Language) from a Web Service URL.

Is possible from SOAP Web Services:

http://www.w3schools.com/xml/tempconvert.asmx

to get the WSDL we have only to add ?WSDL , for example:

http://www.w3schools.com/xml/tempconvert.asmx?WSDL

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.

With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.

Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s

node and Error: EMFILE, too many open files

Building on @blak3r's answer, here's a bit of shorthand I use in case it helps other diagnose:

If you're trying to debug a Node.js script that is running out of file descriptors here's a line to give you the output of lsof used by the node process in question:

openFiles = child_process.execSync(`lsof -p ${process.pid}`);

This will synchronously run lsof filtered by the current running Node.js process and return the results via buffer.

Then use console.log(openFiles.toString()) to convert the buffer to a string and log the results.

Maven in Eclipse: step by step installation

You have to follow the following steps in the Eclipse IDE

  1. Go to Help - > Install New Software
  2. Click add button at top right corner
  3. In the popup coming, type in name as "Maven" and location as "http://download.eclipse.org/technology/m2e/releases"
  4. Click on OK.

Maven integration for eclipse will be dowloaded and installed. Restart the workspace.

In the .m2 folder(usually under C:\user\ directory) add settings.xml. Give proper proxy and profiles. Now create a new Maven project in eclipse.

Overflow Scroll css is not working in the div

For Angular2 + Material2 + Sidenav, you'll need to do the following:

 ngAfterViewInit() {
   this.element.nativeElement.getElementsByClassName('md-sidenav-content')[0].style.overflow = 'hidden'; 
  }

Can an XSLT insert the current date?

...
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:local="urn:local" extension-element-prefixes="msxsl">

    <msxsl:script language="CSharp" implements-prefix="local">
        public string dateTimeNow()
        {       
          return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); 
        } 
    </msxsl:script>  
...
    <xsl:value-of select="local:dateTimeNow()"/>

JavaScript - get the first day of the week from current date

setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.

function getPreviousMonday(fromDate) {
    var dayMillisecs = 24 * 60 * 60 * 1000;

    // Get Date object truncated to date.
    var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));

    // If today is Sunday (day 0) subtract an extra 7 days.
    var dayDiff = d.getDay() === 0 ? 7 : 0;

    // Get date diff in millisecs to avoid setDate() bugs with month boundaries.
    var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;

    // Return date as YYYY-MM-DD string.
    return new Date(mondayMillisecs).toISOString().slice(0, 10);
}

what is Array.any? for javascript

Just use Array.length:

var arr = [];

if (arr.length)
   console.log('not empty');
else
   console.log('empty');

See MDN

How to escape double quotes in a title attribute

The escape code &#34; can also be used instead of &quot;.

How to list physical disks?

This might be 5 years too late :). But as I see no answer for this yet, adding this.

We can use Setup APIs to get the list of disks ie., devices in the system implementing GUID_DEVINTERFACE_DISK.

Once we have their device paths, we can issue IOCTL_STORAGE_GET_DEVICE_NUMBER to construct "\\.\PHYSICALDRIVE%d" with STORAGE_DEVICE_NUMBER.DeviceNumber

See also SetupDiGetClassDevs function

#include <Windows.h>
#include <Setupapi.h>
#include <Ntddstor.h>

#pragma comment( lib, "setupapi.lib" )

#include <iostream>
#include <string>
using namespace std;

#define START_ERROR_CHK()           \
    DWORD error = ERROR_SUCCESS;    \
    DWORD failedLine;               \
    string failedApi;

#define CHK( expr, api )            \
    if ( !( expr ) ) {              \
        error = GetLastError( );    \
        failedLine = __LINE__;      \
        failedApi = ( api );        \
        goto Error_Exit;            \
    }

#define END_ERROR_CHK()             \
    error = ERROR_SUCCESS;          \
    Error_Exit:                     \
    if ( ERROR_SUCCESS != error ) { \
        cout << failedApi << " failed at " << failedLine << " : Error Code - " << error << endl;    \
    }

int main( int argc, char **argv ) {

    HDEVINFO diskClassDevices;
    GUID diskClassDeviceInterfaceGuid = GUID_DEVINTERFACE_DISK;
    SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData;
    DWORD requiredSize;
    DWORD deviceIndex;

    HANDLE disk = INVALID_HANDLE_VALUE;
    STORAGE_DEVICE_NUMBER diskNumber;
    DWORD bytesReturned;

    START_ERROR_CHK();

    //
    // Get the handle to the device information set for installed
    // disk class devices. Returns only devices that are currently
    // present in the system and have an enabled disk device
    // interface.
    //
    diskClassDevices = SetupDiGetClassDevs( &diskClassDeviceInterfaceGuid,
                                            NULL,
                                            NULL,
                                            DIGCF_PRESENT |
                                            DIGCF_DEVICEINTERFACE );
    CHK( INVALID_HANDLE_VALUE != diskClassDevices,
         "SetupDiGetClassDevs" );

    ZeroMemory( &deviceInterfaceData, sizeof( SP_DEVICE_INTERFACE_DATA ) );
    deviceInterfaceData.cbSize = sizeof( SP_DEVICE_INTERFACE_DATA );
    deviceIndex = 0;

    while ( SetupDiEnumDeviceInterfaces( diskClassDevices,
                                         NULL,
                                         &diskClassDeviceInterfaceGuid,
                                         deviceIndex,
                                         &deviceInterfaceData ) ) {

        ++deviceIndex;

        SetupDiGetDeviceInterfaceDetail( diskClassDevices,
                                         &deviceInterfaceData,
                                         NULL,
                                         0,
                                         &requiredSize,
                                         NULL );
        CHK( ERROR_INSUFFICIENT_BUFFER == GetLastError( ),
             "SetupDiGetDeviceInterfaceDetail - 1" );

        deviceInterfaceDetailData = ( PSP_DEVICE_INTERFACE_DETAIL_DATA ) malloc( requiredSize );
        CHK( NULL != deviceInterfaceDetailData,
             "malloc" );

        ZeroMemory( deviceInterfaceDetailData, requiredSize );
        deviceInterfaceDetailData->cbSize = sizeof( SP_DEVICE_INTERFACE_DETAIL_DATA );

        CHK( SetupDiGetDeviceInterfaceDetail( diskClassDevices,
                                              &deviceInterfaceData,
                                              deviceInterfaceDetailData,
                                              requiredSize,
                                              NULL,
                                              NULL ),
             "SetupDiGetDeviceInterfaceDetail - 2" );

        disk = CreateFile( deviceInterfaceDetailData->DevicePath,
                           GENERIC_READ,
                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                           NULL,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           NULL );
        CHK( INVALID_HANDLE_VALUE != disk,
             "CreateFile" );

        CHK( DeviceIoControl( disk,
                              IOCTL_STORAGE_GET_DEVICE_NUMBER,
                              NULL,
                              0,
                              &diskNumber,
                              sizeof( STORAGE_DEVICE_NUMBER ),
                              &bytesReturned,
                              NULL ),
             "IOCTL_STORAGE_GET_DEVICE_NUMBER" );

        CloseHandle( disk );
        disk = INVALID_HANDLE_VALUE;

        cout << deviceInterfaceDetailData->DevicePath << endl;
        cout << "\\\\?\\PhysicalDrive" << diskNumber.DeviceNumber << endl;
        cout << endl;
    }
    CHK( ERROR_NO_MORE_ITEMS == GetLastError( ),
         "SetupDiEnumDeviceInterfaces" );

    END_ERROR_CHK();

Exit:

    if ( INVALID_HANDLE_VALUE != diskClassDevices ) {
        SetupDiDestroyDeviceInfoList( diskClassDevices );
    }

    if ( INVALID_HANDLE_VALUE != disk ) {
        CloseHandle( disk );
    }

    return error;
}

CSS background-size: cover replacement for Mobile Safari

For Safari versions <5.1 the css3 property background-size doesn't work. In such cases you need webkit.

So you need to use -webkit-background-size attribute to specify the background-size.

Hence use -webkit-background-size:cover.

Reference-Safari versions using webkit

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

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

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

How to properly create composite primary keys - MYSQL

Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.

As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.

If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.

So while I'm not answering the original question, I certainly appreciate Adam's direct answer.

Horizontal line using HTML/CSS

I have try this my new code and it might be helpful to you, it works perfectly in google chromr

hr {
     color: #f00;
     background: #f00; 
     width: 75%; 
     height: 5px;
}

Write values in app.config file

string filePath = System.IO.Path.GetFullPath("settings.app.config");

var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
try
{
    // Open App.Config of executable
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

    // Add an Application Setting if not exist

        config.AppSettings.Settings.Add("key1", "value1");
        config.AppSettings.Settings.Add("key2", "value2");

    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);

    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException ex)
{
    if (ex.BareMessage == "Root element is missing.")
    {
        File.Delete(filePath);
        return;
    }
    MessageBox.Show(ex.Message);
}

Event listener for when element becomes visible?

var targetNode = document.getElementById('elementId');
var observer = new MutationObserver(function(){
    if(targetNode.style.display != 'none'){
        // doSomething
    }
});
observer.observe(targetNode, { attributes: true, childList: true });

I might be a little late, but you could just use the MutationObserver to observe any changes on the desired element. If any change occurs, you'll just have to check if the element is displayed.

How can query string parameters be forwarded through a proxy_pass with nginx?

From the proxy_pass documentation:

A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself.

Since you're using $1 in the target, nginx relies on you to tell it exactly what to pass. You can fix this in two ways. First, stripping the beginning of the uri with a proxy_pass is trivial:

location /service/ {
  # Note the trailing slash on the proxy_pass.
  # It tells nginx to replace /service/ with / when passing the request.
  proxy_pass http://apache/;
}

Or if you want to use the regex location, just include the args:

location ~* ^/service/(.*) {
  proxy_pass http://apache/$1$is_args$args;
}

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

redirect COPY of stdout to log file from within bash script itself

Bash 4 has a coproc command which establishes a named pipe to a command and allows you to communicate through it.

spark submit add multiple jars in classpath

I was trying to connect to mysql from the python code that was executed using spark-submit.

I was using HDP sandbox that was using Ambari. Tried lot of options such as --jars, --driver-class-path, etc, but none worked.

Solution

Copy the jar in /usr/local/miniconda/lib/python2.7/site-packages/pyspark/jars/

As of now I'm not sure if it's a solution or a quick hack, but since I'm working on POC so it kind of works for me.

Prevent line-break of span element

Put this in your CSS:

white-space:nowrap;

Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space

white-space

The white-space property declares how white space inside the element is handled.

Values

normal This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.

nowrap This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

pre-line This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

inherit Takes the same specified value as the property for the element's parent.

Check if input is number or letter javascript

Just find the remainder by dividing by 1, that is x%1. If the remainder is 0, it means that x is a whole number. Otherwise, you have to display the message "Must input numbers". This will work even in the case of strings, decimal numbers etc.

function checkInp()
{
    var x = document.forms["myForm"]["age"].value;
    if ((x%1) != 0) 
    {
        alert("Must input numbers");
        return false;
    }
}

Pretty Printing JSON with React

Here is a demo react_hooks_debug_print.html in react hooks that is based on Chris's answer. The json data example is from https://json.org/example.html.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://raw.githubusercontent.com/cassiozen/React-autobind/master/src/autoBind.js"></script>

    <script type="text/babel">

let styles = {
  root: { backgroundColor: '#1f4662', color: '#fff', fontSize: '12px', },
  header: { backgroundColor: '#193549', padding: '5px 10px', fontFamily: 'monospace', color: '#ffc600', },
  pre: { display: 'block', padding: '10px 30px', margin: '0', overflow: 'scroll', }
}

let data = {
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

const DebugPrint = () => {
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} style={styles.root}>
    <div style={styles.header} onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre style={styles.pre}>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}

ReactDOM.render(
  <DebugPrint data={data} />, 
  document.getElementById('root')
);

    </script>

  </body>
</html>

Or in the following way, add the style into header:

    <style>
.root { background-color: #1f4662; color: #fff; fontSize: 12px; }
.header { background-color: #193549; padding: 5px 10px; fontFamily: monospace; color: #ffc600; }
.pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }
    </style>

And replace DebugPrint with the follows:

const DebugPrint = () => {
  // https://stackoverflow.com/questions/30765163/pretty-printing-json-with-react
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} className='root'>
    <div className='header' onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre className='pre'>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}

How to install a specific version of Node on Ubuntu?

To install a specific version of nodejs in Ubuntu you can use below commands, just specify and replace the version number, for example, node_12.x will fetch the latest of 12.

curl https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
sudo apt-add-repository "deb https://deb.nodesource.com/node_7.x $(lsb_release -sc) main"
sudo apt-get update
sudo apt-get install nodejs

How can I change the image displayed in a UIImageView programmatically?

If you want to set image to UIImageView programmatically then Dont Forget to add UIImageView as SubView to the main View.

And also dont forgot to set ImageView Frame.

here is the code

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];

myImage.image = [UIImage imageNamed:@"myImage.png"];

[self.view addSubview:myImage];

Getting Lat/Lng from Google marker

You should add a listener on the marker and listen for the drag or dragend event, and ask the event its position when you receive this event.

See http://code.google.com/intl/fr/apis/maps/documentation/javascript/reference.html#Marker for the description of events triggered by the marker. And see http://code.google.com/intl/fr/apis/maps/documentation/javascript/reference.html#MapsEventListener for methods allowing to add event listeners.

Using C# regular expressions to remove HTML tags

Regex regex = new Regex(@"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline);

Source

Changing the width of Bootstrap popover

Here's the non-coffeescript way of doing it with hover:

$(".product-search-trigger").popover({
    trigger: "hover",
    container: "body",
    html: true,
    placement: "left"
  }).on("show.bs.popover", function() {
    return $(this).data("bs.popover").tip().css({
      maxWidth: "300px"
    });
  });
});

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

Good Question & Matt's was a good answer. To expand on the syntax a little if the oldtable has an identity a user could run the following:

SELECT col1, col2, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable

That would be if the oldtable was scripted something as such:

CREATE TABLE [dbo].[oldtable]
(
    [oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [col1] [nvarchar](50) NULL,
    [col2] [numeric](18, 0) NULL,
)

Convert Python ElementTree to string

Non-Latin Answer Extension

Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

Input

xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???")  # Read Note about Python 2

NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="???")will raise an error...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)

Output

ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="???" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Just for kicks, here's the functions I wrote to do it before I had the .PadRight bit:

    public string insertSpacesAtEnd(string input, int longest)
    {
        string output = input;
        string spaces = "";
        int inputLength = input.Length;
        int numToInsert = longest - inputLength;

        for (int i = 0; i < numToInsert; i++)
        {
            spaces += " ";
        }

        output += spaces;

        return output;
    }

    public int findLongest(List<Results> theList)
    {
        int longest = 0;

        for (int i = 0; i < theList.Count; i++)
        {
            if (longest < theList[i].title.Length)
                longest = theList[i].title.Length;
        }
        return longest;
    }

    ////Usage////
    for (int i = 0; i < storageList.Count; i++)
    {
        output += insertSpacesAtEnd(storageList[i].title, longest + 5) +   storageList[i].rank.Trim() + "     " + storageList[i].term.Trim() + "         " + storageList[i].name + "\r\n";
    }

LINQ to read XML

A couple of plain old foreach loops provides a clean solution:

foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
    result.AppendLine(level1Element.Attribute("name").Value);

    foreach (XElement level2Element in level1Element.Elements("level2"))
    {
        result.AppendLine("  " + level2Element.Attribute("name").Value);
    }
}

A completely free agile software process tool

Try http://www.icescrum.org . It is free to use. And it has lot of cool features. Perfect for scrum teams.

How do I loop through rows with a data reader in C#?

int count = reader.FieldCount;
while(reader.Read()) {
    for(int i = 0 ; i < count ; i++) {
        Console.WriteLine(reader.GetValue(i));
    }
}

Note; if you have multiple grids, then:

do {
    int count = reader.FieldCount;
    while(reader.Read()) {
        for(int i = 0 ; i < count ; i++) {
            Console.WriteLine(reader.GetValue(i));
        }
    }
} while (reader.NextResult())

Iif equivalent in C#

VB.NET:

If(someBool, "true", "false")

C#

someBool ? "true" : "false";

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How can I get the domain name of my site within a Django template?

Similar to user panchicore's reply, this is what I did on a very simple website. It provides a few variables and makes them available on the template.

SITE_URL would hold a value like example.com
SITE_PROTOCOL would hold a value like http or https
SITE_PROTOCOL_URL would hold a value like http://example.com or https://example.com
SITE_PROTOCOL_RELATIVE_URL would hold a value like //example.com.

module/context_processors.py

from django.conf import settings

def site(request):

    SITE_PROTOCOL_RELATIVE_URL = '//' + settings.SITE_URL

    SITE_PROTOCOL = 'http'
    if request.is_secure():
        SITE_PROTOCOL = 'https'

    SITE_PROTOCOL_URL = SITE_PROTOCOL + '://' + settings.SITE_URL

    return {
        'SITE_URL': settings.SITE_URL,
        'SITE_PROTOCOL': SITE_PROTOCOL,
        'SITE_PROTOCOL_URL': SITE_PROTOCOL_URL,
        'SITE_PROTOCOL_RELATIVE_URL': SITE_PROTOCOL_RELATIVE_URL
    }

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

SITE_URL = 'example.com'

Then, on your templates, use them as {{ SITE_URL }}, {{ SITE_PROTOCOL }}, {{ SITE_PROTOCOL_URL }} and {{ SITE_PROTOCOL_RELATIVE_URL }}

printf not printing on console

As others have pointed out, output can be buffered within your program before a console or shell has a chance to see it.

On unix-like systems, including macs, stdout has line-based buffering by default. This means that your program empties its stdout buffer as soon as it sees a newline.

However, on windows, newlines are no longer special, and full buffering is used. Windows doesn't support line buffering at all; see the msdn page on setvbuf.

So on windows, a good approach is to completely shut off stdout buffering like so:

setvbuf (stdout, NULL, _IONBF, 0);

Rendering a template variable as HTML

No need to use the filter or tag in template. Just use format_html() to translate variable to html and Django will automatically turn escape off for you variable.

format_html("<h1>Hello</h1>")

Check out here https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html

Is it possible to read the value of a annotation in java?

You can also use generic types, in my case, taking into account everything said before you can do something like:

public class SomeTypeManager<T> {

    public SomeTypeManager(T someGeneric) {

        //That's how you can achieve all previously said, with generic types.
        Annotation[] an = someGeneric.getClass().getAnnotations();

    }

}

Remember, that this will not equival at 100% to SomeClass.class.get(...)();

But can do the trick...

Are querystring parameters secure in HTTPS (HTTP + SSL)?

Yes. The querystring is also encrypted with SSL. Nevertheless, as this article shows, it isn't a good idea to put sensitive information in the URL. For example:

URLs are stored in web server logs - typically the whole URL of each request is stored in a server log. This means that any sensitive data in the URL (e.g. a password) is being saved in clear text on the server

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

This is what I use.

function getOrientation() {

    // if window.orientation is available...
    if( window.orientation && typeof window.orientation === 'number' ) {

        // ... and if the absolute value of orientation is 90...
        if( Math.abs( window.orientation ) == 90 ) {

              // ... then it's landscape
              return 'landscape';

        } else {

              // ... otherwise it's portrait
              return 'portrait';

        }

    } else {

        return false; // window.orientation not available

    }

}

Implementation

window.addEventListener("orientationchange", function() {

     // if orientation is landscape...
     if( getOrientation() === 'landscape' ) {

         // ...do your thing

    }

}, false);

How to pause in C?

getch() can also be used which is defined in conio.h.

The sample program would look like this :

#include <stdio.h>
#include <conio.h>

int main()
{
    //your code 
    getch();
    return 0; 
} 

getch() waits for any character input from the keyboard (not necessarily enter key).

PHP Multidimensional Array Searching (Find key by specific value)

For the next visitor coming along: use the recursive array walk; it visits every "leaf" in the multidimensional array. Here's for inspiration:

function getMDArrayValueByKey($a, $k) {
    $r = [];
    array_walk_recursive ($a, 
                          function ($item, $key) use ($k, &$r) {if ($key == $k) $r[] = $item;}
                          );
    return $r;
}

How to change the blue highlight color of a UITableViewCell?

Based on @user's answer, you can just add this extension anywhere in your app code and have your selection color directly in storyboard editor for every cells of your app :

@IBDesignable extension UITableViewCell {
    @IBInspectable var selectedColor: UIColor? {
        set {
            if let color = newValue {
                selectedBackgroundView = UIView()
                selectedBackgroundView!.backgroundColor = color
            } else {
                selectedBackgroundView = nil
            }
        }
        get {
            return selectedBackgroundView?.backgroundColor
        }
    }
}

UITableViewCell selection color in storyboard

Find and extract a number from a string

string s = "kg g L000145.50\r\n";
        char theCharacter = '.';
        var getNumbers = (from t in s
                          where char.IsDigit(t) || t.Equals(theCharacter)
                          select t).ToArray();
        var _str = string.Empty;
        foreach (var item in getNumbers)
        {
            _str += item.ToString();
        }
        double _dou = Convert.ToDouble(_str);
        MessageBox.Show(_dou.ToString("#,##0.00"));

POST request via RestTemplate in JSON

If you dont want to process response

private RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(serviceURL, request, Void.class);

If you need response to process

String result = restTemplate.postForObject(url, entity, String.class);

psql: could not connect to server: No such file or directory (Mac OS X)

Maybe this is unrelated but a similar error appears when you upgrade postgres to a major version using brew; using brew info postgresql found out this that helped:

To migrate existing data from a previous major version of PostgreSQL run:
brew postgresql-upgrade-database

Failed to execute removeChild on Node

I was wraped it with <> </> as a parent when I changed it to normal , div , its worked fine

Set variable in jinja

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

Properties order in Margin

<object Margin="left,top,right,bottom"/>
- or - 
<object Margin="left,top"/>
- or - 
<object Margin="thicknessReference"/>

See here: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin.aspx

How to specify different Debug/Release output directories in QMake .pro file

It's also useful to have a slightly different name for the output executable. You can't use something like:

release: Target = ProgramName
debug: Target = ProgramName_d

Why it doesn't work is not clear, but it does not. But:

CONFIG(debug, debug|release) {
    TARGET = ProgramName
} else {
    TARGET = ProgramName_d
}

This does work as long as the CONFIG += line precedes it.

endsWith in JavaScript

if( ("mystring#").substr(-1,1) == '#' )

-- Or --

if( ("mystring#").match(/#$/) )

Where are include files stored - Ubuntu Linux, GCC

See here: Search Path

Summary:

#include <stdio.h>

When the include file is in brackets the preprocessor first searches in paths specified via the -I flag. Then it searches the standard include paths (see the above link, and use the -v flag to test on your system).

#include "myFile.h"

When the include file is in quotes the preprocessor first searches in the current directory, then paths specified by -iquote, then -I paths, then the standard paths.

-nostdinc can be used to prevent the preprocessor from searching the standard paths at all.

Environment variables can also be used to add search paths.

When compiling if you use the -v flag you can see the search paths used.

How to set only time part of a DateTime variable in C#

I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...

You can specify 12/25/2010 4:58 PM by using

DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");

OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:

DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);

The ExistingTime.Date will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.

Java 8 stream reverse order

cyclops-react StreamUtils has a reverse Stream method (javadoc).

  StreamUtils.reverse(Stream.of("1", "2", "20", "3"))
             .forEach(System.out::println);

It works by collecting to an ArrayList and then making use of the ListIterator class which can iterate in either direction, to iterate backwards over the list.

If you already have a List, it will be more efficient

  StreamUtils.reversedStream(Arrays.asList("1", "2", "20", "3"))
             .forEach(System.out::println);

How to get document height and width without using jquery

How to find out the document width and height very easily?

in HTML
<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>

in javascript

     var c=document.querySelector('#hidden_placer');

     var r=c.getBoundingClientRect();
     r.right=document width
     r.bottom=document height`

You may update this on every window resize event, if needed.

How to convert PDF files to images

Regarding PDFiumSharp: After elaboration I was able to create PNG files from a PDF solution.

This is my code:

using PDFiumSharp;
using System.Collections.Generic;
using System.Drawing;
using System.IO;

public class Program
{
    static public void Main(String[] args)
    {
        var renderfoo = new Renderfoo()
        renderfoo.RenderPDFAsImages(@"C:\Temp\example.pdf", @"C:\temp");
    }
}



public class Renderfoo
{

    public void RenderPDFAsImages(string Inputfile, string OutputFolder)
    {
        string fileName = Path.GetFileNameWithoutExtension(Inputfile);

        using (PDFiumSharp.PdfDocument doc = new PDFiumSharp.PdfDocument(Inputfile))
        {
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                var page = doc.Pages[i];
                using (var bitmap = new System.Drawing.Bitmap((int)page.Width, (int)page.Height))
                {
                    var grahpics = Graphics.FromImage(bitmap);
                    grahpics.Clear(Color.White);
                    page.Render(bitmap);
                    var targetFile = Path.Combine(OutputFolder, fileName + "_" + i + ".png");
                    bitmap.Save(targetFile);
                }
            }
        }
    }

}

For starters, you need to take the following steps to get the PDFium wrapper up and running:

  • Run the Custom Code tool for both tt files via right click in Visual Studio
  • Compile the GDIPlus Project
  • Copy the compiled assemblies (from the GDIPlus project) to your project
  • Reference both PDFiumSharp and PDFiumsharp.GdiPlus assemblies in your project

  • Make sure that pdfium_x64.dll and/or pdfium_x86.dll are both found in your project output directory.

phpexcel to download

Use this call

$objWriter->save('php://output');

To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.

Cannot install node modules that require compilation on Windows 7 x64/VS2012

  1. Install Python 2.7 (not 3.x)
  2. Add the path to the directory containing vcbuild.exe on your environment variable PATH
  3. If you need vcbuild.exe get it here https://github.com/kin9puppy/vcbuildFixForNode

How to change letter spacing in a Textview?

For embedding HTML text in your textview you can use Html.fromHTML() syntax. More information you will get from http://developer.android.com/reference/android/text/Html.html#fromHtml%28java.lang.String%29

Copying files into the application folder at compile time

You want to use a Post-Build event on your project. You can specify the output there and there are macro values for frequently used things like project path, item name, etc.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

To remove the hash, you may try using this function

function remove_hash_from_url()
{
    var uri = window.location.toString();
    if (uri.indexOf("#") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("#"));
        window.history.replaceState({}, document.title, clean_uri);
    }
}

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

How do I print the key-value pairs of a dictionary in python

You can access your keys and/or values by calling items() on your dictionary.

for key, value in d.iteritems():
    print(key, value)

Compare dates with javascript

USe this function for date comparison in javascript:

    function fn_DateCompare(DateA, DateB) {
      var a = new Date(DateA);
      var b = new Date(DateB);

      var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
      var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());

      if (parseFloat(msDateA) < parseFloat(msDateB))
        return -1;  // less than
      else if (parseFloat(msDateA) == parseFloat(msDateB))
        return 0;  // equal
      else if (parseFloat(msDateA) > parseFloat(msDateB))
        return 1;  // greater than
      else
        return null;  // error
  }

Extracting .jar file with command line

jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)

Platform.runLater and Task in JavaFX

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

Code using Platform.runLater(...):

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();

it suffers from none of the flaws exhibited in the previous code

Reference : Worker Threading in JavaFX 2.0

How to find the largest file in a directory and its subdirectories?

That is quite simpler way to do it:

ls -l | tr -s " " " " | cut -d " " -f 5,9 | sort -n -r | head -n 1***

And you'll get this: 8445 examples.desktop

Working with select using AngularJS's ng-options

It can be useful. Bindings do not always work.

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products"></select>

For example, you fill the options list source model from a REST service. A selected value was known before filling the list, and it was set. After executing the REST request with $http, the list option is done.

But the selected option is not set. For unknown reasons AngularJS in shadow $digest executing does not bind selected as it should be. I have got to use jQuery to set the selected. It`s important! AngularJS, in shadow, adds the prefix to the value of the attr "value" for generated by ng-repeat options. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
    $http.get('/product/list')
       .then(function (response) {
           $scope.products = response.data;

           if (productId) {
               console.log("" + $("#product option").length);//for clarity
               $timeout(function () {
                   console.log("" + $("#product option").length);//for clarity
                   $('#product').val('number:'+productId);

               }, 200);
           }
       });
}

Copying a rsa public key to clipboard

cat .ssh/id_rsa.pub | bcopy

This works for me.

tsc is not recognized as internal or external command

Me too faced the same problem. Use nodeJS command prompt instead of windows command prompt.

Step 1: Execute the npm install -g typescript

Step 2: tsc filename.ts

New file will be create same name and different extension as ".js"

Step 3: node filename.js

You can see output in screen. It works for me.

How to remove "onclick" with JQuery?

if you are using jquery 1.7

$('html').off('click');

else

$('html').unbind('click');

Flutter: Setting the height of the AppBar

You can use PreferredSize:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example',
      home: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(50.0), // here the desired height
          child: AppBar(
            // ...
          )
        ),
        body: // ...
      )
    );
  }
}

Setting timezone in Python

>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'

To get the specific values you've listed:

>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.strftime('%d')
>>> hour = time.strftime('%H')
>>> minute = time.strftime('%M')

See here for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.

How to use relative/absolute paths in css URLs?

Personally, I would fix this in the .htaccess file. You should have access to that.

Define your CSS URL as such:

url(/image_dir/image.png);

In your .htacess file, put:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1

or

RewriteRule ^image_dir/(.*) images/$1

depending on the site.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

If you are still looking for an answer, try checking this question thread. It helped me resolve a similar problem.

edit: The solution that helped me was to run Update-Package Microsoft.AspNet.WebApi -reinstall from the NugGet package manager, as suggested by Pathoschild. I then had to delete my .suo file and restart VS, as suggested by Sergey Osypchuk in this thread.

Find duplicate lines in a file and count how many time each line was duplicated?

To find duplicate counts use below command as requested by you :

sort filename | uniq -c | awk '{print $2, $1}'

HTML table with 100% width, with vertical scroll inside tbody

For using "overflow: scroll" you must set "display:block" on thead and tbody. And that messes up column widths between them. But then you can clone the thead row with Javascript and paste it in the tbody as a hidden row to keep the exact col widths.

$('.myTable thead > tr').clone().appendTo('.myTable tbody').addClass('hidden-to-set-col-widths');

http://jsfiddle.net/Julesezaar/mup0c5hk/

<table class="myTable">
    <thead>
        <tr>
            <td>Problem</td>
            <td>Solution</td>
            <td>blah</td>
            <td>derp</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>
<p>
  Some text to here
</p>

The css:

table {
  background-color: #aaa;
  width: 100%;
}

thead,
tbody {
  display: block; // Necessary to use overflow: scroll
}

tbody {
  background-color: #ddd;
  height: 150px;
  overflow-y: scroll;
}

tbody tr.hidden-to-set-col-widths,
tbody tr.hidden-to-set-col-widths td {
  visibility: hidden;
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
}

td {
  padding: 3px 10px;
}

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

Convert Go map to json

If you had caught the error, you would have seen this:

jsonString, err := json.Marshal(datas)
fmt.Println(err)

// [] json: unsupported type: map[int]main.Foo

The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using strconv.Itoa.

See this post for more details: https://stackoverflow.com/a/24284721/2679935

What is difference between sjlj vs dwarf vs seh?

SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks

DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.

SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.

source: https://wiki.qt.io/MinGW-64-bit

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

What's the whole point of "localhost", hosts and ports at all?

Well, others have given a good definition of 'localhost'.

It is kind of a defacto for the text representation of the local IP 127.0.0.1.

You can have 'betterhost', 'otherhost', 'someotherhost' if you use a DNS server that can translate it to working IP addresses, OR by modifying the host file. But that's another topic for another day or better day. :P

How to Bulk Insert from XLSX file extension?

Create a linked server to your document

http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm

Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.

You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.

Editing specific line in text file in Python

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

And then:

replace_line('stats.txt', 0, 'Mage')

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Normally this error occurs when you invoke java by supplying the wrong arguments/options. In this case it should be the version option.

java -version

So to double check you can always do java -help, and see if the option exists. In this case, there is no option such as v.

How do I compare two columns for equality in SQL Server?

What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.

CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult

should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

How to change the locale in chrome browser

The easiest way I found, summarized in a few pictures:

Adding Language

Changing Language

Relaunch

You could skip a few steps (up to step 4) by simply navigating to chrome://settings/languages right away.

What is the difference between static func and class func in Swift?

I did some experiments in playground and got some conclusions.

TL;DR enter image description here

As you can see, in the case of class, the use of class func or static func is just a question of habit.

Playground example with explanation:

class Dog {
    final func identity() -> String {
        return "Once a woofer, forever a woofer!"
    }

    class func talk() -> String {
        return "Woof woof!"
    }

    static func eat() -> String {
        return "Miam miam"
    }

    func sleep() -> String {
        return "Zzz"
    }
}

class Bulldog: Dog {
    // Can not override a final function
//    override final func identity() -> String {
//        return "I'm once a dog but now I'm a cat"
//    }

    // Can not override a "class func", but redeclare is ok
    func talk() -> String {
        return "I'm a bulldog, and I don't woof."
    }

    // Same as "class func"
    func eat() -> String {
        return "I'm a bulldog, and I don't eat."
    }

    // Normal function can be overridden
    override func sleep() -> String {
        return "I'm a bulldog, and I don't sleep."
    }
}

let dog = Dog()
let bullDog = Bulldog()

// FINAL FUNC
//print(Dog.identity()) // compile error
print(dog.identity()) // print "Once a woofer, forever a woofer!"
//print(Bulldog.identity()) // compile error
print(bullDog.identity()) // print "Once a woofer, forever a woofer!"

// => "final func" is just a "normal" one but prevented to be overridden nor redeclared by subclasses.


// CLASS FUNC
print(Dog.talk()) // print "Woof woof!", called directly from class
//print(dog.talk()) // compile error cause "class func" is meant to be called directly from class, not an instance.
print(Bulldog.talk()) // print "Woof woof!" cause it's called from Bulldog class, not bullDog instance.
print(bullDog.talk()) // print "I'm a bulldog, and I don't woof." cause talk() is redeclared and it's called from bullDig instance

// => "class func" is like a "static" one, must be called directly from class or subclassed, can be redeclared but NOT meant to be overridden.

// STATIC FUNC
print(Dog.eat()) // print "Miam miam"
//print(dog.eat()) // compile error cause "static func" is type method
print(Bulldog.eat()) // print "Miam miam"
print(bullDog.eat()) // print "I'm a bulldog, and I don't eat."

// NORMAL FUNC
//print(Dog.sleep()) // compile error
print(dog.sleep()) // print "Zzz"
//print(Bulldog.sleep()) // compile error
print(bullDog.sleep()) // print "I'm a bulldog, and I don't sleep."

How to trim white space from all elements in array?

For those (like me) who was looking for the same solution in Kotlin and were pointed to Java only - how to trim in Kotlin:

fun main(args: Array<String>) {
    // array definition
    val array = arrayListOf<String>(" String", "Tom Selleck "," Fish ")
    println(array) // print original -> [ String, Tom Selleck ,  Fish ]

    // remove leading and trailing spaces, result is arrayList
    val sol1 = array.map { it.trim() }
    println("sol1 = $sol1") // -> sol1 = [String, Tom Selleck, Fish]

    // remove leading and trailing spaces, result is String
    val sol2 = array.joinToString { it.trim() }
    println("sol2 = $sol2") // -> sol2 = String, Tom Selleck, Fish
}

Easy way to make a confirmation dialog in Angular?

you can use window.confirm inside your function combined with if condition

 delete(whatever:any){
    if(window.confirm('Are sure you want to delete this item ?')){
    //put your delete method logic here
   }
}

when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.

Populating VBA dynamic arrays

In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are

  1. Creating an array big enough to handle anything you think will be thrown at it
  2. Sensible use of Redim Preserve

The code below provides an example of a routine that will dimension myArray in line with the lngSize variable, then add additional elements (equal to the initial array size) by use of a Mod test whenever the upper bound is about to be exceeded

Option Base 1

Sub ArraySample()
    Dim myArray() As String
    Dim lngCnt As Long
    Dim lngSize As Long

    lngSize = 10
    ReDim myArray(1 To lngSize)

    For lngCnt = 1 To lngSize*5
        If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
        myArray(lngCnt) = "I am record number " & lngCnt
    Next
End Sub

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

How to set full calendar to a specific start date when it's initialized for the 1st time?

In version 2.1.1 this works :

$('#calendar').fullCalendar({
// your calendar settings...
});

$('#calendar').fullCalendar('gotoDate', '2014-05-01');

Documentation about moment time/date format : http://fullcalendar.io/docs/utilities/Moment/ Documentation about the upgrades in version 2 : https://github.com/arshaw/fullcalendar/wiki/Upgrading-to-v2

What does \u003C mean?

It's a unicode character. In this case \u003C and \u003E mean :

U+003C < Less-than sign

U+003E > Greater-than sign

See a list here

Set initially selected item in Select list in Angular2

The easiest way to solve this problem in Angular is to do:

In Template:

<select [ngModel]="selectedObjectIndex">
  <option [value]="i" *ngFor="let object of objects; let i = index;">{{object.name}}</option>
</select>

In your class:

this.selectedObjectIndex = 1/0/your number wich item should be selected

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Do you use NULL or 0 (zero) for pointers in C++?

I try to avoid the whole question by using C++ references where possible. Rather than

void foo(const Bar* pBar) { ... }

you might often be able to write

void foo(const Bar& bar) { ... }

Of course, this doesn't always work; but null pointers can be overused.

What's the best way to cancel event propagation between nested ng-click calls?

I like the idea of using a directive for this:

.directive('stopEvent', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('click', function (e) {
                e.stopPropagation();
            });
        }
    };
 });

Then use the directive like:

<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
    <img src="http://some_src" ng-click="nextImage()" stop-event/>
</div>

If you wanted, you could make this solution more generic like this answer to a different question: https://stackoverflow.com/a/14547223/347216

How do I change the UUID of a virtual disk?

The command fails because it has space in one of the folder name, i.e. 'VirtualBox VMs.

VBoxManage internalcommands sethduuid /home/user/VirtualBox VMs/drupal/drupal.vhd

If there is no space at folder name or file name, then the command will work even without quoting it, e.g. after changing 'VirtualBox VMs' into 'VBoxVMs'

VBoxManage internalcommands sethduuid /home/user/VBoxVMs/drupal/drupal.vhd

How to get values from IGrouping

Since IGrouping<TKey, TElement> implements IEnumerable<TElement>, you can use SelectMany to put all the IEnumerables back into one IEnumerable all together:

List<smth> list = new List<smth>();
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.id);
IEnumerable<smth> smths = groups.SelectMany(group => group);
List<smth> newList = smths.ToList();

Here's an example that builds/runs: https://dotnetfiddle.net/DyuaaP

Video commentary of this solution: https://youtu.be/6BsU1n1KTdo

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

Loop through an array of strings in Bash?

Possible first line of every Bash script/session:

say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }

Use e.g.:

$ aa=( 7 -4 -e ) ; say "${aa[@]}"
7
-4
-e

May consider: echo interprets -e as option here

How to save data in an android app

There is a lot of options to store your data and Android offers you to chose anyone Your data storage options are the following:

Shared Preferences Store private primitive data in key-value pairs. Internal Storage Store private data on the device memory. External Storage Store public data on the shared external storage. SQLite Databases Store structured data in a private database. Network Connection Store data on the web with your own network server

Check here for examples and tuto

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

How to create file object from URL object (image)

Use Apache Common IO's FileUtils:

import org.apache.commons.io.FileUtils

FileUtils.copyURLToFile(url, f);

The method downloads the content of url and saves it to f.

Force a screen update in Excel VBA

@Hubisans comment worked best for me.

ActiveWindow.SmallScroll down:=1
ActiveWindow.SmallScroll up:=1

Heroku: How to push different local Git branches to Heroku/master

You should check out heroku_san, it solves this problem quite nicely.

For example, you could:

git checkout BRANCH
rake qa deploy

It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:

git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates

And of course you can make simpler rake tasks if you do something frequently.

Horizontal list items

Here you can find a working example, with some more suggestions about dynamic resizing of the list.

I've used display:inline-block and a percentage padding so that the parent list can dynamically change size:

display:inline-block;
padding:10px 1%;
width: 30%

plus two more rules to remove padding for the first and last items.

ul#menuItems li:first-child{padding-left:0;}
ul#menuItems li:last-child{padding-right:0;}

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

Testing the type of a DOM element in JavaScript

I usually get it from the toString() return value. It works in differently accessed DOM elements:

var a = document.querySelector('a');

var img = document.createElement('img');

document.body.innerHTML += '<div id="newthing"></div>';
var div = document.getElementById('newthing');

Object.prototype.toString.call(a);    // "[object HTMLAnchorElement]"
Object.prototype.toString.call(img);  // "[object HTMLImageElement]"
Object.prototype.toString.call(div);  // "[object HTMLDivElement]"

Then the relevant piece:

Object.prototype.toString.call(...).split(' ')[1].slice(0, -1);

It works in Chrome, FF, Opera, Edge, IE9+ (in older IE it return "[object Object]").

Python: Importing urllib.quote

If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

You could also use the python compatibility wrapper six to handle this.

from six.moves.urllib.parse import quote

How do I delete multiple rows in Entity Framework (without foreach)

this is as good as it gets, right? I can abstract it with an extension method or helper, but somewhere we're still going to be doing a foreach, right?

Well, yes, except you can make it into a two-liner:

context.Widgets.Where(w => w.WidgetId == widgetId)
               .ToList().ForEach(context.Widgets.DeleteObject);
context.SaveChanges();

How to check certificate name and alias in keystore files?

In a bash-like environment you can use:

keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo

This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep.

Add inline style using Javascript

var div = document.createElement('div');
div.setAttribute('style', 'width:330px; float:left');
div.setAttribute('class', 'well');
var label = document.createElement('label');
label.innerHTML = 'YOUR TEXT HERE';
div.appendChild(label);

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

I got this on WatchOS Sim. The issue persisted even after:

  • Deleting the app
  • Restarting Xcode
  • Deleting Derived Data

...and was finally fixed by "Erase all Content and Settings" in the simulator.

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

I was looking for a listing of macOS but found nothing, maybe this helps someone.

Output on macOS Catalina (10.15.7) using net5.0

# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER

# SpecialFolders (All)
SpecialFolder.AdminTools: 
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonTemplates: 
SpecialFolder.CommonVideos: 
SpecialFolder.Cookies: 
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History: 
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources: 
SpecialFolder.MyComputer: 
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86: 
SpecialFolder.Programs: 
SpecialFolder.Recent: 
SpecialFolder.Resources: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.Startup: 
SpecialFolder.System: /System
SpecialFolder.SystemX86: 
SpecialFolder.Templates: 
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows: 

I have replaced my username with $USER.

Code Snippet from pogosama.

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

Create a simple 10 second countdown

JavaScript has built in to it a function called setInterval, which takes two arguments - a function, callback and an integer, timeout. When called, setInterval will call the function you give it every timeout milliseconds.

For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.

function makeAlert(){ 
    alert("Popup window!");
};

setInterval(makeAlert, 500);

However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.

setInterval(function(){ alert("Popup window!"); }, 500);

Once setInterval is called, it will run until you call clearInterval on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.

_x000D_
_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
  if(timeleft <= 0){_x000D_
    clearInterval(downloadTimer);_x000D_
  }_x000D_
  document.getElementById("progressBar").value = 10 - timeleft;_x000D_
  timeleft -= 1;_x000D_
}, 1000);
_x000D_
<progress value="0" max="10" id="progressBar"></progress>
_x000D_
_x000D_
_x000D_

Alternatively, this will create a text countdown.

_x000D_
_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
  if(timeleft <= 0){_x000D_
    clearInterval(downloadTimer);_x000D_
    document.getElementById("countdown").innerHTML = "Finished";_x000D_
  } else {_x000D_
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";_x000D_
  }_x000D_
  timeleft -= 1;_x000D_
}, 1000);
_x000D_
<div id="countdown"></div>
_x000D_
_x000D_
_x000D_

Jquery, Clear / Empty all contents of tbody element?

Example for Remove table header or table body with jquery

_x000D_
_x000D_
function removeTableHeader(){_x000D_
  $('#myTableId thead').empty();_x000D_
}_x000D_
_x000D_
function removeTableBody(){_x000D_
    $('#myTableId tbody').empty();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id='myTableId'  border="1">_x000D_
  <thead>_x000D_
    <th>1st heading</th>_x000D_
    <th>2nd heading</th>_x000D_
    <th>3rd heading</th>_x000D_
  </thead>  _x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<br/>_x000D_
<form>_x000D_
  <input type='button' value='Remove Table Header' onclick='removeTableHeader()'/>_x000D_
  <input type='button' value='Remove Table Body' onclick='removeTableBody()'/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

ngOnInit not being called when Injectable class is Instantiated

import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
import {Service} from "path/to/service/";

@Injectable()
export class MovieDbService implements OnInit {

userId:number=null;

constructor(private _movieDbRest: RestApiService,
            private instanceMyService : Service ){

   // do evreything like OnInit just on services

   this._movieDbRest.callAnyMethod();

   this.userId = this.instanceMyService.getUserId()


}

Get form data in ReactJS

 onChange(event){
     console.log(event.target.value);
  }
  handleSubmit(event){ 
    event.preventDefault();
    const formData = {};
      for (const data in this.refs) {
        formData[data] = this.refs[data].value;
      }
    console.log(formData);
  }



 <form onSubmit={this.handleSubmit.bind(this)}>
  <input type="text" ref="username" onChange={this.onChange} className="form-control"/>
  <input type="text" ref="password" onChange={this.onChange} className="form-control"/>
  <button type="submit" className="btn-danger btn-sm">Search</button>
 </form>

Output image attached here

Compress images on client side before uploading

I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html

The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...

However, I’m not sure about using canvas to compress images, but you can certainly resize them.

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;

Running vbscript from batch file

Batch files are processed row by row and terminate whenever you call an executable directly.
- To make the batch file wait for the process to terminate and continue, put call in front of it.
- To make the batch file continue without waiting, put start "" in front of it.

I recommend using this single line script to accomplish your goal:

@call cscript "%~dp0necdaily.vbs"

(because this is a single line, you can use @ instead of @echo off)

If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:

@%WINDIR%\SysWOW64\cmd.exe /c call cscript "%~dp0necdaily.vbs"

If you need the window to remain, you can replace /c with /k

Unexpected token ILLEGAL in webkit

This error can also be caused by a javascript line like this one:

navi_elements.style.bottom = 20px;

Notice that the value is not a string.

$http.get(...).success is not a function

If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.

 $scope.login = function () {
        $scope.btntext = "Please wait...!";
        $http({
            method: "POST",
            url: '/Home/userlogin', // link UserLogin with HomeController 
            data: $scope.user
         }).then(function (response) {
            console.log("Result value is : " + parseInt(response));
            data = response.data;
            $scope.btntext = 'Login';
            if (data == 1) {
                window.location.href = '/Home/dashboard';
             }
            else {
            alert(data);
        }
        }, function (error) {

        alert("Failed Login");
        });

The above snipit works for a login page.

Nginx: Job for nginx.service failed because the control process exited

The cause of the issue is this, I already had Apache web server installed and actively listening on port 80 on my local machine.

Apache and Nginx are the two major open-source high-performance web servers capable of handling diverse workloads to satisfy the needs of modern web demands. However, Apache serves primarily as a HTTP server whereas Nginx is a high-performance asynchronous web server and reverse proxy server.

The inability of Nginx to start was because Apache was already listening on port 80 as its default port, which is also the default port for Nginx.

One quick workaround would be to stop Apache server by running the command below

systemctl stop apache2
systemctl status apache2

And then starting up Nginx server by running the command below

systemctl stop nginx
systemctl status nginx

However, this same issue will arise again when we try to start Apache server again, since they both use port 80 as their default port.

Here's how I fixed it:

Run the command below to open the default configuration file of Nginx in Nano editor

sudo nano /etc/nginx/sites-available/default

When the file opens in Nano editor, scroll down and change the default server port to any port of your choice. For me, I chose to change it to port 85

# Default server configuration
#
server {
       listen 85 default_server;
       listen [::]:85 default_server;

Also, scroll down and change the virtual host port to any port of your choice. For me, I also chose to change it to port 85

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
# server {
#        listen 85;
#        listen [::]:85;

Then save and exit the file by pressing on your keyboard:

Ctrl + S
Ctrl + X

You may still be prompted to press Y on your keyboard to save your changes.

Finally, confirm that your configuration is correct and restart the Nginx server:

sudo nginx -t
sudo systemctl restart nginx

You can now navigate to localhost:nginx-port (localhost:85) on your browser to confirm the changes.

Displaying the default Nginx start page

If you want the default Nginx start page to show when you navigate to localhost:nginx-port (localhost:85) on your browser, then follow these steps:

Examine the directory /var/www/html/ which is the default root directory for both Apache and Nginx by listing its contents:

cd ~
ls /var/www/html/

You will 2 files listed in the directory:

index.html                # Apache default start page
index.nginx-debian.html   # Nginx default start page

Run the command below to open the default configuration file of Nginx in Nano editor:

cd ~
sudo nano /etc/nginx/sites-available/default

Change the order of the index files in the root directory from this:

root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

to this (putting the default Nginx start page - index.nginx-debian.html in the 2nd position immediately after index):

root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.nginx-debian.html index.html index.htm;

Then save and exit the file by pressing on your keyboard:

Ctrl + S
Ctrl + X

You may still be prompted to press Y on your keyboard to save your changes.

Finally, confirm that your configuration is correct and restart the Nginx server:

sudo nginx -t
sudo systemctl restart nginx

You can now navigate to localhost:nginx-port (localhost:85) on your browser to confirm the changes.

That's all.

I hope this helps

JavaScript to get rows count of a HTML table

Given a

<table id="tableId">
    <thead>
        <tr><th>Header</th></tr>
    </thead>
    <tbody>
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>
    </tbody>
    <tfoot>
        <tr><td>Footer</td></tr>
    </tfoot>
</table>

and a

var table = document.getElementById("tableId");

there are two ways to count the rows:

var totalRowCount = table.rows.length; // 5
var tbodyRowCount = table.tBodies[0].rows.length; // 3

The table.rows.length returns the amount of ALL <tr> elements within the table. So for the above table it will return 5 while most people would really expect 3. The table.tBodies returns an array of all <tbody> elements of which we grab only the first one (our table has only one). When we count the rows on it, then we get the expected value of 3.

How to check encoding of a CSV file

Use chardet https://github.com/chardet/chardet (documentation is short and easy to read).

Install python, then pip install chardet, at last use the command line command.

I tested under GB2312 and it's pretty accurate. (Make sure you have at least a few characters, sample with only 1 character may fail easily).

file is not reliable as you can see.

enter image description here

How to pass multiple values through command argument in Asp.net?

I checked your code and seems to be no problem at all. please make sure Image commandArgument getting value. check it first binding in label whether you are getting value.

However, here is sample which I'm using in my project

<asp:GridView ID="GridViewUserScraps" ItemStyle-VerticalAlign="Top" AutoGenerateColumns="False" Width="100%" runat="server" OnRowCommand="GridViews_RowCommand" >
        <Columns>
            <asp:TemplateField SortExpression="SendDate">
                <ItemTemplate>
                <asp:Button ID="btnPost" CssClass="submitButton" Text="Comment" runat="server" CommandName="Comment" CommandArgument='<%#Eval("ScrapId")+","+ Eval("UserId")%>' />

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

first bind the GridView.

public void GetData()
{
   //bind ur GridView
   GridViewUserScraps.DataSource = dt;
   GridViewUserScraps.DataBind();
}

protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Comment")
    {
        string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
        string scrapid = commandArgs[0];
        string uid = commandArgs[1];
    }
}

Ruby - test for array

Are you sure it needs to be an array? You may be able to use respond_to?(method) so your code would work for similar things that aren't necessarily arrays (maybe some other enumberable thing). If you do actually need an array, then the post describing the Array#kind\_of? method is best.

['hello'].respond_to?('each')

Parse JSON in TSQL

I do also have a huge masochistic streak as that I've written yet another JSON parser. This one uses a procedural approach. It uses a similat SQL hierarchy list table to store the parsed data. Also in the package are:

  • Reverse process: from hierarchy to JSON
  • Querying functions: to fetch particular values from a JSON object

Please feel free to use and have fun with it

http://www.codeproject.com/Articles/1000953/JSON-for-Sql-Server-Part

How do I limit the number of rows returned by an Oracle query after ordering?

SQL Standard

Since version 12c Oracle supports the SQL:2008 Standard, which provides the following syntax to limit the SQL result set:

SELECT
    title
FROM
    post
ORDER BY
    id DESC
FETCH FIRST 50 ROWS ONLY

Oracle 11g and older versions

Prior to version 12c, to fetch the Top-N records, you had to use a derived table and the ROWNUM pseudocolumn:

SELECT *
FROM (
    SELECT
        title
    FROM
        post
    ORDER BY
        id DESC
)
WHERE ROWNUM <= 50

git push >> fatal: no configured push destination

The command (or the URL in it) to add the github repository as a remote isn't quite correct. If I understand your repository name correctly, it should be;

git remote add demo_app '[email protected]:levelone/demo_app.git'

Show just the current branch in Git

I guess this should be quick and can be used with a Python API:

git branch --contains HEAD
* master

Unsupported method: BaseConfig.getApplicationIdSuffix()

For Android Studio 3 I need to update two files to fix the error:--

1. app/build.gradle

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

2. app/gradle/wrapper/gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

Core dump file is not generated

The answers given here cover pretty well most scenarios for which core dump is not created. However, in my instance, none of these applied. I'm posting this answer as an addition to the other answers.

If your core file is not being created for whatever reason, I recommend looking at the /var/log/messages. There might be a hint in there to why the core file is not created. In my case there was a line stating the root cause:

Executable '/path/to/executable' doesn't belong to any package

To work around this issue edit /etc/abrt/abrt-action-save-package-data.conf and change ProcessUnpackaged from 'no' to 'yes'.

ProcessUnpackaged = yes

This setting specifies whether to create core for binaries not installed with package manager.

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

Here is an small detector written in Java , just copy and run :)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

public class JarValidator {

    public static void main(String[] args) throws IOException {
        Path repositoryPath = Paths.get("C:\\Users\\goxr3plus\\.m2");

        // Check if the main Repository Exists
        if (Files.exists(repositoryPath)) {

            // Create a class instance
            JarValidator jv = new JarValidator();

            List<String> jarReport = new ArrayList<>();
            jarReport.add("Repository to process: " + repositoryPath.toString());

            // Get all the directory files
            List<Path> jarFiles = jv.getFiles(repositoryPath, ".jar");
            jarReport.add("Number of jars to process: " + jarFiles.size());
            jarReport.addAll(jv.openJars(jarFiles, true));

            // Print the report
            jarReport.stream().forEach(System.out::println);

        } else {
            System.out.println("Repository path " + repositoryPath + " does not exist.");
        }
    }

    /**
     * Get all the files from the given directory matching the specified extension
     * 
     * @param filePath      Absolute File Path
     * @param fileExtension File extension
     * @return A list of all the files contained in the directory
     * @throws IOException
     */
    private List<Path> getFiles(Path filePath, String fileExtension) throws IOException {
        return Files.walk(filePath).filter(p -> p.toString().endsWith(fileExtension)).collect(Collectors.toList());
    }

    /**
     * Try to open all the jar files
     * 
     * @param jarFiles
     * @return A List of Messages for Corrupted Jars
     */
    private List<String> openJars(List<Path> jarFiles, boolean showOkayJars) {
        int[] badJars = { 0 };
        List<String> messages = new ArrayList<>();

        // For Each Jar
        jarFiles.forEach(path -> {

            try (JarFile file = new JarFile(path.toFile())) {
                if (showOkayJars)
                    messages.add("OK : " + path.toString());
            } catch (IOException ex) {
                messages.add(path.toAbsolutePath() + " threw exception: " + ex.toString());
                badJars[0]++;
            }
        });

        messages.add("Total bad jars = " + badJars[0]);
        return messages;
    }

}

Output

Repository to process: C:\Users\goxr3plus\.m2
Number of jars to process: 4920
C:\Users\goxr3plus\.m2\repository\bouncycastle\isoparser-1.1.18.jar threw exception: java.util.zip.ZipException: zip END header not found
Total bad jars = 1
BUILD SUCCESSFUL (total time: 2 seconds)

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

How to switch between hide and view password

private int passwordNotVisible=1; 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
 showPassword = (ImageView) findViewById(R.id.show_password);
    showPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText paswword = (EditText) findViewById(R.id.Password);
            if (passwordNotVisible == 1) {
                paswword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                passwordNotVisible = 0;
            } else {

                paswword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                passwordNotVisible = 1;
            }


            paswword.setSelection(paswword.length());

        }
    });
}

Getting the index of a particular item in array

     int i=  Array.IndexOf(temp1,  temp1.Where(x=>x.Contains("abc")).FirstOrDefault());

Try catch statements in C

A quick google search yields kludgey solutions such as this that use setjmp/longjmp as others have mentioned. Nothing as straightforward and elegant as C++/Java's try/catch. I'm rather partial to Ada's exception handling myself.

Check everything with if statements :)

Finding the handle to a WPF window

Just use your window with the WindowsInteropHelper class:

// ... Window myWindow = get your Window instance...
IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;

Right now, you're asking for the Application's main window, of which there will always be one. You can use this same technique on any Window, however, provided it is a System.Windows.Window derived Window class.

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

Excel doesn't update value unless I hit Enter

It sounds like your workbook got set to Manual Calculation. You can change this to Automatic by going to Formulas > Calculation > Calculation Options > Automatic.

Location in Ribbon

Manual calculation can be useful to reduce computational load and improve responsiveness in workbooks with large amounts of formulas. The idea is that you can look at data and make changes, then choose when you want to make your computer go through the effort of calculation.

Generator expressions vs. list comprehensions

Sometimes you can get away with the tee function from itertools, it returns multiple iterators for the same generator that can be used independently.

Managing jQuery plugin dependency in webpack

This works for me on the webpack.config.js

    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),

in another javascript or into HTML add:

global.jQuery = require('jquery');

How to change a DIV padding without affecting the width/height ?

try this trick

div{
 -webkit-box-sizing: border-box; 
 -moz-box-sizing: border-box;    
 box-sizing: border-box;      
}

this will force the browser to calculate the width acording to the "outer"-width of the div, it means the padding will be substracted from the width.

Ignoring NaNs with str.contains

df[df.col.str.contains("foo").fillna(False)]

When should I create a destructor?

It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.

It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.

In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.

A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.

Java - remove last known item from ArrayList

First error: You're casting a ClientThread as a String for some reason.

Second error: You're not calling remove on your List.

Is is homework? If so, you might want to use the tag.

Basic HTTP and Bearer Token Authentication

Try this one to push basic authentication at url:

curl -i http://username:[email protected]/api/users -H "Authorization: Bearer mytoken123"
               ^^^^^^^^^^^^^^^^^^

If above one doesn't work, then you have nothing to do with it. So try the following alternates.

You can pass the token under another name. Because you are handling the authorization from your Application. So you can easily use this flexibility for this special purpose.

curl -i http://dev.myapp.com/api/users \
  -H "Authorization: Basic Ym9zY236Ym9zY28=" \
  -H "Application-Authorization: mytoken123"

Notice I have changed the header into Application-Authorization. So from your application catch the token under that header and process what you need to do.

Another thing you can do is, to pass the token through the POST parameters and grab the parameter's value from the Server side. For example passing token with curl post parameter:

-d "auth-token=mytoken123"

Java random numbers using a seed

Several of the examples here create a new Random instance, but this is unnecessary. There is also no reason to use synchronized as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom class:

double randomGenerator() {
    return ThreadLocalRandom.current().nextDouble(0.5);
}

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent. One way to do so is to serialize it into a JSON string:

var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json

Now all you need to do is pass the string to the post method.

var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+

var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);

How to force HTTPS using a web.config file

The accepted answer did not work for me. I followed the steps on this blog.

A key point that was missing for me was that I needed to download and install the URL Rewrite Tool for IIS. I found it here. The result was the following.

<rewrite>
        <rules>
            <remove name="Http to Https" />
            <rule name="Http to Https" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <serverVariables />
                <action type="Redirect" url="https://{HTTPS_HOST}{REQUEST_URI}" />
            </rule>
        </rules>
    </rewrite>

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

You can give yourself permissions to fix this problem.

Right click on cacerts > choose properties > select Securit tab > Allow all permissions to all the Group and user names.

This worked for me.

Convert dictionary to bytes and back again python?

This should work:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

How to simulate a real mouse click using java?

it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.

jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
 public static void main(String args[]) {
  Robot bot = null;
  try {
   bot = new Robot();
  } catch (Exception failed) {
   System.err.println("Failed instantiating Robot: " + failed);
  }
  int mask = InputEvent.BUTTON1_DOWN_MASK;
  bot.mouseMove(100, 100);
  bot.mousePress(mask);
  bot.mouseRelease(mask);
 }
}

I'm assuming InputEvent.MOUSE_BUTTON1_DOWN in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK in mine; I'm using 1.6.

otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).

[added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?

Class is inaccessible due to its protection level

It may also be the case that the library containing the class in question is not properly signed with a strong name.

ListView with OnItemClickListener

If you define your ListView programatically:

mListView.setDescendantFocusability(ListView.FOCUS_BLOCK_DESCENDANTS);

How to change the docker image installation directory?

A much simpler solution is to create a soft link point to whatever you want, such as

link -s /var/lib/docker /mnt/whatever

It works for me on my CentOS 6.5 server.

Char array in a struct - incompatible assignment?

sara is the struct itself, not a pointer (i.e. the variable representing location on the stack where actual struct data is stored). Therefore, *sara is meaningless and won't compile.

Assert that a WebElement is not present using Selenium WebDriver with java

With Selenium Webdriver would be something like this:

assertTrue(!isElementPresent(By.linkText("Empresas en Misión")));

Sorting object property by values

There are many ways to do this, but since I didn't see any using reduce() I put it here. Maybe it seems utils to someone.

_x000D_
_x000D_
var list = {
    "you": 100,
    "me": 75,
    "foo": 116,
    "bar": 15
};

let result = Object.keys(list).sort((a,b)=>list[a]>list[b]?1:-1).reduce((a,b)=> {a[b]=list[b]; return a},{});

console.log(result);
_x000D_
_x000D_
_x000D_

How can you check for a #hash in a URL using JavaScript?

Put the following:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

How can I deploy an iPhone application from Xcode to a real iPhone device?

You can't, not if you are talking about applications built with the official SDK and deploying straight from xcode.

Android - Set text to TextView

PUT THIS CODE IN YOUR XML FILE

<TextView
    android:id="@+id/textview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

PUT THIS CODE IN YOUR JAVA FILE

// Declaring components like TextView globally is a good habit

TextView mTextView = (TextView) findViewById(R.id.textview1);

// Put this in OnCreate

mTextView.setText("Welcome to Dynamic TextView");

Searching in a ArrayList with custom objects for certain strings

Use Apache CollectionUtils:

CollectionUtils.find(myList, new Predicate() {
   public boolean evaluate(Object o) {
      return name.equals(((MyClass) o).getName());
   }
}

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

How to access the correct `this` inside a callback?

Another approach, which is the standard way since DOM2 to bind this within the event listener, that let you always remove the listener (among other benefits), is the handleEvent(evt)method from the EventListener interface:

var obj = {
  handleEvent(e) {
    // always true
    console.log(this === obj);
  }
};

document.body.addEventListener('click', obj);

Detailed information about using handleEvent can be found here: https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38

Converting a byte array to PNG/JPG

You should be able to do something like this:

byte[] bitmap = GetYourImage();

using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
    image.Save("output.jpg", ImageFormat.Jpeg);  // Or Png
}

Look here for more info.

Hopefully this helps.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

What is the difference between "is None" and "== None"

If you use numpy,

if np.zeros(3)==None: pass

will give you error when numpy does elementwise comparison

Post values from a multiple select

You need to add a name attribute.

Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3.

In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.

Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs

For PHP you can use:

<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

$_SERVER['REMOTE_ADDR'] gives the IP address from which the request was sent to the web server. This is typically the visitor's address, but in your case, it sounds like there is some kind of proxy sitting right before the web server that intercepts the requests, hence to the web server it appears as though the requests are originating from there.

How do you create a read-only user in PostgreSQL?

Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:

test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;

Default values in a C Struct

I'm rusty with structs, so I'm probably missing a few keywords here. But why not start with a global structure with the defaults initialized, copy it to your local variable, then modify it?

An initializer like:

void init_struct( structType * s )
{
   memcopy(s,&defaultValues,sizeof(structType));
}

Then when you want to use it:

structType foo;
init_struct( &foo ); // get defaults
foo.fieldICareAbout = 1; // modify fields
update( &foo ); // pass to function