Programs & Examples On #Sqlworkflowpersistencese

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

How to make a local variable (inside a function) global

Here are two methods to achieve the same thing:

Using parameters and return (recommended)

def other_function(parameter):
    return parameter + 5

def main_function():
    x = 10
    print(x)    
    x = other_function(x)
    print(x)

When you run main_function, you'll get the following output

>>> 10
>>> 15

Using globals (never do this)

x = 0   # The initial value of x, with global scope

def other_function():
    global x
    x = x + 5

def main_function():
    print(x)    # Just printing - no need to declare global yet
    global x   # So we can change the global x
    x = 10
    print(x)
    other_function()
    print(x)

Now you will get:

>>> 0    # Initial global value
>>> 10   # Now we've set it to 10 in `main_function()`
>>> 15   # Now we've added 5 in `other_function()`

Composer: how can I install another dependency without updating old ones?

Actually, the correct solution is:

composer require vendor/package

Taken from the CLI documentation for Composer:

The require command adds new packages to the composer.json file from the current directory.

php composer.phar require

After adding/changing the requirements, the modified requirements will be installed or updated.

If you do not want to choose requirements interactively, you can just pass them to the command.

php composer.phar require vendor/package:2.* vendor/package2:dev-master

While it is true that composer update installs new packages found in composer.json, it will also update the composer.lock file and any installed packages according to any fuzzy logic (> or * chars after the colons) found in composer.json! This can be avoided by using composer update vendor/package, but I wouldn't recommend making a habit of it, as you're one forgotten argument away from a potentially broken project…

Keep things sane and stick with composer require vendor/package for adding new dependencies!

Convert International String to \u Codes in java

There's a command-line tool that ships with java called native2ascii. This converts unicode files to ASCII-escaped files. I've found that this is a necessary step for generating .properties files for localization.

What is the maximum float in Python?

sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.

How do I print debug messages in the Google Chrome JavaScript Console?

Executing following code from the browser address bar:

javascript: console.log(2);

successfully prints message to the "JavaScript Console" in Google Chrome.

Django database query: How to get object by id?

In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404 importing by from django.shortcuts import get_object_or_404.

Use example:

def myFunc(request, my_pk):
    my_var = get_object_or_404(CLASS_NAME, pk=my_pk)

Difference between a View's Padding and Margin

Padding is inside of a View.

Margin is outside of a View.

This difference may be relevant to background or size properties.

For homebrew mysql installs, where's my.cnf?

There is no my.cnf by default. As such, MySQL starts with all of the default settings. If you want to create your own my.cnf to override any defaults, place it at /etc/my.cnf.

Also, you can run mysql --help and look through it for the conf locations listed.

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.

As you can see, there are also some options for bypassing the conf files, or specifying other files to read when you invoke mysql on the command line.

Android Studio : unmappable character for encoding UTF-8

I had the same problem because there was files with windows-1251 encoding and Cyrillic comments. In Android Studio which is based on IntelliJ IDEA you can solve it in two ways:

a) convert file encoding to UTF-8 or

b) set the right file encoding in your build.gradle script:

android {
    ...
    compileOptions.encoding = 'windows-1251' // write your encoding here
    ...

To convert file encoding use the menu at the bottom right corner of IDE. Select right file encoding first -> press Reload -> select UTF-8 -> press Convert.

Also read this Use the UTF-8, Luke! File Encodings in IntelliJ IDEA

SQL Server - Adding a string to a text column (concat equivalent)

hmm, try doing CAST(' ' AS TEXT) + [myText]

Although, i am not completely sure how this will pan out.

I also suggest against using the Text datatype, use varchar instead.

If that doesn't work, try ' ' + CAST ([myText] AS VARCHAR(255))

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

HTML checkbox - allow to check only one checkbox

 $(function () {
     $('input[type=checkbox]').click(function () {
         var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
         for (i = 0; i < chks.length; i++) {
            chks[i].checked = false;
         }
         if (chks.length > 1)
            $(this)[0].checked = true;
     });
 });

Rails create or update magic?

You can do it in one statement like this:

CachedObject.where(key: "the given key").first_or_create! do |cached|
   cached.attribute1 = 'attribute value'
   cached.attribute2 = 'attribute value'
end

What is the difference between primary, unique and foreign key constraints, and indexes?

1)A primary key is a set of one or more attributes that uniquely identifies tuple within relation.

2)A foreign key is a set of attributes from a relation scheme which can be uniquely identify tuples fron another relation scheme.

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

TypeScript error TS1005: ';' expected (II)

The issue was in my code.

In large code base, issue was not clear.

A simplified code is below:

Bad:

 collection.insertMany(
    [[],
    function (err, result) {
    });

Good:

collection.insertMany(
    [],
    function (err, result) {
    });

That is, the first one has [[], instead of normal array []

TS error was not clear enough, and it showed error in the last line with });

Hope this helps.

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Angular, Http GET with parameter?

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.

Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).

If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial").

If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.

Matplotlib scatter plot with different text at each data point

I would love to add that you can even use arrows /text boxes to annotate the labels. Here is what I mean:

import random
import matplotlib.pyplot as plt


y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
    arrowprops=dict(facecolor='red', shrink=0.05))

ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
    arrowprops = dict(  arrowstyle="->",
                        connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
    arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))

ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
    arrowprops = dict(arrowstyle="fancy"))

ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
    bbox=dict(boxstyle="round", alpha=0.1), 
    arrowprops = dict(arrowstyle="simple"))

plt.show()

Which will generate the following graph: enter image description here

Change the Arrow buttons in Slick slider

Content property of pseudo element :before accepts images too. In slick-theme.css change:

_x000D_
_x000D_
// change_x000D_
$slick-prev-character: "?" !default; _x000D_
_x000D_
// to_x000D_
$slick-prev-character: url('image-prev.png');_x000D_
_x000D_
// and _x000D_
$slick-next-character: "?" !default;_x000D_
_x000D_
// to _x000D_
$slick-next-character: url('image-next.jpg');
_x000D_
_x000D_
_x000D_

or directly change the content property on slick-prev:before and slick-next:before

_x000D_
_x000D_
.slick-prev {_x000D_
    left: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: auto;_x000D_
        right: -25px;_x000D_
    }_x000D_
    &:before {_x000D_
        content: url('image-prev.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-next.jpg'); // <<<<<<<<_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
.slick-next {_x000D_
    right: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: -25px;_x000D_
        right: auto;_x000D_
    }_x000D_
    &:before {_x000D_
        content: url('image-next.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-prev.jpg'); // <<<<<<<<_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

What to do about Eclipse's "No repository found containing: ..." error messages?

Simple!!!!!!!!

Right click on eclipse folder and go to properties. Uncheck checkbox "read only" if checked. apply changes.click oK.

after go to Help>Install new software>Uncheck “Contact all update sites during install to find required software”.

Align <div> elements side by side

_x000D_
_x000D_
.section {
  display: flex;
}

.element-left {
  width: 94%;
}

.element-right {
  flex-grow: 1;
}
_x000D_
<div class="section">
  <div id="dB" class="element-left" }>
    <a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
  </div>
  <div id="gB" class="element-right">
    <a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
  </div>
</div>
_x000D_
_x000D_
_x000D_

or

_x000D_
_x000D_
.section {
  display: flex;
  flex-wrap: wrap;
}

.element-left {
  flex: 2;
}

.element-right {
  width: 100px;
}
_x000D_
<div class="section">
  <div id="dB" class="element-left" }>
    <a href="http://notareallink.com" title="Download" id="buyButton">Download</a>
  </div>
  <div id="gB" class="element-right">
    <a href="#" title="Gallery" onclick="$j('#galleryDiv').toggle('slow');return false;" id="galleryButton">Gallery</a>
  </div>
</div>
_x000D_
_x000D_
_x000D_

XDocument or XmlDocument

XmlDocument is great for developers who are familiar with the XML DOM object model. It's been around for a while, and more or less corresponds to a W3C standard. It supports manual navigation as well as XPath node selection.

XDocument powers the LINQ to XML feature in .NET 3.5. It makes heavy use of IEnumerable<> and can be easier to work with in straight C#.

Both document models require you to load the entire document into memory (unlike XmlReader for example).

PHP/MySQL: How to create a comment section in your website

This is my way i do comments (I think its secure):

<h1>Comment's:</h1>
<?php 
$i  = addslashes($_POST['a']);
$ip = addslashes($_POST['b']);
$a  = addslashes($_POST['c']);
$b  = addslashes($_POST['d']);
if(isset($i) & isset($ip) & isset($a) & isset($b))
{
    $r = mysql_query("SELECT COUNT(*) FROM $db.ban WHERE ip=$ip"); //Check if banned
    $r = mysql_fetch_array($r);
    if(!$r[0]) //Phew, not banned
    {
        if(mysql_query("INSERT INTO $db.com VALUES ($a, $b, $ip, $i)"))
        {
            ?>
            <script type="text/javascript">
                window.location="/index.php?id=".<?php echo $i; ?>;
            </script>
            <?php
        }
        else echo "Error, in mysql query";  
    }
    else echo "Error, You are banned.";
}
$x = mysql_query("SELECT * FROM $db.com WHERE i=$i");
while($r = mysql_fetch_object($x) echo '<div class="c">'.$r->a.'<p>'.$row->b.'</p> </div>';

?>  
<h1>Leave a comment, pl0x:</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="hidden" name="a" value="<?php $echo $_GET['id']; ?>" />
    <input type="hidden" name="b" value="<?php $echo $_SERVER['REMOTE_ADDR']; ?>" />
    <input type="text" name="c" value="Name"/></br>
    <textarea name="d">
    </textarea>
    <input type="submit" />
</form>

This does it all in one page (This is only the comments section, some configuration is needed)

How to format Joda-Time DateTime to only mm/dd/yyyy?

Please try to this one

public void Method(Datetime time)
{
    time.toString("yyyy-MM-dd'T'HH:mm:ss"));
}

How to do a scatter plot with empty circles in Python?

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

example image

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

example image

What evaluates to True/False in R?

T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

How to simulate a real mouse click using java?

Some applications may detect click source at low OS level. If you really need that kind of hack, you may just run target app in virtual machine's window, and run cliker in host OS, it can help.

How do I list loaded plugins in Vim?

Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following VIM Tips site:

" where was an option set  
:scriptnames            : list all plugins, _vimrcs loaded (super)  
:verbose set history?   : reveals value of history and where set  
:function               : list functions  
:func SearchCompl       : List particular function

Illegal Character when trying to compile java code

The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don't specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.

The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn't write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.

Just make sure that the file you create doesn't get compiled by a machine in another corner of the world. It will produce mojibake.

Create thumbnail image

The following code will write an image in proportional to the response, you can modify the code for your purpose:

public void WriteImage(string path, int width, int height)
{
    Bitmap srcBmp = new Bitmap(path);
    float ratio = srcBmp.Width / srcBmp.Height;
    SizeF newSize = new SizeF(width, height * ratio);
    Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height);
    HttpContext.Response.Clear();
    HttpContext.Response.ContentType = "image/jpeg";
    using (Graphics graphics = Graphics.FromImage(target))
    {
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);
        using (MemoryStream memoryStream = new MemoryStream()) 
        {
            target.Save(memoryStream, ImageFormat.Jpeg);
            memoryStream.WriteTo(HttpContext.Response.OutputStream);
        }
    }
    Response.End();
}

How to skip a iteration/loop in while-loop

while (rs.next())
{
  if (f.exists() && !f.isDirectory())
    continue;

  //proceed
}

Try/catch does not seem to have an effect

It is also possible to set the error action preference on individual cmdlets, not just for the whole script. This is done using the parameter ErrorAction (alisa EA) which is available on all cmdlets.

Example

try 
{
 Write-Host $ErrorActionPreference; #Check setting for ErrorAction - the default is normally Continue
 get-item filethatdoesntexist; # Normally generates non-terminating exception so not caught
 write-host "You will hit me as exception from line above is non-terminating";  
 get-item filethatdoesntexist -ErrorAction Stop; #Now ErrorAction parameter with value Stop causes exception to be caught 
 write-host "you won't reach me as exception is now caught";
}
catch
{
 Write-Host "Caught the exception";
 Write-Host $Error[0].Exception;
}

Reverse Singly Linked List Java

The method for reversing a linked list is as below;

Reverse Method

public void reverseList() {
    Node<E> curr = head;
    Node<E> pre = null;
    Node<E> incoming = null;

    while(curr != null) {
        incoming = curr.next;   // store incoming item

        curr.next = pre;        // swap nodes
        pre = curr;             // increment also pre

        curr = incoming;        // increment current
    }

    head = pre; // pre is the latest item where
                // curr is null
}

Three references are needed to reverse a list: pre, curr, incoming

...      pre     curr    incoming
... --> (n-1) --> (n) --> (n+1) --> ...

To reverse a node, you have to store previous element, so that you can use the simple stament;

curr.next = pre;

To reverse the current element's direction. However, to iterate over the list, you have to store incoming element before the execution of the statement above because as reversing the current element's next reference, you don't know the incoming element anymore, that's why a third reference needed.

The demo code is as below;

LinkedList Sample Class

public class LinkedList<E> {

    protected Node<E> head;

    public LinkedList() {
        head = null;
    }

    public LinkedList(E[] list) {
        this();
        addAll(list);
    }

    public void addAll(E[] list) {
        for(int i = 0; i < list.length; i++)
            add(list[i]);
    }

    public void add(E e) {
        if(head == null)
            head = new Node<E>(e);
        else {
            Node<E> temp = head;

            while(temp.next != null)
                temp = temp.next;

            temp.next = new Node<E>(e);
        }
    }

    public void reverseList() {
        Node<E> curr = head;
        Node<E> pre = null;
        Node<E> incoming = null;

        while(curr != null) {
            incoming = curr.next;   // store incoming item

            curr.next = pre;        // swap nodes
            pre = curr;             // increment also pre

            curr = incoming;        // increment current
        }

        head = pre; // pre is the latest item where
                    // curr is null
    }

    public void printList() {
        Node<E> temp = head;

        System.out.print("List: ");
        while(temp != null) {
            System.out.print(temp + " ");
            temp = temp.next;
        }

        System.out.println();
    }

    public static class Node<E> {

        protected E e;
        protected Node<E> next;

        public Node(E e) {
            this.e = e;
            this.next = null;
        }

        @Override
        public String toString() {
            return e.toString();
        }

    }

}

Test Code

public class ReverseLinkedList {

    public static void main(String[] args) {
        Integer[] list = { 4, 3, 2, 1 };

        LinkedList<Integer> linkedList = new LinkedList<Integer>(list);

        linkedList.printList();
        linkedList.reverseList();
        linkedList.printList();
    }

}

Output

List: 4 3 2 1 
List: 1 2 3 4 

Stop setInterval call in JavaScript

The answers above have already explained how setInterval returns a handle, and how this handle is used to cancel the Interval timer.

Some architectural considerations:

Please do not use "scope-less" variables. The safest way is to use the attribute of a DOM object. The easiest place would be "document". If the refresher is started by a start/stop button, you can use the button itself:

<a onclick="start(this);">Start</a>

<script>
function start(d){
    if (d.interval){
        clearInterval(d.interval);
        d.innerHTML='Start';
    } else {
        d.interval=setInterval(function(){
          //refresh here
        },10000);
        d.innerHTML='Stop';
    }
}
</script>

Since the function is defined inside the button click handler, you don't have to define it again. The timer can be resumed if the button is clicked on again.

Iterating over arrays in Python 3

You can use

    nditer

Here I calculated no. of positive and negative coefficients in a logistic regression:

b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
    if i>0:
    pos_coef=pos_coef+1
    else:
    neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))

Output:

no. of positive coefficients is : 85035
no. of negative coefficients is : 36199

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

How to refresh a page with jQuery by passing a parameter to URL

You should be able to accomplish this by using location.href

if(window.location.hostname == "www.myweb.com"){
   window.location.href = window.location.href + "?single";
}

How to add http:// if it doesn't exist in the URL

nickf's solution modified:

function addhttp($url) {
    if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

ssh : Permission denied (publickey,gssapi-with-mic)

According to the line debug1: Authentications that can continue: publickey,gssapi-with-mic , ssh password authentication is disabled and apparently you are not using public key authentication.

Login to your server using console and open /etc/ssh/sshd_config file with an editor with root user and look for line PasswordAuthentication then set it's value to yes and finally restart sshd service.

System.loadLibrary(...) couldn't find native library in my case

please add all suport

app/build.gradle

ndk {
        moduleName "serial_port"
        ldLibs "log", "z", "m"
        abiFilters "arm64-v8a","armeabi", "armeabi-v7a", "x86","x86_64","mips","mips64"
}

app\src\jni\Application.mk

APP_ABI := arm64-v8a armeabi armeabi-v7a x86 x86_64 mips mips64

Creating an instance using the class name and calling constructor

when using (i.e.) getConstructor(String.lang) the constructor has to be declared public. Otherwise a NoSuchMethodException is thrown.

if you want to access a non-public constructor you have to use instead (i.e.) getDeclaredConstructor(String.lang).

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

How can I read command line parameters from an R script?

Dirk's answer here is everything you need. Here's a minimal reproducible example.

I made two files: exmpl.bat and exmpl.R.

  • exmpl.bat:

    set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe"
    %R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
    

    Alternatively, using Rterm.exe:

    set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe"
    %R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
    
  • exmpl.R:

    options(echo=TRUE) # if you want see commands in output file
    args <- commandArgs(trailingOnly = TRUE)
    print(args)
    # trailingOnly=TRUE means that only your arguments are returned, check:
    # print(commandArgs(trailingOnly=FALSE))
    
    start_date <- as.Date(args[1])
    name <- args[2]
    n <- as.integer(args[3])
    rm(args)
    
    # Some computations:
    x <- rnorm(n)
    png(paste(name,".png",sep=""))
    plot(start_date+(1L:n), x)
    dev.off()
    
    summary(x)
    

Save both files in the same directory and start exmpl.bat. In the result you'll get:

  • example.png with some plot
  • exmpl.batch with all that was done

You could also add an environment variable %R_Script%:

"C:\Program Files\R-3.0.2\bin\RScript.exe"

and use it in your batch scripts as %R_Script% <filename.r> <arguments>

Differences between RScript and Rterm:

Simple conversion between java.util.Date and XMLGregorianCalendar

I had to make some changes to make it work, as some things seem to have changed in the meantime:

  • xjc would complain that my adapter does not extend XmlAdapter
  • some bizarre and unneeded imports were drawn in (org.w3._2001.xmlschema)
  • the parsing methods must not be static when extending the XmlAdapter, obviously

Here's a working example, hope this helps (I'm using JodaTime but in this case SimpleDate would be sufficient):

import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.joda.time.DateTime;

public class DateAdapter extends XmlAdapter<Object, Object> {
    @Override
    public Object marshal(Object dt) throws Exception {
        return new DateTime((Date) dt).toString("YYYY-MM-dd");
    }

    @Override
        public Object unmarshal(Object s) throws Exception {
        return DatatypeConverter.parseDate((String) s).getTime();
    }
}

In the xsd, I have followed the excellent references given above, so I have included this xml annotation:

<xsd:appinfo>
    <jaxb:schemaBindings>
        <jaxb:package name="at.mycomp.xml" />
    </jaxb:schemaBindings>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:date"
              parseMethod="at.mycomp.xml.DateAdapter.unmarshal"
          printMethod="at.mycomp.xml.DateAdapter.marshal" />
    </jaxb:globalBindings>
</xsd:appinfo>

How to vertically align an image inside a div

http://jsfiddle.net/MBs64/

.frame {
    height: 35px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    text-align: center;
    margin: 1em 0;
    display: table-cell;
    vertical-align: middle;
}
img {
    background: #3A6F9A;
    display: block;
    max-height: 35px;
    max-width: 160px;
}

The key property is display: table-cell; for .frame. Div.frame is displayed as inline with this, so you need to wrap it in a block element.

This works in Firefox, Opera, Chrome, Safari and Internet Explorer 8 (and later).

UPDATE

For Internet Explorer 7 we need to add a CSS expression:

*:first-child+html img {
    position: relative;
    top: expression((this.parentNode.clientHeight-this.clientHeight)/2+"px");
}

Pure CSS scroll animation

You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

Remove a folder from git tracking

if file is committed and pushed to github then you should run

git rm --fileName

git ls-files to make sure that the file is removed or untracked

git commit -m "UntrackChanges"

git push

Importing packages in Java

Here is the right way to do imports in Java.

import Dan.Vik;
class Kab
{
public static void main(String args[])
{
    Vik Sam = new Vik();
    Sam.disp();
}
}

You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.

Static variable inside of a function in C

Output: 6 7

Reason: static variable is initialised only once (unlike auto variable) and further definition of static variable would be bypassed during runtime. And if it is not initialised manually, it is initialised by value 0 automatically. So,

void foo() {
    static int x = 5; // assigns value of 5 only once
    x++;
    printf("%d", x);
}

int main() {
    foo(); // x = 6
    foo(); // x = 7
    return 0;
}

Could not instantiate mail function. Why this error occurring

An old thread, but it may help someone like me. I resolved the issue by setting up SMTP server value to a legitimate value in PHP.ini

How to get the ASCII value of a character

Note that ord() doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä') can be 228 if you're using Latin-1, or it can raise a TypeError if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:

>>> ord(u'?')
12354

Creating random colour in Java?

I have used this simple and clever way for creating random color in Java,

Random random = new Random();
        System.out.println(String.format("#%06x", random.nextInt(256*256*256)));

Where #%06x gives you zero-padded hex (always 6 characters long).

How to set ANDROID_HOME path in ubuntu?

In the terminal just type these 3 commands to set the ANDROID_HOME Variable :

$ export ANDROID_HOME=~/Android/Sdk 

/Android/Sdk is the location of Sdk, this might get change in your case

$ PATH=$PATH:$ANDROID_HOME/tools
$ PATH=$PATH:$ANDROID_HOME/platform-tools `   

Note : This will set the path temporarily so what ever action you have to perform, perform on the same terminal.

How do I remove packages installed with Python's easy_install?

I ran into the same problem on my MacOS X Leopard 10.6.blah.

Solution is to make sure you're calling the MacPorts Python:

sudo port install python26
sudo port install python_select
sudo python_select python26
sudo port install py26-mysql

Hope this helps.

How to find a min/max with Ruby

You can do

[5, 10].min

or

[4, 7].max

They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

@nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

[4, 5, 7, 10].minmax
=> [4, 10]

jQuery select child element by class with unknown path

This should do the trick:

$('#thisElement').find('.classToSelect')

Invoke(Delegate)

It means that the delegate will run on the UI thread, even if you call that method from a background worker or thread-pool thread. UI elements have thread affinity - they only like talking directly to one thread: the UI thread. The UI thread is defined as the thread that created the control instance, and is therefore associated with the window handle. But all of that is an implementation detail.

The key point is: you would call this method from a worker thread so that you can access the UI (to change the value in a label, etc) - since you are not allowed to do that from any other thread than the UI thread.

Why is Node.js single threaded?

Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.

At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ

Sending a mail from a linux shell script

If the server is well configured, eg it has an up and running MTA, you can just use the mail command.

For instance, to send the content of a file, you can do this:

$ cat /path/to/file | mail -s "your subject" [email protected]

man mail for more details.

Center HTML Input Text Field Placeholder

By using the code snippet below, you are selecting the placeholder inside your input, and any code placed inside will affect only the placeholder.

input::-webkit-input-placeholder {
      text-align: center
}

How to clear or stop timeInterval in angularjs?

var interval = $interval(function() {
  console.log('say hello');
}, 1000);

$interval.cancel(interval);

Python vs Cpython

implementation means what language was used to implement Python and not how python Code would be implemented. The advantage of using CPython is the availability of C Run-time as well as easy integration with C/C++.

So CPython was originally implemented using C. There were other forks to the original implementation which enabled Python to lever-edge Java (JYthon) or .NET Runtime (IronPython).

Based on which Implementation you use, library availability might vary, for example Ctypes is not available in Jython, so any library which uses ctypes would not work in Jython. Similarly, if you want to use a Java Class, you cannot directly do so from CPython. You either need a glue (JEPP) or need to use Jython (The Java Implementation of Python)

(SC) DeleteService FAILED 1072

I had this error also, make sure the exe the service is pointing to is stopped. Also make sure you don't have any Windows dialog boxes behind your other windows. That is why mine wasn't deleting. There was a windows message behind it saying this service has been deleted or something similar.. just had to click ok, there it went.

User GETDATE() to put current date into SQL variable

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

Checking if a number is a prime number in Python

def is_prime(x):
    n = 2
    if x < n:
        return False
    else:    
        while n < x:
           print n
            if x % n == 0:
                return False
                break
            n = n + 1
        else:
            return True

How to find out which package version is loaded in R?

You can use sessionInfo() to accomplish that.

> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=C                 LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] graphics  grDevices utils     datasets  stats     grid      methods   base     

other attached packages:
[1] ggplot2_0.9.0  reshape2_1.2.1 plyr_1.7.1    

loaded via a namespace (and not attached):
 [1] colorspace_1.1-1   dichromat_1.2-4    digest_0.5.2       MASS_7.3-18        memoise_0.1        munsell_0.3       
 [7] proto_0.3-9.2      RColorBrewer_1.0-5 scales_0.2.0       stringr_0.6       
> 

However, as per comments and the answer below, there are better options

> packageVersion("snow")

[1] ‘0.3.9’

Or:

"Rmpi" %in% loadedNamespaces()

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

It's worth noting some other things:

  1. As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.

    In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.

  2. AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.

    Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.

  3. I don't know the impact upon an installer of using something other than numeric file version numbers, though.

What is [Serializable] and when should I use it?

What is it?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.

Uses for Serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Apply SerializableAttribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute even if the class also implements the ISerializable interface to control the serialization process.

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute to that field.

See MSDN for more details.

Edit 1

Any reason to not mark something as serializable

When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.

Cannot open output file, permission denied

Hello I realize this post is old, but here is my opinion anyway. This error arises when you close the console output window using the close icon instead of pressing "any key to continue"

How to print a string multiple times?

If you want to print something = '@' 2 times in a line, you can write this:

print(something * 2)

If you want to print 4 lines of something, you can use a for loop:

for i in range(4):
     print(something)

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

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

what is the use of $this->uri->segment(3) in codeigniter pagination

By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);

It helps avoid having to write code like this:

[if ($this->uri->segment(3) === FALSE)
{
    $product_id = 0;
}
else
{
    $product_id = $this->uri->segment(3);
}]

How do I remove  from the beginning of a file?

For those with shell access here is a little command to find all files with the BOM set in the public_html directory - be sure to change it to what your correct path on your server is

Code:

grep -rl $'\xEF\xBB\xBF' /home/username/public_html

and if you are comfortable with the vi editor, open the file in vi:

vi /path-to-file-name/file.php

And enter the command to remove the BOM:

set nobomb

Save the file:

wq

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

Font Awesome icon inside text input element

Easy way ,but you need bootstrap

 <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text"><i class="fa fa-envelope"></i></span> <!-- icon envelope "class="fa fa-envelope""-->
    </div>
    <input type="email" id="senha_nova" placeholder="Email">
  </div><!-- input-group -->

enter image description here

ant build.xml file doesn't exist

Please install at ubuntu openjdk-7-jdk

sudo apt-get install openjdk-7-jdk

on Windows try find find openjdk

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

I have same problem and this

mvn clean install -U

command fixed the error.

Apache VirtualHost and localhost

This worked for me!

To run projects like http://localhost/projectName

<VirtualHost localhost:80>
   ServerAdmin localhost
    DocumentRoot path/to/htdocs/
    ServerName localhost
</VirtualHost>

To run projects like http://somewebsite.com locally

<VirtualHost somewebsite.com:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/somewebsiteFolder
     ServerName www.somewebsite.com
     ServerAlias somewebsite.com
</VirtualHost>

Same for other websites

<VirtualHost anothersite.local:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/anotherSiteFolder
     ServerName www.anothersite.local
     ServerAlias anothersite.com
</VirtualHost>

How do I compare strings in Java?

== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.

The equals() method will check whether the contents or the states of 2 objects are the same.

Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 Strings hold the same text.

Definitely the use of the equals() method is recommended.

Don't worry about the performance. Some things to encourage using String.equals():

  1. Implementation of String.equals() first checks for reference equality (using ==), and if the 2 strings are the same by reference, no further calculation is performed!
  2. If the 2 string references are not the same, String.equals() will next check the lengths of the strings. This is also a fast operation because the String class stores the length of the string, no need to count the characters or code points. If the lengths differ, no further check is performed, we know they cannot be equal.
  3. Only if we got this far will the contents of the 2 strings be actually compared, and this will be a short-hand comparison: not all the characters will be compared, if we find a mismatching character (at the same position in the 2 strings), no further characters will be checked.

When all is said and done, even if we have a guarantee that the strings are interns, using the equals() method is still not that overhead that one might think, definitely the recommended way. If you want an efficient reference check, then use enums where it is guaranteed by the language specification and implementation that the same enum value will be the same object (by reference).

In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote

,"vote": {
  ".read" : true
  ,".write" : true
  ,"$issue" : {
    "user" : {
      "$user" : {
        ".validate" : "!data.exists() && 
             newData.val()==data.parent().parent().child('count').getPriority()+1 &&
             newData.val()==newData.GetPriority()" 

user can only vote once && count must be one higher than current count && data value must be same as priority.

      }
    }
    ,"count" : {
      ".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
             newData.getPriority()==data.getPriority()+1 "
    }

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

  }
}

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
  window.fb = new Firebase('https:...vote/iss1/');
  window.fb.child('count').once('value', function (dss) {
    votes = dss.getPriority();
    for (var i=1;i<10;i++) vote(dss,i+votes);
  } );

function vote(dss,count)
{
  var user='user/zz' + count; // replace with auth.id or whatever
  window.fb.child(user).setWithPriority(count,count);
  window.fb.child('count').setWithPriority(user,count);
}
</script>

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

How can I get a Dialog style activity window to fill the screen?

Matthias' answer is mostly right but it's still not filling the entire screen as it has a small padding on each side (pointed out by @Holmes). In addition to his code, we could fix this by extending Theme.Dialog style and add some attributes like this.

<style name="MyDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then we simply declare Activity with theme set to MyDialog:

<activity
    android:name=".FooActivity"
    android:theme="@style/MyDialog" />

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]

Load different application.yml in SpringBoot Test

You can set your test properties in src/test/resources/config/application.yml file. Spring Boot test cases will take properties from application.yml file in test directory.

The config folder is predefined in Spring Boot.

As per documentation:

If you do not like application.properties as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property. You can also refer to an explicit location by using the spring.config.location environment property (which is a comma-separated list of directory locations or file paths). The following example shows how to specify a different file name:

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

The same works for application.yml

Documentation:

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-application-property-files

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Graphviz: How to go from .dot to a graph?

there is no requirement of any conversion.

We can simply use xdot command in Linux which is an Interactive viewer for Graphviz dot files.

ex: xdot file.dot

for more infor:https://github.com/rakhimov/cppdep/wiki/How-to-view-or-work-with-Graphviz-Dot-files

Format Date/Time in XAML in Silverlight

C#: try this

  • yyyy(yy/yyy) - years
  • MM - months(like '03'), MMMM - months(like 'March')
  • dd - days(like 09), ddd/dddd - days(Sun/Sunday)
  • hh - hour 12(AM/PM), HH - hour 24
  • mm - minute
  • ss - second

Use some delimeter,like this:

  1. MessageBox.Show(DateValue.ToString("yyyy-MM-dd")); example result: "2014-09-30"
  2. empty format string: MessageBox.Show(DateValue.ToString()); example result: "30.09.2014 0:00:00"

Pushing from local repository to GitHub hosted remote

This worked for my GIT version 1.8.4:

  1. From the local repository folder, right click and select 'Git Commit Tool'.
  2. There, select the files you want to upload, under 'Unstaged Changes' and click 'Stage Changed' button. (You can initially click on 'Rescan' button to check what files are modified and not uploaded yet.)
  3. Write a Commit Message and click 'Commit' button.
  4. Now right click in the folder again and select 'Git Bash'.
  5. Type: git push origin master and enter your credentials. Done.

'router-outlet' is not a known element

It works for me, when i add following code in app.module.ts

@NgModule({
...,
   imports: [
     AppRoutingModule
    ],
...
})

Find kth smallest element in a binary search tree in Optimum way

Solution for complete BST case :-

Node kSmallest(Node root, int k) {
  int i = root.size(); // 2^height - 1, single node is height = 1;
  Node result = root;
  while (i - 1 > k) {
    i = (i-1)/2;  // size of left subtree
    if (k < i) {
      result = result.left;
    } else {
      result = result.right;
      k -= i;
    }  
  }
  return i-1==k ? result: null;
}

Comparing two arrays & get the values which are not common

PS > $c = Compare-Object -ReferenceObject (1..5) -DifferenceObject (1..6) -PassThru
PS > $c
6

Remove portion of a string after a certain character

$var = "Posted On April 6th By Some Dude";
$new_var = substr($var, 0, strpos($var, " By"));

How to validate a form with multiple checkboxes to have atleast one checked

The above addMethod by Lod Lawson is not completely correct. It's $.validator and not $.validate and the validator method name cb_selectone requires quotes. Here is a corrected version that I tested:

$.validator.addMethod('cb_selectone', function(value,element){
    if(element.length>0){
        for(var i=0;i<element.length;i++){
            if($(element[i]).val('checked')) return true;
        }
        return false;
    }
    return false;
}, 'Please select at least one option');

How to set editor theme in IntelliJ Idea

For IntelliJ in Mac

View -> Quick Switch theme (^`)-> color schema

How do I return clean JSON from a WCF Service?

In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare

 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]

    List<personClass> Getperson(string id);

How to get Domain name from URL using jquery..?

This worked for me.

http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery

$(location).attr('host');                        www.test.com:8082
$(location).attr('hostname');                    www.test.com
$(location).attr('port');                        8082
$(location).attr('protocol');                    http:
$(location).attr('pathname');                    index.php
$(location).attr('href');                        http://www.test.com:8082/index.php#tab2
$(location).attr('hash');                       #tab2
$(location).attr('search');                     ?foo=123

Amazon products API - Looking for basic overview and information

I found a good alternative for requesting amazon product information here: http://api-doc.axesso.de/

Its an free rest api which return alle relevant information related to the requested product.

How to edit a JavaScript alert box title?

There's quite a nice 'hack' here - https://stackoverflow.com/a/14565029 where you use an iframe with an empty src to generate the alert / confirm message - it doesn't work on Android (for security's sake) - but may suit your scenario.

@RequestParam in Spring MVC handling optional parameters

You need to give required = false for name and password request parameters as well. That's because, when you provide just the logout parameter, it actually expects for name and password as well as they are still mandatory.

It worked when you just gave name and password because logout wasn't a mandatory parameter thanks to required = false already given for logout.

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

How to get all enum values in Java?

One can also use the java.util.EnumSet like this

@Test
void test(){
    Enum aEnum =DayOfWeek.MONDAY;
    printAll(aEnum);
}

void printAll(Enum value){
    Set allValues = EnumSet.allOf(value.getClass());
    System.out.println(allValues);
}

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The servlet API .jar file must not be embedded inside the webapp since, obviously, the container already has these classes in its classpath: it implements the interfaces contained in this jar.

The dependency should be in the provided scope, rather than the default compile scope, in your Maven pom:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

casting Object array to Integer array error

Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.

Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);

Here the reason to hitting an ClassCastException is you can't treat an array of Integer as an array of Object. Integer[] is a subtype of Object[] but Object[] is not a Integer[].

And the following also will not give an ClassCastException.

Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;

importing pyspark in python shell

On Mac, I use Homebrew to install Spark (formula "apache-spark"). Then, I set the PYTHONPATH this way so the Python import works:

export SPARK_HOME=/usr/local/Cellar/apache-spark/1.2.0
export PYTHONPATH=$SPARK_HOME/libexec/python:$SPARK_HOME/libexec/python/build:$PYTHONPATH

Replace the "1.2.0" with the actual apache-spark version on your mac.

Update Item to Revision vs Revert to Revision

The text from the Tortoise reference:

Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.

If you want to undo an earlier change permanently, use Revert to this revision instead.

Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.

If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.

What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.

If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.

If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.

PHP Constants Containing Arrays?

If you are looking this from 2009, and you don't like AbstractSingletonFactoryGenerators, here are a few other options.

Remember, arrays are "copied" when assigned, or in this case, returned, so you are practically getting the same array every time. (See copy-on-write behaviour of arrays in PHP.)

function FRUITS_ARRAY(){
  return array('chicken', 'mushroom', 'dirt');
}

function FRUITS_ARRAY(){
  static $array = array('chicken', 'mushroom', 'dirt');
  return $array;
}

function WHAT_ANIMAL( $key ){
  static $array = (
    'Merrick' => 'Elephant',
    'Sprague' => 'Skeleton',
    'Shaun'   => 'Sheep',
  );
  return $array[ $key ];
}

function ANIMAL( $key = null ){
  static $array = (
    'Merrick' => 'Elephant',
    'Sprague' => 'Skeleton',
    'Shaun'   => 'Sheep',
  );
  return $key !== null ? $array[ $key ] : $array;
}

Add an element to an array in Swift

Example: students = ["Ben" , "Ivy" , "Jordell"]

1) To add single elements to the end of an array, use the append(_:)

students.append(\ "Maxime" )

2) Add multiple elements at the same time by passing another array or a sequence of any kind to the append(contentsOf:) method

students.append(contentsOf: ["Shakia" , "William"])

3) To add new elements in the middle of an array by using the insert(_:at:) method for single elements

students.insert("Liam" , at:2 )

4) Using insert(contentsOf:at:) to insert multiple elements from another collection or array literal

students.insert(['Tim','TIM' at: 2 )

How to call a PHP function on the click of a button

You can simply do this. In php, you can determine button click by use of

if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}

Therefore you should modify you code as follows:


<?php

if(isset($_Post['select']){
 echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
 echo "insert button clicked and insert method should be executed";
}
           
        ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <body>
        <form action="functioncalling.php">
            <input type="text" name="txt" />
            <input type="submit" name="insert" value="insert" onclick="insert()" />
            <input type="submit" name="select" value="select" onclick="select()" />
        </form>

<script>
//This will be processed on the client side
function insert(){
  window.alert("You click insert button");
}

function select(){
  window.alert("You click insert button");
}
</script>
</body>
</html>


        

Using AngularJS date filter with UTC date

Seems like AngularJS folks are working on it in version 1.3.0. All you need to do is adding : 'UTC' after the format string. Something like:

{{someDate | date:'d MMMM yyyy' : 'UTC'}}

As you can see in the docs, you can also play with it here: Plunker example

BTW, I think there is a bug with the Z parameter, since it still show local timezone even with 'UTC'.

The activity must be exported or contain an intent-filter

Check your manifest,Open the file with .xml extension and then all your activities are listed your first activity should have this code enclosed in its tags

<intent-filter>
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

or there is another way u can choose from configuration which is drop down list on the left side of run button choose from App from it Hope it will help!!

What is the correct JSON content type?

As many others have mentioned, application/json is the correct answer.

But what haven't been explained yet is what the other options you proposed mean.

  • application/x-javascript: Experimental MIME type for JavaScript before application/javascript was made standard.

  • text/javascript: Now obsolete. You should use application/javascript when using javascript.

  • text/x-javascript: Experimental MIME type for the above situation.

  • text/x-json: Experimental MIME type for JSON before application/json got officially registered.

All in all, whenever you have any doubts about content types, you should check this link

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations

Then you can do things like:

var day = moment("12-25-1995", "MM-DD-YYYY");

or

var day = moment("25/12/1995", "DD/MM/YYYY");

then operate on the date

day.add('days', 7)

and to get the native javascript date

day.toDate();

How do I check if file exists in Makefile so I can delete it?

One line solution:

   [ -f ./myfile ] && echo exists

One line solution with error action:

   [ -f ./myfile ] && echo exists || echo not exists

Example used in my make clean directives:

clean:
    @[ -f ./myfile ] && rm myfile || true

And make clean works without error messages!

How to use putExtra() and getExtra() for string data

put function

etname=(EditText)findViewById(R.id.Name);
        tvname=(TextView)findViewById(R.id.tvName);

        b1= (ImageButton) findViewById(R.id.Submit);

        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                String s=etname.getText().toString();

                Intent ii=new Intent(getApplicationContext(), MainActivity2.class);
                ii.putExtra("name", s);
                Toast.makeText(getApplicationContext(),"Page 222", Toast.LENGTH_LONG).show();
                startActivity(ii);
            }
        });



getfunction 

public class MainActivity2 extends Activity {
    TextView tvname;
    EditText etname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);
        tvname = (TextView)findViewById(R.id.tvName);
        etname=(EditText)findViewById(R.id.Name);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {

          String j2 =(String) b.get("name");

etname.setText(j2);
            Toast.makeText(getApplicationContext(),"ok",Toast.LENGTH_LONG).show();
        }
    }

How to initialize java.util.date to empty

Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date. If you make it null means that it is not referring any instance of java.util.Date.

You have tried date2=""; what you mean to do by this statement you want to reference the instance of String to a variable that is suppose to store java.util.Date. This is not possible as Java is Strongly Typed Language.

Edit

After seeing the comment posted to the answer of LastFreeNickname

I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it

I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null as shown below:

if(textBox.getText() == null || textBox.getText().equals(""){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Also I can assume since you are asking user to enter a date in a TextBox, you are using a DateFormat to parse the text that is entered in the TextBox. If this is the case you could simply call the dateFormat.parse() which throws a ParseException if the format in which the date was written is incorrect or is empty string. Here in the catch block you could put the above statements as show below:

try{
    date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

error C2065: 'cout' : undeclared identifier

Just use printf!

Include stdio.h in your stdafx.h header file for printf.

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

Declare this in your CSS and you should be good:

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

This solution can be implemented without using additional wrappers.

This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.

addEventListener in Internet Explorer

Here's something for those who like beautiful code.

function addEventListener(obj,evt,func){
    if ('addEventListener' in window){
        obj.addEventListener(evt,func, false);
    } else if ('attachEvent' in window){//IE
        obj.attachEvent('on'+evt,func);
    }
}

Shamelessly stolen from Iframe-Resizer.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

it can only be lazily loaded whilst within a transaction. So you could access the collection in your repository, which has a transaction - or what I normally do is a get with association, or set fetchmode to eager.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

That's how I would handle different images (sizes and proportions) in a flexible grid.

_x000D_
_x000D_
.images {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  margin: -20px;_x000D_
}_x000D_
_x000D_
.imagewrapper {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  width: calc(50% - 20px);_x000D_
  height: 300px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.image {_x000D_
  display: block;_x000D_
  object-fit: cover;_x000D_
  width: 100%;_x000D_
  height: 100%; /* set to 'auto' in IE11 to avoid distortions */_x000D_
}
_x000D_
<div class="images">_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/800x600" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1024x768" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1000x800" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/500x800" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/800x600" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1024x768" />_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java 8 Lambda filter by Lists

Something like:

clients.stream.filter(c->{
   users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());

This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.

You should not use <Link> outside a <Router>

Whenever you try to show a Link on a page thats outside the BrowserRouter you will get that error.

This error message is essentially saying that any component that is not a child of our <Router> cannot contain any React Router related components.

You need to migrate your component hierarchy to how you see it in the first answer above. For anyone else reviewing this post who may need to look at more examples.

Let's say you have a Header.jscomponent that looks like this:

import React from 'react';
import { Link } from 'react-router-dom';

const Header = () => {
    return (
        <div className="ui secondary pointing menu">
            <Link to="/" className="item">
                Streamy
            </Link>
            <div className="right menu">
                <Link to="/" className="item">
                    All Streams
                </Link>
            </div>
        </div>
    );
};

export default Header;

And your App.js file looks like this:

import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';

const App = () => {
  return (
    <div className="ui container">
      <Header />
      <BrowserRouter>
        <div>
        <Route path="/" exact component={StreamList} />
        <Route path="/streams/new" exact component={StreamCreate} />
        <Route path="/streams/edit" exact component={StreamEdit} />
        <Route path="/streams/delete" exact component={StreamDelete} />
        <Route path="/streams/show" exact component={StreamShow} />
        </div> 
      </BrowserRouter>
    </div>
  );
};

export default App;

Notice that the Header.js component is making use of the Link tag from react-router-dom but the componet was placed outside the <BrowserRouter>, this will lead to the same error as the one experience by the OP. In this case, you can make the correction in one move:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';

const App = () => {
  return (
    <div className="ui container">
      <BrowserRouter>
        <div>
        <Header />
        <Route path="/" exact component={StreamList} />
        <Route path="/streams/new" exact component={StreamCreate} />
        <Route path="/streams/edit" exact component={StreamEdit} />
        <Route path="/streams/delete" exact component={StreamDelete} />
        <Route path="/streams/show" exact component={StreamShow} />
        </div> 
      </BrowserRouter>
    </div>
  );
};

export default App;

Please review carefully and ensure you have the <Header /> or whatever your component may be inside of not only the <BrowserRouter> but also inside of the <div>, otherwise you will also get the error that a Router may only have one child which is referring to the <div> which is the child of <BrowserRouter>. Everything else such as Route and components must go within it in the hierarchy.

So now the <Header /> is a child of the <BrowserRouter> within the <div> tags and it can successfully make use of the Link element.

g++ undefined reference to typeinfo

In my case it was a virtual function in an interface class that wasn't defined as a pure virtual.

class IInterface
{
public:
  virtual void Foo() = 0;
}

I forgot the = 0 bit.

make *** no targets specified and no makefile found. stop

If you create Makefile in the VSCode, your makefile doesnt run. I don't know the cause of this issue. Maybe the configuration of the file is not added to system. But I solved this way. delete created makefile, then go to project directory and right click mouse later create a file and named Makefile. After fill the Makefile and run it. It will work.

How can I check whether an array is null / empty?

Method to check array for null or empty also is present on org.apache.commons.lang:

import org.apache.commons.lang.ArrayUtils;

ArrayUtils.isEmpty(array);

What is the purpose of the return statement?

return means, "output this value from this function".

print means, "send this value to (generally) stdout"

In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).

This is an example of print:

>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

This is an example of return:

>>> def getN():
...    return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

how to list all sub directories in a directory

show all directry and sub directories

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):
{

     for item in dir:

            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
         print(dir)
}

sys.argv[1], IndexError: list index out of range

sys.argv is the list of command line arguments passed to a Python script, where sys.argv[0] is the script name itself.

It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv[1] is out of bounds.

To "fix", just make sure to pass a commandline argument when you run the script, e.g.

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

How does Git handle symbolic links?

"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.

Symlinked directories:

It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.

Example

Before

 ls -l
 lrwxrwxrwx 1 admin adm   29 Sep 30 15:28 src/somedir -> /mnt/somedir

git add/commit/push

It remains the same

After git pull AND some updates found

 drwxrwsr-x 2 admin adm 4096 Oct  2 05:54 src/somedir

Alter MySQL table to add comments on columns

try:

 ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'  

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

Answer is adding this 2 lines of code to Global.asax.cs Application_Start method

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;

Reference: Handling Circular Object References

How do I load a file from resource folder?

Import the following:

import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;

The following method returns a file in an ArrayList of Strings:

public ArrayList<String> loadFile(String filename){

  ArrayList<String> lines = new ArrayList<String>();

  try{

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classloader.getResourceAsStream(filename);
    InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    BufferedReader reader = new BufferedReader(streamReader);
    for (String line; (line = reader.readLine()) != null;) {
      lines.add(line);
    }

  }catch(FileNotFoundException fnfe){
    // process errors
  }catch(IOException ioe){
    // process errors
  }
  return lines;
}

There has been an error processing your request, Error log record number

You can see the error information from:

Magento/var/report

Most of the time it is cause by broken database connection especially at local server, when one forget to start XAMPP or WAMPP server.

Check if EditText is empty.

You could call this function for each of the edit texts:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}

Regex replace uppercase with lowercase letters

Try this

  • Find: ([A-Z])([A-Z]+)\b
  • Replace: $1\L$2

Make sure case sensitivity is on (Alt + C)

Case insensitive string compare in LINQ-to-SQL

Sometimes value stored in Database could contain spaces so running this could be fail

String.Equals(row.Name, "test", StringComparison.OrdinalIgnoreCase)

Solution to this problems is to remove space then convert its case then select like this

 return db.UsersTBs.Where(x => x.title.ToString().ToLower().Replace(" ",string.Empty).Equals(customname.ToLower())).FirstOrDefault();

Note in this case

customname is value to match with Database value

UsersTBs is class

title is the Database column

How are iloc and loc different?

.loc and .iloc are used for indexing, i.e., to pull out portions of data. In essence, the difference is that .loc allows label-based indexing, while .iloc allows position-based indexing.

If you get confused by .loc and .iloc, keep in mind that .iloc is based on the index (starting with i) position, while .loc is based on the label (starting with l).

.loc

.loc is supposed to be based on the index labels and not the positions, so it is analogous to Python dictionary-based indexing. However, it can accept boolean arrays, slices, and a list of labels (none of which work with a Python dictionary).

iloc

.iloc does the lookup based on index position, i.e., pandas behaves similarly to a Python list. pandas will raise an IndexError if there is no index at that location.

Examples

The following examples are presented to illustrate the differences between .iloc and .loc. Let's consider the following series:

>>> s = pd.Series([11, 9], index=["1990", "1993"], name="Magic Numbers")
>>> s
1990    11
1993     9
Name: Magic Numbers , dtype: int64

.iloc Examples

>>> s.iloc[0]
11
>>> s.iloc[-1]
9
>>> s.iloc[4]
Traceback (most recent call last):
    ...
IndexError: single positional indexer is out-of-bounds
>>> s.iloc[0:3] # slice
1990 11
1993  9
Name: Magic Numbers , dtype: int64
>>> s.iloc[[0,1]] # list
1990 11
1993  9
Name: Magic Numbers , dtype: int64

.loc Examples

>>> s.loc['1990']
11
>>> s.loc['1970']
Traceback (most recent call last):
    ...
KeyError: ’the label [1970] is not in the [index]’
>>> mask = s > 9
>>> s.loc[mask]
1990 11
Name: Magic Numbers , dtype: int64
>>> s.loc['1990':] # slice
1990    11
1993     9
Name: Magic Numbers, dtype: int64

Because s has string index values, .loc will fail when indexing with an integer:

>>> s.loc[0]
Traceback (most recent call last):
    ...
KeyError: 0

Event handler not working on dynamic content

You are missing the selector in the .on function:

.on(eventType, selector, function)

This selector is very important!

http://api.jquery.com/on/

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler

See jQuery 1.9 .live() is not a function for more details.

Credentials for the SQL Server Agent service are invalid

I had a domain account with a strong password, but it didn´t work, then I used Network Service account. I tried to change it on SQL Server Configuration Manager after installation and it worked.

jquery function val() is not equivalent to "$(this).value="?

Note that :

typeof $(this) is JQuery object.

and

typeof $(this)[0] is HTMLElement object

then : if you want to apply .val() on HTMLElement , you can add this extension .

HTMLElement.prototype.val=function(v){
   if(typeof v!=='undefined'){this.value=v;return this;}
   else{return this.value}
}

Then :

document.getElementById('myDiv').val() ==== $('#myDiv').val()

And

 document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')

????? INVERSE :

Conversely? if you want to add value property to jQuery object , follow those steps :

  1. Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .

  2. Insert Line after L96 , add this code value:"" to init this new prop enter image description here

  3. Search on jQuery.fn.init , it will be almost Line 2747

enter image description here

  1. Now , assign a value to value prop : (Before return statment add this.value=jQuery(selector).val()) enter image description here

Enjoy now : $('#myDiv').value

Regex match text between tags

Try

str.match(/<b>(.*?)<\/b>/g);

Centering in CSS Grid

I know this question is a couple years old, but I am surprised to find that no one suggested:

   text-align: center;

this is a more universal property than justify-content, and is definitely not unique to grid, but I find that when dealing with text, which is what this question specifically asks about, that it aligns text to the center with-out affecting the space between grid items, or the vertical centering. It centers text horizontally where its stands on its vertical axis. I also find it to remove a layer of complexity that justify-content and align-items adds. justify-content and align-items affects the entire grid item or items, text-align centers the text without affecting the container it is in. Hope this helps.

Is there any way I can define a variable in LaTeX?

Use \def command:

\def \variable {Something that's better to use as a variable}

Be aware that \def overrides preexisting macros without any warnings and therefore can cause various subtle errors. To overcome this either use namespaced variables like my_var or fall back to \newcommand, \renewcommand commands instead.

How do I add a tool tip to a span element?

In most browsers, the title attribute will render as a tooltip, and is generally flexible as to what sorts of elements it'll work with.

<span title="This will show as a tooltip">Mouse over for a tooltip!</span>
<a href="http://www.stackoverflow.com" title="Link to stackoverflow.com">stackoverflow.com</a>
<img src="something.png" alt="Something" title="Something">

All of those will render tooltips in most every browser.

What's wrong with foreign keys?

I always use them, but then I make databases for financial systems. The database is the critical part of the application. If the data in a financial database isn't totally accurate then it really doesn't matter how much effort you put into your code/front-end design. You're just wasting your time.

There's also the fact that multiple systems generally need to interface directly with the database - from other systems that just read data out (Crystal Reports) to systems that insert data (not necessarily using an API I've designed; it may be written by a dull-witted manager who has just discovered VBScript and has the SA password for the SQL box). If the database isn't as idiot-proof as it can possibly be, well - bye bye database.

If your data is important, then yes, use foreign keys, create a suite of stored procedures to interact with the data, and make the toughest DB you can. If your data isn't important, why are you making a database to begin with?

Java multiline string

Sadly, Java does not have multi-line string literals. You either have to concatenate string literals (using + or StringBuilder being the two most common approaches to this) or read the string in from a separate file.

For large multi-line string literals I'd be inclined to use a separate file and read it in using getResourceAsStream() (a method of the Class class). This makes it easy to find the file as you don't have to worry about the current directory versus where your code was installed. It also makes packaging easier, because you can actually store the file in your jar file.

Suppose you're in a class called Foo. Just do something like this:

Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);

The one other annoyance is that Java doesn't have a standard "read all of the text from this Reader into a String" method. It's pretty easy to write though:

public static String readAll(Reader input) {
    StringBuilder sb = new StringBuilder();
    char[] buffer = new char[4096];
    int charsRead;
    while ((charsRead = input.read(buffer)) >= 0) {
        sb.append(buffer, 0, charsRead);
    }
    input.close();
    return sb.toString();
}

Generating CSV file for Excel, how to have a newline inside a value

I found this and it has worked for me

$delimiter = ',';
$enc1 = '"';
$enc2 = '""';

Then where you need to have stuff enclosed

$myfile = ('/path/to/myfile.csv');
//erase any previous contents
$fp = fopen($myfile, 'w+');
fwrite($fp, $enc1 .  'Column Heading 1' . $enc1 . $delimiter );
//append to new file
$fp2 = fopen($myfile, 'a');
fwrite($fp2, $enc1 .  'Column Heading 2' . $enc1 . $delimiter );

.....

fwrite($fp2, $enc1 .  'Last Column Heading' . $enc1 . $delimiter. PHP_EOL );

Then when you need to write something out - like HTML that includes the " you can do this

fwrite($fp2, $enc2 .  $myhtmlstring . $enc2 . $delimiter);

New lines end with . PHP_EOL

The end of the script prints out a link so that the user can download the file.

echo 'Click <a href="myfile.csv">here</a> to download file';

What is the difference between :focus and :active?

:focus is when an element is able to accept input - the cursor in a input box or a link that has been tabbed to.

:active is when an element is being activated by a user - the time between when a user presses a mouse button and then releases it.

Get the first key name of a JavaScript object

Try this:

for (var firstKey in ahash) break;

alert(firstKey);  // 'one'

Simple (I think) Horizontal Line in WPF?

For anyone else struggling with this: Qwertie's comment worked well for me.

<Border Width="1" Margin="2" Background="#8888"/>

This creates a vertical seperator which you can talior to suit your needs.

Regex pattern including all special characters

Try:

(?i)^([[a-z][^a-z0-9\\s\\(\\)\\[\\]\\{\\}\\\\^\\$\\|\\?\\*\\+\\.\\<\\>\\-\\=\\!\\_]]*)$

(?i)^(A)$: indicates that the regular expression A is case insensitive.

[a-z]: represents any alphabetic character from a to z.

[^a-z0-9\\s\\(\\)\\[\\]\\{\\}\\\\^\\$\\|\\?\\*\\+\\.\\<\\>\\-\\=\\!\\_]: represents any alphabetic character except a to z, digits, and special characters i.e. accented characters.

[[a-z][^a-z0-9\\s\\(\\)\\[\\]\\{\\}\\\\^\\$\\|\\?\\*\\+\\.\\<\\>\\-\\=\\!\\_]]: represents any alphabetic(accented or unaccented) character only characters.

*: one or more occurrence of the regex that precedes it.

Is there a C++ decompiler?

Depending on how large and how well-written the original code was, it might be worth starting again in your favourite language (which might still be C++) and learning from any mistakes made in the last version. Didn't someone once say about writing one to throw away?

n.b. Clearly if this is a huge product, then it may not be worth the time.

Xcode 6 Storyboard the wrong size?

For anyone using XCode 7, it's very easy to design for a specific device size (instead of the default square-ish canvas).

In Interface Builder, select your ViewController or Scene from the left menu. Then under Show the Attributes Inspector, go to the Simulated Metrics, and pick the desired Size from the dropdown menu.

How to make an input type=button act like a hyperlink and redirect using a get request?

    <script type="text/javascript">
<!-- 
function newPage(num) {
var url=new Array();
url[0]="http://www.htmlforums.com";
url[1]="http://www.codingforums.com.";
url[2]="http://www.w3schools.com";
url[3]="http://www.webmasterworld.com";
window.location=url[num];``
}
// -->
</script>
</head>
<body>
<form action="#">
<div id="container">
<input class="butts" type="button" value="htmlforums" onclick="newPage(0)"/>
<input class="butts" type="button" value="codingforums" onclick="newPage(1)"/>
<input class="butts" type="button" value="w3schools" onclick="newPage(2)"/>
<input class="butts" type="button" value="webmasterworld" onclick="newPage(3)"/>
</div>
</form>
</body>

Here's the other way, it's simpler than the other one.

<input id="inp" type="button" value="Home Page" onclick="location.href='AdminPage.jsp';" />

It's simpler.

php how to go one level up on dirname(__FILE__)

Try this

dirname(dirname( __ FILE__))

Edit: removed "./" because it isn't correct syntax. Without it, it works perfectly.

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

Assigning the output of a command to a variable

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
#multiline/multiple command/s
EOF
)

Or:

output=$(
#multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

Can't Autowire @Repository annotated interface in Spring Boot

You are scanning the wrong package:

@ComponentScan("**org**.pharmacy")

Where as it should be:

@ComponentScan("**com**.pharmacy")

Since your package names start with com and not org.

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

Using Jquery Datatable with AngularJs

I know it's tempting to use drag and drop angular modules created by other devs - but actually, unless you are doing something non-standard like dynamically adding / removing rows from the ng-repeated data set by calling $http services chance are you really don't need a directive based solution, so if you do go this direction you probably just created extra watchers you don't actually need.

What this implementation provides:

  • Pagination is always correct
  • Filtering is always correct (even if you add custom filters but of course they just need to be in the same closure)

The implementation is easy. Just use angular's version of jQuery dom ready from your view's controller:

Inside your controller:

'use strict';

var yourApp = angular.module('yourApp.yourController.controller', []);

yourApp.controller('yourController', ['$scope', '$http', '$q', '$timeout', function ($scope, $http, $q, $timeout) {

    $scope.users = [
        {
            email: '[email protected]',
            name: {
                first: 'User',
                last: 'Last Name'
            },
            phone: '(416) 555-5555',
            permissions: 'Admin'
        },
        {
            email: '[email protected]',
            name: {
                first: 'First',
                last: 'Last'
            },
            phone: '(514) 222-1111',
            permissions: 'User'
        }
    ];

    angular.element(document).ready( function () {
         dTable = $('#user_table')
         dTable.DataTable();
     });

}]);

Now in your html view can do:

<div class="table table-data clear-both" data-ng-show="viewState === possibleStates[0]">
        <table id="user_table" class="users list dtable">
            <thead>
                <tr>
                    <th>E-mail</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Phone</th>
                    <th>Permissions</th>
                    <th class="blank-cell"></th>
                </tr>
            </thead>
            <tbody>
                <tr data-ng-repeat="user in users track by $index">
                    <td>{{ user.email }}</td>
                    <td>{{ user.name.first }}</td>
                    <td>{{ user.name.last }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.permissions }}</td>
                    <td class="users controls blank-cell">
                        <a class="btn pointer" data-ng-click="showEditUser( $index )">Edit</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

Maven error "Failure to transfer..."

This worked for me in Windows:

  1. Locate the {user}/.m2/repository
  2. In the Search field in upper right of window, type ".lastupdated". Windows will look through all subfolders for these files in the directory.
  3. Remove all the .lastupdated files.
  4. Go back into Eclipse, Right-click on the project and select Maven > Update Project.
  5. Select "Force Update of Snapshots/Releases".
  6. Click Ok and the dependencies will finally resolve correctly.

javascript toISOString() ignores timezone offset

moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.

The following works as well:

var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
// => '2015-01-26T06:40:36.181'

The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.

Bind class toggle to window scroll event

Maybe this can help :)

Controller

$scope.scrollevent = function($e){
   // Your code
}

Html

<div scroll scroll-event="scrollevent">//scrollable content</div>

Or

<body scroll scroll-event="scrollevent">//scrollable content</body>

Directive

.directive("scroll", function ($window) {
   return {
      scope: {
         scrollEvent: '&'
      },
      link : function(scope, element, attrs) {
        $("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ?  scope.scrollEvent()($e) : null })
      }
   }
})

C# how to create a Guid value?

Guid.NewGuid() creates a new random guid.

VBA, if a string contains a certain letter

Try:

If myString like "*A*" Then

How to check if a number is between two values?

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Newline character in StringBuilder

I would make use of the Environment.NewLine property.

Something like:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Foo{0}Bar", Environment.NewLine);
string s = sb.ToString();

Or

StringBuilder sb = new StringBuilder();
sb.Append("Foo");
sb.Append("Foo2");
sb.Append(Environment.NewLine);
sb.Append("Bar");
string s = sb.ToString();

If you wish to have a new line after each append, you can have a look at Ben Voigt's answer.

How to explicitly obtain post data in Spring MVC?

You can simply just pass the attribute you want without any annotations in your controller:

@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
 //do stuff with valueOne variable here
}

Works with GET and POST

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

How to close the current fragment by using Button like the back button?

I change the code from getActivity().getFragmentManager().beginTransaction().remove(this).commit();

to

getActivity().getFragmentManager().popBackStack();

And it can close the fragment.

Count elements with jQuery

try this:

var count_element = $('.element').length

exception in initializer error in java when using Netbeans

Retrofit have recently updated to 2.7.1 version. After that Android 4.x clients have crashed. See https://stackoverflow.com/a/60071876/2914140.

Downgrade Retrofit to 2.6.4.

AngularJS view not updating on model change

As Ajay beniwal mentioned above you need to use Apply to start digestion.

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

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
        console.log($scope.testValue++);
        $scope.$apply() 
    }, 500);
});

Update multiple rows in same query using PostgreSQL

Based on the solution of @Roman, you can set multiple values:

update users as u set -- postgres FTW
  email = u2.email,
  first_name = u2.first_name,
  last_name = u2.last_name
from (values
  (1, '[email protected]', 'Hollis', 'O\'Connell'),
  (2, '[email protected]', 'Robert', 'Duncan')
) as u2(id, email, first_name, last_name)
where u2.id = u.id;

select and echo a single field from mysql db using PHP

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

Usually you do something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

Unless your app is using some special encryption you can simply add Boolean a key to your Info.plist with name ITSAppUsesNonExemptEncryption and value NO.

If your app is using custom encryption then you will need to provide extra legal documents and go through a review of your encryption before being able to select builds.

If you continue with selecting that version for testing, it will ask for the compliance information manually. Choosing "No" presents you with the plist recommendation above.

iTunes Connect encryption export compliance alert for testing

This is change has been announced in the 2015 WWDC, but I guess it has been enforced only very recently. See this and this for a transcript of the WWDC session related to the export compliance, just to a text search for "export".

There are other similar questions on SO, see:

How to use requirements.txt to install all dependencies in a python project

If you are using Linux OS:

  1. Remove matplotlib==1.3.1 from requirements.txt
  2. Try to install with sudo apt-get install python-matplotlib
  3. Run pip install -r requirements.txt (Python 2), or pip3 install -r requirements.txt (Python 3)
  4. pip freeze > requirements.txt

If you are using Windows OS:

  1. python -m pip install -U pip setuptools
  2. python -m pip install matplotlib

Using "Object.create" instead of "new"

The advantage is that Object.create is typically slower than new on most browsers

In this jsperf example, in a Chromium, browser new is 30 times as fast as Object.create(obj) although both are pretty fast. This is all pretty strange because new does more things (like invoking a constructor) where Object.create should be just creating a new Object with the passed in object as a prototype (secret link in Crockford-speak)

Perhaps the browsers have not caught up in making Object.create more efficient (perhaps they are basing it on new under the covers ... even in native code)

Render HTML to an image

All the answers here use third party libraries while rendering HTML to an image can be relatively simple in pure Javascript. There is was even an article about it on the canvas section on MDN.

The trick is this:

  • create an SVG with a foreignObject node containing your XHTML
  • set the src of an image to the data url of that SVG
  • drawImage onto the canvas
  • set canvas data to target image.src

_x000D_
_x000D_
const {body} = document_x000D_
_x000D_
const canvas = document.createElement('canvas')_x000D_
const ctx = canvas.getContext('2d')_x000D_
canvas.width = canvas.height = 100_x000D_
_x000D_
const tempImg = document.createElement('img')_x000D_
tempImg.addEventListener('load', onTempImageLoad)_x000D_
tempImg.src = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml"><style>em{color:red;}</style><em>I</em> lick <span>cheese</span></div></foreignObject></svg>')_x000D_
_x000D_
const targetImg = document.createElement('img')_x000D_
body.appendChild(targetImg)_x000D_
_x000D_
function onTempImageLoad(e){_x000D_
  ctx.drawImage(e.target, 0, 0)_x000D_
  targetImg.src = canvas.toDataURL()_x000D_
}
_x000D_
_x000D_
_x000D_

Some things to note

  • The HTML inside the SVG has to be XHTML
  • For security reasons the SVG as data url of an image acts as an isolated CSS scope for the HTML since no external sources can be loaded. So a Google font for instance has to be inlined using a tool like this one.
  • Even when the HTML inside the SVG exceeds the size of the image it wil draw onto the canvas correctly. But the actual height cannot be measured from that image. A fixed height solution will work just fine but dynamic height will require a bit more work. The best is to render the SVG data into an iframe (for isolated CSS scope) and use the resulting size for the canvas.

SQL - Update multiple records in one query

Camille's solution worked. Turned it into a basic PHP function, which writes up the SQL statement. Hope this helps someone else.

    function _bulk_sql_update_query($table, $array)
    {
        /*
         * Example:
        INSERT INTO mytable (id, a, b, c)
        VALUES (1, 'a1', 'b1', 'c1'),
        (2, 'a2', 'b2', 'c2'),
        (3, 'a3', 'b3', 'c3'),
        (4, 'a4', 'b4', 'c4'),
        (5, 'a5', 'b5', 'c5'),
        (6, 'a6', 'b6', 'c6')
        ON DUPLICATE KEY UPDATE id=VALUES(id),
        a=VALUES(a),
        b=VALUES(b),
        c=VALUES(c);
    */
        $sql = "";

        $columns = array_keys($array[0]);
        $columns_as_string = implode(', ', $columns);

        $sql .= "
      INSERT INTO $table
      (" . $columns_as_string . ")
      VALUES ";

        $len = count($array);
        foreach ($array as $index => $values) {
            $sql .= '("';
            $sql .= implode('", "', $array[$index]) . "\"";
            $sql .= ')';
            $sql .= ($index == $len - 1) ? "" : ", \n";
        }

        $sql .= "\nON DUPLICATE KEY UPDATE \n";

        $len = count($columns);
        foreach ($columns as $index => $column) {

            $sql .= "$column=VALUES($column)";
            $sql .= ($index == $len - 1) ? "" : ", \n";
        }

        $sql .= ";";

        return $sql;
    }

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

Convert pandas data frame to series

Another way -

Suppose myResult is the dataFrame that contains your data in the form of 1 col and 23 rows

# label your columns by passing a list of names
myResult.columns = ['firstCol']

# fetch the column in this way, which will return you a series
myResult = myResult['firstCol']

print(type(myResult))

In similar fashion, you can get series from Dataframe with multiple columns.

import error: 'No module named' *does* exist

I set the PYTHONPATH to '.' and that solved it for me.

export PYTHONPATH='.'

For a one-liner you could as easily do:

PYTHONPATH='.' your_python_script

These commands are expected to be run in a terminal

How to find and turn on USB debugging mode on Nexus 4

Step 1 : Go to Settings >> About Phone >> scroll to the bottom >> tap Build number seven times; this message will appear “You are now 3 steps away from being a developer.”

Step 2 : Now go to Settings >> Developer Options >> Check USB Debugging

this is great article will help you to enable this mode on your phone

Enable USB Debugging Mode on Android

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

You can also use replace(tzinfo=None) for other datetime.

if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):

Replace non-ASCII characters with a single space

For character processing, use Unicode strings:

PythonWin 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32.
>>> s='ABC??def'
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r' ',s)   # Each char is a Unicode codepoint.
'ABC  def'
>>> b = s.encode('utf8')
>>> re.sub(rb'[^\x00-\x7f]',rb' ',b) # Each char is a 3-byte UTF-8 sequence.
b'ABC      def'

But note you will still have a problem if your string contains decomposed Unicode characters (separate character and combining accent marks, for example):

>>> s = 'mañana'
>>> len(s)
6
>>> import unicodedata as ud
>>> n=ud.normalize('NFD',s)
>>> n
'man~ana'
>>> len(n)
7
>>> re.sub(r'[^\x00-\x7f]',r' ',s) # single codepoint
'ma ana'
>>> re.sub(r'[^\x00-\x7f]',r' ',n) # only combining mark replaced
'man ana'