Programs & Examples On #Log4cpp

A library of C++ classes for flexible logging to files, syslog, IDSA and other destinations. It is modelled after the Java library log4j, staying as close to their API as is reasonable.

Laravel Request::all() Should Not Be Called Statically

use the request() helper instead. You don't have to worry about use statements and thus this sort of problem wont happen again.

$input = request()->all();

simple

Bootstrap Modal sitting behind backdrop

First make sure the modal is not in any parent div. Then add $('#myModal').appendTo("body")

It worked fine for me.

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

Chrome disable SSL checking for sites?

In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.

I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?

Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,

There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.

The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).

Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.

What are native methods in Java and where should they be used?

Java native code necessities:

  • h/w access and control.
  • use of commercial s/w and system services[h/w related].
  • use of legacy s/w that hasn't or cannot be ported to Java.
  • Using native code to perform time-critical tasks.

hope these points answers your question :)

Option to ignore case with .contains method?

With a null check on the dvdList and your searchString

    if (!StringUtils.isEmpty(searchString)) {
        return Optional.ofNullable(dvdList)
                       .map(Collection::stream)
                       .orElse(Stream.empty())
                       .anyMatch(dvd >searchString.equalsIgnoreCase(dvd.getTitle()));
      }

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

I tried using phyatt's AspectRatioPixmapLabel class, but experienced a few problems:

  • Sometimes my app entered an infinite loop of resize events. I traced this back to the call of QLabel::setPixmap(...) inside the resizeEvent method, because QLabel actually calls updateGeometry inside setPixmap, which may trigger resize events...
  • heightForWidth seemed to be ignored by the containing widget (a QScrollArea in my case) until I started setting a size policy for the label, explicitly calling policy.setHeightForWidth(true)
  • I want the label to never grow more than the original pixmap size
  • QLabel's implementation of minimumSizeHint() does some magic for labels containing text, but always resets the size policy to the default one, so I had to overwrite it

That said, here is my solution. I found that I could just use setScaledContents(true) and let QLabel handle the resizing. Of course, this depends on the containing widget / layout honoring the heightForWidth.

aspectratiopixmaplabel.h

#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H

#include <QLabel>
#include <QPixmap>

class AspectRatioPixmapLabel : public QLabel
{
    Q_OBJECT
public:
    explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
    virtual int heightForWidth(int width) const;
    virtual bool hasHeightForWidth() { return true; }
    virtual QSize sizeHint() const { return pixmap()->size(); }
    virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};

#endif // ASPECTRATIOPIXMAPLABEL_H

aspectratiopixmaplabel.cpp

#include "aspectratiopixmaplabel.h"

AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
    QLabel(parent)
{
    QLabel::setPixmap(pixmap);
    setScaledContents(true);
    QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
    policy.setHeightForWidth(true);
    this->setSizePolicy(policy);
}

int AspectRatioPixmapLabel::heightForWidth(int width) const
{
    if (width > pixmap()->width()) {
        return pixmap()->height();
    } else {
        return ((qreal)pixmap()->height()*width)/pixmap()->width();
    }
}

Is it valid to have a html form inside another html form?

In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.

<form method="post" action="ServerFileToExecute.php">
    <input type="submit" name="save" value="Click here to save" />
    <input type="submit" name="delete" value="Click here to delete" />
</form>

The server side could look something like this if you use php:

<?php
    if(isset($_POST['save']))
        echo "Stored!";
    else if(isset($_POST['delete']))
        echo "Deleted!";
    else
        echo "Action is missing!";
?>

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Might wxChart be an option? I have not used it myself however and it looks like it hasnt been updated for a while.

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

Just try to run the following command manually:

C:\wamp\bin\mysql\mysql5.6.17\bin\mysqld.exe --console

It worked for me :)

Disable button in jQuery

Simply it's work fine, in HTML:

<button type="button" id="btn_CommitAll"class="btn_CommitAll">save</button>

In JQuery side put this function for disable button:

function disableButton() {
    $('.btn_CommitAll').prop("disabled", true);
}

For enable button:

function enableButton() {
    $('.btn_CommitAll').prop("disabled", false);
}

That's all.

Using gradle to find dependency tree

You can render the dependency tree with the command gradle dependencies. For more information check the section 11.6.4 Listing project dependencies in the online user guide.

TCPDF ERROR: Some data has already been output, can't send PDF file

use ob_end_clean();

$pdf->Output($file, 'I'); to open pdf. It works for me

getOutputStream() has already been called for this response

I got the same problem, and I solved just adding "return;" at the end of the FileInputStream.

Here is my JSP

_x000D_
_x000D_
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"_x000D_
 pageEncoding="ISO-8859-1"%>_x000D_
<%@ page import="java.io.*"%>_x000D_
<%@ page trimDirectiveWhitespaces="true"%>_x000D_
_x000D_
<%_x000D_
_x000D_
 try {_x000D_
  FileInputStream ficheroInput = new FileInputStream("C:\\export_x_web.pdf");_x000D_
  int tamanoInput = ficheroInput.available();_x000D_
  byte[] datosPDF = new byte[tamanoInput];_x000D_
  ficheroInput.read(datosPDF, 0, tamanoInput);_x000D_
_x000D_
  response.setHeader("Content-disposition", "inline; filename=export_sise_web.pdf");_x000D_
  response.setContentType("application/pdf");_x000D_
  response.setContentLength(tamanoInput);_x000D_
  response.getOutputStream().write(datosPDF);_x000D_
_x000D_
  response.getOutputStream().flush();_x000D_
  response.getOutputStream().close();_x000D_
_x000D_
  ficheroInput.close();_x000D_
  return;_x000D_
_x000D_
 } catch (Exception e) {_x000D_
_x000D_
 }_x000D_
%>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

In the GSM specification 3GPP TS 11.11, there are 10 bytes set aside in the MSISDN EF (6F40) for 'dialing number'. Since this is the GSM representation of a phone number, and it's usage is nibble swapped, (and there is always the possibility of parentheses) 22 characters of data should be plenty.

In my experience, there is only one instance of open/close parentheses, that is my reasoning for the above.

When should I use nil and NULL in Objective-C?

You can use nil about anywhere you can use null. The main difference is that you can send messages to nil, so you can use it in some places where null cant work.

In general, just use nil.

toggle show/hide div with button?

Here's a plain Javascript way of doing toggle:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">

How do I validate a date in this format (yyyy-mm-dd) using jquery?

I recommend to use the Using jquery validation plugin and jquery ui date picker

jQuery.validator.addMethod("customDateValidator", function(value, element) {
// dd-mm-yyyy
   var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
   if (! re.test(value) ) return false
   // parseDate throws exception if the value is invalid
   try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
   catch(e){return false;} 
   },
   "Please enter a valid date format dd-mm-yyyy"
);

this.ui.form.validate({
    debug: true,
    rules : {
    title : { required : true, minlength: 4 }, 
    date : { required: true, customDateValidator: true }
    }
}) ;

Using Jquery and date picker just create a function with

// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
 if (! re.test(value) ) return false
// parseDate throws exception if the value is invalid
try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
catch(e){return false;}

You might use only the regular expression for validation

// dd-mm-yyyy
var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
return re.test(value) 

Of course the date format should be of your region

How do I download NLTK data?

It's very simple....

  1. Open pyScripter or any editor
  2. Create a python file eg: install.py
  3. write the below code in it.
import nltk
nltk.download()
  1. A pop-up window will apper and click on download .

The download window]

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

Can vue-router open a link in a new tab?

The simplest way of doing this using an anchor tag would be this:

<a :href="$router.resolve({name: 'posts.show', params: {post: post.id}}).href" target="_blank">
    Open Post in new tab
</a>

fs.writeFile in a promise, asynchronous-synchronous stuff

Update Sept 2017: fs-promise has been deprecated in favour of fs-extra.


I haven't used it, but you could look into fs-promise. It's a node module that:

Proxies all async fs methods exposing them as Promises/A+ compatible promises (when, Q, etc). Passes all sync methods through as values.

How to calculate number of days between two given dates?

Days until Christmas:

>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86

More arithmetic here.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

What is an AssertionError? In which case should I throw it from my own code?

I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionError in particular.

assert and throw new AssertionError() are very similar and serve the same conceptual purpose, but there are differences.

  1. throw new AssertionError() will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -ea switch).
  2. The compiler knows that throw new AssertionError() will exit the block, so using it will let you avoid certain compiler errors that assert will not.

For example:

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            throw new AssertionError();
        }
        System.out.println("n = " + n);
    }

    {
        boolean b = true;
        final int n;
        if ( b ) {
            n = 5;
        } else {
            assert false;
        }
        System.out.println("n = " + n);
    }

The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that n has been initialized by the time the code tries to print it out.

Using intents to pass data between activities

You can use Bundle to get data :

Bundle extras = intent.getExtras();
String data = extras.getString("data"); // use your key 

And again you can opass this data to next activity :

 Intent intent = new Intent(this, next_Activity.class);
   intent.putExtra("data", data);
   startActivity(intent);

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

calculating execution time in c++

Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.

For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings and set Build Timing option to 'yes'. After that the time of every build will be displayed in the Output window.

<Django object > is not JSON serializable

The easiest way is to use a JsonResponse.

For a queryset, you should pass a list of the the values for that queryset, like so:

from django.http import JsonResponse

queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})

Python: most idiomatic way to convert None to empty string?

Probably the shortest would be str(s or '')

Because None is False, and "x or y" returns y if x is false. See Boolean Operators for a detailed explanation. It's short, but not very explicit.

Launch an event when checking a checkbox in Angular2

Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html

  CheckBox: use change event to call the function and pass the event.

<label class="container">    
   <input type="checkbox" [(ngModel)]="theCheckbox"  data-md-icheck 
    (change)="toggleVisibility($event)"/>
      Checkbox is <span *ngIf="marked">checked</span><span 
     *ngIf="!marked">unchecked</span>
     <span class="checkmark"></span>
</label>
 <div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>

Finding second occurrence of a substring in a string in Java

Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:

str.indexOf("is", str.indexOf("is") + 1);

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

time delayed redirect?

Include this code somewhere when you slide to your 'section' called blog.

$("#myLink").click(function() {
    setTimeout(function() {
        window.navigate("the url of the page you want to navigate back to");
    }, 2000);
});

Where myLink is the id of your href.

How to convert Javascript datetime to C# datetime?

JS:

 function createDateObj(date) {
            var day = date.getDate();           // yields 
            var month = date.getMonth();    // yields month
            var year = date.getFullYear();      // yields year
            var hour = date.getHours();         // yields hours 
            var minute = date.getMinutes();     // yields minutes
            var second = date.getSeconds();     // yields seconds
            var millisec = date.getMilliseconds();
            var jsDate = Date.UTC(year, month, day, hour, minute, second, millisec);
            return jsDate;
        }

JS:

var oRequirementEval = new Object();
var date = new Date($("#dueDate").val());

CS:

requirementEvaluations.DeadLine = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(Convert.ToDouble( arrayUpdateRequirementEvaluationData["DeadLine"]))
    .ToLocalTime();

Change the class from factor to numeric of many columns in a data frame

I had problems converting all columns to numeric with an apply() call:

apply(data, 2, as.numeric)

The problem turns out to be because some of the strings had a comma in them -- e.g. "1,024.63" instead of "1024.63" -- and R does not like this way of formatting numbers. So I removed them and then ran as.numeric():

data = as.data.frame(apply(data, 2, function(x) {
  y = str_replace_all(x, ",", "") #remove commas
  return(as.numeric(y)) #then convert
}))

Note that this requires the stringr package to be loaded.

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

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

How to create EditText with rounded corners?

Try this one,

  1. Create rounded_edittext.xml file in your Drawable

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" android:padding="15dp">
    
        <solid android:color="#FFFFFF" />
        <corners
            android:bottomRightRadius="0dp"
            android:bottomLeftRadius="0dp"
            android:topLeftRadius="0dp"
            android:topRightRadius="0dp" />
        <stroke android:width="1dip" android:color="#f06060" />
    </shape>
    
  2. Apply background for your EditText in xml file

    <EditText
        android:id="@+id/edit_expiry_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:background="@drawable/rounded_edittext"
        android:hint="@string/shop_name"
        android:inputType="text" />  
    
  3. You will get output like this

enter image description here

How do I pause my shell script for a second before continuing?

On Mac OSX, sleep does not take minutes/etc, only seconds. So for two minutes,

sleep 120

How to get the Android Emulator's IP address?

Like this:

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Check the docs for more info: NetworkInterface.

Javascript reduce() on Object

This is not very difficult to implement yourself:

function reduceObj(obj, callback, initial) {
    "use strict";
    var key, lastvalue, firstIteration = true;
    if (typeof callback !== 'function') {
        throw new TypeError(callback + 'is not a function');
    }   
    if (arguments.length > 2) {
        // initial value set
        firstIteration = false;
        lastvalue = initial;
    }
    for (key in obj) {
        if (!obj.hasOwnProperty(key)) continue;
        if (firstIteration)
            firstIteration = false;
            lastvalue = obj[key];
            continue;
        }
        lastvalue = callback(lastvalue, obj[key], key, obj);
    }
    if (firstIteration) {
        throw new TypeError('Reduce of empty object with no initial value');
    }
    return lastvalue;
}

In action:

var o = {a: {value:1}, b: {value:2}, c: {value:3}};
reduceObj(o, function(prev, curr) { prev.value += cur.value; return prev;}, {value:0});
reduceObj(o, function(prev, curr) { return {value: prev.value + curr.value};});
// both == { value: 6 };

reduceObj(o, function(prev, curr) { return prev + curr.value; }, 0);
// == 6

You can also add it to the Object prototype:

if (typeof Object.prototype.reduce !== 'function') {
    Object.prototype.reduce = function(callback, initial) {
        "use strict";
        var args = Array.prototype.slice(arguments);
        args.unshift(this);
        return reduceObj.apply(null, args);
    }
}

open resource with relative path in Java

@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:

String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;



// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);

How to get the cookie value in asp.net website

HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
    lbl_cookie_value.Text = cook.Value;
}
else
{
    lbl_cookie_value.Text = "Empty value";
}

Reference Click here

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:

<?php

///////    SYNTAX ERROR CHECK    ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');

//replace "pageToTest.php" with the file path that you want to test. 
include('pageToTest.php'); 

?>

Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.

Indentation shortcuts in Visual Studio

Visual studio’s smart indenting does automatically indenting, but we can select a block or all the code for indentation.

  1. Select all the code: Ctrl+a

  2. Use either of the two ways to indentation the code:

    • Shift+Tab,

    • Ctrl+k+f.

How do I get the path of the current executed file in Python?

First, you need to import from inspect and os

from inspect import getsourcefile
from os.path import abspath

Next, wherever you want to find the source file from you just use

abspath(getsourcefile(lambda:0))

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

Find out where MySQL is installed on Mac OS X

If you run SHOW VARIABLES from a mysql console you can look for basedir.

When I run the following:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';

on my system I get /usr/local/mysql as the Value returned. (I am not using MAMP - I installed MySQL with homebrew.

mysqldon my machine is in /usr/local/mysql/bin so the basedir is where most everything will be installed to.

Also util:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir'; 

To find where the DBs are stored.

For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html

and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir

What is the best way to iterate over multiple lists at once?

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

Possible to extend types in Typescript?

What you are trying to achieve is equivalent to

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.

Communication between multiple docker-compose projects

All containers from api can join the front default network with following config:

# api/docker-compose.yml

...

networks:
  default:
    external:
      name: front_default

See docker compose guide: using a pre existing network (see at the bottom)

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Your import has a subtle error:

import java.awt.List;

It should be:

import java.util.List;

The problem is that both awt and Java's util package provide a class called List. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList extends java.util.List, not java.awt.List so if it wasn't for the generics, it would have still been a problem.

Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.

import org.omg.DynamicAny.NameValuePair;

should be

import org.apache.http.NameValuePair

nameValuePairs now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity, which is List<? extends NameValuePair>, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair did not extend org.apache.http.NameValuePair and the shortened type name NameValuePair evaluated to org.omg... in your file, but org.apache... in their code.

Opening the Settings app from another app

iOS 10 update

Apple changed the method to open async on the main thread. However, from now it is only possible to open the app settings in native settings.

[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];

iOS 9 update

It is now possible to go directly to sub-settings menu. However, a URL scheme has to be created. It can be done using two ways:

  1. XCode - You will find it in Target, Info, URL Scheme. Then, just type prefs.
  2. Directly adding to *-Info.plist. Add the following: <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <string>prefs</string> </array> </dict> </array>

Then the code:

Swift

UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=General&path=Keyboard")!)

Objective-c

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General&path=Keyboard"]];

Integer expression expected error in shell script

If you are just comparing numbers, I think there's no need to change syntax, just correct those lines, lines 6 and 9 brackets.

Line 6 before: if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]

After: if [ "$age" -le "7" -o "$age" -ge "65" ]

Line 9 before: elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]

After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}

JS strings "+" vs concat method

  • We can't concatenate a string variable to an integer variable using concat() function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.
  • As we know, functions are pretty slower than operators. functions needs to pass values to the predefined functions and need to gather the results of the functions. which is slower than doing operations using operators because operators performs operations in-line but, functions used to jump to appropriate memory locations... So, As mentioned in previous answers the other difference is obviously the speed of operation.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to add ID property to Html.BeginForm() in asp.net mvc?

I've added some code to my project, so it's more convenient.

HtmlExtensions.cs:

namespace System.Web.Mvc.Html
{
    public static class HtmlExtensions
    {
        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId)
        {
            return htmlHelper.BeginForm(null, null, FormMethod.Post, new { id = formId });
        }

        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId, FormMethod method)
        {
            return htmlHelper.BeginForm(null, null, method, new { id = formId });
        }
    }
}

MySignupForm.cshtml:

@using (Html.BeginForm("signupform")) 
{
    @* Some fields *@
}

API vs. Webservice

API's are a published interface which defines how component A communicates with component B.

For example, Doubleclick have a published Java API which allows users to interrogate the database tables to get information about their online advertising campaign.

e.g. call GetNumberClicks (user name)

To implement the API, you have to add the Doubleclick .jar file to your class path. The call is local.

A web service is a form of API where the interface is defined by means of a WSDL. This allows remote calling of an interface over HTTP.

If Doubleclick implemented their interface as a web service, they would use something like Axis2 running inside Tomcat.

The remote user would call the web service

e.g. call GetNumberClicksWebService (user name)

and the GetNumberClicksWebService service would call GetNumberClicks locally.

C++ - Assigning null to a std::string

I won't argue that it's a good idea (or the semantics of using nullptr with things that aren't pointers), but it's relatively simple to create a class which would provide "nullable" semantics (see nullable_string).

However, this is a much better fit for C++17's std::optional:

#include <string>
#include <iostream>
#include <optional>

// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b)
{
    if (b)
        return "Godzilla";
    else
        return {};
}

int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << std::endl;

    // optional-returning factory functions are usable as conditions of while and if
    if (auto str = create(true))
    {
        std::cout << "create(true) returned " << *str << std::endl;
    }
}

std::optional, as shown in the example, is convertible to bool, or you may use the has_value() method, has exceptions for bad access, etc. This provides you with nullable semantics, which seems to be what Maria was trying to accomplish.

And if you don't want to wait around for C++17 compatibility, see this answer about Boost.Optional.

How to make a gui in python

Tkinter is the "standard" GUI for Python, meaning it should be available with every Python installation.

In terms of learning it, and particularly learning how to use recent versions of Tkinter (which have improved a lot), I very highly recommend the TkDocs tutorial that I put together a while back - see http://www.tkdocs.com

Loaded with examples, covers basic concepts and all of the core widgets.

How to insert a timestamp in Oracle?

For my own future reference:

With cx_Oracle use cursor.setinputsize(...):

mycursor = connection.cursor();

mycursor.setinputsize( mytimestamp=cx_Oracle.TIMESTAMP );
params = { 'mytimestamp': timestampVar };
cusrsor.execute("INSERT INTO mytable (timestamp_field9 VALUES(:mytimestamp)", params);

No converting in the db needed. See Oracle Documentation

How to dynamically build a JSON object with Python?

All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object

(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

enter image description here

How can I check for "undefined" in JavaScript?

Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

Testing Spring's @RequestBody using Spring MockMVC

the following works for me,

  mockMvc.perform(
            MockMvcRequestBuilders.post("/api/test/url")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(asJsonString(createItemForm)))
            .andExpect(status().isCreated());

  public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

POST data with request module on Node.JS

EDIT: You should check out Needle. It does this for you and supports multipart data, and a lot more.

I figured out I was missing a header

var request = require('request');
request.post({
  headers: {'content-type' : 'application/x-www-form-urlencoded'},
  url:     'http://localhost/test2.php',
  body:    "mes=heydude"
}, function(error, response, body){
  console.log(body);
});

FileSystemWatcher Changed event is raised twice

I spent some significant amount of time using the FileSystemWatcher, and some of the approaches here will not work. I really liked the disabling events approach, but unfortunately, it doesn't work if there is >1 file being dropped, second file will be missed most if not all times. So I use the following approach:

private void EventCallback(object sender, FileSystemEventArgs e)
{
    var fileName = e.FullPath;

    if (!File.Exists(fileName))
    {
        // We've dealt with the file, this is just supressing further events.
        return;
    }

    // File exists, so move it to a working directory. 
    File.Move(fileName, [working directory]);

    // Kick-off whatever processing is required.
}

Button Listener for button in fragment in android

This works for me.

private OnClickListener mDisconnectListener;
mDisconnectListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    };

...

... onCreateView(...){

mButtonDisconnect = (Button) rootView.findViewById(R.id.button_disconnect);
mButtonDisconnect.setOnClickListener(mDisconnectListener);
...
}

How to connect android emulator to the internet

check if you are using more than one internet connection to your pc like one is LAN second one is Modem , so disable all lan or modem .

How to set Internet options for Android emulator?

LaTeX table positioning

Not necessary to use \restylefloat and destroys other options, like caption placement. just use [H] or [!h] after \begin{table}.

How to know user has clicked "X" or the "Close" button?

I always use a Form Close method in my applications that catches alt + x from my exit Button, alt + f4 or another form closing event was initiated. All my classes have the class name defined as Private string mstrClsTitle = "grmRexcel" in this case, an Exit method that calls the Form Closing Method and a Form Closing Method. I also have a statement for the Form Closing Method - this.FormClosing = My Form Closing Form Closing method name.

The code for this:

namespace Rexcel_II
{
    public partial class frmRexcel : Form
    {
        private string mstrClsTitle = "frmRexcel";

        public frmRexcel()
        {
            InitializeComponent();

            this.FormClosing += frmRexcel_FormClosing;
        }

        /// <summary>
        /// Handles the Button Exit Event executed by the Exit Button Click
        /// or Alt + x
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {            
            this.Close();        
        }


        /// <summary>
        /// Handles the Form Closing event
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmRexcel_FormClosing(object sender, FormClosingEventArgs e)
        {

            // ---- If windows is shutting down, 
            // ---- I don't want to hold up the process
            if (e.CloseReason == CloseReason.WindowsShutDown) return;
            {

                // ---- Ok, Windows is not shutting down so
                // ---- either btnExit or Alt + x or Alt + f4 has been clicked or
                // ---- another form closing event was intiated
                //      *)  Confirm user wants to close the application
                switch (MessageBox.Show(this, 
                                    "Are you sure you want to close the Application?",
                                    mstrClsTitle + ".frmRexcel_FormClosing",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {

                    // ---- *)  if No keep the application alive 
                    //----  *)  else close the application
                    case DialogResult.No:
                        e.Cancel = true;
                        break;
                    default:
                        break;
                }
            }
        }
    }
}

How do I implement IEnumerable<T>

Note that the IEnumerable<T> allready implemented by the System.Collections so another approach is to derive your MyObjects class from System.Collections as a base class (documentation):

System.Collections: Provides the base class for a generic collection.

We can later make our own implemenation to override the virtual System.Collections methods to provide custom behavior (only for ClearItems, InsertItem, RemoveItem, and SetItem along with Equals, GetHashCode, and ToString from Object). Unlike the List<T> which is not designed to be easily extensible.

Example:

public class FooCollection : System.Collections<Foo>
{
    //...
    protected override void InsertItem(int index, Foo newItem)
    {
        base.InsertItem(index, newItem);     
        Console.Write("An item was successfully inserted to MyCollection!");
    }
}

public static void Main()
{
    FooCollection fooCollection = new FooCollection();
    fooCollection.Add(new Foo()); //OUTPUT: An item was successfully inserted to FooCollection!
}

Please note that driving from collection recommended only in case when custom collection behavior is needed, which is rarely happens. see usage.

Insert a line break in mailto body

For the Single line and double line break here are the following codes.

Single break: %0D0A
Double break: %0D0A%0D0A

Remove trailing zeros from decimal in SQL Server

SELECT CONVERT(DOUBLE PRECISION, [ColumnName])

why should I make a copy of a data frame in pandas

The primary purpose is to avoid chained indexing and eliminate the SettingWithCopyWarning.

Here chained indexing is something like dfc['A'][0] = 111

The document said chained indexing should be avoided in Returning a view versus a copy. Here is a slightly modified example from that document:

In [1]: import pandas as pd

In [2]: dfc = pd.DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})

In [3]: dfc
Out[3]:
    A   B
0   aaa 1
1   bbb 2
2   ccc 3

In [4]: aColumn = dfc['A']

In [5]: aColumn[0] = 111
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [6]: dfc
Out[6]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

Here the aColumn is a view and not a copy from the original DataFrame, so modifying aColumn will cause the original dfc be modified too. Next, if we index the row first:

In [7]: zero_row = dfc.loc[0]

In [8]: zero_row['A'] = 222
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [9]: dfc
Out[9]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

This time zero_row is a copy, so the original dfc is not modified.

From these two examples above, we see it's ambiguous whether or not you want to change the original DataFrame. This is especially dangerous if you write something like the following:

In [10]: dfc.loc[0]['A'] = 333
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [11]: dfc
Out[11]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

This time it didn't work at all. Here we wanted to change dfc, but we actually modified an intermediate value dfc.loc[0] that is a copy and is discarded immediately. It’s very hard to predict whether the intermediate value like dfc.loc[0] or dfc['A'] is a view or a copy, so it's not guaranteed whether or not original DataFrame will be updated. That's why chained indexing should be avoided, and pandas generates the SettingWithCopyWarning for this kind of chained indexing update.

Now is the use of .copy(). To eliminate the warning, make a copy to express your intention explicitly:

In [12]: zero_row_copy = dfc.loc[0].copy()

In [13]: zero_row_copy['A'] = 444 # This time no warning

Since you are modifying a copy, you know the original dfc will never change and you are not expecting it to change. Your expectation matches the behavior, then the SettingWithCopyWarning disappears.

Note, If you do want to modify the original DataFrame, the document suggests you use loc:

In [14]: dfc.loc[0,'A'] = 555

In [15]: dfc
Out[15]:
    A   B
0   555 1
1   bbb 2
2   ccc 3

SQL Server - copy stored procedures from one db to another

use

select * from sys.procedures

to show all your procedures;

sp_helptext @objname = 'Procedure_name'

to get the code

and your creativity to build something to loop through them all and generate the export code :)

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

Node.js heap out of memory

If you want to increase the memory usage of the node globally - not only single script, you can export environment variable, like this:
export NODE_OPTIONS=--max_old_space_size=4096

Then you do not need to play with files when running builds like npm run build.

Deserialize JSON with C#

Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer, DataContractJsonSerializer.

In this sample, you can the following:

var jsonData = JObject.Parse("your JSON data here");

Then you can cast jsonData to JArray, and you can use a for loop to get data at each iteration.

Also, I want to add something:

for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
    var data = jsonData[i - 1];
}

Working with dynamic object and using Newtonsoft serialize is a good choice.

Dynamically add properties to a existing object

If you have a class with an object property, or if your property actually casts to an object, you can reshape the object by reassigning its properties, as in:

  MyClass varClass = new MyClass();
  varClass.propObjectProperty = new { Id = 1, Description = "test" };

  //if you need to treat the class as an object
  var varObjectProperty = ((dynamic)varClass).propObjectProperty;
  ((dynamic)varClass).propObjectProperty = new { Id = varObjectProperty.Id, Description = varObjectProperty.Description, NewDynamicProperty = "new dynamic property description" };

  //if your property is an object, instead
  var varObjectProperty = varClass.propObjectProperty;
  varClass.propObjectProperty = new { Id = ((dynamic)varObjectProperty).Id, Description = ((dynamic)varObjectProperty).Description, NewDynamicProperty = "new dynamic property description" };

With this approach, you basically rewrite the object property adding or removing properties as if you were first creating the object with the

new { ... }

syntax.

In your particular case, you're probably better off creating an actual object to which you assign properties like "dob" and "address" as if it were a person, and at the end of the process, transfer the properties to the actual "Person" object.

Oracle SELECT TOP 10 records

try

SELECT * FROM users FETCH NEXT 10 ROWS ONLY;

How to watch for a route change in AngularJS?

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });

Differences between cookies and sessions?

Cookie is basically a global array accessed across web browsers. Many a times used to send/receive values. it acts as a storage mechanism to access values between forms. Cookies can be disabled by the browser which adds a constraint to their use in comparison to session.

Session can be defined as something between logging in and logging out. the time between the user logging in and logging out is a session. Session stores values only for the session time i.e before logging out. Sessions are used to track the activities of the user, once he logs on.

SQL Server: Error converting data type nvarchar to numeric

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

Example: Left(Field,4)

Basically, the query will look like:

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

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

Creating Dynamic button with click event in JavaScript

<!DOCTYPE html>
<html>
<body>

<p>Click the button to make a BUTTON element with text.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("CLICK ME");

    btn.setAttribute("style","color:red;font-size:23px");

    btn.appendChild(t);
    document.body.appendChild(btn);

    btn.setAttribute("onclick", alert("clicked"));

}
</script>

</body>
</html>

AngularJS $watch window resize inside directive

You shouldn't need a $watch. Just bind to resize event on window:

DEMO

'use strict';

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

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'E',
        template: '<div>window size: {{width}}px</div>'
     };

     function link(scope, element, attrs){

       scope.width = $window.innerWidth;

       angular.element($window).bind('resize', function(){

         scope.width = $window.innerWidth;

         // manuall $digest required as resize event
         // is outside of angular
         scope.$digest();
       });

     }

 }]);

Select objects based on value of variable in object using jq

I had a similar related question: What if you wanted the original object format back (with key names, e.g. FOO, BAR)?

Jq provides to_entries and from_entries to convert between objects and key-value pair arrays. That along with map around the select

These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries, useful for doing some operation to all keys and values of an object. from_entries accepts key, Key, name, Name, value and Value as keys.

jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'

{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

Using the with_entries shorthand, this becomes:

jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

How to get JQuery.trigger('click'); to initiate a mouse click

You just need to put a small timeout event before doing .click() like this :

setTimeout(function(){ $('#btn').click()}, 100);

How to get current PHP page name

In your case you can use __FILE__ variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php

View google chrome's cached pictures

Modified version from @dovidev as his version loads the image externally instead of reading the local cache.

  1. Navigate to chrome://cache/
  2. In the chrome top menu go to "View > Developer > Javascript Console"
  3. In the console that opens paste the below and press enter

_x000D_
_x000D_
var cached_anchors = $$('a');_x000D_
document.body.innerHTML = '';_x000D_
for (var i in cached_anchors) {_x000D_
    var ca = cached_anchors[i];_x000D_
    if(ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {_x000D_
        var xhr = new XMLHttpRequest();_x000D_
        xhr.open("GET", ca.href);_x000D_
        xhr.responseType = "document";_x000D_
        xhr.onload = response;_x000D_
        xhr.send();_x000D_
    }_x000D_
}_x000D_
_x000D_
function response(e) {_x000D_
  var hexdata = this.response.getElementsByTagName("pre")[2].innerHTML.split(/\r?\n/).slice(0,-1).map(e => e.split(/[\s:]+\s/)[1]).map(e => e.replace(/\s/g,'')).join('');_x000D_
  var byteArray = new Uint8Array(hexdata.length/2);_x000D_
  for (var x = 0; x < byteArray.length; x++){_x000D_
      byteArray[x] = parseInt(hexdata.substr(x*2,2), 16);_x000D_
  }_x000D_
  var blob = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
  var image = new Image();_x000D_
  image.src = URL.createObjectURL(blob);_x000D_
  document.body.appendChild(image);_x000D_
}
_x000D_
_x000D_
_x000D_

PHP Echo text Color

If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:

echo '<p style="color: red; text-align: center">
      Request has been sent. Please wait for my reply!
      </p>';

Find OpenCV Version Installed on Ubuntu

You can look at the headers or libs installed. pkg-config can tell you where they are:

pkg-config --cflags opencv
pkg-config --libs opencv

Alternatively you can write a simple program and print the following defs:

CV_MAJOR_VERSION
CV_MINOR_VERSION

A similar question has been also asked here:

Usage of \b and \r in C

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

Code:

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

How do you check if a JavaScript Object is a DOM Object?

differentiate a raw js object from a HTMLElement

function isDOM (x){
     return /HTML/.test( {}.toString.call(x) );
 }

use:

isDOM( {a:1} ) // false
isDOM( document.body ) // true

// OR

Object.defineProperty(Object.prototype, "is",
    {
        value: function (x) {
            return {}.toString.call(this).indexOf(x) >= 0;
        }
    });

use:

o={}; o.is("HTML") // false o=document.body; o.is("HTML") // true

Dynamically add event listener

I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:

ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }

If i´m adding a listener

this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
    alert('Clicking the document');
})

I´d expect my function to execute what i intended, not the total opposite which is remove the listener.

// I´d expect an alert('Clicking the document'); 
this.listenToClick();
// what you actually get is removing the listener, so nothing...

In the given scenario, It´d actually make to more sense to name it like:

// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
    console.log('Clicking the document', evt);
})

let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
    console.log('Clicking the button', evt);
});

There must be a good reason for this but in my opinion it´s very misleading and not intuitive.

Lining up labels with radio buttons in bootstrap

In Bootstrap 4 you can use the form-check-inline class.

<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="queryFieldName" id="option1" value="1">
  <label class="form-check-label" for="option1">First</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="queryFieldName" id="option2" value="2">
  <label class="form-check-label" for="option2">Second</label>
</div>

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

How to put more than 1000 values into an Oracle IN clause

I wound up here looking for a solution as well.

Depending on the high-end number of items you need to query against, and assuming your items are unique, you could split your query into batches queries of 1000 items, and combine the results on your end instead (pseudocode here):

//remove dupes
items = items.RemoveDuplicates();

//how to break the items into 1000 item batches        
batches = new batch list;
batch = new batch;
for (int i = 0; i < items.Count; i++)
{
    if (batch.Count == 1000)
    {
        batches.Add(batch);
        batch.Clear()
    }
    batch.Add(items[i]);
    if (i == items.Count - 1)
    {
        //add the final batch (it has < 1000 items).
        batches.Add(batch); 
    }
}

// now go query the db for each batch
results = new results;
foreach(batch in batches)
{
    results.Add(query(batch));
}

This may be a good trade-off in the scenario where you don't typically have over 1000 items - as having over 1000 items would be your "high end" edge-case scenario. For example, in the event that you have 1500 items, two queries of (1000, 500) wouldn't be so bad. This also assumes that each query isn't particularly expensive in of its own right.

This wouldn't be appropriate if your typical number of expected items got to be much larger - say, in the 100000 range - requiring 100 queries. If so, then you should probably look more seriously into using the global temporary tables solution provided above as the most "correct" solution. Furthermore, if your items are not unique, you would need to resolve duplicate results in your batches as well.

jQuery Event : Detect changes to the html/text of a div

Try the MutationObserver:

browser support: http://caniuse.com/#feat=mutationobserver

_x000D_
_x000D_
<html>_x000D_
  <!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->_x000D_
_x000D_
  <head>_x000D_
    </head>_x000D_
  <body>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script type="text/javascript">_x000D_
      // Inspect the array of MutationRecord objects to identify the nature of the change_x000D_
function mutationObjectCallback(mutationRecordsList) {_x000D_
  console.log("mutationObjectCallback invoked.");_x000D_
_x000D_
  mutationRecordsList.forEach(function(mutationRecord) {_x000D_
    console.log("Type of mutation: " + mutationRecord.type);_x000D_
    if ("attributes" === mutationRecord.type) {_x000D_
      console.log("Old attribute value: " + mutationRecord.oldValue);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
      _x000D_
// Create an observer object and assign a callback function_x000D_
var observerObject = new MutationObserver(mutationObjectCallback);_x000D_
_x000D_
      // the target to watch, this could be #yourUniqueDiv _x000D_
      // we use the body to watch for changes_x000D_
var targetObject = document.body; _x000D_
      _x000D_
// Register the target node to observe and specify which DOM changes to watch_x000D_
      _x000D_
      _x000D_
observerObject.observe(targetObject, { _x000D_
  attributes: true,_x000D_
  attributeFilter: ["id", "dir"],_x000D_
  attributeOldValue: true,_x000D_
  childList: true_x000D_
});_x000D_
_x000D_
// This will invoke the mutationObjectCallback function (but only after all script in this_x000D_
// scope has run). For now, it simply queues a MutationRecord object with the change information_x000D_
targetObject.appendChild(document.createElement('div'));_x000D_
_x000D_
// Now a second MutationRecord object will be added, this time for an attribute change_x000D_
targetObject.dir = 'rtl';_x000D_
_x000D_
_x000D_
      </script>_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

How can I reference a commit in an issue comment on GitHub?

To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.

See also:

How to prevent form from submitting multiple times from client side?

The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"

Just Disable the form submit button, like below code.

<form ... onsubmit="buttonName.disabled=true; return true;">
  <input type="submit" name="buttonName" value="Submit">
</form>

It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.

How do I measure separate CPU core usage for a process?

htop gives a nice overview of individual core usage

Is there a way to create and run javascript in Chrome?

How to create a Javascript Bookmark in Chrome:

You can use a Javascript bookmark: https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/. Just create a bookmark to look like this:

Ex:

Name:

Test javascript bookmark in Chrome

URL:

javascript:alert('Hello world!');

Just precede the URL with javascript:, followed by your Javascript code. No space after the colon is required.

Here's how it looks as I'm typing it in:

enter image description here

Now save and then click on your newly-created Javascript bookmark, and you'll see this:

enter image description here

You can do multi-line scripts too. If you include any comments, however, be sure to use the C-style multi-line comments ONLY (/* comment */), and NOT the C++-style single-line comments (// comment), as they will interfere. Here's an example:

URL:

javascript:

/* This is my javascript demo */

function multiply(a, b) 
{
    return a * b;
}

var a = 1.4108;
var b = 3.7654;
var result = multiply(a, b);
alert('The result of ' + a + ' x ' + b + ' = ' + result.toFixed(4));

And here's what it looks like as you edit the bookmark, after copying and pasting the above multi-line script into the URL field for the bookmark:

enter image description here.

And here's the output when you click on it:

enter image description here

References:

  1. https://superuser.com/questions/192437/case-sensitive-searches-in-google-chrome/582280#582280
  2. https://gist.github.com/borisdiakur/9f9d751b4c9cf5acafa2
  3. Google search for "chrome javascript() in bookmark"
  4. https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/
  5. https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/
  6. https://javascript.info/hello-world
  7. JavaScript equivalent to printf/String.Format

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Even if your annotations are declared correctly to properly manage the one-to-many relationship you may still encounter this precise exception. When adding a new child object, Transaction, to an attached data model you'll need to manage the primary key value - unless you're not supposed to. If you supply a primary key value for a child entity declared as follows before calling persist(T), you'll encounter this exception.

@Entity
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
....

In this case, the annotations are declaring that the database will manage the generation of the entity's primary key values upon insertion. Providing one yourself (such as through the Id's setter) causes this exception.

Alternatively, but effectively the same, this annotation declaration results in the same exception:

@Entity
public class Transaction {
    @Id
    @org.hibernate.annotations.GenericGenerator(name="system-uuid", strategy="uuid")
    @GeneratedValue(generator="system-uuid")
    private Long id;
....

So, don't set the id value in your application code when it's already being managed.

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I have faced same issue after install macOS Catalina. I had try below command and its working.

sudo gem update

Difference between 2 dates in SQLite

The SQLite documentation is a great reference and the DateAndTimeFunctions page is a good one to bookmark.

It's also helpful to remember that it's pretty easy to play with queries with the sqlite command line utility:

sqlite> select julianday(datetime('now'));
2454788.09219907
sqlite> select datetime(julianday(datetime('now')));
2008-11-17 14:13:55

changing permission for files and folder recursively using shell command in mac

I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:

find . -type d -exec chmod 755 {} \+

but this also does the same thing:

chmod 755 `find . -type d`

and so does this:

chmod 755 $(find . -type d)

The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.

So I think in your case that the following will do what you want.

chmod 777 $(find "/Users/Test/Desktop/PATH")

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

Yes , Jared and Kelly Orr are right. I use the following code like in edit exception.

foreach (var issue in dinner.GetRuleViolations())
{
    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}

in stead of

ModelState.AddRuleViolations(dinner.GetRuleViolations());

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

Xcode doesn't see my iOS device but iTunes does

My app worked on all simulators but not on my device. I tried just about all the steps from each comment and didn't have any luck. I went to my device settings and switched my "Personal Hotspot" from off to on. Then it was all good!

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Error display @ operator

For undesired and redundant notices, one could use the dedicated @ operator to »hide« undefined variable/index messages.

$var = @($_GET["optional_param"]);
  • This is usually discouraged. Newcomers tend to way overuse it.
  • It's very inappropriate for code deep within the application logic (ignoring undeclared variables where you shouldn't), e.g. for function parameters, or in loops.
  • There's one upside over the isset?: or ?? super-supression however. Notices still can get logged. And one may resurrect @-hidden notices with: set_error_handler("var_dump");
    • Additonally you shouldn't habitually use/recommend if (isset($_POST["shubmit"])) in your initial code.
    • Newcomers won't spot such typos. It just deprives you of PHPs Notices for those very cases. Add @ or isset only after verifying functionality.
    • Fix the cause first. Not the notices.

  • @ is mainly acceptable for $_GET/$_POST input parameters, specifically if they're optional.

And since this covers the majority of such questions, let's expand on the most common causes:

$_GET / $_POST / $_REQUEST undefined input

  • First thing you do when encountering an undefined index/offset, is check for typos:
    $count = $_GET["whatnow?"];

    • Is this an expected key name and present on each page request?
    • Variable names and array indicies are case-sensitive in PHP.
  • Secondly, if the notice doesn't have an obvious cause, use var_dump or print_r to verify all input arrays for their curent content:

    var_dump($_GET);
    var_dump($_POST);
    //print_r($_REQUEST);
    

    Both will reveal if your script was invoked with the right or any parameters at all.

  • Alternativey or additionally use your browser devtools (F12) and inspect the network tab for requests and parameters:

    browser developer tools / network tab

    POST parameters and GET input will be be shown separately.

  • For $_GET parameters you can also peek at the QUERY_STRING in

    print_r($_SERVER);
    

    PHP has some rules to coalesce non-standard parameter names into the superglobals. Apache might do some rewriting as well. You can also look at supplied raw $_COOKIES and other HTTP request headers that way.

  • More obviously look at your browser address bar for GET parameters:

    http://example.org/script.php?id=5&sort=desc

    The name=value pairs after the ? question mark are your query (GET) parameters. Thus this URL could only possibly yield $_GET["id"] and $_GET["sort"].

  • Finally check your <form> and <input> declarations, if you expect a parameter but receive none.

    • Ensure each required input has an <input name=FOO>
    • The id= or title= attribute does not suffice.
    • A method=POST form ought to populate $_POST.
    • Whereas a method=GET (or leaving it out) would yield $_GET variables.
    • It's also possible for a form to supply action=script.php?get=param via $_GET and the remaining method=POST fields in $_POST alongside.
    • With modern PHP configurations (= 5.6) it has become feasible (not fashionable) to use $_REQUEST['vars'] again, which mashes GET and POST params.
  • If you are employing mod_rewrite, then you should check both the access.log as well as enable the RewriteLog to figure out absent parameters.

$_FILES

  • The same sanity checks apply to file uploads and $_FILES["formname"].
  • Moreover check for enctype=multipart/form-data
  • As well as method=POST in your <form> declaration.
  • See also: PHP Undefined index error $_FILES?

$_COOKIE

  • The $_COOKIE array is never populated right after setcookie(), but only on any followup HTTP request.
  • Additionally their validity times out, they could be constraint to subdomains or individual paths, and user and browser can just reject or delete them.

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
                                   // also makes this class abstract.
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
    // Your implementation
}

// Provide implementation for the second method
void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

Capitalize the first letter of both words in a two word string

Alternative way with substring and regexpr:

substring(name, 1) <- toupper(substring(name, 1, 1))
pos <- regexpr(" ", name, perl=TRUE) + 1
substring(name, pos) <- toupper(substring(name, pos, pos))

Why are only final variables accessible in anonymous class?

There is a trick that allows anonymous class to update data in the outer scope.

private void f(Button b, final int a) {
    final int[] res = new int[1];
    b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            res[0] = a * 5;
        }
    });

    // But at this point handler is most likely not executed yet!
    // How should we now res[0] is ready?
}

However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated

This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:

// ...

final int[] res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);

// ...

How to add more than one machine to the trusted hosts list using winrm

I prefer to work with the PSDrive WSMan:\.

Get TrustedHosts

Get-Item WSMan:\localhost\Client\TrustedHosts

Set TrustedHosts

provide a single, comma-separated, string of computer names

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'

or (dangerous) a wild-card

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'

to append to the list, the -Concatenate parameter can be used

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate

Trim whitespace from a String

I think that substr() throws an exception if str only contains the whitespace.

I would modify it to the following code:

string trim(string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (first == std::string::npos)
        return "";
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last-first+1));
}

How should I tackle --secure-file-priv in MySQL?

The thing that worked for me:

  1. Put your file inside of the folder specified in secure-file-priv.

    To find that type:

    mysql> show variables like "secure_file_priv";  
    
  2. Check if you have local_infile = 1.

    Do that typing:

    mysql> show variables like "local_infile";
    

    If you get:

    +---------------+-------+
    | Variable_name | Value |
    +---------------+-------+
    | local_infile  | OFF   |
    +---------------+-------+
    

    Then set it to one typing:

    mysql> set global local_infile = 1;
    
  3. Specify the full path for your file. In my case:

    mysql> load data infile "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/file.txt" into table test;
    

Determine distance from the top of a div to top of window with javascript

I used this function to detect if the element is visible in view port

Code:

const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
$(window).scroll(function(){
var scrollTop     = $(window).scrollTop(),
elementOffset = $('.for-scroll').offset().top,
distance      = (elementOffset - scrollTop);
if(distance < vh){
    console.log('in view');
}
else{
    console.log('not in view');
}
});

How to print a stack trace in Node.js?

Try Error.captureStackTrace(targetObject[, constructorOpt]).

const myObj = {};
function c() {
  // pass
}

function b() {
    Error.captureStackTrace(myObj)
    c()
} 

function a() {
    b()
}

a()

console.log(myObj.stack)

The function a and b are captured in error stack and stored in myObj.

C/C++ line number

Try __FILE__ and __LINE__.
You might also find __DATE__ and __TIME__ useful.
Though unless you have to debug a program on the clientside and thus need to log these informations you should use normal debugging.

Delete all files of specific type (extension) recursively down a directory using a batch file

You can use this to delete ALL Files Inside a Folder and Subfolders:

DEL "C:\Folder\*.*" /S /Q

Or use this to Delete Certain File Types Only:

DEL "C:\Folder\*.mp4" /S /Q 
DEL "C:\Folder\*.dat" /S /Q 

How can I format a String number to have commas and round?

You can do the entire conversion in one line, using the following code:

String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));

The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.

How do I get the last four characters from a string in C#?

assuming you wanted the strings in between a string which is located 10 characters from the last character and you need only 3 characters.

Let's say StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"

In the above, I need to extract the "273" that I will use in database query

        //find the length of the string            
        int streamLen=StreamSelected.Length;

        //now remove all characters except the last 10 characters
        string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));   

        //extract the 3 characters using substring starting from index 0
        //show Result is a TextBox (txtStreamSubs) with 
        txtStreamSubs.Text = streamLessTen.Substring(0, 3);

The difference between fork(), vfork(), exec() and clone()

The fork(),vfork() and clone() all call the do_fork() to do the real work, but with different parameters.

asmlinkage int sys_fork(struct pt_regs regs)
{
    return do_fork(SIGCHLD, regs.esp, &regs, 0);
}

asmlinkage int sys_clone(struct pt_regs regs)
{
    unsigned long clone_flags;
    unsigned long newsp;

    clone_flags = regs.ebx;
    newsp = regs.ecx;
    if (!newsp)
        newsp = regs.esp;
    return do_fork(clone_flags, newsp, &regs, 0);
}
asmlinkage int sys_vfork(struct pt_regs regs)
{
    return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, &regs, 0);
}
#define CLONE_VFORK 0x00004000  /* set if the parent wants the child to wake it up on mm_release */
#define CLONE_VM    0x00000100  /* set if VM shared between processes */

SIGCHLD means the child should send this signal to its father when exit.

For fork, the child and father has the independent VM page table, but since the efficiency, fork will not really copy any pages, it just set all the writeable pages to readonly for child process. So when child process want to write something on that page, an page exception happen and kernel will alloc a new page cloned from the old page with write permission. That's called "copy on write".

For vfork, the virtual memory is exactly by child and father---just because of that, father and child can't be awake concurrently since they will influence each other. So the father will sleep at the end of "do_fork()" and awake when child call exit() or execve() since then it will own new page table. Here is the code(in do_fork()) that the father sleep.

if ((clone_flags & CLONE_VFORK) && (retval > 0))
down(&sem);
return retval;

Here is the code(in mm_release() called by exit() and execve()) which awake the father.

up(tsk->p_opptr->vfork_sem);

For sys_clone(), it is more flexible since you can input any clone_flags to it. So pthread_create() call this system call with many clone_flags:

int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SYSVSEM);

Summary: the fork(),vfork() and clone() will create child processes with different mount of sharing resource with the father process. We also can say the vfork() and clone() can create threads(actually they are processes since they have independent task_struct) since they share the VM page table with father process.

JavaScript naming conventions

You can follow this Google JavaScript Style Guide

In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.

EDIT: See nice collection of JavaScript Style Guides And Beautifiers.

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

Add ... if string is too long PHP

The PHP way of doing this is simple:

$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;

But you can achieve a much nicer effect with this CSS:

.ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

Now, assuming the element has a fixed width, the browser will automatically break off and add the ... for you.

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.

Outputting data from unit test in Python

Another option - start a debugger where the test fails.

Try running your tests with Testoob (it will run your unittest suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.

Here's a terminal session on windows:

C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
  1     from unittest import TestCase
  2     class MyTests(TestCase):
  3       def test_foo(self):
  4         x = 1
  5         y = 2
  6  ->     self.assertEqual(x, y)
[EOF]
(Pdb)

How to define optional methods in Swift protocol?

One option is to store them as optional function variables:

struct MyAwesomeStruct {
    var myWonderfulFunction : Optional<(Int) -> Int> = nil
}

let squareCalculator =
    MyAwesomeStruct(myWonderfulFunction: { input in return input * input })
let thisShouldBeFour = squareCalculator.myWonderfulFunction!(2)

Empty responseText from XMLHttpRequest

This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.

In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.

Now sure why it worked, but it did.

SQL select everything in an array

$SQL_Part="("
$i=0;
while ($i<length($cat)-1)
{
   $SQL_Part+=$cat[i]+",";
}
$SQL_Part=$SQL_Part+$cat[$i+1]+")"

$SQL="SELECT * FROM products WHERE catid IN "+$SQL_Part;

It's more generic and will fit for any array!!

Email & Phone Validation in Swift

"validate Email"-Solution for Swift 4: Create this class:

import Foundation

public class EmailAddressValidator {
    public init() {
    }

    public func validateEmailAddress(_ email: String) -> Bool {
        let emailTest = NSPredicate(format: "SELF MATCHES %@", String.emailValidationRegEx)

        return emailTest.evaluate(with: email)
    }
}

private extension String {
    static let emailValidationRegEx = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
        "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
        "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
        "z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" +
        "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
        "9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
    "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
}

and use it like this:

let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("[email protected]")

Ping with timestamp on Windows CLI

Try this:

Create a batch file with the following:

echo off

cd\

:start

echo %time% >> c:\somedirectory\pinghostname.txt

ping pinghostname >> c:\somedirectory\pinghostname.txt

goto start

You can add your own options to the ping command based on your requirements. This doesn't put the time stamp on the same line as the ping, but it still gets you the info you need.

An even better way is to use fping, go here http://www.kwakkelflap.com/fping.html to download it.

How can I count the number of characters in a Bash variable

Use the wc utility with the print the byte counts (-c) option:

$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
    13

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

Convert HTML string to image

       <!--ForExport data in iamge -->
        <script type="text/javascript">
            function ConvertToImage(btnExport) {
                html2canvas($("#dvTable")[0]).then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=hfImageData]").val(base64);
                    __doPostBack(btnExport.name, "");
                });
                return false;
            }
        </script>

        <!--ForExport data in iamge -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="../js/html2canvas.min.js"></script> 





<table>
                <tr>
                    <td valign="top">
                        <asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
                            OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
                        <div id="dvTable" class="divsection2" style="width: 350px">
                            <asp:HiddenField ID="hfImageData" runat="server" />
                            <table width="100%">
                                <tr>
                                    <td>
                                        <br />

                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
                                    </td>
                                </tr>

                            </table>
                        </div>
                    </td>
                </tr>
            </table>


         protected void ExportToImage(object sender, EventArgs e)
                {
                    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
                    byte[] bytes = Convert.FromBase64String(base64);
                    Response.Clear();
                    Response.ContentType = "image/png";
                    Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytes);
                    Response.End();

                }

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

How can I find all of the distinct file extensions in a folder hierarchy?

My awk-less, sed-less, Perl-less, Python-less POSIX-compliant alternative:

find . -type f | rev | cut -d. -f1 | rev  | tr '[:upper:]' '[:lower:]' | sort | uniq --count | sort -rn

The trick is that it reverses the line and cuts the extension at the beginning.
It also converts the extensions to lower case.

Example output:

   3689 jpg
   1036 png
    610 mp4
     90 webm
     90 mkv
     57 mov
     12 avi
     10 txt
      3 zip
      2 ogv
      1 xcf
      1 trashinfo
      1 sh
      1 m4v
      1 jpeg
      1 ini
      1 gqv
      1 gcs
      1 dv

Exposing a port on a live Docker container

Read Ricardo's response first. This worked for me.

However, there exists a scenario where this won't work if the running container was kicked off using docker-compose. This is because docker-compose (I'm running docker 1.17) creates a new network. The way to address this scenario would be

docker network ls

Then append the following docker run -d --name sqlplus --link db:db -p 1521:1521 sqlplus --net network_name

No such keg: /usr/local/Cellar/git

Give another go at force removing the brewed version of git

brew uninstall --force git

Then cleanup any older versions and clear the brew cache

brew cleanup -s git

Remove any dead symlinks

brew cleanup --prune-prefix

Then try reinstalling git

brew install git

If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix directory (/usr/local by default), you can simply rm -rf $(brew --prefix). Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh

Using str_replace so that it only acts on the first match?

I created this little function that replaces string on string (case-sensitive) with limit, without the need of Regexp. It works fine.

function str_replace_limit($search, $replace, $string, $limit = 1) {
    $pos = strpos($string, $search);

    if ($pos === false) {
        return $string;
    }

    $searchLen = strlen($search);

    for ($i = 0; $i < $limit; $i++) {
        $string = substr_replace($string, $replace, $pos, $searchLen);

        $pos = strpos($string, $search);

        if ($pos === false) {
            break;
        }
    }

    return $string;
}

Example usage:

$search  = 'foo';
$replace = 'bar';
$string  = 'foo wizard makes foo brew for evil foo and jack';
$limit   = 2;

$replaced = str_replace_limit($search, $replace, $string, $limit);

echo $replaced;
// bar wizard makes bar brew for evil foo and jack

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

Android: How can I print a variable on eclipse console?

Window->Show View->Other…->Android->LogCat

Convert byte[] to char[]

byte[] a = new byte[50];

char [] cArray= System.Text.Encoding.ASCII.GetString(a).ToCharArray();

From the URL thedixon posted

http://bytes.com/topic/c-sharp/answers/250261-byte-char

You cannot ToCharArray the byte without converting it to a string first.

To quote Jon Skeet there

There's no need for the copying here - just use Encoding.GetChars. However, there's no guarantee that ASCII is going to be the appropriate encoding to use.

PHP - warning - Undefined property: stdClass - fix?

If think this will work:

if(sizeof($response->records)>0)
$role_arr = getRole($response->records);

newly defined proprties included too.

CSS @font-face not working with Firefox, but working with Chrome and IE

I don't know how you created the syntax as I neved used svg in font declaration, but Font Squirel has a really good tool to create a bullet proof syntax font-face from just one font.

http://www.fontsquirrel.com/fontface/generator

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

Bash: Echoing a echo command with a variable in bash

echo "echo "we are now going to work with ${ser}" " >> $servfile

Escape all " within quotes with \. Do this with variables like \$servicetest too:

echo "echo \"we are now going to work with \${ser}\" " >> $servfile    
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile

REST / SOAP endpoints for a WCF service

If you only want to develop a single web service and have it hosted on many different endpoints (i.e. SOAP + REST, with XML, JSON, CSV, HTML outputes). You should also consider using ServiceStack which I've built for exactly this purpose where every service you develop is automatically available on on both SOAP and REST endpoints out-of-the-box without any configuration required.

The Hello World example shows how to create a simple with service with just (no config required):

public class Hello {
    public string Name { get; set; }
}

public class HelloResponse {
    public string Result { get; set; }
}

public class HelloService : IService
{
    public object Any(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
}

No other configuration is required, and this service is immediately available with REST in:

It also comes in-built with a friendly HTML output (when called with a HTTP client that has Accept:text/html e.g a browser) so you're able to better visualize the output of your services.

Handling different REST verbs are also as trivial, here's a complete REST-service CRUD app in 1 page of C# (less than it would take to configure WCF ;):

Setting DEBUG = False causes 500 Error

Its mid 2019 and I faced this error after a few years of developing with Django. Baffled me for an entire night! It wasn't allowed host (which should throw a 400), everything else checked out, finally did some error logging only to discover that some missing / or messed up static files manifest (after collectstatic) were screwing with the setup. Long story short, for those who are stumped AND SO HAPPEN ARE USING WHITENOISE OR THE DJANGO STATICFILE BACKEND WITH CACHE (manifest static files) , maybe this is for you.

  1. Make sure you setup everything (as I did for the whitenoise backend...django backends read on nonetheless) http://whitenoise.evans.io/en/stable/django.html

  2. If error code 500 still shoots you down, take note on your settings.STATICFILES_STORAGE.

Set it to either (for whitenoise backend with compression)

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

or (leave as django default)

STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage

All in all, THE PROBLEM seemed to come from the fact that this whitenoise cache + compression backend -->

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

or the django's own caching backend -->

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

...didnt quite work well for me, since my css was referencing some other sources which may be mixed up during collectstatic / backend caching. This issue is also potentially highlighted in http://whitenoise.evans.io/en/stable/django.html#storage-troubleshoot

What is the command to exit a Console application in C#?

Console applications will exit when the main function has finished running. A "return" will achieve this.

    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("I'm running!");
            return; //This will exit the console application's running thread
        }
    }

If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:

    System.Environment.Exit(-1);

How do I monitor the computer's CPU, memory, and disk usage in Java?

Have a look at this very detailled article: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime

To get the percentage of CPU used, all you need is some simple maths:

MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();

OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);

long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();

// Call an expensive task, or sleep if you are monitoring a remote process

long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();

long percent;
if (nanoAfter > nanoBefore)
 percent = ((cpuAfter-cpuBefore)*100L)/
   (nanoAfter-nanoBefore);
else percent = 0;

System.out.println("Cpu usage: "+percent+"%");

Note: You must import com.sun.management.OperatingSystemMXBean and not java.lang.management.OperatingSystemMXBean.

Java Date vs Calendar

tl;dr

advise the current "best practice" around Date and Calendar

is it best to always favour Calendar over Date

Avoid these legacy classes entirely. Use java.time classes instead.

  • For a moment in UTC, use Instant
    (the modern equivalent of Date)
  • For a moment in a particular time zone, use ZonedDateTime
    (the modern equivalent of GregorianCalendar)
  • For a moment in a particular offset-from-UTC, use OffsetDateTime
    (no equivalent in legacy classes)
  • For a date-time (not a moment) with unknown time zone or offset, use LocalDateTime
    (no equivalent in legacy classes)

Table of all date-time types in Java, both modern and legacy

Details

The Answer by Ortomala Lokni is right to suggest using the modern java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.). But that Answer suggests the wrong class as equivalent (see my comment on that Answer).

Using java.time

The java.time classes are a vast improvement over the legacy date-time classes, night-and-day difference. The old classes are poorly-designed, confusing, and troublesome. You should avoid the old classes whenever possible. But when you need to convert to/from the old/new, you can do so by calling new methods add to the old classes.

For much more information on conversion, see my Answer and nifty diagram to another Question, Convert java.util.Date to what “java.time” type?.

Searching Stack Overflow gives many hundreds of example Questions and Answers on using java.time. But here is a quick synopsis.

Instant

Get the current moment with an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now();

ZonedDateTime

To see that same simultaneous moment through the lens of some particular region’s wall-clock time, apply a time zone (ZoneId) to get a ZonedDateTime.

Time zone

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone();

Offset

A time zone is a region’s history of changes in its offset-from-UTC. But sometimes you are given only an offset without the full zone. In that case, use the OffsetDateTime class.

ZoneOffset offset = ZoneOffset.parse( "+05:30" );
OffsetDateTime odt = instant.atOffset( offset );

Use of a time zone is preferable over use of a mere offset.

LocalDateTime

The “Local” in the Local… classes means any locality, not a particular locality. So the name can be counter-intuitive.

LocalDateTime, LocalDate, and LocalTime purposely lack any information about offset or time zone. So they do not represent actual moments, they are not points on the timeline. When in doubt or in confusion, use ZonedDateTime rather than LocalDateTime. Search Stack Overflow for much more discussion.

Strings

Do not conflate date-time objects with strings that represent their value. You can parse a string to get a date-time object, and you can generate a string from a date-time object. But the string is never the date-time itself.

Learn about standard ISO 8601 formats, used by default in the java.time classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Hidden Features of C#?

true and false operators are really weird.

More comprehensive example can be found here.

Edit: There is related SO question What’s the false operator in C# good for?

How to add extra whitespace in PHP?

To render more than one whitespace on most web browsers use &nbsp; instead of normal white spaces.

echo "<p>Hello &nbsp;&nbsp;&nbsp; punt"; // This will render as Hello   Punt (with 4 white spaces)
echo "<p> Hello       punt"; // This will render as Hello punt (with one space)

For showing data in raw format (with exact number of spaces and "enters") use HTML <pre> tag.

echo "<pre>Hello        punt</pre>"; //Will render exactly as written here (8 white spaces)

Or you can use some CSS to style current block, not to break text or strip spaces (I don't know, but this one)

Any way you do the output will be the same but the browser itself strips double white spaces and renders as one.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

For starters ignore all answers with tell you to use $watch. Angular works off of a listener already. I guarantee you that you are complicating things by merely thinking in this direction.

Ignore all answers that tell you to user $timeout. You cannot know how long the page will take to load, therefore this is not the best solution.

You only need to know when the page is done rendering.

<div ng-app='myApp'>
<div ng-controller="testctrl">
    <label>{{total}}</label>
    <table>
      <tr ng-repeat="item in items track by $index;" ng-init="end($index);">
        <td>{{item.number}}</td>
      </tr>
    </table>
</div>

var app = angular.module('myApp', ["testctrl"]);
var controllers = angular.module("testctrl", []);
 controllers.controller("testctrl", function($scope) {

  $scope.items = [{"number":"one"},{"number":"two"},{"number":"three"}];

  $scope.end = function(index){
  if(index == $scope.items.length -1
        && typeof $scope.endThis == 'undefined'){

            ///  DO STUFF HERE
      $scope.total = index + 1;
      $scop.endThis  = true;
 }
}
});

Track the ng-repeat by $index and when the length of array equals the index stop the loop and do your logic.

jsfiddle

'Field required a bean of type that could not be found.' error spring restful API using mongodb

In my case i have just put the Class MyprojectApplication in a package(com.example.start) with the same level of model, controller,service packages.

How to set default value to all keys of a dict object in python?

In case you actually mean what you seem to ask, I'll provide this alternative answer.

You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict does. This will do so:

class DictWithDefault(dict):
    def __init__(self, default, **kwargs):
        self.default = default
        super(DictWithDefault, self).__init__(**kwargs)

    def __getitem__(self, key):
        if key in self:
            return super(DictWithDefault, self).__getitem__(key)
        return self.default

Use like this:

d = DictWIthDefault(99, x=5, y=3)
print d["x"]   # 5
print d[42]    # 99
42 in d        # False
d[42] = 3
42 in d        # True

Alternatively, you can use a standard dict like this:

d = {3: 9, 4: 2}
default = 99
print d.get(3, default)  # 9
print d.get(42, default) # 99

Rename computer and join to domain in one step with PowerShell

This will prompt for computer name and join to domain then restart.

$computerName = Get-WmiObject Win32_ComputerSystem 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Desired Computer Name ")
$computername.rename("$name")
Add-Computer -DomainName [domainname] -Credential [user\domain]  -Verbose
Restart-Computer

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

Switch statement fall-through...should it be allowed?

In some instances, using fall-throughs is an act of laziness on the part of the programmer - they could use a series of || statements, for example, but instead use a series of 'catch-all' switch cases.

That being said, I've found them to be especially helpful when I know that eventually I'm going to need the options anyway (for example in a menu response), but have not yet implemented all the choices. Likewise, if you're doing a fall-through for both 'a' and 'A', I find it substantially cleaner to use the switch fall-through than a compound if statement.

It's probably a matter of style and how the programmers think, but I'm not generally fond of removing components of a language in the name of 'safety' - which is why I tend towards C and its variants/descendants more than, say, Java. I like being able to monkey-around with pointers and the like, even when I have no "reason" to.

How to check if JSON return is empty with jquery

$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});

How to convert Nvarchar column to INT

If you want to convert from char to int, why not think about unicode number?

SELECT UNICODE(';') -- 59

This way you can convert any char to int without any error. Cheers.

Service vs IntentService in the Android platform

Service

  • Invoke by startService()
  • Triggered from any Thread
  • Runs on Main Thread
  • May block main (UI) thread. Always use thread within service for long task
  • Once task has done, it is our responsibility to stop service by calling stopSelf() or stopService()

IntentService

  • It performs long task usually no communication with main thread if communication is needed then it is done by Handler or BroadcastReceiver
  • Invoke via Intent
  • Triggered from Main Thread
  • Runs on the separate thread
  • Can't run the task in parallel and multiple intents are Queued on the same worker thread.

How to get the user input in Java?

Here is how you can get the keyboard inputs:

Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");  
name = scanner.next(); // Get what the user types.

Recommendations of Python REST (web services) framework?

web2py includes support for easily building RESTful API's, described here and here (video). In particular, look at parse_as_rest, which lets you define URL patterns that map request args to database queries; and smart_query, which enables you to pass arbitrary natural language queries in the URL.

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

How to get dictionary values as a generic list

You probably want to flatten all of the lists in Values into a single list:

List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();

Android 6.0 multiple permissions

I just use an array to achieved multiple requests, hope it helps someone. (Kotlin)

    // got all permission
    private fun requestPermission(){
        var mIndex: Int = -1
        var requestList: Array<String> = Array(10, { "" } )

        // phone call Permission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            mIndex ++
            requestList[mIndex] = Manifest.permission.CALL_PHONE
        }
        // SMS Permission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            mIndex ++
            requestList[mIndex] = Manifest.permission.SEND_SMS
        }

        // Access photos Permission
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            mIndex ++
            requestList[mIndex] = Manifest.permission.READ_EXTERNAL_STORAGE
        }

        // Location Permission
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            mIndex ++
            requestList[mIndex] = Manifest.permission.ACCESS_FINE_LOCATION
        }

        if(mIndex != -1){
            ActivityCompat.requestPermissions(this, requestList, PERMISSIONS_REQUEST_ALL)
        }
    }


    // permission response
    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSIONS_REQUEST_ALL -> {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission accept location
                    if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "Phone Call permission accept.")
                    }

                    // permission accept location
                    if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "SMS permission accept.")
                    }

                    // permission accept location
                    if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "SMS permission accept.")
                    }

                    // permission accept location
                    if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "Location permission accept.")
                    }

                } else {
                    Toast.makeText(mContext, "Permission Failed!", Toast.LENGTH_LONG).show()
                }
                return
            }
        }
    }

Is it possible to append Series to rows of DataFrame without making a list first?

Convert the series to a dataframe and transpose it, then append normally.

srs = srs.to_frame().T
df = df.append(srs)

Disable dragging an image from an HTML page

Directly use this: ondragstart="return false;" in your image tag.

<img src="http://image-example.png" ondragstart="return false;"/>

If you have multiple images, wrapped on a <div> tag:

<div ondragstart="return false;">
   <img src="image1.png"/>
   <img scr="image2.png"/>
</div>

Works in all major browsers.

Select the top N values by group

Just sort by whatever (mpg for example, question is not clear on this)

mt <- mtcars[order(mtcars$mpg), ]

then use the by function to get the top n rows in each group

d <- by(mt, mt["cyl"], head, n=4)

If you want the result to be a data.frame:

Reduce(rbind, d)

Edit: Handling ties is more difficult, but if all ties are desired:

by(mt, mt["cyl"], function(x) x[rank(x$mpg) %in% sort(unique(rank(x$mpg)))[1:4], ])

Another approach is to break ties based on some other information, e.g.,

mt <- mtcars[order(mtcars$mpg, mtcars$hp), ]
by(mt, mt["cyl"], head, n=4)

Bootstrap 3 jquery event for active tab change

Thanks to @Gerben's post came to know there are two events show.bs.tab (before the tab is shown) and shown.bs.tab (after the tab is shown) as explained in the docs - Bootstrap Tab usage

An additional solution if we're only interested in a specific tab, and maybe add separate functions without having to add an if - else block in one function, is to use the a href selector (maybe along with additional selectors if required)

 $("a[href='#tab_target_id']").on('shown.bs.tab', function(e) {
      console.log('shown - after the tab has been shown');
 });

 // or even this one if we want the earlier event
 $("a[href='#tab_target_id']").on('show.bs.tab', function(e) {
      console.log('show - before the new tab has been shown');
 });

demo

Get text from DataGridView selected cells

In this specific case, the ToString() will return the name of the object retruned by the SelectedCell Property.( a collection of the currently selected cells).

This behavior occurs when an object has no specific implenetation for the ToString() methods.

in our case, all you have to do is to iterate the collection of the cells and to accumulate its values to a string. then push this string to the TextBox.

have a look here how to implement the iteration:

msdn

Split a List into smaller lists of N size

Addition after very useful comment of mhand at the end

Original answer

Although most solutions might work, I think they are not very efficiently. Suppose if you only want the first few items of the first few chunks. Then you wouldn't want to iterate over all (zillion) items in your sequence.

The following will at utmost enumerate twice: once for the Take and once for the Skip. It won't enumerate over any more elements than you will use:

public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>
    (this IEnumerable<TSource> source, int chunkSize)
{
    while (source.Any())                     // while there are elements left
    {   // still something to chunk:
        yield return source.Take(chunkSize); // return a chunk of chunkSize
        source = source.Skip(chunkSize);     // skip the returned chunk
    }
}

How many times will this Enumerate the sequence?

Suppose you divide your source into chunks of chunkSize. You enumerate only the first N chunks. From every enumerated chunk you'll only enumerate the first M elements.

While(source.Any())
{
     ...
}

the Any will get the Enumerator, do 1 MoveNext() and returns the returned value after Disposing the Enumerator. This will be done N times

yield return source.Take(chunkSize);

According to the reference source this will do something like:

public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count)
{
    return TakeIterator<TSource>(source, count);
}

static IEnumerable<TSource> TakeIterator<TSource>(IEnumerable<TSource> source, int count)
{
    foreach (TSource element in source)
    {
        yield return element;
        if (--count == 0) break;
    }
}

This doesn't do a lot until you start enumerating over the fetched Chunk. If you fetch several Chunks, but decide not to enumerate over the first Chunk, the foreach is not executed, as your debugger will show you.

If you decide to take the first M elements of the first chunk then the yield return is executed exactly M times. This means:

  • get the enumerator
  • call MoveNext() and Current M times.
  • Dispose the enumerator

After the first chunk has been yield returned, we skip this first Chunk:

source = source.Skip(chunkSize);

Once again: we'll take a look at reference source to find the skipiterator

static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
    using (IEnumerator<TSource> e = source.GetEnumerator()) 
    {
        while (count > 0 && e.MoveNext()) count--;
        if (count <= 0) 
        {
            while (e.MoveNext()) yield return e.Current;
        }
    }
}

As you see, the SkipIterator calls MoveNext() once for every element in the Chunk. It doesn't call Current.

So per Chunk we see that the following is done:

  • Any(): GetEnumerator; 1 MoveNext(); Dispose Enumerator;
  • Take():

    • nothing if the content of the chunk is not enumerated.
    • If the content is enumerated: GetEnumerator(), one MoveNext and one Current per enumerated item, Dispose enumerator;

    • Skip(): for every chunk that is enumerated (NOT the contents of the chunk): GetEnumerator(), MoveNext() chunkSize times, no Current! Dispose enumerator

If you look at what happens with the enumerator, you'll see that there are a lot of calls to MoveNext(), and only calls to Current for the TSource items you actually decide to access.

If you take N Chunks of size chunkSize, then calls to MoveNext()

  • N times for Any()
  • not yet any time for Take, as long as you don't enumerate the Chunks
  • N times chunkSize for Skip()

If you decide to enumerate only the first M elements of every fetched chunk, then you need to call MoveNext M times per enumerated Chunk.

The total

MoveNext calls: N + N*M + N*chunkSize
Current calls: N*M; (only the items you really access)

So if you decide to enumerate all elements of all chunks:

MoveNext: numberOfChunks + all elements + all elements = about twice the sequence
Current: every item is accessed exactly once

Whether MoveNext is a lot of work or not, depends on the type of source sequence. For lists and arrays it is a simple index increment, with maybe an out of range check.

But if your IEnumerable is the result of a database query, make sure that the data is really materialized on your computer, otherwise the data will be fetched several times. DbContext and Dapper will properly transfer the data to local process before it can be accessed. If you enumerate the same sequence several times it is not fetched several times. Dapper returns an object that is a List, DbContext remembers that the data is already fetched.

It depends on your Repository whether it is wise to call AsEnumerable() or ToLists() before you start to divide the items in Chunks

How can I replace a regex substring match in Javascript?

I would get the part before and after what you want to replace and put them either side.

Like:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

var matches = str.match(regex);

var result = matches[1] + "1" + matches[2];

// With ES6:
var result = `${matches[1]}1${matches[2]}`;

How to use switch statement inside a React component?

lenkan's answer is a great solution.

<div>
  {{ beep: <div>Beep</div>,
     boop: <div>Boop</div>
  }[greeting]}
</div>

If you need a default value, then you can even do

<div>
  {{ beep: <div>Beep</div>,
     boop: <div>Boop</div>
  }[greeting] || <div>Hello world</div>}
</div>

Alternatively, if that doesn't read well to you, then you can do something like

<div>
  { 
    rswitch(greeting, {
      beep: <div>Beep</div>,
      boop: <div>Boop</div>,
      default: <div>Hello world</div>
    }) 
  }
</div>

with

function rswitch (param, cases) {
  if (cases[param]) {
    return cases[param]
  } else {
    return cases.default
  }
}

Define a fixed-size list in Java

You can define a generic function like this:

@SuppressWarnings("unchecked")
public static <T> List<T> newFixedSizeList(int size) {
    return (List<T>)Arrays.asList(new Object[size]);
}

And

List<String> s = newFixedSizeList(3);  // All elements are initialized to null
s.set(0, "zero");
s.add("three");  // throws java.lang.UnsupportedOperationException

How do I copy a 2 Dimensional array in Java?

Arrays in java are objects, and all objects are passed by reference. In order to really "copy" an array, instead of creating another name for an array, you have to go and create a new array and copy over all the values. Note that System.arrayCopy will copy 1-dimensional arrays fully, but NOT 2-dimensional arrays. The reason is that a 2D array is in fact a 1D array of 1D arrays, and arrayCopy copies over pointers to the same internal 1D arrays.

SQL - How to select a row having a column with max value

Technically, this is the same answer as @Sujee. It also depends on your version of Oracle as to whether it works. (I think this syntax was introduced in Oracle 12??)

SELECT *
FROM   table
ORDER BY value DESC, date_column ASC
FETCH  first 1 rows only;

As I say, if you look under the bonnet, I think this code is unpacked internally by the Oracle Optimizer to read like @Sujee's. However, I'm a sucker for pretty coding, and nesting select statements without a good reason does not qualify as beautiful!! :-P

Still Reachable Leak detected by Valgrind

There is more than one way to define "memory leak". In particular, there are two primary definitions of "memory leak" that are in common usage among programmers.

The first commonly used definition of "memory leak" is, "Memory was allocated and was not subsequently freed before the program terminated." However, many programmers (rightly) argue that certain types of memory leaks that fit this definition don't actually pose any sort of problem, and therefore should not be considered true "memory leaks".

An arguably stricter (and more useful) definition of "memory leak" is, "Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block." In other words, you cannot free memory that you no longer have any pointers to. Such memory is therefore a "memory leak". Valgrind uses this stricter definition of the term "memory leak". This is the type of leak which can potentially cause significant heap depletion, especially for long lived processes.

The "still reachable" category within Valgrind's leak report refers to allocations that fit only the first definition of "memory leak". These blocks were not freed, but they could have been freed (if the programmer had wanted to) because the program still was keeping track of pointers to those memory blocks.

In general, there is no need to worry about "still reachable" blocks. They don't pose the sort of problem that true memory leaks can cause. For instance, there is normally no potential for heap exhaustion from "still reachable" blocks. This is because these blocks are usually one-time allocations, references to which are kept throughout the duration of the process's lifetime. While you could go through and ensure that your program frees all allocated memory, there is usually no practical benefit from doing so since the operating system will reclaim all of the process's memory after the process terminates, anyway. Contrast this with true memory leaks which, if left unfixed, could cause a process to run out of memory if left running long enough, or will simply cause a process to consume far more memory than is necessary.

Probably the only time it is useful to ensure that all allocations have matching "frees" is if your leak detection tools cannot tell which blocks are "still reachable" (but Valgrind can do this) or if your operating system doesn't reclaim all of a terminating process's memory (all platforms which Valgrind has been ported to do this).

How to pause for specific amount of time? (Excel/VBA)

Just a cleaned up version of clemo's code - works in Access, which doesn't have the Application.Wait function.

Public Sub Pause(sngSecs As Single)
    Dim sngEnd As Single
    sngEnd = Timer + sngSecs
    While Timer < sngEnd
        DoEvents
    Wend
End Sub

Public Sub TestPause()
    Pause 1
    MsgBox "done"
End Sub

Passing a varchar full of comma delimited values to a SQL Server IN function

I think a very simple solution could be following:

DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';

SELECT * 
FROM sometable 
WHERE ','+@Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),tableid)+',%';

JavaScript variable number of arguments to function

While @roufamatic did show use of the arguments keyword and @Ken showed a great example of an object for usage I feel neither truly addressed what is going on in this instance and may confuse future readers or instill a bad practice as not explicitly stating a function/method is intended to take a variable amount of arguments/parameters.

function varyArg () {
    return arguments[0] + arguments[1];
}

When another developer is looking through your code is it very easy to assume this function does not take parameters. Especially if that developer is not privy to the arguments keyword. Because of this it is a good idea to follow a style guideline and be consistent. I will be using Google's for all examples.

Let's explicitly state the same function has variable parameters:

function varyArg (var_args) {
    return arguments[0] + arguments[1];
}

Object parameter VS var_args

There may be times when an object is needed as it is the only approved and considered best practice method of an data map. Associative arrays are frowned upon and discouraged.

SIDENOTE: The arguments keyword actually returns back an object using numbers as the key. The prototypal inheritance is also the object family. See end of answer for proper array usage in JS

In this case we can explicitly state this also. Note: this naming convention is not provided by Google but is an example of explicit declaration of a param's type. This is important if you are looking to create a more strict typed pattern in your code.

function varyArg (args_obj) {
    return args_obj.name+" "+args_obj.weight;
}
varyArg({name: "Brian", weight: 150});

Which one to choose?

This depends on your function's and program's needs. If for instance you are simply looking to return a value base on an iterative process across all arguments passed then most certainly stick with the arguments keyword. If you need definition to your arguments and mapping of the data then the object method is the way to go. Let's look at two examples and then we're done!

Arguments usage

function sumOfAll (var_args) {
    return arguments.reduce(function(a, b) {
        return a + b;
    }, 0);
}
sumOfAll(1,2,3); // returns 6

Object usage

function myObjArgs(args_obj) {
    // MAKE SURE ARGUMENT IS AN OBJECT OR ELSE RETURN
    if (typeof args_obj !== "object") {
        return "Arguments passed must be in object form!";
    }

    return "Hello "+args_obj.name+" I see you're "+args_obj.age+" years old.";
}
myObjArgs({name: "Brian", age: 31}); // returns 'Hello Brian I see you're 31 years old

Accessing an array instead of an object ("...args" The rest parameter)

As mentioned up top of the answer the arguments keyword actually returns an object. Because of this any method you want to use for an array will have to be called. An example of this:

Array.prototype.map.call(arguments, function (val, idx, arr) {});

To avoid this use the rest parameter:

function varyArgArr (...var_args) {
    return var_args.sort();
}
varyArgArr(5,1,3); // returns 1, 3, 5

Initialization of all elements of an array to one default value in C++?

With {} you assign the elements as they are declared; the rest is initialized with 0.

If there is no = {} to initalize, the content is undefined.

Add a new line to the end of a JtextArea

When you want to create a new line or wrap in your TextArea you have to add \n (newline) after the text.

TextArea t = new TextArea();
t.setText("insert text when you want a new line add \nThen more text....);
setBounds();
setFont();
add(t);

This is the only way I was able to do it, maybe there is a simpler way but I havent discovered that yet.

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

How to check Elasticsearch cluster health?

PROBLEM :-

Sometimes, Localhost may not get resolved. So it tends to return an output as seen below :

# curl -XGET localhost:9200/_cluster/health?pretty

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

# curl -XGET localhost:9200/_cat/indices

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

SOLUTION :-

Guess, this error is most probably returned by Local Squid deployed in the server.

So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I know that this is a super-old post. Assuming that you are calling into your application, here is an idea that has worked for me:

  1. Implement the ICallbackEventHandler on your page
  2. Call ClientScriptManager.GetCallbackEventReference to call your server side code
  3. As the error message states, you could then call ClientScriptManager.RegisterForEventValidation

If you don't need total control, you could use an update panel which would do this for you.

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".

Beginner Python Practice?

Try Project Euler:

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The problem is:

Add all the natural numbers below 1000 that are multiples of 3 or 5.

This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.

How to perform Unwind segue programmatically?

Here's a complete answer with Objective C and Swift:

1) Create an IBAction unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.

// Objective C

    - (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {

    }

// Swift

 @IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {

    }

2) On the source view controller (the controller you're segueing from), ^ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.

enter image description here

3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.

enter image description here

4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.

// Objective C

[self performSegueWithIdentifier:@"unwindToContainerVC" sender:self];

// Swift

self.performSegueWithIdentifier("unwindToContainerVC", sender: self)

NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.