Programs & Examples On #Imodelbinder

PHP Configuration: It is not safe to rely on the system's timezone settings

I modified /etc/php.ini

[Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone =('Asia/kolkata')

and now working fine.

Vipin Pal

subquery in codeigniter active record

Like this in simple way .

    $this->db->select('*');
    $this->db->from('certs');
    $this->db->where('certs.id NOT IN (SELECT id_cer FROM revokace)');

    return $this->db->get()->result();

python to arduino serial read & write

You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.

while running:  
    # Serial write section
    setTempCar1 = 63
    setTempCar2 = 37
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(6) # with the port open, the response will be buffered 
                  # so wait a bit longer for response here

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read everything in the input buffer
    print ("Message from arduino: ")
    print (msg)

The Python Serial.read function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.

On the Arduino side, you should consider what happens in your loop function when no data is available.

void loop()
{
  // serial read section
  while (Serial.available()) // this will be skipped if no data present, leading to
                             // the code sitting in the delay function below
  {
    delay(30);  //delay to allow buffer to fill 
    if (Serial.available() >0)
    {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

Instead, wait at the start of the loop function until data arrives:

void loop()
{
  while (!Serial.available()) {} // wait for data to arrive
  // serial read section
  while (Serial.available())
  {
    // continue as before

EDIT 2

Here's what I get when interfacing with your Arduino app from Python:

>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'

So that seems to be working fine.

In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:

#!/usr/bin/python
import serial
import syslog
import time

#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X


ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino

i = 0

while (i < 4):
    # Serial write section

    setTempCar1 = 63
    setTempCar2 = 37
    ard.flush()
    setTemp1 = str(setTempCar1)
    setTemp2 = str(setTempCar2)
    print ("Python value sent: ")
    print (setTemp1)
    ard.write(setTemp1)
    time.sleep(1) # I shortened this to match the new value in your Arduino code

    # Serial read section
    msg = ard.read(ard.inWaiting()) # read all characters in buffer
    print ("Message from arduino: ")
    print (msg)
    i = i + 1
else:
    print "Exiting"
exit()

Here's the output of the above now:

$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1


Exiting

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

How to disable Paste (Ctrl+V) with jQuery?

The following code will disable cut, copy and paste from full page.

$(document).ready(function () {
   $('body').bind('cut copy paste', function (e) {
      e.preventDefault();
   });
});

The full tutorial and working demo can be found from here - Disable cut, copy and paste using jQuery

Render partial from different folder (not shared)

I've created a workaround that seems to be working pretty well. I found the need to switch to the context of a different controller for action name lookup, view lookup, etc. To implement this, I created a new extension method for HtmlHelper:

public static IDisposable ControllerContextRegion(
    this HtmlHelper html, 
    string controllerName)
{
    return new ControllerContextRegion(html.ViewContext.RouteData, controllerName);
}

ControllerContextRegion is defined as:

internal class ControllerContextRegion : IDisposable
{
    private readonly RouteData routeData;
    private readonly string previousControllerName;

    public ControllerContextRegion(RouteData routeData, string controllerName)
    {
        this.routeData = routeData;
        this.previousControllerName = routeData.GetRequiredString("controller");
        this.SetControllerName(controllerName);
    }

    public void Dispose()
    {
        this.SetControllerName(this.previousControllerName);
    }

    private void SetControllerName(string controllerName)
    {
        this.routeData.Values["controller"] = controllerName;
    }
}

The way this is used within a view is as follows:

@using (Html.ControllerContextRegion("Foo")) {
    // Html.Action, Html.Partial, etc. now looks things up as though
    // FooController was our controller.
}

There may be unwanted side effects for this if your code requires the controller route component to not change, but in our code so far, there doesn't seem to be any negatives to this approach.

Python Matplotlib figure title overlaps axes label when using twiny

I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:

plt.title(figure_title, y=1.08)

This also works for plt.suptitle(), but not (yet) for plt.xlabel(), etc.

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.

How to disable Excel's automatic cell reference change after copy/paste?

I found another workaround that is very simple: 1. Cut the contents 2. Paste them in the new location 3. Copy the contents that you just pasted into the new location you want. 4. Undo the Cut-Paste operation, putting the original contents back where you got them. 5. Paste the contents from the clipboard to the same location. These contents will have the original references.

It looks like a lot, but is super fast with keyboard shortcuts: 1. Ctrl-x, 2. Ctrl-v, 3. Ctrl-c, 4. Ctrl-z, 5. Ctrl-v

PHP cURL HTTP PUT

Using Postman for Chrome, selecting CODE you get this... And works

_x000D_
_x000D_
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
  CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
  CURLOPT_RETURNTRANSFER => true,_x000D_
  CURLOPT_ENCODING => "",_x000D_
  CURLOPT_MAXREDIRS => 10,_x000D_
  CURLOPT_TIMEOUT => 30,_x000D_
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
  CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
  CURLOPT_POSTFIELDS => "{\n  \"customer\" : \"con\",\n  \"customerID\" : \"5108\",\n  \"customerEmail\" : \"[email protected]\",\n  \"Phone\" : \"34600000000\",\n  \"Active\" : false,\n  \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
  CURLOPT_HTTPHEADER => array(_x000D_
    "cache-control: no-cache",_x000D_
    "content-type: application/json",_x000D_
    "x-api-key: whateveriyouneedinyourheader"_x000D_
  ),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
  echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
  echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

Adding CSRFToken to Ajax request

You can use this:

var token = "SOME_TOKEN";

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  jqXHR.setRequestHeader('X-CSRF-Token', token);
});

From documentation:

jQuery.ajaxPrefilter( [dataTypes ], handler(options, originalOptions, jqXHR) )

Description: Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().

Read

'adb' is not recognized as an internal or external command, operable program or batch file

If you didn't set a path for ADB, you can run .\adb instead of adb at sdk/platformtools.

Mean per group in a data.frame

You can also accomplish this using the sqldf package as shown below:

library(sqldf)

x <- read.table(text='Name     Month  Rate1     Rate2
Aira       1      12        23
                Aira       2      18        73
                Aira       3      19        45
                Ben        1      53        19
                Ben        2      22        87
                Ben        3      19        45
                Cat        1      22        87
                Cat        2      67        43
                Cat        3      45        32', header=TRUE)

sqldf("
select 
  Name
  ,avg(Rate1) as Rate1_float
  ,avg(Rate2) as Rate2_float
  ,avg(Rate1) as Rate1
  ,avg(Rate2) as Rate2
from x
group by 
  Name
")

#  Name Rate1_float Rate2_float Rate1 Rate2
#1 Aira    16.33333    47.00000    16    47
#2  Ben    31.33333    50.33333    31    50
#3  Cat    44.66667    54.00000    44    54

I am a recent convert to dplyr as shown in other answers, but sqldf is nice as most data analysts/data scientists/developers have at least some fluency in SQL. In this way, I think it tends to make for more universally readable code than dplyr or other solutions presented above.

UPDATE: In responding to the comment below, I attempted to update the code as shown above. However, the behavior was not as I expected. It seems that the column definition (i.e. int vs float) is only carried through when the column alias matches the original column name. When you specify a new name, the aggregate column is returned without rounding.

Copying from one text file to another using Python

f = open('list1.txt')
f1 = open('output.txt', 'a')

# doIHaveToCopyTheLine=False

for line in f.readlines():
    if 'tests/file/myword' in line:
        f1.write(line)

f1.close()
f.close()

Now Your code will work. Try This one.

How can I setup & run PhantomJS on Ubuntu?

For Ubuntu, download the suitable file from http://phantomjs.org/download.html. CD to the downloaded folder. Then:

sudo tar xvf phantomjs-1.9.0-linux-x86_64.tar.bz2
sudo mv phantomjs-1.9.0-linux-x86_64 /usr/local/share/phantomjs
sudo ln -s /usr/local/share/phantomjs/bin/phantomjs /usr/bin/phantomjs

Make sure to replace the file name in these commands with the file you have downloaded.

Setting the correct encoding when piping stdout in Python

On Windows, I had this problem very often when running a Python code from an editor (like Sublime Text), but not if running it from command-line.

In this case, check your editor's parameters. In the case of SublimeText, this Python.sublime-build solved it:

{
  "cmd": ["python", "-u", "$file"],
  "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  "selector": "source.python",
  "encoding": "utf8",
  "env": {"PYTHONIOENCODING": "utf-8", "LANG": "en_US.UTF-8"}
}

Where can I find my Facebook application id and secret key?

You should use the Developer App.

On the right is a section titled "My Applications" from which you can select an application to see its information.

You can also go straight here as well, which will list your apps on the left.

Mac install and open mysql using terminal

This command works for me:

./mysql -u root -p

(PS: I'm working on mac through terminal)

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

The JROCKIT JVM currently owned by Oracle supports non-contiguous heap usage, thus allowing the 32 bit JVM to access more then 3.8 GB of memory when the JVM is running on a 64 bit windows OS. (2.8 GB when running on a 32 bit OS).

http://blogs.oracle.com/jrockit/entry/how_to_get_almost_3_gb_heap_on_windows

The JVM can be freely downloaded (registration required) at

http://www.oracle.com/technetwork/middleware/jrockit/downloads/index.html

SQL: How To Select Earliest Row

In this case a relatively simple GROUP BY can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER():

Runnable example (Wofkflow20 error in original data corrected)

;WITH partitioned AS (
    SELECT company
        ,workflow
        ,date
        ,other_columns
        ,ROW_NUMBER() OVER(PARTITION BY company, workflow
                            ORDER BY date) AS seq
    FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1

How to enable Logger.debug() in Log4j

This is probably happening because your log4j configuration is set to ERROR. Look for a log4j.properties file with contents like the following:

log4j.rootLogger=ERROR, CONSOLE

# console logging
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d %-5p %-20.20t %-24c{1}: %m%n

The rootLogger is set to ERROR level here using a CONSOLE appender.

Note that some appenders like the console appender also have a Threshold property that can be used to overrule the rootLoggers level. You need to check both in this case.

onActivityResult is not being called in Fragment

If you are using nested fragments, this is also working:

getParentFragment().startActivityForResult(intent, RequestCode);

In addition to this, you have to call super.onActivityResult from parent activity and fill the onActivityResult method of the fragment.

How to run iPhone emulator WITHOUT starting Xcode?

You can get it to launch via spotlight if you create an Automator launcher for it:

  1. Open Automator.app
  2. Choose type of Application
  3. Select Actions > Library > Utilities > Launch Application
  4. Open the dropdown of applications that can be launched and choose Other
  5. You can't directly select the Simulator app because it's inside the Xcode.app package. So instead you'll have to navigate to it in a separate Finder window and drag it onto the file selector window. It will be at one of the following paths depending on your version of Xcode (oldest to newest):
    • /Applications/Xcode.app/Contents/Developer/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
  6. Finally, save this Automator app in your applications folder as iOS Simulator.app

Create Automator app

To get a nice icon for the Automator app you just made, you can do the following:

  1. Right click iOS Simulator.app and choose Get Info
  2. Click the icon in the upper left corner and do Cmd-C to copy it
  3. Right click your Automator app and choose Get Info
  4. Click the icon in the upper left corner and do Cmd-V to paste

Copy icon

Using Gradle to build a jar with dependencies

The answer from @ben almost works for me except that my dependencies are too big and I got the following error

Execution failed for task ':jar'.
> archive contains more than 65535 entries.

  To build this archive, please enable the zip64 extension.

To fix this problem, I have to use the following code

mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  
  zip64 = true
  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

EL access a map value by Integer key

Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.

One way to get around this is to do something like this.

<c:set var="longKey" value="${param.selectedIndex + 0}"/>

This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.

Then, continue as usual with something like

${map[longKey]}

How to set multiple commands in one yaml file with Kubernetes?

If you're willing to use a Volume and a ConfigMap, you can mount ConfigMap data as a script, and then run that script:

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  entrypoint.sh: |-
    #!/bin/bash
    echo "Do this"

    echo "Do that"
---
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: my-container
    image: "ubuntu:14.04"
    command:
    - /bin/entrypoint.sh
    volumeMounts:
    - name: configmap-volume
      mountPath: /bin/entrypoint.sh
      readOnly: true
      subPath: entrypoint.sh
  volumes:
  - name: configmap-volume
    configMap:
      defaultMode: 0700
      name: my-configmap

This cleans up your pod spec a little and allows for more complex scripting.

$ kubectl logs my-pod
Do this
Do that

How to change permissions for a folder and its subfolders/files in one step?

You can change permission by using following commands

sudo chmod go=rwx /opt/lampp/htdocs

Overflow:hidden dots at the end

Most of solutions use static width here. But it can be sometimes wrong for some reasons.

Example: I had table with many columns. Most of them are narrow (static width). But the main column should be as wide as possible (depends on screen size).

HTML:

<table style="width: 100%">
  <tr>
    <td style="width: 60px;">narrow</td>
    <td>
      <span class="cutwrap" data-cutwrap="dynamic column can have really long text which can be wrapped on two rows, but we just need not wrapped texts using as much space as possible">
        dynamic column can have really long text which can be wrapped on two rows
        but we just need not wrapped texts using as much space as possible
      </span>
    </td>
  </tr>
</table>

CSS:

.cutwrap {
  position: relative;
  overflow: hidden;
  display: block;
  width: 100%;
  height: 18px;
  white-space: normal;
  color: transparent !important;
}
.cutwrap::selection {
  color: transparent !important;
}
.cutwrap:before {
  content: attr(data-cutwrap);
  position: absolute;
  left: 0;
  right: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}
/* different styles for links */
a.cutwrap:before {
  text-decoration: underline;
  color: #05c;
}

In android how to set navigation drawer header image and name programmatically in class file?

As mentioned in the bug 190226, Since version 23.1.0 getting header layout view with: navigationView.findViewById(R.id.navigation_header_text) no longer works.

A workaround is to inflate the headerview programatically and find view by ID from the inflated header view.

For example:

View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
headerView.findViewById(R.id.navigation_header_text);

Ideally there should be a method getHeaderView() but it has already been proposed, let's see and wait for it to be released in the feature release of design support library.

Running Selenium Webdriver with a proxy in Python

The result stated above may be correct, but isn't working with the latest webdriver. Here is my solution for the above question. Simple and sweet


        http_proxy  = "ip_addr:port"
        https_proxy = "ip_addr:port"

        webdriver.DesiredCapabilities.FIREFOX['proxy']={
            "httpProxy":http_proxy,
            "sslProxy":https_proxy,
            "proxyType":"MANUAL"
        }

        driver = webdriver.Firefox()

OR

    http_proxy  = "http://ip:port"
    https_proxy = "https://ip:port"

    proxyDict = {
                    "http"  : http_proxy,
                    "https" : https_proxy,
                }

    driver = webdriver.Firefox(proxy=proxyDict)

How to save picture to iPhone photo library?

For Swift 5.0

I used this code to copy images to photo albums my application had created; When I want to copy images files I call "startSavingPhotoAlbume()" function. First I get UIImage from App folder then save it to photo albums. Because it is irrelevant I dont show how to read image from App folder.

var saveToPhotoAlbumCounter = 0



func startSavingPhotoAlbume(){
    saveToPhotoAlbumCounter = 0
    saveToPhotoAlbume()
}

func saveToPhotoAlbume(){  
    let image = loadImageFile(fileName: imagefileList[saveToPhotoAlbumCounter], folderName: folderName)
    UIImageWriteToSavedPhotosAlbum(image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}

@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
    if (error != nil) {
        print("ptoto albume savin error for \(imageFileList[saveToPhotoAlbumCounter])")
    } else {
        
        if saveToPhotoAlbumCounter < imageFileList.count - 1 {
            saveToPhotoAlbumCounter += 1
            saveToPhotoAlbume()
        } else {
            print("saveToPhotoAlbume is finished with \(saveToPhotoAlbumCounter) files")
        }
    }
}

How to Replace Multiple Characters in SQL?

While this question was asked about SQL Server 2005, it's worth noting that as of Sql Server 2017, the request can be done with the new TRANSLATE function.

https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql

I hope this information helps people who get to this page in the future.

In Swift how to call method with parameters on GCD main thread?

The proper way to do this is to use dispatch_async in the main_queue, as I did in the following code

dispatch_async(dispatch_get_main_queue(), {
    (self.delegate as TBGQRCodeViewController).displayQRCode(receiveAddr, withAmountInBTC:amountBTC)
})

Get MIME type from filename extension

My take at those mimetypes, using the apache list, the below script will give you a dictionary with all the mimetypes.

var mimeTypeListUrl = "http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types";
var webClient = new WebClient();
var rawData = webClient.DownloadString(mimeTypeListUrl).Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);

var extensionToMimeType = new Dictionary<string, string>();
var mimeTypeToExtension = new Dictionary<string, string[]>();

foreach (var row in rawData)
{
    if (row.StartsWith("#")) continue;

    var rowData = row.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
    if (rowData.Length != 2) continue;

    var extensions = rowData[1].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
    if (!mimeTypeToExtension.ContainsKey(rowData[0]))
    {
        mimeTypeToExtension.Add(rowData[0], extensions);
    }

    foreach (var extension in extensions)
    {
        if (!extensionToMimeType.ContainsKey(extension))
        {
            extensionToMimeType.Add(extension, rowData[0]);
        }
    }

}

Determine number of pages in a PDF file

I have good success using CeTe Dynamic PDF products. They're not free, but are well documented. They did the job for me.

http://www.dynamicpdf.com/

How to make a Div appear on top of everything else on the screen?

One form to do this is insert the panel that you want to expand inside a DIV setted as relative: let me show you:

<div style="position:relative">
  <div style="position:absolute; z-index: 1000;">
    your code
  </div>
</div>

You use the first div to position the inner content in a specific area inside your page and the second absolute should be referred to the container (because is relative) The z-index in this case is referred also to container and if it higher that the container should be at top. You can put the style in a CSS class and change the size of the absolute div to expand it on hover or another action that you want to control.

I hope that this help

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

How to set time to a date object in java

I should like to contribute the modern answer. This involves using java.time, the modern Java date and time API, and not the old Date nor Calendar except where there’s no way to avoid it.

Your issue is very likely really a timezone issue. When it is Tue Aug 09 00:00:00 IST 2011, in time zones west of IST midnight has not yet been reached. It is still Aug 8. If for example your API for putting the date into Excel expects UTC, the date will be the day before the one you intended. I believe the real and good solution is to produce a date-time of 00:00 UTC (or whatever time zone or offset is expected and used at the other end).

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    ZonedDateTime utcDateDime = yourDate.atStartOfDay(ZoneOffset.UTC);
    System.out.println(utcDateDime);

This prints

2018-02-27T00:00Z

Z means UTC (think of it as offset zero from UTC or Zulu time zone). Better still, of course, if you could pass the LocalDate from the first code line to Excel. It doesn’t include time-of-day, so there is no confusion possible. On the other hand, if you need an old-fashioned Date object for that, convert just before handing the Date on:

    Date oldfashionedDate = Date.from(utcDateDime.toInstant());
    System.out.println(oldfashionedDate);

On my computer this prints

Tue Feb 27 01:00:00 CET 2018

Don’t be fooled, it is correct. My time zone (Central European Time) is at offset +01:00 from UTC in February (standard time), so 01:00:00 here is equal to 00:00:00 UTC. It’s just Date.toString() grabbing the JVMs time zone and using it for producing the string.

How can I set it to something like 5:30 pm?

To answer your direct question directly, if you have a ZonedDateTime, OffsetDateTime or LocalDateTime, in all of these cases the following will accomplish what you asked for:

    yourDateTime = yourDateTime.with(LocalTime.of(17, 30));

If yourDateTime was a LocalDateTime of 2018-02-27T00:00, it will now be 2018-02-27T17:30. Similarly for the other types, only they include offset and time zone too as appropriate.

If you only had a date, as in the first snippet above, you can also add time-of-day information to it:

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    LocalDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30));

For most purposes you should prefer to add the time-of-day in a specific time zone, though, for example

    ZonedDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30))
            .atZone(ZoneId.of("Asia/Kolkata"));

This yields 2018-02-27T17:30+05:30[Asia/Kolkata].

Date and Calendar vs java.time

The Date class that you use as well as Calendar and SimpleDateFormat used in the other answers are long outdated, and SimpleDateFormat in particular has proven troublesome. In all cases the modern Java date and time API is so much nicer to work with. Which is why I wanted to provide this answer to an old question that is still being visited.

Link: Oracle Tutorial Date Time, explaining how to use java.time.

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

this is a select command

   FROM
    user
WHERE
    application_key = 'dsfdsfdjsfdsf'
        AND email NOT LIKE '%applozic.com'
        AND email NOT LIKE '%gmail.com'
        AND email NOT LIKE '%kommunicate.io';

this update command

 UPDATE user
    SET email = null
    WHERE application_key='dsfdsfdjsfdsf' and  email not like '%applozic.com' 
    and email not like '%gmail.com'  and email not like '%kommunicate.io';

Use of document.getElementById in JavaScript

the line

age=document.getElementById("age").value;

says 'the variable I called 'age' has the value of the element with id 'age'. In this case the input field.

The line

voteable=(age<18)?"Too young":"Old enough";

says in a variable I called 'voteable' I store the value following the rule :

"If age is under 18 then show 'Too young' else show 'Old enough'"

The last line tell to put the value of 'voteable' in the element with id 'demo' (in this case the 'p' element)

Move view with keyboard using Swift

If you have 2 or more text fields on the same VC, and the user taps on one of them and then taps on the other one, without calling the function keyboardWillHide, the view is going upwards one more time, which is not necessary, because you'll have the keyboard, a blank space which has the height of the keyboard, and then the view, using the code in the answer I edited:

override func viewDidLoad() {       
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y -= keyboardSize.height
    }
}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        self.view.frame.origin.y += keyboardSize.height
    }
}

To solve this, replace the two functions "KeyboardWillShow/Hide" to these:

func keyboardWillShow(notification: NSNotification) {
 if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    if view.frame.origin.y == 0{
        self.view.frame.origin.y -= keyboardSize.height
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        if view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

Where is Maven Installed on Ubuntu

$ mvn --version

and look for Maven home: in the output , mine is: Maven home: /usr/share/maven

How does one represent the empty char?

There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:

char* my_variable = "";

or, if you want to be explicit:

char my_variable = '\0';

The way posted above is only for a character. And, the second way:

#include <string.h>
char* my_variable = strdup("");

Don't forget to use free() with this one because strdup() use malloc inside.

How to convert float value to integer in php?

Use round()

$float_val = 4.5;

echo round($float_val);

You can also set param for precision and rounding mode, for more info

Update (According to your updated question):

$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201

Get int value from enum in C#

Try this one instead of convert enum to int:

public static class ReturnType
{
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        
}

count number of rows in a data frame in R based on group

Here's an example that shows how table(.) (or, more closely matching your desired output, data.frame(table(.)) does what it sounds like you are asking for.

Note also how to share reproducible sample data in a way that others can copy and paste into their session.

Here's the (reproducible) sample data:

mydf <- structure(list(ID = c(110L, 111L, 121L, 131L, 141L), 
                       MONTH.YEAR = c("JAN. 2012", "JAN. 2012", 
                                      "FEB. 2012", "FEB. 2012", 
                                      "MAR. 2012"), 
                       VALUE = c(1000L, 2000L, 3000L, 4000L, 5000L)), 
                  .Names = c("ID", "MONTH.YEAR", "VALUE"), 
                  class = "data.frame", row.names = c(NA, -5L))

mydf
#    ID MONTH.YEAR VALUE
# 1 110  JAN. 2012  1000
# 2 111  JAN. 2012  2000
# 3 121  FEB. 2012  3000
# 4 131  FEB. 2012  4000
# 5 141  MAR. 2012  5000

Here's the calculation of the number of rows per group, in two output display formats:

table(mydf$MONTH.YEAR)
# 
# FEB. 2012 JAN. 2012 MAR. 2012 
#         2         2         1

data.frame(table(mydf$MONTH.YEAR))
#        Var1 Freq
# 1 FEB. 2012    2
# 2 JAN. 2012    2
# 3 MAR. 2012    1

Make a phone call programmatically

In Swift 3.0,

static func callToNumber(number:String) {

        let phoneFallback = "telprompt://\(number)"
        let fallbackURl = URL(string:phoneFallback)!

        let phone = "tel://\(number)"
        let url = URL(string:phone)!

        let shared = UIApplication.shared

        if(shared.canOpenURL(fallbackURl)){
            shared.openURL(fallbackURl)
        }else if (shared.canOpenURL(url)){
            shared.openURL(url)
        }else{
            print("unable to open url for call")
        }

    }

Cast IList to List

    public async Task<List<TimeAndAttendanceShift>> FindEntitiesByExpression(Expression<Func<TimeAndAttendanceShift, bool>> predicate)
    {
        IList<TimeAndAttendanceShift> result = await _dbContext.Set<TimeAndAttendanceShift>().Where(predicate).ToListAsync<TimeAndAttendanceShift>();

        return result.ToList<TimeAndAttendanceShift>();
    }

Read file-contents into a string in C++

This depends on a lot of things, such as what is the size of the file, what is its type (text/binary) etc. Some time ago I benchmarked the following function against versions using streambuf iterators - it was about twice as fast:

unsigned int FileRead( std::istream & is, std::vector <char> & buff ) {
    is.read( &buff[0], buff.size() );
    return is.gcount();
}

void FileRead( std::ifstream & ifs, string & s ) {
    const unsigned int BUFSIZE = 64 * 1024; // reasoable sized buffer
    std::vector <char> buffer( BUFSIZE );

    while( unsigned int n = FileRead( ifs, buffer ) ) {
        s.append( &buffer[0], n );
    }
}

Upgrade to python 3.8 using conda

Update for 2020/07

Finally, Anaconda3-2020.07 is out and its core is Python 3.8!

You can now download Anaconda packed with Python 3.8 goodness at:

Is Safari on iOS 6 caching $.ajax results?

I had the same problem with a webapp getting data from ASP.NET webservice

This worked for me:

public WebService()
{
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    ...
}

Ignore self-signed ssl cert using Jersey Client

This code will only ever be run against test servers so I don't want to go to the hassle of adding new trusted certs each time we set up a new test server.

This is the kind of code that will eventually find its way in production (if not from you, someone else who's reading this question will copy and paste the insecure trust managers that have been suggested into their applications). It's just so easy to forget to remove this sort of code when you have a deadline, since it doesn't show up as a problem.

If you're worried about having to add new certificates every time you have a test server, create your own little CA, issue all the certificates for the test servers using that CA and import this CA certificate into your client trust store. (Even if you don't deal with things like online certificate revocation in a local environment, this is certainly better than using a trust manager that lets anything through.)

There are tools to help you do this, for example TinyCA or XCA.

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

Convert URL to File or Blob for FileReader.readAsDataURL

Expanding on Felix Turner s response, here is how I would use this approach with the fetch API.

async function createFile(){
  let response = await fetch('http://127.0.0.1:8080/test.jpg');
  let data = await response.blob();
  let metadata = {
    type: 'image/jpeg'
  };
  let file = new File([data], "test.jpg", metadata);
  // ... do something with the file or return it
}
createFile();

Find the IP address of the client in an SSH session

Check if there is an environment variable called:

$SSH_CLIENT 

OR

$SSH_CONNECTION

(or any other environment variables) which gets set when the user logs in. Then process it using the user login script.

Extract the IP:

$ echo $SSH_CLIENT | awk '{ print $1}'
1.2.3.4
$ echo $SSH_CONNECTION | awk '{print $1}'
1.2.3.4

Create a new line in Java's FileWriter

Try:

String.format("%n");

See this question for more details.

Best way to stress test a website

JMeter would be one such tool. Can be a bit hard to learn and configure, but it's usually worth it.

How to remove all listeners in an element?

If you’re not opposed to jquery, this can be done in one line:

jQuery 1.7+

$("#myEl").off()

jQuery < 1.7

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/

cartesian product in pandas

If you have no overlapping columns, don't want to add one, and the indices of the data frames can be discarded, this may be easier:

df1.index[:] = df2.index[:] = 0
df_cartesian = df1.join(df2, how='outer')
df_cartesian.index[:] = range(len(df_cartesian))

SQL search multiple values in same field

Try this

Using UNION

$sql = '';
$count = 0;
foreach($search as $text)
{
  if($count > 0)
     $sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
  else
     $sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";

  $count++;
}

Using WHERE IN

$comma_separated = "('" . implode("','", $search) . "')";  // ('1','2','3')
$sql = "Select name From myTable WHERE name IN ".$comma_separated ;

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

Eliminate space before \begin{itemize}

The cleanest way for you to accomplish this is to use the enumitem package (https://ctan.org/pkg/enumitem). For example,

enter image description here

\documentclass{article}
\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\begin{document}
\noindent Here is some text and I want to make sure
there is no spacing the different items. 
\begin{itemize}[noitemsep]
  \item Item 1
  \item Item 2
  \item Item 3
\end{itemize}
\noindent Here is some text and I want to make sure
there is no spacing between this line and the item
list below it.
\begin{itemize}[noitemsep,topsep=0pt]
  \item Item 1
  \item Item 2
  \item Item 3
\end{itemize}
\end{document}

Furthermore, if you want to use this setting globally across lists, you can use

\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\setlist[itemize]{noitemsep, topsep=0pt}

However, note that this package does not work well with the beamer package which is used to make presentations in Latex.

Programmatically navigate to another view controller/scene

In addition to the good answers above to set the navigation view controller on top of your screen on your app, you can add it to your AppDelegate.swift file inside the block as follows

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow()
    window?.makeKeyAndVisible()
    window?.rootViewController = UINavigationController(rootViewController: LoginViewController())

    return true

}

Matplotlib figure facecolor (background color)

If you want to change background color, try this:

plt.rcParams['figure.facecolor'] = 'white'

Configuring angularjs with eclipse IDE

You'd first wanna make sure you have the JSDT installed.

Next thing is to install some dedicated tools for the job, so check out AngularJS Eclipse Tools. The AngularJS Eclipse Templates might be of help, too, and here's a visual guide written for it to get you started.

Also see the AngularJS Eclipse getting started page.


Since this answer had been posted, the AngularJS Eclipse plugin was released, as other answers stated. You might wanna check it out first.

force browsers to get latest js and css files in asp.net application

In ASP.NET Core (MVC 6) this works out of the box via the asp-append-version tag helper:

<script src="scripts/myjavascript.js" asp-append-version="true"></script>
<link href="styles/mystyle.css rel="stylesheet" asp-append-version="true" />

When I catch an exception, how do I get the type, file, and line number?

Source (Py v2.7.3) for traceback.format_exception() and called/related functions helps greatly. Embarrassingly, I always forget to Read the Source. I only did so for this after searching for similar details in vain. A simple question, "How to recreate the same output as Python for an exception, with all the same details?" This would get anybody 90+% to whatever they're looking for. Frustrated, I came up with this example. I hope it helps others. (It sure helped me! ;-)

import sys, traceback

traceback_template = '''Traceback (most recent call last):
  File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item

# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)

try:
    1/0
except:
    # http://docs.python.org/2/library/sys.html#sys.exc_info
    exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default

    '''
    Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
    or if we do not delete the labels on (not much) older versions of Py, the
    reference we created can linger.

    traceback.format_exc/print_exc do this very thing, BUT note this creates a
    temp scope within the function.
    '''

    traceback_details = {
                         'filename': exc_traceback.tb_frame.f_code.co_filename,
                         'lineno'  : exc_traceback.tb_lineno,
                         'name'    : exc_traceback.tb_frame.f_code.co_name,
                         'type'    : exc_type.__name__,
                         'message' : exc_value.message, # or see traceback._some_str()
                        }

    del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
    # This still isn't "completely safe", though!
    # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
    # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

    print
    print traceback.format_exc()
    print
    print traceback_template % traceback_details
    print

In specific answer to this query:

sys.exc_info()[0].__name__, os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), sys.exc_info()[2].tb_lineno

ImportError: No module named MySQLdb

If you're having issues compiling the binary extension, or on a platform where you cant, you can try using the pure python PyMySQL bindings.

Simply pip install pymysql and switch your SQLAlchemy URI to start like this:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....'

There are some other drivers you could also try.

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.

This two threads explain it better:

PostgreSQL Error: Relation already exists

You cannot create a table with a name that is identical to an existing table or view in the cluster. To modify an existing table, use ALTER TABLE (link), or to drop all data currently in the table and create an empty table with the desired schema, issue DROP TABLE before CREATE TABLE.

It could be that the sequence you are creating is the culprit. In PostgreSQL, sequences are implemented as a table with a particular set of columns. If you already have the sequence defined, you should probably skip creating it. Unfortunately, there's no equivalent in CREATE SEQUENCE to the IF NOT EXISTS construct available in CREATE TABLE. By the looks of it, you might be creating your schema unconditionally, anyways, so it's reasonable to use

DROP TABLE IF EXISTS csd_relationship;
DROP SEQUENCE IF EXISTS csd_relationship_csd_relationship_id_seq;

before the rest of your schema update; In case it isn't obvious, This will delete all of the data in the csd_relationship table, if there is any

How to copy a file from remote server to local machine?

For example, your remote host is example.com and remote login name is user1:

scp [email protected]:/path/to/file /path/to/store/file

Boolean vs boolean in Java

One observation: (though this can be thought of side effect)

boolean being a primitive can either say yes or no.

Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)

REST response code for invalid data

400 is the best choice in both cases. If you want to further clarify the error you can either change the Reason Phrase or include a body to explain the error.

412 - Precondition failed is used for conditional requests when using last-modified date and ETags.

403 - Forbidden is used when the server wishes to prevent access to a resource.

The only other choice that is possible is 422 - Unprocessable entity.

Fade In Fade Out Android Animation in Java

Another alternative:

No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.

So you can do this with Animation.REVERSE like this:

AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);

then onAnimationEnd:

alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
        public void onAnimationStart(Animation animation) {
            //TODO: Run when animation start
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //TODO: Run when animation end
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            //TODO: Run when animation repeat
        }
    });

jquery $.each() for objects

You are indeed passing the first data item to the each function.

Pass data.programs to the each function instead. Change the code to as below:

<script>     
    $(document).ready(function() {         
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };         
        $.each(data.programs, function(key,val) {             
            alert(key+val);         
        });     
    }); 
</script> 

CSS media query to target iPad and iPad only?

These days you can use a Media Queries Level 4 feature to check if the device has the ability to 'hover' over elements.

@media (hover: hover) { ... }

Since the ipad has no 'hover' state you can effectively target touch devices like the ipad.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

How to Replace dot (.) in a string in Java

If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.

replace replaces each matching substring but does not interpret its argument as a regular expression.

str = xpath.replace(".", "/*/");

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Workaround: We need to call the callback functions (Task and Anonymous):

function electronTask(callbackA)
{
    return gulp.series(myFirstTask, mySeccondTask, (callbackB) =>
    {
        callbackA();
        callbackB();
    })();    
}

How to store image in SQL Server database tables column

Insert Into FEMALE(ID, Image)
Select '1', BulkColumn 
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image

You will also need admin rights to run the query.

Best way to alphanumeric check in JavaScript

Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal

_x000D_
_x000D_
function isAlphaNumeric ( str ) {

  /* Iterating character by character to get ASCII code for each character */
  for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {

    /* Collecting charCode from i index value in a string */
    code = str.charCodeAt( i ); 

    /* Validating charCode falls into anyone category */
    if (
        ( code > 47 && code < 58) // numeric (0-9)
        || ( code > 64 && code < 91) // upper alpha (A-Z)
        || ( code > 96 && code < 123 ) // lower alpha (a-z)
    ) {
      continue;
    } 

    /* If nothing satisfies then returning false */
    return false
  }

  /* After validating all the characters and we returning success message*/
  return true;
};

console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));
_x000D_
_x000D_
_x000D_

How do you decompile a swf file

erlswf is an opensource project written in erlang for decompiling .swf files.

Here's the site: https://github.com/bef/erlswf

Change Screen Orientation programmatically using a Button

Use this to set the orientation of the screen:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

or

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

and don't forget to add this to your manifest:

android:configChanges = "orientation"

How to decrease prod bundle size?

The following solution assumes you are serving your dist/ folder using nodejs. Please use the following app.js in root level

const express = require('express'),http = require('http'),path = require('path'),compression = require('compression');

const app = express();

app.use(express.static(path.join(__dirname, 'dist')));
app.use(compression()) //compressing dist folder 
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
})

const port = process.env.PORT || '4201';
app.set('port', port);

const server = http.createServer(app);
server.listen(port, () => console.log('Running at port ' + port))

Make sure you install dependencies;

npm install compression --save
npm install express --save;

Now build the app

ng build --prod --build-optimizer

If you want to further compress the build say reduce 300kb(approx) from , then follow the below process;

Create a folder called vendor inside the src folder and inside vendor folder create a file rxjs.ts and paste the below code in it;

export {Subject} from 'rxjs/Subject';
export {Observable} from 'rxjs/Observable';
export {Subscription} from 'rxjs/Subscription';

And then add the follwing in the tsconfig.json file in your angular-cli application. Then in the compilerOptions , add the following json;

"paths": {
      "rxjs": [
        "./vendor/rxjs.ts"
      ]
    }

This will make your build size way too smaller. In my project I reduced the size from 11mb to 1mb. Hope it helps

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Does bootstrap 4 have a built in horizontal divider?

I am using this example in my project:

html:

 <hr class="my-3 dividerClass"/>

css:

.dividerClass{
  border-top-color: #999
 }

FontAwesome icons not showing. Why?

I use:

<link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<a class="icon fa-car" aria-hidden="true" style="color:white;" href="http://viettelquangbinh.com"></a>

and style after:

.icon::before {
display: inline-block;
margin-right: .5em;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
transform: translate(0, 0);
}

How do you change video src using jQuery?

Try $("#divVideo video")[0].load(); after you changed the src attribute.

TempData keep() vs peek()

TempData is also a dictionary object that stays for the time of an HTTP Request. So, TempData can be used to maintain data between one controller action to the other controller action.

TempData is used to check the null values each time. TempData contain two method keep() and peek() for maintain data state from one controller action to others.

When TempDataDictionary object is read, At the end of request marks as deletion to current read object.

The keep() and peek() method is used to read the data without deletion the current read object.

You can use Peek() when you always want to hold/prevent the value for another request. You can use Keep() when prevent/hold the value depends on additional logic.

Overloading in TempData.Peek() & TempData.Keep() as given below.

TempData.Keep() have 2 overloaded methods.

  1. void keep() : That menace all the data not deleted on current request completion.

  2. void keep(string key) : persist the specific item in TempData with help of name.

TempData.Peek() no overloaded methods.

  1. object peek(string key) : return an object that contain items with specific key without making key for deletion.

Example for return type of TempData.Keep() & TempData.Peek() methods as given below.

public void Keep(string key) { _retainedKeys.Add(key); }

public object Peek(string key) { object value = values; return value; }

Getting list of pixel values from PIL

pixVals = list(pilImg.getdata())

output is a list of all RGB values from the picture:

[(248, 246, 247), (246, 248, 247), (244, 248, 247), (244, 248, 247), (246, 248, 247), (248, 246, 247), (250, 246, 247), (251, 245, 247), (253, 244, 247), (254, 243, 247)]

ASP.NET MVC Global Variables

You could also use a static class, such as a Config class or something along those lines...

public static class Config
{
    public static readonly string SomeValue = "blah";
}

C# ASP.NET Single Sign-On Implementation

I am late to the party, but for option #1, I would go with IdentityServer3(.NET 4.6 or below) or IdentityServer4 (compatible with Core) .

You can reuse your existing user store in your app and plug that to be IdentityServer's User Store. Then the clients must be pointed to your IdentityServer as the open id provider.

Algorithm to calculate the number of divisors of a given number

Here is a straight forward O(sqrt(n)) algorithm. I used this to solve project euler

def divisors(n):
    count = 2  # accounts for 'n' and '1'
    i = 2
    while i ** 2 < n:
        if n % i == 0:
            count += 2
        i += 1
    if i ** 2 == n:
        count += 1
    return count

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

Excel formula to search if all cells in a range read "True", if not, then show "False"

As it appears you have the values as text, and not the numeric True/False, then you can use either COUNTIF or SUMPRODUCT

=IF(SUMPRODUCT(--(A2:D2="False")),"False","True")
=IF(COUNTIF(A3:D3,"False*"),"False","True")

Cannot implicitly convert type 'int?' to 'int'.

simple

(i == null) ? i.Value : 0;

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

If the file is local to your machine use the LOCAL in your command

LOAD DATA LOCAL INFILE "text.txt" INTO table mytable;

How to use componentWillMount() in React Hooks?

https://reactjs.org/docs/hooks-reference.html#usememo

Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.

Why do python lists have pop() but not push()

Probably because the original version of Python (CPython) was written in C, not C++.

The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

Try this code:

CONVERT(varchar(15), date_started, 103)

How can I get customer details from an order in WooCommerce?

Maybe look at the WooCommerce Order class? For example, to get the customer's email address:

$order = new WC_Order($order_id);
echo $order->get_billing_email();

Just a thought...

How do I update Homebrew?

Alternatively you could update brew by installing it again. (Think I did this as El Capitan changed something)

Note: this is a heavy handed approach that will remove all applications installed via brew!

Try to install brew a fresh and it will tell how to uninstall.

At original time of writing to uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Edit: As of 2020 to uninstall:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Insert the same fixed value into multiple rows

You're looking for UPDATE not insert.

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

how to configure lombok in eclipse luna

It began to work only after

eclipse -clean.

And I have to launch it so each time. -clean in eclipse.ini doesn't help.

Other solutions weren't helpful too.

How to add an event after close the modal window?

$('.close').click(function() {
  //Code to be executed when close is clicked
  $('#result').html('yes,result');
});

Input group - two inputs close to each other

My solution requires no additional css and works with any combination of input-addon, input-btn and form-control. It just uses pre-existing bootstrap classes

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
    <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MinVal">_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MaxVal">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

This will be inline if there is space and wrap for smaller screens.

Full Example ( input-addon, input-btn and form-control. )

jsfiddle

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <br>_x000D_
_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How does Trello access the user's clipboard?

I actually built a Chrome extension that does exactly this, and for all web pages. The source code is on GitHub.

I find three bugs with Trello's approach, which I know because I've faced them myself :)

The copy doesn't work in these scenarios:

  1. If you already have Ctrl pressed and then hover a link and hit C, the copy doesn't work.
  2. If your cursor is in some other text field in the page, the copy doesn't work.
  3. If your cursor is in the address bar, the copy doesn't work.

I solved #1 by always having a hidden span, rather than creating one when user hits Ctrl/Cmd.

I solved #2 by temporarily clearing the zero-length selection, saving the caret position, doing the copy and restoring the caret position.

I haven't found a fix for #3 yet :) (For information, check the open issue in my GitHub project).

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

Change window location Jquery

you can use the new push/pop state functions in the history manipulation API.

How do I copy an entire directory of files into an existing directory using Python?

Here's a solution that's part of the standard library:

from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")

See this similar question.

Copy directory contents into a directory with python

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

To add a little bit more information that confused me; I had always thought the same result could be achieved like so;

theDate.ToString("yyyy-MM-dd HH:mm:ss")

However, If your Current Culture doesn't use a colon(:) as the hour separator, and instead uses a full-stop(.) it could return as follow:

2009-06-15 13.45.30

Just wanted to add why the answer provided needs to be as it is;

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

:-)

jQuery show/hide not working

The content is not ready yet, you can move your js to the end of the file or do

<script>
$(function () { 
    $( '.expand' ).click(function() {
       $( '.img_display_content' ).show();
    });
});

So that the document waits to be loaded before running.

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

Enum Naming Convention - Plural

On the other thread C# naming convention for enum and matching property someone pointed out what I think is a very good idea:

"I know my suggestion goes against the .NET Naming conventions, but I personally prefix enums with 'E' and enum flags with 'F' (similar to how we prefix Interfaces with 'I')."

How to get current working directory using vba?

Simple Example below:

Sub openPath()
Dim path As String
path = Application.ActivePresentation.path
Shell Environ("windir") & "\explorer.exe """ & path & "", vbNormalFocus
End Sub

ng is not recognized as an internal or external command

1- Install

$ npm install -g @angular/cli

2- Make sure where your ng.cmd is present.

enter image description here

3- Then add this path into variables.

enter image description here

Creating layout constraints programmatically

Please also note that from iOS9 we can define constraints programmatically "more concise, and easier to read" using subclasses of the new helper class NSLayoutAnchor.

An example from the doc:

[self.cancelButton.leadingAnchor constraintEqualToAnchor:self.saveButton.trailingAnchor constant: 8.0].active = true;

How to check if command line tools is installed

Open your terminal and check to see if you have Xcode installed already with this:

xcode-select -p

in return, if you get this:

/Library/Developer/CommandLineTools

That means you have that Xcode is installed.

Another way you can check would you if you have "HomeBrew" installed you can use the following command to see if you have Xcode and the version:

brew config

And finally, if you don't have the Xcode follow this link to download the Xcode from the Appstore. Xcode from the App Store.

Good Luck.

To show only file name without the entire directory path

There are several ways you can achieve this. One would be something like:

for filepath in /path/to/dir/*
do
    filename=$(basename $filepath)

    ... whatever you want to do with the file here
done

JPA - Persisting a One to Many relationship

You have to set the associatedEmployee on the Vehicle before persisting the Employee.

Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);

newEmployee.setVehicles(vehicles);

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

Measuring text height to be drawn on Canvas ( Android )

If anyone still has problem, this is my code.

I have a custom view which is square (width = height) and I want to assign a character to it. onDraw() shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.

public class SideBarPointer extends View {

    private static final String TAG = "SideBarPointer";

    private Context context;
    private String label = "";
    private int width;
    private int height;

    public SideBarPointer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    private void init() {
//        setBackgroundColor(0x64FF0000);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        height = this.getMeasuredHeight();
        width = this.getMeasuredWidth();

        setMeasuredDimension(width, width);
    }

    protected void onDraw(Canvas canvas) {
        float mDensity = context.getResources().getDisplayMetrics().density;
        float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        Paint previewPaint = new Paint();
        previewPaint.setColor(0x0C2727);
        previewPaint.setAlpha(200);
        previewPaint.setAntiAlias(true);

        Paint previewTextPaint = new Paint();
        previewTextPaint.setColor(Color.WHITE);
        previewTextPaint.setAntiAlias(true);
        previewTextPaint.setTextSize(90 * mScaledDensity);
        previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));

        float previewTextWidth = previewTextPaint.measureText(label);
//        float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
        RectF previewRect = new RectF(0, 0, width, width);

        canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
        canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);

        super.onDraw(canvas);
    }

    public void setLabel(String label) {
        this.label = label;
        Log.e(TAG, "Label: " + label);

        this.invalidate();
    }
}

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

In my situation, the problem was due to running powershell as an admin, so it was looking for the aws credentials in the root of my admin user. There's probably a better way to resolve this, but what worked quickly for me was recreating my .aws folder in the root of my admin user.

Get root password for Google Cloud Engine VM

This work at least in the Debian Jessie image hosted by Google:

The way to enable to switch from you regular to the root user (AKA “super user”) after authentificating with your Google Computer Engine (GCE) User in the local environment (your Linux server in GCE) is pretty straight forward, in fact it just involves just one command to enable it and another every time to use it:

$ sudo passwd
Enter the new UNIX password: <your new root password>
Retype the new UNIX password: <your new root password>
passwd: password updated successfully

After executing the previous command and once logged with your GCE User you will be able to switch to root anytime by just entering the following command:

$ su
Password: <your newly created root password>
root@intance:/#

As we say in economics “caveat emptor” or buyer be aware: Using the root user is far from a best practice in system’s administration. Using it can be the cause a lot of trouble, from wiping everything in your drives and boot disks without a hiccup to many other nasty stuff that would be laborious to backtrack, troubleshoot and rebuilt. On the other hand, I have never met a SysAdmin that doesn’t think he knows better and root more than he should.

REMEMBER: We humans are programmed in such a way that given enough time at one at some point or another are going to press enter without taking into account that we have escalated to root and I can assure you that it will great source of pain, regret and extra work. PLEASE USE ROOT PRIVILEGES SPARSELY AND WITH EXTREME CARE.

Having said all the boring stuff, Have fun, live on the edge, life is short, you only get to live it once, the more you break the more you learn.

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

What is the difference between ( for... in ) and ( for... of ) statements?

The for...in statement iterates over the enumerable properties of an object, in an arbitrary order. Enumerable properties are those properties whose internal [[Enumerable]] flag is set to true, hence if there is any enumerable property in the prototype chain, the for...in loop will iterate on those as well.

The for...of statement iterates over data that iterable object defines to be iterated over.

Example:

Object.prototype.objCustom = function() {}; 
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];

for (let i in iterable) {
  console.log(i); // logs: 0, 1, 2, "arrCustom", "objCustom"
}

for (let i in iterable) {
  if (iterable.hasOwnProperty(i)) {
    console.log(i); // logs: 0, 1, 2,
  }
}

for (let i of iterable) {
  console.log(i); // logs: 3, 5, 7
}

Like earlier, you can skip adding hasOwnProperty in for...of loops.

Creating Dynamic button with click event in JavaScript

this:

element.setAttribute("onclick", alert("blabla"));

should be:

element.onclick = function () {
  alert("blabla");
}

Because you call alert instead push alert as string in attribute

How do I check two or more conditions in one <c:if>?

This look like a duplicate of JSTL conditional check.

The error is having the && outside the expression. Instead use

<c:if test="${ISAJAX == 0 && ISDATE == 0}">

python replace single backslash with double backslash

Use escape characters: "full\\path\\here", "\\" and "\\\\"

Convert normal date to unix timestamp

var date = new Date('2012.08.10');
var unixTimeStamp = Math.floor(date.getTime() / 1000);

In this case it's important to return only a whole number (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses Math.floor() and not Math.round()).

How to decode HTML entities using jQuery?

Extend a String class:

String::decode = ->
  $('<textarea />').html(this).text()

and use as method:

"&lt;img src='myimage.jpg'&gt;".decode()

Suppress output of a function

Making Hadley's comment to an answer (hope to make it better visible). Use of apply family without printing is possible with use of the plyr package

x <- 1:2
lapply(x, function(x) x + 1)
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 3

plyr::l_ply(x, function(x) x + 1)

Created on 2020-05-19 by the reprex package (v0.3.0)

Delete all local git branches

The simpler way to delete all branches but keeping others like "develop" and "master" is the following:

git branch | grep -v "develop" | grep -v "master" | xargs git branch -D

very useful !

Download multiple files with a single action

You can create a temporary set of hidden iframes, initiate download by GET or POST inside of them, wait for downloads to start and remove iframes:

<!DOCTYPE HTML>
<html>
<body>
  <button id="download">Download</button> 

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

     $('#download').click(function() {
       download('http://nogin.info/cv.doc','http://nogin.info/cv.doc');
     });

     var download = function() {
       for(var i=0; i<arguments.length; i++) {
         var iframe = $('<iframe style="visibility: collapse;"></iframe>');
         $('body').append(iframe);
         var content = iframe[0].contentDocument;
         var form = '<form action="' + arguments[i] + '" method="GET"></form>';
         content.write(form);
         $('form', content).submit();
         setTimeout((function(iframe) {
           return function() { 
             iframe.remove(); 
           }
         })(iframe), 2000);
       }
     }      

  </script>
</body>
</html>

Or, without jQuery:

 function download(...urls) {
    urls.forEach(url => {
      let iframe = document.createElement('iframe');
      iframe.style.visibility = 'collapse';
      document.body.append(iframe);

      iframe.contentDocument.write(
        `<form action="${url.replace(/\"/g, '"')}" method="GET"></form>`
      );
      iframe.contentDocument.forms[0].submit();

      setTimeout(() => iframe.remove(), 2000);
    });
  }

How to trigger click on page load?

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

HTML - Arabic Support

This is the answer that was required but everybody answered only part one of many.

  • Step 1 - You cannot have the multilingual characters in unicode document.. convert the document to UTF-8 document

advanced editors don't make it simple for you... go low level...
use notepad to save the document as meName.html & change the encoding
type to UTF-8

  • Step 2 - Mention in your html page that you are going to use such characters by

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    
  • Step 3 - When you put in some characters make sure your container tags have the following 2 properties set

    dir='rtl'
    lang='ar'
    
  • Step 4 - Get the characters from some specific tool\editor or online editor like i did with Arabic-Keyboard.org

example

<p dir="rtl" lang="ar" style="color:#e0e0e0;font-size:20px;">????? ??????? ??????</p>

NOTE: font type, font family, font face setting will have no effect on special characters

Controlling a USB power supply (on/off) with Linux

USB 5v power is always on (even when the computer is turned off, on some computers and on some ports.) You will probably need to program an Arduino with some sort of switch, and control it via Serial library from USB plugged in to the computer.

In other words, a combination of this switch tutorial and this tutorial on communicating via Serial libary to Arduino plugged in via USB.

Simplest way to form a union of two lists

If it is a list, you can also use AddRange method.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4, 5};

listA.AddRange(listB); // listA now has elements of listB also.

If you need new list (and exclude the duplicate), you can use Union

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Union(listB);

If you need new list (and include the duplicate), you can use Concat

  var listB = new List<int>{3, 4, 5};  
  var listA = new List<int>{1, 2, 3, 4, 5};
  var listFinal = listA.Concat(listB);

If you need common items, you can use Intersect.

var listB = new List<int>{3, 4, 5};  
var listA = new List<int>{1, 2, 3, 4};  
var listFinal = listA.Intersect(listB); //3,4

Running an outside program (executable) in Python?

Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.

So you might try:

import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')

(Beware of the double quotes inside the single quotes...)

How to use a ViewBag to create a dropdownlist?

@Html.DropDownListFor(m => m.Departments.id, (SelectList)ViewBag.Department, "Select", htmlAttributes: new { @class = "form-control" })

Enable UTF-8 encoding for JavaScript

Just like any other text file, .js files have specific encodings they are saved in. This message means you are saving the .js file with a non-UTF8 encoding (probably ASCII), and so your non-ASCII characters never even make it to the disk.

That is, the problem is not at the level of HTML or <meta charset> or Content-Type headers, but instead a very basic issue of how your text file is saved to disk.

To fix this, you'll need to change the encoding that Dreamweaver saves files in. It looks like this page outlines how to do so; choose UTF8 without saving a Byte Order Mark (BOM). This Super User answer (to a somewhat-related question) even includes screenshots.

How can we draw a vertical line in the webpage?

There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.

Try this:

CSS

.vr {
    width:10px;
    background-color:#000;
    position:absolute;
    top:0;
    bottom:0;
    left:150px;
}

HTML

<div class="vr">&nbsp;</div>

Demo

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)

https://www.microsoft.com/en-us/download/details.aspx?id=29062

If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :

https://msdn.microsoft.com/en-us/mt186501

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How to insert a picture into Excel at a specified cell position with VBA

If it's simply about inserting and resizing a picture, try the code below.

For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.

Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.

Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
    Dim Pic As Picture, Shp as Shape
    Set Pic = wsDestination.Pictures.Insert(FilePath)
    Pic.Name = "myPicture"
    'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
    Set Shp = wsDestination.Shapes("myPicture")
    With Shp
        .Height = 100
        .Width = 75
        .LockAspectRatio = msoTrue  'Put this later so that changing height doesn't change width and vice-versa)
        .Placement = 1
        .Top = 100
        .Left = 100
    End with
End Sub

Good luck!

Python send POST with header

Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.

import requests
import json

url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
    "Host": "www.mywbsite.fr",
    "Connection": "keep-alive",
    "Content-Length": 129,
    "Origin": "https://www.mywbsite.fr",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Referer": "https://www.mywbsite.fr/data/mult.aspx",
    "Accept-Encoding": "gzip,deflate,sdch",
    "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)

Inline onclick JavaScript variable

There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider

JS

var myvar=15;
function init(){
    document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;

HTML

<input id="EditBanner" type="button"  value="Edit Image" />

Send POST data on redirect with JavaScript/jQuery?

Generic function to post any JavaScript object to the given URL.

function postAndRedirect(url, postData)
{
    var postFormStr = "<form method='POST' action='" + url + "'>\n";

    for (var key in postData)
    {
        if (postData.hasOwnProperty(key))
        {
            postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
        }
    }

    postFormStr += "</form>";

    var formElement = $(postFormStr);

    $('body').append(formElement);
    $(formElement).submit();
}

How to access a dictionary element in a Django template?

choices = {'key1':'val1', 'key2':'val2'}

Here's the template:

<ul>
{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
{% endfor %}
</ul>

Basically, .items is a Django keyword that splits a dictionary into a list of (key, value) pairs, much like the Python method .items(). This enables iteration over a dictionary in a Django template.

Populating a ComboBox using C#

  Language[] items = new Language[]{new Language("English", "En"),
                new Language("Italian", "It")};

            languagesCombo.ValueMember = "Alias";
            languagesCombo.DisplayMember = "FullName";
            languagesCombo.DataSource = items.ToList();

            languagesCombo.DropDownStyle = ComboBoxStyle.DropDownList;

 class Language
    {
        public string FullName { get; set; }
        public string Alias { get; set; }

        public Language(string fullName, string alias)
        {
            this.FullName = fullName;
            this.Alias = alias;
        }
    }

By making your drop down box "read-only" I am assuming you want to prevent user's typing in other options as opposed to being fully read-only where users cannot select a value??

If you wanted it to be fully read-only you could set the enabled property to be false.

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

"The given path's format is not supported."

Does using the Path.Combine method help? It's a safer way for joining file paths together. It could be that it's having problems joining the paths together

What are NDF Files?

From Files and Filegroups Architecture

Secondary data files

Secondary data files make up all the data files, other than the primary data file. Some databases may not have any secondary data files, while others have several secondary data files. The recommended file name extension for secondary data files is .ndf.

Also from file extension NDF - Microsoft SQL Server secondary data file

See Understanding Files and Filegroups

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

The recommended file name extension for secondary data files is .ndf.

/

For example, three files, Data1.ndf, Data2.ndf, and Data3.ndf, can be created on three disk drives, respectively, and assigned to the filegroup fgroup1. A table can then be created specifically on the filegroup fgroup1. Queries for data from the table will be spread across the three disks; this will improve performance. The same performance improvement can be accomplished by using a single file created on a RAID (redundant array of independent disks) stripe set. However, files and filegroups let you easily add new files to new disks.

How to get filename without extension from file path in Ruby

You can get directory path to current script with:

File.dirname __FILE__

JFrame Exit on close Java

You need the line

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

Because the default behaviour for the JFrame when you press the X button is the equivalent to

frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

So almost all the times you'll need to add that line manually when creating your JFrame

I am currently referring to constants in WindowConstants like WindowConstants.EXIT_ON_CLOSE instead of the same constants declared directly in JFrame as the prior reflect better the intent.

Setting Camera Parameters in OpenCV/Python

If anyone is still wondering what the value in CV_CAP_PROP_EXPOSURE might be:

Depends. For my cheap webcam I have to enter the desired value directly, e.g. 0.1 for 1/10s. For my expensive industrial camera I have to enter -5 to get an exposure time of 2^-5s = 1/32s.

GCC dump preprocessor defines

Yes, use -E -dM options instead of -c. Example (outputs them to stdout):

 gcc -dM -E - < /dev/null

For C++

 g++ -dM -E -x c++ - < /dev/null

From the gcc manual:

Instead of the normal output, generate a list of `#define' directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file foo.h, the command

touch foo.h; cpp -dM foo.h

will show all the predefined macros.

If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach.

Android: Scale a Drawable or background image?

Kotlin:

If you needed to draw a bitmap in a View, scaled to FIT.

You can do the proper calculations to set bm the height equal to the container and adjust width, in the case bm width to height ratio is less than container width to height ratio, or the inverse in the opposite scenario.

Images:

Example Image 1

Example Image 2

// binding.fragPhotoEditDrawCont is the RelativeLayout where is your view
// bm is the Bitmap
val ch = binding.fragPhotoEditDrawCont.height
val cw = binding.fragPhotoEditDrawCont.width
val bh = bm.height
val bw = bm.width
val rc = cw.toFloat() / ch.toFloat()
val rb = bw.toFloat() / bh.toFloat()

if (rb < rc) {
    // Bitmap Width to Height ratio is less than Container ratio
    // Means, bitmap should pin top and bottom, and have some space on sides.
    //              _____          ___
    // container = |_____|   bm = |___| 
    val bmHeight = ch - 4 //4 for container border
    val bmWidth = rb * bmHeight //new width is bm_ratio * bm_height
    binding.fragPhotoEditDraw.layoutParams = RelativeLayout.LayoutParams(bmWidth.toInt(), bmHeight)
}
else {
    val bmWidth = cw - 4 //4 for container border
    val bmHeight = 1f/rb * cw
    binding.fragPhotoEditDraw.layoutParams = RelativeLayout.LayoutParams(bmWidth, bmHeight.toInt())
}

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I faced the same issue and solved it by setting the Collation to utf8_general_ci for each column.

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

keycode 13 is for which key

It's the Return or Enter key on keyboard.

JSON.NET Error Self referencing loop detected for type

C# code:

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            };

            var jsonString = JsonConvert.SerializeObject(object2Serialize, jsonSerializerSettings);

            var filePath = @"E:\json.json";

            File.WriteAllText(filePath, jsonString);

How to get a web page's source code from Java

Try the following code with an added request property:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class SocketConnection
{
    public static String getURLSource(String url) throws IOException
    {
        URL urlObject = new URL(url);
        URLConnection urlConnection = urlObject.openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

        return toString(urlConnection.getInputStream());
    }

    private static String toString(InputStream inputStream) throws IOException
    {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
        {
            String inputLine;
            StringBuilder stringBuilder = new StringBuilder();
            while ((inputLine = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(inputLine);
            }

            return stringBuilder.toString();
        }
    }
}

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

Hexadecimal value 0x00 is a invalid character

I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.

It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.

PHP foreach loop key value

You can also use array_keys() . Newbie friendly:

$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk); 

for($i=0; $i < $arraySize; $i++) {
    echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}

How do I setup the InternetExplorerDriver so it works

Another way to resolve this problem is:

Let's assume:

path_to_driver_directory = C:\Work\drivers\

driver = IEDriverServer.exe

When getting messsage about path you can always add path_to_driver_directory containing driver to the PATH environment variable. Check: http://java.com/en/download/help/path.xml

Then simply check in cmd window if driver is available - just run cmd in any location and type name of driver.

If everything works fine then you get:

C:\Users\A>IEDriverServer.exe
Started InternetExplorerDriver server (32-bit)
2.28.0.0
Listening on port 5555

Thats it.

How to see log files in MySQL?

From the MySQL reference manual:

By default, all log files are created in the data directory.

Check /var/lib/mysql folder.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.

Converting String to Double in Android

I had the same issue, but I have just figured out that :

  • parsing the EditText value in the Oncreate method caused the app to crash because when the app starts, there are no values to parse or maybe the placeholders which are letter.

My code:

package com.example.herodav.volumeapp;

import android.renderscript.Double2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    EditText height, length, depth;
    TextView volume;
    double h,l,d,vol;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        height = (EditText)findViewById(R.id.h);
        length = (EditText)findViewById(R.id.l);
        depth = (EditText)findViewById(R.id.d);
        volume = (TextView)findViewById(R.id.v);

        Button btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculateVolume();
                volume.setText("Volume = " + String.valueOf(vol));
            }
        });
    }

    public void calculateVolume(){
        h = Double.parseDouble(height.getText().toString());
        l = Double.parseDouble(length.getText().toString());
        d = Double.parseDouble(depth.getText().toString());
        vol = h*l*d;
    }
}

I

Save PL/pgSQL output from PostgreSQL to a CSV file

In terminal (while connected to the db) set output to the cvs file

1) Set field seperator to ',':

\f ','

2) Set output format unaligned:

\a

3) Show only tuples:

\t

4) Set output:

\o '/tmp/yourOutputFile.csv'

5) Execute your query:

:select * from YOUR_TABLE

6) Output:

\o

You will then be able to find your csv file in this location:

cd /tmp

Copy it using the scp command or edit using nano:

nano /tmp/yourOutputFile.csv

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

Is it possible to ping a server from Javascript?

const ping = (url, timeout = 6000) => {
  return new Promise((reslove, reject) => {
    const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]');
    if (!urlRule.test(url)) reject('invalid url');
    try {
      fetch(url)
        .then(() => reslove(true))
        .catch(() => reslove(false));
      setTimeout(() => {
        reslove(false);
      }, timeout);
    } catch (e) {
      reject(e);
    }
  });
};

use like this:

ping('https://stackoverflow.com/')
  .then(res=>console.log(res))
  .catch(e=>console.log(e))

How can I initialise a static Map?

I like using the static initializer "technique" when I have a concrete realization of an abstract class that has defined an initializing constructor but no default constructor but I want my subclass to have a default constructor.

For example:

public abstract class Shape {

    public static final String COLOR_KEY = "color_key";
    public static final String OPAQUE_KEY = "opaque_key";

    private final String color;
    private final Boolean opaque;

    /**
     * Initializing constructor - note no default constructor.
     *
     * @param properties a collection of Shape properties
     */
    public Shape(Map<String, Object> properties) {
        color = ((String) properties.getOrDefault(COLOR_KEY, "black"));
        opaque = (Boolean) properties.getOrDefault(OPAQUE_KEY, false);
    }

    /**
     * Color property accessor method.
     *
     * @return the color of this Shape
     */
    public String getColor() {
        return color;
    }

    /**
     * Opaque property accessor method.
     *
     * @return true if this Shape is opaque, false otherwise
     */
    public Boolean isOpaque() {
        return opaque;
    }
}

and my concrete realization of this class -- but it wants/needs a default constructor:

public class SquareShapeImpl extends Shape {

    private static final Map<String, Object> DEFAULT_PROPS = new HashMap<>();

    static {
        DEFAULT_PROPS.put(Shape.COLOR_KEY, "yellow");
        DEFAULT_PROPS.put(Shape.OPAQUE_KEY, false);
    }

    /**
     * Default constructor -- intializes this square to be a translucent yellow
     */
    public SquareShapeImpl() {
        // the static initializer was useful here because the call to 
        // this(...) must be the first statement in this constructor
        // i.e., we can't be mucking around and creating a map here
        this(DEFAULT_PROPS);
    }

    /**
     * Initializing constructor -- create a Square with the given
     * collection of properties.
     *
     * @param props a collection of properties for this SquareShapeImpl
     */
    public SquareShapeImpl(Map<String, Object> props) {
        super(props);
    }
}

then to use this default constructor, we simply do:

public class StaticInitDemo {

    public static void main(String[] args) {

        // create a translucent, yellow square...
        Shape defaultSquare = new SquareShapeImpl();

        // etc...
    }
}

Adding a Time to a DateTime in C#

   DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));

How does delete[] know it's an array?

Hey ho well it depends of what you allocating with new[] expression when you allocate array of build in types or class / structure and you don't provide your constructor and destructor the operator will treat it as a size "sizeof(object)*numObjects" rather than object array therefore in this case number of allocated objects will not be stored anywhere, however if you allocate object array and you provide constructor and destructor in your object than behavior change, new expression will allocate 4 bytes more and store number of objects in first 4 bytes so the destructor for each one of them can be called and therefore new[] expression will return pointer shifted by 4 bytes forward, than when the memory is returned the delete[] expression will call a function template first, iterate through array of objects and call destructor for each one of them. I've created this simple code witch overloads new[] and delete[] expressions and provides a template function to deallocate memory and call destructor for each object if needed:

// overloaded new expression 
void* operator new[]( size_t size )
{
    // allocate 4 bytes more see comment below 
    int* ptr = (int*)malloc( size + 4 );

    // set value stored at address to 0 
    // and shift pointer by 4 bytes to avoid situation that
    // might arise where two memory blocks 
    // are adjacent and non-zero
    *ptr = 0;
    ++ptr; 

    return ptr;
}
//////////////////////////////////////////

// overloaded delete expression 
void static operator delete[]( void* ptr )
{
    // decrement value of pointer to get the
    // "Real Pointer Value"
    int* realPtr = (int*)ptr;
    --realPtr;

    free( realPtr );
}
//////////////////////////////////////////

// Template used to call destructor if needed 
// and call appropriate delete 
template<class T>
void Deallocate( T* ptr )
{
    int* instanceCount = (int*)ptr;
    --instanceCount;

    if(*instanceCount > 0) // if larger than 0 array is being deleted
    {
        // call destructor for each object
        for(int i = 0; i < *instanceCount; i++)
        {
            ptr[i].~T();
        }
        // call delete passing instance count witch points
        // to begin of array memory 
        ::operator delete[]( instanceCount );
    }
    else
    {
        // single instance deleted call destructor
        // and delete passing ptr
        ptr->~T();
        ::operator delete[]( ptr );
    }
}

// Replace calls to new and delete
#define MyNew ::new
#define MyDelete(ptr) Deallocate(ptr)

// structure with constructor/ destructor
struct StructureOne
{
    StructureOne():
    someInt(0)
    {}
    ~StructureOne() 
    {
        someInt = 0;
    }

    int someInt;
};
//////////////////////////////

// structure without constructor/ destructor
struct StructureTwo
{
    int someInt;
};
//////////////////////////////


void main(void)
{
    const unsigned int numElements = 30;

    StructureOne* structOne = nullptr;
    StructureTwo* structTwo = nullptr;
    int* basicType = nullptr;
    size_t ArraySize = 0;

/**********************************************************************/
    // basic type array 

    // place break point here and in new expression
    // check size and compare it with size passed 
    // in to new expression size will be the same
    ArraySize = sizeof( int ) * numElements;

    // this will be treated as size rather than object array as there is no 
    // constructor and destructor. value assigned to basicType pointer
    // will be the same as value of "++ptr" in new expression
    basicType = MyNew int[numElements];

    // Place break point in template function to see the behavior
    // destructors will not be called and it will be treated as 
    // single instance of size equal to "sizeof( int ) * numElements"
    MyDelete( basicType );

/**********************************************************************/
    // structure without constructor and destructor array 

    // behavior will be the same as with basic type 

    // place break point here and in new expression
    // check size and compare it with size passed 
    // in to new expression size will be the same
    ArraySize = sizeof( StructureTwo ) * numElements;

    // this will be treated as size rather than object array as there is no 
    // constructor and destructor value assigned to structTwo pointer
    // will be the same as value of "++ptr" in new expression
    structTwo = MyNew StructureTwo[numElements]; 

    // Place break point in template function to see the behavior
    // destructors will not be called and it will be treated as 
    // single instance of size equal to "sizeof( StructureTwo ) * numElements"
    MyDelete( structTwo );

/**********************************************************************/
    // structure with constructor and destructor array 

    // place break point check size and compare it with size passed in
    // new expression size in expression will be larger by 4 bytes
    ArraySize = sizeof( StructureOne ) * numElements;

    // value assigned to "structOne pointer" will be different 
    // of "++ptr" in new expression  "shifted by another 4 bytes"
    structOne = MyNew StructureOne[numElements];

    // Place break point in template function to see the behavior
    // destructors will be called for each array object 
    MyDelete( structOne );
}
///////////////////////////////////////////

jQuery if statement, syntax

jQuery is just a library which enhances the capabilities of the DOM within a web browser; the underlying language is JavaScript, which has, as you might hope to expect from a programming language, the ability to perform conditional logic, i.e.

if( condition ) {
    // do something
}

Testing two conditions is straightforward, too:

if( A && B ) {
    // do something
}

Dear God, I hope this isn't a troll...

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

How do you know if Tomcat Server is installed on your PC

You can check in windows services if tomcat is installed it will be listed in windows services.

To check the windows service list of services installed on windows machine use

  WINDOWS KEY + R   and type services.msc

There you can find all the services related with Jasperreport server like Tomcat and MySQL with name starting Jasperreport server Tomcat and MySQL only if these services are installed and its need to be started by selecting the option.Then you can access it through browser using this link :-

   http://localhost:8080

default port for tomcat is 8080.

Convert System.Drawing.Color to RGB and Hex Value

I found an extension method that works quite well

public static string ToHex(this Color color)
{
    return String.Format("#{0}{1}{2}{3}"
        , color.A.ToString("X").Length == 1 ? String.Format("0{0}", color.A.ToString("X")) : color.A.ToString("X")
        , color.R.ToString("X").Length == 1 ? String.Format("0{0}", color.R.ToString("X")) : color.R.ToString("X")
        , color.G.ToString("X").Length == 1 ? String.Format("0{0}", color.G.ToString("X")) : color.G.ToString("X")
        , color.B.ToString("X").Length == 1 ? String.Format("0{0}", color.B.ToString("X")) : color.B.ToString("X"));
}

Ref: https://social.msdn.microsoft.com/Forums/en-US/4c77ba6c-6659-4a46-920a-7261dd4a15d0/how-to-convert-rgba-value-into-its-equivalent-hex-code?forum=winappswithcsharp

Trigger a button click with JavaScript on the Enter key in a text box

To add a completely plain JavaScript solution that addressed @icedwater's issue with form submission, here's a complete solution with form.

NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.


Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/

HTML

<body>
    <form>
        <input type="text" id="txt" />
        <input type="button" id="go" value="Click Me!" />
        <div id="outige"></div>
    </form>
</body>

JavaScript

// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://stackoverflow.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
    var go = document.getElementById("go"),
        txt = document.getElementById("txt"),
        outige = document.getElementById("outige");

    // Note that jQuery handles "empty" selections "for free".
    // Since we're plain JavaScripting it, we need to make sure this DOM exists first.
    if (txt && go)    {
        txt.addEventListener("keypress", function (e) {
            if (event.keyCode === 13)   {
                go.click();
                e.preventDefault(); // <<< Most important missing piece from icedwater
            }
        });

        go.addEventListener("click", function () {
            if (outige) {
                outige.innerHTML += "Clicked!<br />";
            }
        });
    }
});

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

How to compare two Carbon Timestamps?

This is how I am comparing 2 dates, now() and a date from the table

@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
    .....
    .....
@endif

Should work just right. I have used the comparison functions provided by Carbon.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

For self-hiding you can use getCmdPID.bat and windowMode.bat:

@echo off

echo --- self hiding bat ----
pause
call getCmdPid.bat
set PID=%errorlevel%
call windowMode.bat -pid %PID% -mode hidden

Here's my collection of ways to achieve that - and even more - where it was possible I've tried to return also the PID of the started process (all linked scripts can be downloaded and saved with whatever name you find convenient):

  1. The IEXPRESS solution can be used even on old win 95/98 machines. Iexpress is a really ancient tool that is still packaged with Windows - as arguments accepts only the command and its arguments.

Example usage:

call IEXPhidden.bat "cmd /c myBat.bat"  "argument"
  1. SCHTASKS - Again accepts only two arguments - the command and the arguments.Also checks if it's started with elevated permissions and if possible gets the PID of the process with WEVTUTIL (available from Vista and above so the newer version of windows will receive the PID) command.

Example usage:

call SCHPhidden.bat "cmd /c myBat.bat"  "argument"
  1. 'WScript.Shell' - the script is full wrapper of 'WScript.Shell' and every possible option can be set through the command line options.It's a jscript/batch hybrid and can be called as a bat.

Example usage (for more info print the help with '-h'):

call ShellRunJS.bat "notepad.exe" -style 0 -wait no 
  1. 'Win32_ProcessStartup' - again full wrapper and all options are accessible through the command line arguments.This time it's WSF/batch hybrid with some Jscript and some VBScript pieces of code - but it returns the PID of the started process.If process is not hidden some options like X/Y coordinates can be used (not applicable for every executable - but for example cmd.exe accepts coordinates).

Example usage (for more info print the help with '-h'):

call win32process.bat "notepad" -arguments "/A openFile.txt"  -showWindows 0 -title "notepad"
  1. The .NET solution . Most of the options of ProcessStartInfo options are used (but at the end I was too tired to include everything):

Example usage (for more info print the help with '-h'):

call ProcessStartJS.bat "notepad" -arguments "/A openFile.txt"  -style Hidden -directory "." -title "notepad" -priority Normal

problem with php mail 'From' header

I realize this is an old thread, but i had the same problem since i moved to bluehost yesterday. It may not have been the selected answer but i support the bluehost article 206 reply.

I created a valid email in control panel and used it as my From address and it worked.

xxxxxx.exe is not a valid Win32 application

There are at least two solutions:

  1. You need Visual Studio 2010 installed, then from Visual Studio 2010, View -> Solution Explorer -> Right Click on your project -> Choose Properties from the context menu, you'll get the windows "your project name" Property Pages -> Configuration Properties -> General -> Platform toolset, choose "Visual Studio 2010 (v100)".
  2. You need the Visual Studio 2012 Update 1 described in Windows XP Targeting with C++ in Visual Studio 2012

Convert row names into first column

Or you can use dplyr's add_rownames which does the same thing as David's answer:

library(dplyr)
df <- tibble::rownames_to_column(df, "VALUE")

UPDATE (mid-2016): (incorporated to the above)

old function called add_rownames() has been deprecated and is being replaced by tibble::rownames_to_column() (same functions, but Hadley refactored dplyr a bit).