Programs & Examples On #Dllhost

Access is denied when attaching a database

The sa user uses NTFS accounts SQLServerMSSQLUser$<computer_name>$<instance_name> and SQLServerSQLAgentUser$<computer_name>$<instance_name> to access the database files. You may want to try adding permissions for one or both these users.

I don't know if solves your problem since you say you have no problems with the sa user, but I hope it helps.

How to pass a JSON array as a parameter in URL

Send Json data string to a web address and get a result with method post

in C#

public string SendJsonToUrl(string Url, string StrJsonData)
{
    if (Url == "" || StrJsonData == "") return "";
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = StrJsonData.Length;
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(StrJsonData);
            streamWriter.Close();
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    catch (Exception exp)
    {
        throw new Exception("SendJsonToUrl", exp);
    }
}

in PHP

<?php

$input = file_get_contents('php://input');
$json = json_decode($input ,true);

?>

How to change theme for AlertDialog

Arve Waltin's solution looks good, although I haven't tested it yet. There is another solution in case you have trouble getting that to work.... Extend AlertDialog.Builder and override all the methods (eg. setText, setTitle, setView, etc) to not set the actual Dialog's text/title/view, but to create a new view within the Dialog's View do everything in there. Then you are free to style everything as you please.

To clarify, as far as the parent class is concerned, the View is set, and nothing else.

As far as your custom extended class is concerned, everything is done within that view.

How to find the operating system version using JavaScript?

You can use this javascript function to check users' OS simply

  function getOS() {
  var userAgent = window.navigator.userAgent,
      platform = window.navigator.platform,
      macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
      windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
      iosPlatforms = ['iPhone', 'iPad', 'iPod'],
      os = null;

  if (macosPlatforms.indexOf(platform) !== -1) {
    os = 'Mac OS';
  } else if (iosPlatforms.indexOf(platform) !== -1) {
    os = 'iOS';
  } else if (windowsPlatforms.indexOf(platform) !== -1) {
    os = 'Windows';
  } else if (/Android/.test(userAgent)) {
    os = 'Android';
  } else if (!os && /Linux/.test(platform)) {
    os = 'Linux';
  }

  return os;
}

alert(getOS());

Why I can't access remote Jupyter Notebook server?

The other reason can be a firewall. We had same issue even with

jupyter notebook --ip xx.xx.xx.xxx --port xxxx.

Then it turns out to be a firewall on our new centOS7.

Getting today's date in YYYY-MM-DD in Python?

I prefer this, because this is simple, but maybe somehow inefficient and buggy. You must check the exit code of shell command if you want a strongly error-proof program.

os.system('date +%Y-%m-%d')

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

The main differenece is that bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.

Note that navigational access is not always good, especially for "one-to-very-many" and "many-to-very-many" relationships. Imagine a Group that contains thousands of Users:

  • How would you access them? With so many Users, you usually need to apply some filtering and/or pagination, so that you need to execute a query anyway (unless you use collection filtering, which looks like a hack for me). Some developers may tend to apply filtering in memory in such cases, which is obviously not good for performance. Note that having such a relationship can encourage this kind of developers to use it without considering performance implications.

  • How would you add new Users to the Group? Fortunately, Hibernate looks at the owning side of relationship when persisting it, so you can only set User.group. However, if you want to keep objects in memory consistent, you also need to add User to Group.users. But it would make Hibernate to fetch all elements of Group.users from the database!

So, I can't agree with the recommendation from the Best Practices. You need to design bidirectional relationships carefully, considering use cases (do you need navigational access in both directions?) and possible performance implications.

See also:

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

Multi value Dictionary

Just create a Pair<TFirst, TSecond> type and use that as your value.

I have an example of one in my C# in Depth source code. Reproduced here for simplicity:

using System;
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond>
    : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first;
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second)
    {
        this.first = first;
        this.second = second;
    }

    public TFirst First
    {
        get { return first; }
    }

    public TSecond Second
    {
        get { return second; }
    }

    public bool Equals(Pair<TFirst, TSecond> other)
    {
        if (other == null)
        {
            return false;
        }
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
               EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

    public override bool Equals(object o)
    {
        return Equals(o as Pair<TFirst, TSecond>);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
               EqualityComparer<TSecond>.Default.GetHashCode(second);
    }
}

Creating a 3D sphere in Opengl using Visual C++

In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.

glutSolidSphere is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?

#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>

// your framework of choice here

class SolidSphere
{
protected:
    std::vector<GLfloat> vertices;
    std::vector<GLfloat> normals;
    std::vector<GLfloat> texcoords;
    std::vector<GLushort> indices;

public:
    SolidSphere(float radius, unsigned int rings, unsigned int sectors)
    {
        float const R = 1./(float)(rings-1);
        float const S = 1./(float)(sectors-1);
        int r, s;

        vertices.resize(rings * sectors * 3);
        normals.resize(rings * sectors * 3);
        texcoords.resize(rings * sectors * 2);
        std::vector<GLfloat>::iterator v = vertices.begin();
        std::vector<GLfloat>::iterator n = normals.begin();
        std::vector<GLfloat>::iterator t = texcoords.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                float const y = sin( -M_PI_2 + M_PI * r * R );
                float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
                float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

                *t++ = s*S;
                *t++ = r*R;

                *v++ = x * radius;
                *v++ = y * radius;
                *v++ = z * radius;

                *n++ = x;
                *n++ = y;
                *n++ = z;
        }

        indices.resize(rings * sectors * 4);
        std::vector<GLushort>::iterator i = indices.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                *i++ = r * sectors + s;
                *i++ = r * sectors + (s+1);
                *i++ = (r+1) * sectors + (s+1);
                *i++ = (r+1) * sectors + s;
        }
    }

    void draw(GLfloat x, GLfloat y, GLfloat z)
    {
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glTranslatef(x,y,z);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
        glNormalPointer(GL_FLOAT, 0, &normals[0]);
        glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
        glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
        glPopMatrix();
    }
};

SolidSphere sphere(1, 12, 24);

void display()
{
    int const win_width  = …; // retrieve window dimensions from
    int const win_height = …; // framework of choice here
    float const win_aspect = (float)win_width / (float)win_height;

    glViewport(0, 0, win_width, win_height);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, win_aspect, 1, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

#ifdef DRAW_WIREFRAME
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
    sphere.draw(0, 0, -5);

    swapBuffers();
}

int main(int argc, char *argv[])
{
    // initialize and register your framework of choice here
    return 0;
}

Error handling in getJSON calls

I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.

If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)

try:
    snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
    db.session.delete(snip)
    db.session.commit()
    return jsonify(success=True)
except Exception, e:
    logging.debug(e)
    return jsonify(error="Sorry, we couldn't delete that clip.")

Then you can check on Javascript like this;

$.getJSON('/ajax/deleteSnip/' + data_id,
    function(data){
    console.log(data);
    if (data.success === true) {
       console.log("successfully deleted snip");
       $('.snippet[data-id="' + data_id + '"]').slideUp();
    }
    else {
       //only shows if the data object was returned
    }
});

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

Why is null an object and what's the difference between null and undefined?

To add to the answer of What is the differrence between undefined and null, from JavaScript Definitive Guide 6th Edition, p.41 on this page:

You might consider undefined to represent system-level, unexpected, or error-like absense of value and null to represent program-level, normal, or expected absence of value. If you need to assign one of these values to a variable or property or pass one of these values to a function, null is almost always the right choice.

Should I call Close() or Dispose() for stream objects?

For what it's worth, the source code for Stream.Close explains why there are two methods:

// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable.  However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern.  We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup now.

In short, Close is only there because it predates Dispose, and it can't be deleted for compatibility reasons.

How to update record using Entity Framework Core?

Microsoft Docs gives us two approaches.

Recommended HttpPost Edit code: Read and update

This is the same old way we used to do in previous versions of Entity Framework. and this is what Microsoft recommends for us.

Advantages

  • Prevents overposting
  • EFs automatic change tracking sets the Modified flag on the fields that are changed by form input.

Alternative HttpPost Edit code: Create and attach

an alternative is to attach an entity created by the model binder to the EF context and mark it as modified.

As mentioned in the other answer the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflicts.

jQuery How do you get an image to fade in on load?

To do this with multiple images you need to run though an .each() function. This works but I'm not sure how efficient it is.

$('img').hide();
$('img').each( function(){
    $(this).on('load', function () {
        $(this).fadeIn();
    });
});

How can a file be copied?

Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the shutil stdlib module for that.

def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while True:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)

If you want to copy by filename you could do something like this:

def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)

How to make a .NET Windows Service start right after the installation?

You can do this all from within your service executable in response to events fired from the InstallUtil process. Override the OnAfterInstall event to use a ServiceController class to start the service.

http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx

How to add 20 minutes to a current date?

Use .getMinutes() to get the current minutes, then add 20 and use .setMinutes() to update the date object.

var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);

How do I use NSTimer?

Firstly I'd like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called "Companion Guides", which lists guides for the topic being documented (if any exist). For example, with NSTimer, the documentation lists two companion guides:

For your situation, the Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it's divided into two parts:

  • Timers
  • Using Timers

For articles that take this format, there is often an overview of the class and what it's used for, and then some sample code on how to use it, in this case in the "Using Timers" section. There are sections on "Creating and Scheduling a Timer", "Stopping a Timer" and "Memory Management". From the article, creating a scheduled, non-repeating timer can be done something like this:

[NSTimer scheduledTimerWithTimeInterval:2.0
    target:self
    selector:@selector(targetMethod:)
    userInfo:nil
    repeats:NO];

This will create a timer that is fired after 2.0 seconds and calls targetMethod: on self with one argument, which is a pointer to the NSTimer instance.

If you then want to look in more detail at the method you can refer back to the docs for more information, but there is explanation around the code too.

If you want to stop a timer that is one which repeats, (or stop a non-repeating timer before it fires) then you need to keep a pointer to the NSTimer instance that was created; often this will need to be an instance variable so that you can refer to it in another method. You can then call invalidate on the NSTimer instance:

[myTimer invalidate];
myTimer = nil;

It's also good practice to nil out the instance variable (for example if your method that invalidates the timer is called more than once and the instance variable hasn't been set to nil and the NSTimer instance has been deallocated, it will throw an exception).

Note also the point on Memory Management at the bottom of the article:

Because the run loop maintains the timer, from the perspective of memory management there's typically no need to keep a reference to a timer after you’ve scheduled it. Since the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method. In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can send it an invalidate message whenever appropriate. If you create an unscheduled timer (see “Unscheduled Timers”), then you must maintain a strong reference to the timer (in a reference-counted environment, you retain it) so that it is not deallocated before you use it.

php resize image on upload

This thing worked for me. No any external liabraries used

    define ("MAX_SIZE","3000");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
    $image =$_FILES["image-1"]["name"];
    $uploadedfile = $_FILES['image-1']['tmp_name'];


    if ($image) 
    {

        $filename = stripslashes($_FILES['image-1']['name']);

        $extension = getExtension($filename);
        $extension = strtolower($extension);


 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
        {
            echo "Unknown Extension..!";
        }
        else
        {

 $size=filesize($_FILES['image-1']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
    echo "File Size Excedeed..!!";
}


if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES['image-1']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else 
{
$src = imagecreatefromgif($uploadedfile);
echo $scr;
}

list($width,$height)=getimagesize($uploadedfile);


$newwidth=1000;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=1000;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);


$filename = "../images/product-image/Cars/". $_FILES['image-1']['name'];

$filename1 = "../images/product-image/Cars/small". $_FILES['image-1']['name'];



imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

Is there a way to specify a max height or width for an image?

You can try this one

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

You can check this post

What does FETCH_HEAD in Git mean?

FETCH_HEAD is a short-lived ref, to keep track of what has just been fetched from the remote repository.

Actually, ... not always considering that, with Git 2.29 (Q4 2020), "git fetch"(man) learned --no-write-fetch-head option to avoid writing the FETCH_HEAD file.

See commit 887952b (18 Aug 2020) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit b556050, 24 Aug 2020)

fetch: optionally allow disabling FETCH_HEAD update

Signed-off-by: Derrick Stolee

If you run fetch but record the result in remote-tracking branches, and either if you do nothing with the fetched refs (e.g. you are merely mirroring) or if you always work from the remote-tracking refs (e.g. you fetch and then merge origin/branchname separately), you can get away with having no FETCH_HEAD at all.

Teach "git fetch"(man) a command line option "--[no-]write-fetch-head".

  • The default is to write FETCH_HEAD, and the option is primarily meant to be used with the "--no-" prefix to override this default, because there is no matching fetch.writeFetchHEAD configuration variable to flip the default to off (in which case, the positive form may become necessary to defeat it).

Note that under "--dry-run" mode, FETCH_HEAD is never written; otherwise you'd see list of objects in the file that you do not actually have.

Passing --write-fetch-head does not force [git fetch](https://github.com/git/git/blob/887952b8c680626f4721cb5fa57704478801aca4/Documentation/git-fetch.txt)<sup>([man](https://git-scm.com/docs/git-fetch))</sup> to write the file.

fetch-options now includes in its man page:

--[no-]write-fetch-head

Write the list of remote refs fetched in the FETCH_HEAD file directly under $GIT_DIR.
This is the default.

Passing --no-write-fetch-head from the command line tells Git not to write the file.
Under --dry-run option, the file is never written.


Consider also, still with Git 2.29 (Q4 2020), the FETCH_HEAD is now always read from the filesystem regardless of the ref backend in use, as its format is much richer than the normal refs, and written directly by "git fetch"(man) as a plain file..

See commit e811530, commit 5085aef, commit 4877c6c, commit e39620f (19 Aug 2020) by Han-Wen Nienhuys (hanwen).
(Merged by Junio C Hamano -- gitster -- in commit 98df75b, 27 Aug 2020)

refs: read FETCH_HEAD and MERGE_HEAD generically

Signed-off-by: Han-Wen Nienhuys

The FETCH_HEAD and MERGE_HEAD refs must be stored in a file, regardless of the type of ref backend. This is because they can hold more than just a single ref.

To accomodate them for alternate ref backends, read them from a file generically in refs_read_raw_ref().


With Git 2.29 (Q4 2020), Updates to on-demand fetching code in lazily cloned repositories.

See commit db3c293 (02 Sep 2020), and commit 9dfa8db, commit 7ca3c0a, commit 5c3b801, commit abcb7ee, commit e5b9421, commit 2b713c2, commit cbe566a (17 Aug 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit b4100f3, 03 Sep 2020)

fetch: no FETCH_HEAD display if --no-write-fetch-head

Signed-off-by: Jonathan Tan

887952b8c6 ("fetch: optionally allow disabling FETCH_HEAD update", 2020-08-18, Git v2.29.0 -- merge listed in batch #10) introduced the ability to disable writing to FETCH_HEAD during fetch, but did not suppress the "<source> -> FETCH_HEAD" message when this ability is used.

This message is misleading in this case, because FETCH_HEAD is not written.

Also, because "fetch" is used to lazy-fetch missing objects in a partial clone, this significantly clutters up the output in that case since the objects to be fetched are potentially numerous.

Therefore, suppress this message when --no-write-fetch-head is passed (but not when --dry-run is set).

Upgrade python without breaking yum

If you want to try out rpm packages, you can install binary packages based on the newest Fedora rpms, but recompiled for RHEL6/CentOS6/ScientificLinux-6 on:

http://www.jur-linux.org/download/el-updates/6/

best regards,

Florian La Roche

Using an if statement to check if a div is empty

You can extend jQuery functionality like this :

Extend :

(function($){
    jQuery.fn.checkEmpty = function() {
       return !$.trim(this.html()).length;
    };
}(jQuery));

Use :

<div id="selector"></div>

if($("#selector").checkEmpty()){
     console.log("Empty");
}else{
     console.log("Not Empty");
}

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

I used Mike Hansen's solution, it is great. I modified his solution in one point, instead of replacing parts of the string I modified the XML-attribute. Maybe it is too much of an effort when you can modify the string but anyway, here is my solution for that. This could easily be further modified to change the table etc. too, which is very nice imho.

What was helpful for me was a helper sub to write the XML to a file so I could check the structure and content of it:

Sub writeStringToFile(strPath As String, strText As String)
    '#### writes a given string into a given filePath, overwriting a document if it already exists
        Dim objStream
        
        Set objStream = CreateObject("ADODB.Stream")
        objStream.Charset = "utf-8"
        objStream.Open
        objStream.WriteText strText
        objStream.SaveToFile strPath, 2
    End Sub

The XML of an/my ImportExportSpecification for a table with 2 columns looks like this:

<?xml version="1.0"?>
<ImportExportSpecification Path="mypath\mydocument.xlsx" xmlns="urn:www.microsoft.com/office/access/imexspec">
    <ImportExcel FirstRowHasNames="true" AppendToTable="myTableName" Range="myExcelWorksheetName">
        <Columns PrimaryKey="{Auto}">
            <Column Name="Col1" FieldName="SomeFieldName" Indexed="NO" SkipColumn="false" DataType="Double"/>
            <Column Name="Col2" FieldName="SomeFieldName" Indexed="NO" SkipColumn="false" DataType="Text"/>
        </Columns>
    </ImportExcel>
</ImportExportSpecification>

Then I wrote a function to modify the path. I left out error-handling here:

Function modifyDataSourcePath(strNewPath As String, strXMLSpec As String) As String
'#### Changes the path-name of an import-export specification
    Dim xDoc As MSXML2.DOMDocument60
    Dim childNodes As IXMLDOMNodeList
    Dim nodeImExSpec As MSXML2.IXMLDOMNode
    Dim childNode As MSXML2.IXMLDOMNode
    Dim attributesImExSpec As IXMLDOMNamedNodeMap
    Dim attributeImExSpec As IXMLDOMAttribute

    
    Set xDoc = New MSXML2.DOMDocument60
    xDoc.async = False: xDoc.validateOnParse = False
    xDoc.LoadXML (strXMLSpec)
    Set childNodes = xDoc.childNodes
 
    For Each childNode In childNodes
           If childNode.nodeName = "ImportExportSpecification" Then
                Set nodeImExSpec = childNode
                Exit For
            End If
    Next childNode
    
    Set attributesImExSpec = nodeImExSpec.Attributes
    
    For Each attributeImExSpec In attributesImExSpec
        If attributeImExSpec.nodeName = "Path" Then
            attributeImExSpec.Value = strNewPath
            Exit For
        End If
    Next attributeImExSpec
    
    modifyDataSourcePath = xDoc.XML
End Function

I use this in Mike's code before the newSpec is executed and instead of the replace statement. Also I write the XML-string into an XML-file in a location relative to the database but that line is optional:

Set myNewSpec = CurrentProject.ImportExportSpecifications.item("TemporaryImport")
    myNewSpec.XML = modifyDataSourcePath(myPath, myNewSpec.XML)
    Call writeStringToFile(Application.CurrentProject.Path & "\impExpSpec.xml", myNewSpec.XML)
    myNewSpec.Execute

ActiveRecord: size vs count

Sometimes size "picks the wrong one" and returns a hash (which is what count would do)

In that case, use length to get an integer instead of hash.

How to add an element to the beginning of an OrderedDict?

EDIT (2019-02-03) Note that the following answer only works on older versions of Python. More recently, OrderedDict has been rewritten in C. In addition this does touch double-underscore attributes which is frowned upon.

I just wrote a subclass of OrderedDict in a project of mine for a similar purpose. Here's the gist.

Insertion operations are also constant time O(1) (they don't require you to rebuild the data structure), unlike most of these solutions.

>>> d1 = ListDict([('a', '1'), ('b', '2')])
>>> d1.insert_before('a', ('c', 3))
>>> d1
ListDict([('c', 3), ('a', '1'), ('b', '2')])

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

Onclick event to remove default value in a text input field

Use onclick="this.value=''":

<input name="Name" value="Enter Your Name" onclick="this.value=''">

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Bootstrap 4, how to make a col have a height of 100%?

Although it is not a good solution but may solve your problem. You need to use position absolute in #yellow element!

_x000D_
_x000D_
#yellow {height: 100%; background: yellow; position: absolute; top: 0px; left: 0px;}_x000D_
.container-fluid {position: static !important;}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<div class="container-fluid">_x000D_
  <div class="row justify-content-center">_x000D_
_x000D_
    <div class="col-4" id="yellow">_x000D_
      XXXX_x000D_
    </div>_x000D_
_x000D_
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">_x000D_
      Form Goes Here_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

List comprehension vs. lambda + filter

This is a somewhat religious issue in Python. Even though Guido considered removing map, filter and reduce from Python 3, there was enough of a backlash that in the end only reduce was moved from built-ins to functools.reduce.

Personally I find list comprehensions easier to read. It is more explicit what is happening from the expression [i for i in list if i.attribute == value] as all the behaviour is on the surface not inside the filter function.

I would not worry too much about the performance difference between the two approaches as it is marginal. I would really only optimise this if it proved to be the bottleneck in your application which is unlikely.

Also since the BDFL wanted filter gone from the language then surely that automatically makes list comprehensions more Pythonic ;-)

filtering a list using LINQ

We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags. So we can use Linq Except to get those tags which are not included. Then we can use Count() == 0 to have only those which excluded no tags:

var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);

Or we can make it slightly faster with by replacing Count() == 0 with !Any():

var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

Well for me the issue was even more annoying, I was using a service within a service and forgot to add it as dependency in the appModule! Hope this helps someone save several hours breaking the app down only to build it back up again

How can I add new array elements at the beginning of an array in Javascript?

Another way to do that through concat

_x000D_
_x000D_
var arr = [1, 2, 3, 4, 5, 6, 7];_x000D_
console.log([0].concat(arr));
_x000D_
_x000D_
_x000D_

The difference between concat and unshift is that concat returns a new array. The performance between them could be found here.

function fn_unshift() {
  arr.unshift(0);
  return arr;
}

function fn_concat_init() {
  return [0].concat(arr)
}

Here is the test result

enter image description here

iterrows pandas get next rows value

a combination of answers gave me a very fast running time. using the shift method to create new column of next row values, then using the row_iterator function as @alisdt did, but here i changed it from iterrows to itertuples which is 100 times faster.

my script is for iterating dataframe of duplications in different length and add one second for each duplication so they all be unique.

# create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
    if row.column_value == row.next_column_value:
         t = t + add_sec
         df_result.at[row.Index, 'column_name'] = t
    else:
         # here i resetting the 'last' and 't' values
         last = row
         t = last[your_column_num]

Hope it will help.

Numpy converting array from float to strings

This is probably slower than what you want, but you can do:

>>> tostring = vectorize(lambda x: str(x))
>>> numpy.where(tostring(phis).astype('float64') != phis)
(array([], dtype=int64),)

It looks like it rounds off the values when it converts to str from float64, but this way you can customize the conversion however you like.

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

How can I toggle word wrap in Visual Studio?

  1. Open the output window.

  2. Look for the little icon on the very right-hand side of the toolbar that starts with the text "Show output from:" in it. It looks like a small window with a carriage return icon. When you hover over it Visual Studio should display "Toggle Word Wrap" near your mouse pointer.

  3. Click that icon.

You now have learned something that was so painfully obvious I feel embarrassed for not knowing this long ago and thus have chosen to pay my dues and share my answer with others so they don't suffer the same agony I have.

Seriously, this is really useful for those with small screens. I have a small Lilliput USB monitor that is good for small tool windows, Skype IM, etc. It works great for putting the output window on, except that it sucks having to always sideways scroll. After just putting up with sideways scroll for months I finally decided to see if I could make it word wrap. The answer was so easy but the amount of time/effort it saves is tremendous.

CSS - Expand float child DIV height to parent's height

I learned of this neat trick in an internship interview. The original question is how do you ensure the height of each top component in three columns have the same height that shows all the content available. Basically create a child component that is invisible that renders the maximum possible height.

<div class="parent">
    <div class="assert-height invisible">
        <!-- content -->
    </div>
    <div class="shown">
        <!-- content -->
    </div>
</div>

How do I run a Java program from the command line on Windows?

You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they're in the same directory

If you're having an issue resulting with "could not find or load main class" you may not have jre in your path. Have a look at this question: Could not find or load main class

How do I change the figure size with subplots?

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

HTML text input field with currency symbol

Use a parent .input-icon div. Optionally add .input-icon-right.

<div class="input-icon">
  <input type="text">
  <i>$</i>
</div>

<div class="input-icon input-icon-right">
  <input type="text">
  <i>€</i>
</div>

Align the icon vertically with transform and top, and set pointer-events to none so that clicks focus on the input. Adjust the padding and width as appropriate:

.input-icon {
  position: relative;
}

.input-icon > i {
  position: absolute;
  display: block;
  transform: translate(0, -50%);
  top: 50%;
  pointer-events: none;
  width: 25px;
  text-align: center;
  font-style: normal;
}

.input-icon > input {
  padding-left: 25px;
  padding-right: 0;
}

.input-icon-right > i {
  right: 0;
}

.input-icon-right > input {
  padding-left: 0;
  padding-right: 25px;
  text-align: right;
}

Unlike the accepted answer, this will retain input validation highlighting, such as a red border when there's an error.

JSFiddle usage example with Bootstrap and Font Awesome

m2eclipse error

in my case there was a dependency without a version. in eclipse m2e does not force you to enter a version so i left it blank. once i put the version in pom.xml from within eclipse all was fine

Send HTML in email via PHP

It is pretty simple, leave the images on the server and send the PHP + CSS to them...

$to = '[email protected]';

$subject = 'Website Change Reqest';

$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$message = '<p><strong>This is strong text</strong> while this is not.</p>';


mail($to, $subject, $message, $headers);

It is this line that tells the mailer and the recipient that the email contains (hopefully) well formed HTML that it will need to interpret:

$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

Here is the link I got the info.. (link...)

You will need security though...

jQuery selector for id starts with specific text

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

Parsing a JSON string in Ruby

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so:

require 'json'
JSON.parse(json_string)

If you’re using an older Ruby, you may need to install the json gem.


There are also other implementations of JSON for Ruby that may fit some use-cases better:

Cannot find Microsoft.Office.Interop Visual Studio

If you're using Visual Studio 2015 and you're encountering this problem, you can install MS Office Developer Tools for VS2015 here.

What is the best way to access redux store outside a react component?

Found a solution. So I import the store in my api util and subscribe to it there. And in that listener function I set the axios' global defaults with my newly fetched token.

This is what my new api.js looks like:

// tooling modules
import axios from 'axios'

// store
import store from '../store'
store.subscribe(listener)

function select(state) {
  return state.auth.tokens.authentication_token
}

function listener() {
  let token = select(store.getState())
  axios.defaults.headers.common['Authorization'] = token;
}

// configuration
const api = axios.create({
  baseURL: 'http://localhost:5001/api/v1',
  headers: {
    'Content-Type': 'application/json',
  }
})

export default api

Maybe it can be further improved, cause currently it seems a bit inelegant. What I could do later is add a middleware to my store and set the token then and there.

What file uses .md extension and how should I edit them?

A .md file stands for a Markdown file extension. A popular app for editing these files is Typora

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

Adding an assets folder in Android Studio

An image of how to in Android Studio 1.5.1.

Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...

enter image description here

Catching FULL exception message

The following worked well for me

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

The result of this is the following as a string instead of an ErrorRecord object

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

$(document).ready not Working

I had copy pasted my inline js from some other .php project, inside that block of code there was some php code outputting some value, now since the variable wasn't defined in my new file, it was producing the typical php undefined warning/error, and because of that the js code was being messed up, and wasn't responding to any event, even alert("xyz"); would fail silently!! Although the erronous line was way near the end of the file, still the js would just die that too,

without any errors!!! >:(

Now one thing confusing is that debugger console/output gave no hint/error/warning whatsoever, the js was dying silently.

So try checking if you have php inline coded with the js, and see if it is outputting any error. Once removed/sorted your js should work fine.

How is the default max Java heap size determined?

The Xms and Xmx are flag of Java virtual machine (JVM):

  • Xms: initial and minimum JVM heap size
    • Format: -Xms<size>[g|G|m|M|k|K]
    • Default Size:
      • -server mode: 25% of free physical memory, >=8MB and <= 64MB
      • -client mode: 25% of free physical memory, >=8MB and <= 16MB
    • Typical Size:
      • -Xms128M
      • -Xms256M
      • -Xms512M
    • Function/Effect:
      • -> JVM start with allocate Xms size memory
  • Xmx: maximum JVM heap size
    • Format: -Xmx<size>[g|G|m|M|k|K]
    • Default Size:
      • <= R27.2
        • Windows: 75% of total physical memory up to 1GB
        • Linux/Solaris: 50% of available physical memory up to 1GB
      • >= R27.3
        • Windows X64: 75% of total physical memory up to 2GB
        • Linux/Solaris X64: 50% of available physical memory up to 2GB
        • Windows x86: 75% of total physical memory up to 1GB
        • Linux/Solaris X86: 50% of available physical memory up to 1GB
    • Typical Size:
      • -Xmx1g
      • -Xmx2084M
      • -Xmx4g
      • -Xmx6g
      • -Xmx8g
    • Function/Effect:
      • -> JVM allow use maxium of Xmx size memory
        • when exceed Xmx, will java.lang.OutOfMemoryError
          • How to fix OutOfMemoryError ?
            • exceed Xmx value
              • eg: from -Xmx4g to -Xmx8g

More detail

see official doc: -X Command-line Options

How to convert string to float?

Use atof() or strtof()* instead:

printf("float value : %4.8f\n" ,atof(s)); 
printf("float value : %4.8f\n" ,strtof(s, NULL)); 

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
http://www.cplusplus.com/reference/cstdlib/strtof/

  • atoll() is meant for integers.
  • atof()/strtof() is for floats.

The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit.

*Note that strtof() requires C99 or C++11.

Android Layout Animations from bottom to top and top to bottom on ImageView click

Try this :

Create anim folder inside your res folder and copy this four files :

slide_in_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>  

slide_out_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0" 
android:duration="@android:integer/config_longAnimTime" /> 

slide_in_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
 android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />

slide_out_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />

When you click on image view call:

overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);

When you click on original place call:

overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);

Main Activity :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1 = (Button) findViewById(R.id.btn1);


    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, test.class));

        }
    });


}
    }

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

test.java :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class test extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    btn1 = (Button) findViewById(R.id.btn1);

    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
         finish();
            overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_right);
            startActivity(new Intent(test.this, MainActivity.class));


        }
    });
}

    }

test.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

Hope this helps.

Browser Caching of CSS files

It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.

Undo a merge by pull request?

Look at your commit graph (with gitk or a similar program). You will see commits from the pull request, and you will see your own commits, and a merge commit (if it was not a fast-forward merge). You just have to find the last of your own commits before the merge, and reset the branch to this commit.

(If you have the branch's reflog, it should be even easier to find the commit before the merge.)


(Edit after more information in comments:)

Okay, lets look at the graph:

screenshot 1

I assume the last (rightmost) commit was your wrong merge by pull request, which merged the blue line seen here. Your last good commit would be the one before on the black line, here marked in red:

enter image description here

Reset to this commit, and you should be fine.

This means, in your local working copy do this (after making sure you have no more uncommitted stuff, for example by git stash):

git checkout master
git reset --hard 7a62674ba3df0853c63539175197a16122a739ef
gitk 

Now confirm that you are really on the commit I marked there, and you will see none of the pulled stuff in its ancestry.

git push -f origin master

(if your github remote is named origin - else change the name).

Now everything should look right on github, too. The commits will still be in your repository, but not reachable by any branch, thus should not do any harm there. (And they will be still on RogerPaladin's repository, of course.)

(There might be a Github specific web-only way of doing the same thing, but I'm not too familiar with Github and its pull request managing system.)

Note that if anyone else already might have pulled your master with the wrong commit, they then have the same problem as you currently have, and can't really contribute back. before resetting to your new master version.

If it is likely that this happened, or you simply want to avoid any problems, use the git revert command instead of git reset, to revert the changes with a new commit, instead of setting back to an older one. (Some people think you should never do reset with published branches.) See other answers to this question on how to do this.

For the future:

If you want only some of the commits of RogerPaladin's branch, consider using cherry-pick instead of merge. Or communicate to RogerPaladin to move them to a separate branch and send a new pull request.

How to start anonymous thread class

Add: now you can use lambda to simplify your syntax. Requirement: Java 8+

public class A {
    public static void main(String[] arg)
    {
        Thread th = new Thread(() -> {System.out.println("blah");});
        th.start();
    }
}

Angularjs how to upload multipart form data and a file?

First of all

  1. You don't need any special changes in the structure. I mean: html input tags.

_x000D_
_x000D_
<input accept="image/*" name="file" ng-value="fileToUpload"_x000D_
       value="{{fileToUpload}}" file-model="fileToUpload"_x000D_
       set-file-data="fileToUpload = value;" _x000D_
       type="file" id="my_file" />
_x000D_
_x000D_
_x000D_

1.2 create own directive,

_x000D_
_x000D_
.directive("fileModel",function() {_x000D_
 return {_x000D_
  restrict: 'EA',_x000D_
  scope: {_x000D_
   setFileData: "&"_x000D_
  },_x000D_
  link: function(scope, ele, attrs) {_x000D_
   ele.on('change', function() {_x000D_
    scope.$apply(function() {_x000D_
     var val = ele[0].files[0];_x000D_
     scope.setFileData({ value: val });_x000D_
    });_x000D_
   });_x000D_
  }_x000D_
 }_x000D_
})
_x000D_
_x000D_
_x000D_

  1. In module with $httpProvider add dependency like ( Accept, Content-Type etc) with multipart/form-data. (Suggestion would be, accept response in json format) For e.g:

$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';

  1. Then create separate function in controller to handle form submit call. like for e.g below code:

  2. In service function handle "responseType" param purposely so that server should not throw "byteerror".

  3. transformRequest, to modify request format with attached identity.

  4. withCredentials : false, for HTTP authentication information.

_x000D_
_x000D_
in controller:_x000D_
_x000D_
  // code this accordingly, so that your file object _x000D_
  // will be picked up in service call below._x000D_
  fileUpload.uploadFileToUrl(file); _x000D_
_x000D_
_x000D_
in service:_x000D_
_x000D_
  .service('fileUpload', ['$http', 'ajaxService',_x000D_
    function($http, ajaxService) {_x000D_
_x000D_
      this.uploadFileToUrl = function(data) {_x000D_
        var data = {}; //file object _x000D_
_x000D_
        var fd = new FormData();_x000D_
        fd.append('file', data.file);_x000D_
_x000D_
        $http.post("endpoint server path to whom sending file", fd, {_x000D_
            withCredentials: false,_x000D_
            headers: {_x000D_
              'Content-Type': undefined_x000D_
            },_x000D_
            transformRequest: angular.identity,_x000D_
            params: {_x000D_
              fd_x000D_
            },_x000D_
            responseType: "arraybuffer"_x000D_
          })_x000D_
          .then(function(response) {_x000D_
            var data = response.data;_x000D_
            var status = response.status;_x000D_
            console.log(data);_x000D_
_x000D_
            if (status == 200 || status == 202) //do whatever in success_x000D_
            else // handle error in  else if needed _x000D_
          })_x000D_
          .catch(function(error) {_x000D_
            console.log(error.status);_x000D_
_x000D_
            // handle else calls_x000D_
          });_x000D_
      }_x000D_
    }_x000D_
  }])
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
_x000D_
_x000D_

Add item to array in VBScript

Based on Charles Clayton's answer, but slightly simplified...

' add item to array
Sub ArrayAdd(arr, val)
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = val
End Sub

Used like so

a = Array()
AddItem(a, 5)
AddItem(a, "foo")

ASP.Net MVC: Calling a method from a view

You should create custom helper for just changing string format except using controller call.

Can I change the scroll speed using css or jQuery?

Just use this js file. (I mentioned 2 examples with different js files. hope the second one is what you need) You can simply change the scroll amount, speed etc by changing the parameters.

https://github.com/nathco/jQuery.scrollSpeed

Here's a Demo

You can also try this. Here's a demo

How to add google-services.json in Android?

  1. Download the "google-service.json" file from Firebase
  2. Go to this address in windows explorer "C:\Users\Your-Username\AndroidStudioProjects" You will see a list of your Android Studio projects
  3. Open a desired project, navigate to "app" folder and paste the .json file
  4. Go to Android Studio and click on "Sync with file system", located in dropdown menu (File>Sync with file system)
  5. Now sync with Gradle and everything should be fine

Using %s in C correctly - very basic level

%s will get all the values until it gets NULL i.e. '\0'.

char str1[] = "This is the end\0";
printf("%s",str1);

will give

This is the end

char str2[] = "this is\0 the end\0";
printf("%s",str2);

will give

this is

how to properly display an iFrame in mobile safari

<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" src="url" />
</div>

I'm building my first site and this helped me get this working for all sites that I use iframe embededding for.

Thanks!

How do you get AngularJS to bind to the title attribute of an A tag?

Sometimes it is not desirable to use interpolation on title attribute or on any other attributes as for that matter, because they get parsed before the interpolation takes place. So:

<!-- dont do this -->
<!-- <a title="{{product.shortDesc}}" ...> -->

If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute. This allows you to bind to attributes that would otherwise be eagerly processed by browsers. The attribute will be set only when the binding is done. The prefix is then removed:

<!-- do this -->
<a ng-attr-title="{{product.shortDesc}}" ...>

(Ensure that you are not using a very earlier version of Angular). Here's a demo fiddle using v1.2.2:

Fiddle

SQL Query to fetch data from the last 30 days?

SELECT productid FROM product WHERE purchase_date > sysdate-30

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Import and Export Excel - What is the best library?

Check the ExcelPackage project, it uses the Office Open XML file format of Excel 2007, it's lightweight and open source...

Check if string contains a value in array

If your $string is always consistent (ie. the domain name is always at the end of the string), you can use explode() with end(), and then use in_array() to check for a match (as pointed out by @Anand Solanki in their answer).

If not, you'd be better off using a regular expression to extract the domain from the string, and then use in_array() to check for a match.

$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);

if (empty($matches[1])) {
  // no domain name was found in $string
} else {
  if (in_array($matches[1], $owned_urls)) {
    // exact match found
  } else {
    // exact match not found
  }
}

The expression above could probably be improved (I'm not particularly knowledgeable in this area)

Here's a demo

How do I clear the std::queue efficiently?

I'd rather not rely on swap() or setting the queue to a newly created queue object, because the queue elements are not properly destroyed. Calling pop()invokes the destructor for the respective element object. This might not be an issue in <int> queues but might very well have side effects on queues containing objects.

Therefore a loop with while(!queue.empty()) queue.pop();seems unfortunately to be the most efficient solution at least for queues containing objects if you want to prevent possible side effects.

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;
}

#header {
    position: relative;
    height: 50px;
    padding: 10px;
}

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Update

Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;
}

Here's a post talking about how box-sizing works.

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

How to run python script with elevated privilege on windows

Here is a solution which needed ctypes module only. Support pyinstaller wrapped program.

#!python
# coding: utf-8
import sys
import ctypes

def run_as_admin(argv=None, debug=False):
    shell32 = ctypes.windll.shell32
    if argv is None and shell32.IsUserAnAdmin():
        return True

    if argv is None:
        argv = sys.argv
    if hasattr(sys, '_MEIPASS'):
        # Support pyinstaller wrapped program.
        arguments = map(unicode, argv[1:])
    else:
        arguments = map(unicode, argv)
    argument_line = u' '.join(arguments)
    executable = unicode(sys.executable)
    if debug:
        print 'Command line: ', executable, argument_line
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
    if int(ret) <= 32:
        return False
    return None


if __name__ == '__main__':
    ret = run_as_admin()
    if ret is True:
        print 'I have admin privilege.'
        raw_input('Press ENTER to exit.')
    elif ret is None:
        print 'I am elevating to admin privilege.'
        raw_input('Press ENTER to exit.')
    else:
        print 'Error(ret=%d): cannot elevate privilege.' % (ret, )

Datagrid binding in WPF

try to do this in the behind code

   public diagboxclass()
   {
         List<object> list = new List<object>();
         list = GetObjectList();
         Imported.ItemsSource = null;
         Imported.ItemsSource = list;
   }

Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.

Assign a synthesizable initial value to a reg in Verilog

The always @* would never trigger as no Right hand arguments change. Why not use a wire with assign?

module top (
    input wire clk,
    output wire [7:0] led   
);

wire [7:0] data_reg ; 
assign data_reg   = 8'b10101011;
assign led        = data_reg;

endmodule

If you actually want a flop where you can change the value, the default would be in the reset clause.

module top
(
    input        clk,
    input        rst_n,
    input  [7:0] data,
    output [7:0] led   
 );

reg [7:0] data_reg ; 
always @(posedge clk or negedge rst_n) begin
  if (!rst_n)
    data_reg <= 8'b10101011;
  else
    data_reg <= data ; 
end

assign led = data_reg;

endmodule

Hope this helps

Simple java program of pyramid

This code will print a pyramid of dollars.

public static void main(String[] args) {

     for(int i=0;i<5;i++) {
         for(int j=0;j<5-i;j++) {
             System.out.print(" ");
         }
        for(int k=0;k<=i;k++) {
            System.out.print("$ ");
        }
        System.out.println();  
    }

}

OUPUT :

     $ 
    $ $ 
   $ $ $ 
  $ $ $ $ 
 $ $ $ $ $

How to print a dictionary's key?

# highlighting how to use a named variable within a string:
mapping = {'a': 1, 'b': 2}

# simple method:
print(f'a: {mapping["a"]}')
print(f'b: {mapping["b"]}')

# programmatic method:
for key, value in mapping.items():
    print(f'{key}: {value}')

# yields:
# a 1
# b 2

# using list comprehension
print('\n'.join(f'{key}: {value}' for key, value in dict.items()))


# yields:
# a: 1
# b: 2

Edit: Updated for python 3's f-strings...

AngularJS/javascript converting a date String to date object

I know this is in the above answers, but my point is that I think all you need is

new Date(collectionDate);

if your goal is to convert a date string into a date (as per the OP "How do I convert it to a date object?").

Accessing variables from other functions without using global variables

What you're looking for is technically known as currying.

function getMyCallback(randomValue)
{
    return function(otherParam)
    {
        return randomValue * otherParam //or whatever it is you are doing.
    }

}

var myCallback = getMyCallBack(getRand())

alert(myCallBack(1));
alert(myCallBack(2));

The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.

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

Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.

example

=SUMIF(A2:A100,"=January",B2:B100)

Why would I use dirname(__FILE__) in an include or include_once statement?

I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:

Project root directory:
                       file1.php
                       file3.php
                       dir1/
                            file2.php

(dir1 is a directory and file2.php is inside it)

And this is the content of each of the three files above:

//file1.php:
<?php include "dir1/file2.php"

//file2.php:
<?php include "../file3.php"

//file3.php:
<?php echo "Hello, Test!";

Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!

The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).

Now, what should we do ?!

Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!

So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!

The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!

So now if we turn the project above to this:

//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");

//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");

//file3.php:
<?php echo "Hello, Test!";

if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).

It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!

Hope that helps.

Simple way to find if two different lists contain exactly the same elements?

If you're using (or are happy to use) Apache Commons Collections, you can use CollectionUtils.isEqualCollection which "returns true iff the given Collections contain exactly the same elements with exactly the same cardinalities."

What's the difference between "Layers" and "Tiers"?

Why always trying to use complex words?

A layer = a part of your code, if your application is a cake, this is a slice.

A tier = a physical machine, a server.

A tier hosts one or more layers.


Example of layers:

  • Presentation layer = usually all the code related to the User Interface
  • Data Access layer = all the code related to your database access

Tier:

Your code is hosted on a server = Your code is hosted on a tier.

Your code is hosted on 2 servers = Your code is hosted on 2 tiers.

For example, one machine hosting the Web Site itself (the Presentation layer), another machine more secured hosting all the more security sensitive code (real business code - business layer, database access layer, etc.).


There are so many benefits to implement a layered architecture. This is tricky and properly implementing a layered application takes time. If you have some, have a look at this post from Microsoft: http://msdn.microsoft.com/en-gb/library/ee658109.aspx

Get the filename of a fileupload in a document through JavaScript

RaYell, You don't need to parse the value returned. document.getElementById("FileUpload1").value returns only the file name with extension. This was useful for me because I wanted to copy the name of the file to be uploaded to an input box called 'title'. In my application, the uploaded file is renamed to the index generated by the backend database and the title is stored in the database.

How to remove duplicate white spaces in string using Java?

Like this:

yourString = yourString.replaceAll("\\s+", " ");

For example

System.out.println("lorem  ipsum   dolor \n sit.".replaceAll("\\s+", " "));

outputs

lorem ipsum dolor sit.

What does that \s+ mean?

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.


Source: Java: Removing duplicate white spaces in strings

Full width layout with twitter bootstrap

Because the accepted answer isn't on the same planet as BS3, I'll share what I'm using to achieve nearly full-width capabilities.

First off, this is cheating. It's not really fluid width - but it appears to be - depending on the size of the screen viewing the site.

The problem with BS3 and fluid width sites is that they have taken this "mobile first" approach, which requires that they define every freaking screen width up to what they consider to be desktop (1200px) I'm working on a laptop with a 1900px wide screen - so I end up with 350px on either side of the content at what BS3 thinks is a desktop sized width.

They have defined 10 screen widths (really only 5, but anyway). I don't really feel comfortable changing those, because they are common widths. So, I chose to define some extra widths for BS to choose from when deciding the width of the container class.

The way I use BS is to take all of the Bootstrap provided LESS files, omit the variables.less file to provide my own, and add one of my own to the end to override the things I want to change. Within my less file, I add the following to achieve 2 common screen width settings:

@media screen and (min-width: 1600px) {
    .container {
        max-width: (1600px - @grid-gutter-width);
    }
}
@media screen and (min-width: 1900px) {
    .container {
        max-width: (1900px - @grid-gutter-width);
    }
}

These two settings set the example for what you need to do to achieve different screen widths. Here, you get full width at 1600px, and 1900px. Any less than 1600 - BS falls back to the 1200px width, then to 768px and so forth - down to phone size.

If you have larger to support, just create more @media screen statements like these. If you're building the CSS instead, you'll want to determine what gutter width was used and subtract it from your target screen width.

Update:

Bootstrap 3.0.1 and up (so far) - it's as easy as setting @container-large-desktop to 100%

docker: executable file not found in $PATH

A Docker container might be built without a shell (e.g. https://github.com/fluent/fluent-bit-docker-image/issues/19).

In this case, you can copy-in a statically compiled shell and execute it, e.g.

docker create --name temp-busybox busybox:1.31.0
docker cp temp-busybox:/bin/busybox busybox
docker cp busybox mycontainerid:/busybox
docker exec -it mycontainerid /bin/busybox sh

Set session variable in laravel

In Laravel 6.x

// Retrieve a piece of data from the session...
$value = session('key');

// Specifying a default value...
$value = session('key', 'default');

// Store a piece of data in the session...
session(['key' => 'value']);

https://laravel.com/docs/6.x/session

C# DateTime.ParseExact

Your format string is wrong. Change it to

insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);

How to get the date 7 days earlier date from current date in Java

For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.

How do I get which JRadioButton is selected from a ButtonGroup

The following code displays which JRadiobutton is selected from Buttongroup on click of a button.
It is done by looping through all JRadioButtons in a particular buttonGroup.

 JRadioButton firstRadioButton=new JRadioButton("Female",true);  
 JRadioButton secondRadioButton=new JRadioButton("Male");  

 //Create a radio button group using ButtonGroup  
 ButtonGroup btngroup=new ButtonGroup();  

 btngroup.add(firstRadioButton);  
 btngroup.add(secondRadioButton);  

 //Create a button with text ( What i select )  
 JButton button=new JButton("What i select");  

 //Add action listener to created button  
 button.addActionListener(this);  

 //Get selected JRadioButton from ButtonGroup  
  public void actionPerformed(ActionEvent event)  
  {  
     if(event.getSource()==button)  
     {  
        Enumeration<AbstractButton> allRadioButton=btngroup.getElements();  
        while(allRadioButton.hasMoreElements())  
        {  
           JRadioButton temp=(JRadioButton)allRadioButton.nextElement();  
           if(temp.isSelected())  
           {  
            JOptionPane.showMessageDialog(null,"You select : "+temp.getText());  
           }  
        }            
     }
  }

php static function

Simply, static functions function independently of the class where they belong.

$this means, this is an object of this class. It does not apply to static functions.

class test {
    public function sayHi($hi = "Hi") {
        $this->hi = $hi;
        return $this->hi;
    }
}
class test1 {
    public static function sayHi($hi) {
        $hi = "Hi";
        return $hi;
    }
}

//  Test
$mytest = new test();
print $mytest->sayHi('hello');  // returns 'hello'
print test1::sayHi('hello');    //  returns 'Hi'

How to prevent a click on a '#' link from jumping to top of page?

In jQuery, when you handle the click event, return false to stop the link from responding the usual way prevent the default action, which is to visit the href attribute, from taking place (per PoweRoy's comment and Erik's answer):

$('a.someclass').click(function(e)
{
    // Special stuff to do when this link is clicked...

    // Cancel the default action
    e.preventDefault();
});

detect key press in python?

As OP mention about raw_input - that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.

This code will detect keys until new line is pressed.

import curses
import os

def main(win):
    win.nodelay(True)
    key=""
    win.clear()                
    win.addstr("Detected key:")
    while 1:          
        try:                 
           key = win.getkey()         
           win.clear()                
           win.addstr("Detected key:")
           win.addstr(str(key)) 
           if key == os.linesep:
              break           
        except Exception as e:
           # No input   
           pass         

curses.wrapper(main)

'cannot find or open the pdb file' Visual Studio C++ 2013

Try go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.

PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for.[...]

See Cannot find or open the PDB file in Visual Studio C++ 2010

The project cannot be built until the build path errors are resolved.

In Eclipse this worked for me: right click project. -> Properties -> Library Section; Add (any library at all) -> select library and click remove -> press okay.

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Issue: The Jet OLE DB provider reads a registry key to determine how many rows are to be read to guess the type of the source column. By default, the value for this key is 8. Hence, the provider scans the first 8 rows of the source data to determine the data types for the columns. If any field looks like text and the length of data is more than 255 characters, the column is typed as a memo field. So, if there is no data with a length greater than 255 characters in the first 8 rows of the source, Jet cannot accurately determine the nature of the data type. As the first 8 row length of data in the exported sheet is less than 255 its considering the source length as VARCHAR(255) and unable to read data from the column having more length.

Fix: The solution is just to sort the comment column in descending order. In 2012 onwards we can update the values in Advance tab in the Import wizard.

How can I do a line break (line continuation) in Python?

From the horse's mouth: Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

Split string into array

You can try this:

var entryArray = Array.prototype.slice.call(entry)

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

Hello World in Python

In python 3.x. you use

print("Hello, World")

In Python 2.x. you use

print "Hello, World!"

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

This might happen if you place .cs files in App_Code and changed their build action to compile in a Web Application Project.

Either have the build action for the .cs files in App_Code as Content or change the name of App_Code to something else. I changed the name since intellisense won't fix .cs files marked as content.

More info at http://vishaljoshi.blogspot.se/2009/07/appcode-folder-doesnt-work-with-web.html

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

HTML favicon won't show on google chrome

These are the locations where browsers store the Temporary data in Linux:

Note: you can see hidden files in File Manager using Ctrl + H

for Terminal use the command ls -la

Chromium

~/.cache/chromium/[profile]/Cache/

Google Chrome

~/.cache/google-chrome/[profile]/Cache/

Also, Chromium and Google Chrome store some additional cache at

~/.config/chromium/[profile]/Application Cache/Cache/ 

and

~/.config/google-chrome/[profile]/Application Cache/Cache/

and generally here:

/tmp/

so to apply new FAVICON or try to show it up is to clean them

make sure u are inside each of these directories use the command:

rm -rf *

Printing result of mysql query from variable

This will print out the query:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());
print $query;

This will print out the results:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($dave)){
    foreach($row as $cname => $cvalue){
        print "$cname: $cvalue\t";
    }
    print "\r\n";
}

Java 8 lambda Void argument

That is not possible. A function that has a non-void return type (even if it's Void) has to return a value. However you could add static methods to Action that allows you to "create" a Action:

interface Action<T, U> {
   U execute(T t);

   public static Action<Void, Void> create(Runnable r) {
       return (t) -> {r.run(); return null;};
   }

   public static <T, U> Action<T, U> create(Action<T, U> action) {
       return action;
   } 
}

That would allow you to write the following:

// create action from Runnable
Action.create(()-> System.out.println("Hello World")).execute(null);
// create normal action
System.out.println(Action.create((Integer i) -> "number: " + i).execute(100));

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

Is it possible to validate the size and type of input=file in html5

    <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>
    <script>
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more then' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct- '+fileSize+' bytes');
            }
        }else{
            alert('choose file, please');
            return false;
        }

    });
});
    </script>

http://jsfiddle.net/9bhcB/2/

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

I got this error but it is resolved interesting. As first, i got this error at api level 17. When i call a thread (AsyncTask or others) without progress dialog then i call an other thread method again using progress dialog, i got that crash and the reason is about usage of progress dialog.

In my case, there are two results that;

  • I took show(); method of progress dialog before first thread starts then i took dismiss(); method of progress dialog before last thread ends.

So :

ProgresDialog progressDialog = new ...

//configure progressDialog 

progressDialog.show();

start firstThread {
...
}

...

start lastThread {
...
} 

//be sure to finish threads

progressDialog.dismiss();
  • This is so strange but that error has an ability about destroy itself at least for me :)

For-loop vs while loop in R

The variable in the for loop is an integer sequence, and so eventually you do this:

> y=as.integer(60000)*as.integer(60000)
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

whereas in the while loop you are creating a floating point number.

Its also the reason these things are different:

> seq(0,2,1)
[1] 0 1 2
> seq(0,2)
[1] 0 1 2

Don't believe me?

> identical(seq(0,2),seq(0,2,1))
[1] FALSE

because:

> is.integer(seq(0,2))
[1] TRUE
> is.integer(seq(0,2,1))
[1] FALSE

How to get the index of an element in an IEnumerable?

I'd question the wisdom, but perhaps:

source.TakeWhile(x => x != value).Count();

(using EqualityComparer<T>.Default to emulate != if needed) - but you need to watch to return -1 if not found... so perhaps just do it the long way

public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
    int index = 0;
    var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
    foreach (T item in source)
    {
        if (comparer.Equals(item, value)) return index;
        index++;
    }
    return -1;
}

How to find my php-fpm.sock?

I encounter this issue when I first run LEMP on centos7 refer to this post.

I restart nginx to test the phpinfo page, but get this

http://xxx.xxx.xxx.xxx/info.php is not unreachable now.

Then I use tail -f /var/log/nginx/error.log to see more info. I find is the php-fpm.sock file not exist. Then I reboot the system, everything is OK.

Here may not need to reboot the system as Fath's post, just reload nginx and php-fpm.

restart php-fpm

reload nginx config

docker error - 'name is already in use by container'

Ok, so I didn't understand either, then I left my pc, went to do other things, and upon my return, it clicked :D

  1. You download a docker image file. docker pull *image-name* will just pull the image from docker hub without running it.

  2. Now, you use docker run, and give it a name (e.g. newWebServer).

    docker run -d -p 8080:8080 -v volume --name newWebServer image-name/version

You perhaps only need docker run --name *name* *image*, but the other stuff will become useful quickly.

-d (detached) - means the container will exit when the root process used to run the container exits.

-p (port) - specify the container port and the host port. Kind of the internal and external port. The internal one being the port the container uses, and the external one is the port you use outside of it and probably the one you need to put in your web browser if that's how you access your app.

--name (what you want to call this instance of the container) - you could have several instances of the same container all with different names, which is useful when you're trying to test something.

image-name/version is the actual image you want to create the container from. You can see a list of all the images on your system with docker images -a. You may have more than one version, so make sure you choose the correct one/tag.

-v (volume) - perhaps not needed initially, but soon you'll want to persist data after your container exits.

OK. So now, docker run just created a container from your image. If it isn't running, you can now start it with it's name:

docker start newWebServer

You can check all your containers (they may or may not be running) with

docker ps -a

You can stop and start them (or pause them) with their name or the container id (or just the first few characters of it) from the CONTAINER ID column e.g:

docker stop newWebServer

docker start c3028a89462c

And list all your images, with

docker images -a

In a nutshell, download an image; docker run creates a container from it; start it with docker start (name or container id); stop it with docker stop (name or container id).

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

My answer might not be solution to your question but it will surely help others looking for similar issue like this one: javax.net.ssl.SSLHandshakeException: Chain validation failed

You just need to check your Android Device's Date and Time, it should be fix the issue. This resoled my problem.

"Parse Error : There is a problem parsing the package" while installing Android application

Similar issue, using this "borrowed" and slightly modified code:

                Intent intent = new Intent(Intent.ACTION_VIEW);
                File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "myapp.apk");
                intent.setDataAndType(Uri.fromFile(newApk), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                result = true;

Needed to change the file creation to this (comma instead of plus in the File constructor, was missing '/' after the download directory):

                    File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "myapp.apk");

JavaFX Application Icon

If you have have a images folder and the icon is saved in that use this

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/images/comparison.png")));

and if you are directly using it from your package which is not a good practice use this

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("comparison.png")));

and if you have a folder structure and you have your icon inside that use

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("../images/comparison.png")));

Cannot find or open the PDB file in Visual Studio C++ 2010

I ran into a similar problem where Visual Studio (2017) said it could not find my project's PDB file. I could see the PDB file did exist in the correct path. I had to Clean and Rebuild the project, then Visual Studio recognized the PDB file and debugging worked.

Npm Please try using this command again as root/administrator

For those doing this on a MAC. Simply put sudo in front of the command. It will ask you for your password and then run fine. Cheers

Init function in javascript and how it works

Self invoking anonymous function (SIAF)

Self-invoking functions runs instantly, even if DOM isn't completely ready.

jQuery document.ready vs self calling anonymous function

Can I restore a single table from a full mysql mysqldump file?

You should try @bryn command but with the ` delimiter otherwise you will also extract the tables having a prefix or a suffix, this is what I usually do:

sed -n -e '/DROP TABLE.*`mytable`/,/UNLOCK TABLES/p' dump.sql > mytable.sql

Also for testing purpose, you may want to change the table name before importing:

sed -n -e 's/`mytable`/`mytable_restored`/g' mytable.sql > mytable_restored.sql

To import you can then use the mysql command:

mysql -u root -p'password' mydatabase < mytable_restore.sql

Oracle Convert Seconds to Hours:Minutes:Seconds

Unfortunately not... However, there's a simple trick if it's going to be less than 24 hours.

Oracle assumes that a number added to a date is in days. Convert the number of seconds into days. Add the current day, then use the to_date function to take only the parts your interested in. Assuming you have x seconds:

select to_char(sysdate + (x / ( 60 * 60 * 24 ) ), 'HH24:MI:SS')
  from dual

This won't work if there's more than 24 hours, though you can remove the current data again and get the difference in days, hours, minutes and seconds.

If you want something like: 51:10:05, i.e. 51 hours, 10 minutes and 5 seconds then you're going to have to use trunc.

Once again assuming that you have x seconds...

  • The number of hours is trunc(x / 60 / 60)
  • The number of minutes is trunc((x - ( trunc(x / 60 / 60) * 60 * 60 )) / 60)
  • The number of seconds is therefore the x - hours * 60 * 60 - minutes * 60

Leaving you with:

with hrs as (
  select x, trunc(x / 60 / 60) as h
    from dual
         )
 , mins as (
  select x, h, trunc((x - h * 60 * 60) / 60) as m
    from hrs
         )
select h, m, x - (h * 60 * 60) - (m * 60)
  from mins

I've set up a SQL Fiddle to demonstrate.

How does Trello access the user's clipboard?

Daniel LeCheminant's code didn't work for me after converting it from CoffeeScript to JavaScript (js2coffee). It kept bombing out on the _.defer() line.

I assumed this was something to do with jQuery deferreds, so I changed it to $.Deferred() and it's working now. I tested it in Internet Explorer 11, Firefox 35, and Chrome 39 with jQuery 2.1.1. The usage is the same as described in Daniel's post.

var TrelloClipboard;

TrelloClipboard = new ((function () {
    function _Class() {
        this.value = "";
        $(document).keydown((function (_this) {
            return function (e) {
                var _ref, _ref1;
                if (!_this.value || !(e.ctrlKey || e.metaKey)) {
                    return;
                }
                if ($(e.target).is("input:visible,textarea:visible")) {
                    return;
                }
                if (typeof window.getSelection === "function" ? (_ref = window.getSelection()) != null ? _ref.toString() : void 0 : void 0) {
                    return;
                }
                if ((_ref1 = document.selection) != null ? _ref1.createRange().text : void 0) {
                    return;
                }
                return $.Deferred(function () {
                    var $clipboardContainer;
                    $clipboardContainer = $("#clipboard-container");
                    $clipboardContainer.empty().show();
                    return $("<textarea id='clipboard'></textarea>").val(_this.value).appendTo($clipboardContainer).focus().select();
                });
            };
        })(this));

        $(document).keyup(function (e) {
            if ($(e.target).is("#clipboard")) {
                return $("#clipboard-container").empty().hide();
            }
        });
    }

    _Class.prototype.set = function (value) {
        this.value = value;
    };

    return _Class;

})());

Is using 'var' to declare variables optional?

Check out this Fiddle: http://jsfiddle.net/GWr6Z/2/

function doMe(){

a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+"  --  b:"+b);

b = "something else"; // still local (not global)
alert("a:"+a+"  --  b:"+b);

};


doMe()
alert("a:"+a+"  --  b:"+b); // `b` will not be defined, check console.log

Parsing string as JSON with single quotes?

The JSON standard requires double quotes and will not accept single quotes, nor will the parser.

If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

R: Select values from data table in range

Construct some data

df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )

Extract exact matches:

subset(df, date==3)

  name date
1 John    3

Extract matches in range:

subset(df, date>4 & date<6)

  name date
2 Adam    5

The following syntax produces identical results:

df[df$date>4 & df$date<6, ]

  name date
2 Adam    5

How does Spring autowire by name when more than one matching bean is found?

You can use the @Qualifier annotation

From here

Fine-tuning annotation-based autowiring with qualifiers

Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:

class Main {
    private Country country;
    @Autowired
    @Qualifier("country")
    public void setCountry(Country country) {
        this.country = country;
    }
}

This will use the UK add an id to USA bean and use that if you want the USA.

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

How does one use the onerror attribute of an img element

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

JavaScript/jQuery doesn't support the default behavior of links "clicked" programmatically.

Instead, you can create a form and submit it. This way you don't have to use window.location or window.open, which are often blocked as unwanted popups by browsers.

This script has two different methods: one that tries to open three new tabs/windows (it opens only one in Internet Explorer and Chrome, more information is below) and one that fires a custom event on a link click.

Here is how:

HTML

<html>
<head>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="script.js" type="text/javascript"></script>
</head>

<body>
    <button id="testbtn">Test</button><br><br>

    <a href="https://google.nl">Google</a><br>
    <a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a><br>
    <a href="https://stackoverflow.com/">Stack Overflow</a>
</body>

</html>

jQuery (file script.js)

$(function()
{
    // Try to open all three links by pressing the button
    // - Firefox opens all three links
    // - Chrome only opens one of them without a popup warning
    // - Internet Explorer only opens one of them WITH a popup warning
    $("#testbtn").on("click", function()
    {
        $("a").each(function()
        {
            var form = $("<form></form>");
            form.attr(
            {
                id     : "formform",
                action : $(this).attr("href"),
                method : "GET",
                // Open in new window/tab
                target : "_blank"
            });

            $("body").append(form);
            $("#formform").submit();
            $("#formform").remove();
        });
    });

    // Or click the link and fire a custom event
    // (open your own window without following 
    // the link itself)
    $("a").on("click", function()
    {
        var form = $("<form></form>");
        form.attr(
        {
            id     : "formform",
            // The location given in the link itself
            action : $(this).attr("href"),
            method : "GET",
            // Open in new window/tab
            target : "_blank"
        });

        $("body").append(form);
        $("#formform").submit();
        $("#formform").remove();

        // Prevent the link from opening normally
        return false;
    });
});

For each link element, it:

  1. Creates a form
  2. Gives it attributes
  3. Appends it to the DOM so it can be submitted
  4. Submits it
  5. Removes the form from the DOM, removing all traces *Insert evil laugh*

Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).


More information on how I got to this method is found here:

Python: "TypeError: __str__ returned non-string" but still prints to output?

The problem that you are facing is : TypeError : str returned non-string (type NoneType)

Here you have to understand the str function's working: the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one. In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used. This was the explaination for your error

You can solve this problem by using the return in str function like: *simply returnig the string value instead of printing it

 class Summary(models.Model):
   book = models.ForeignKey(Book,on_delete = models.CASCADE)
   summary = models.TextField(max_length=600)

    def __str__(self):
        return self.summary

but if the value you are returning in not of string type then you can do like this to return string value from your str function

*typeconverting the value to string that your str function returns

class Summary(models.Model):
   book = models.ForeignKey(Book,on_delete = models.CASCADE)
   summary = models.TextField(max_length=600)

   def __str__(self):
       return str(self.summary)
            `

Memory address of an object in C#

Instead of this code, you should call GetHashCode(), which will return a (hopefully-)unique value for each instance.

You can also use the ObjectIDGenerator class, which is guaranteed to be unique.

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

How can you debug a CORS request with cURL?

The bash script "corstest" below works for me. It is based on Jun's comment above.

usage

corstest [-v] url

examples

./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *

the positive result is displayed in green

./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS

the negative result is displayed in red and blue

the -v option will show the full curl headers

corstest

#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'  
red='\033[0;31m'  
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# show the usage
#
usage() {
  echo "usage: [-v] $0 url"
  echo "  -v |--verbose: show curl result" 
  exit 1 
}

if [ $# -lt 1 ]
then
  usage
fi

# commandline option
while [  "$1" != ""  ]
do
  url=$1
  shift

  # optionally show usage
  case $url in      
    -v|--verbose)
       verbose=true;
       ;;          
  esac
done  


if [ "$verbose" = "true" ]
then
  curl -s -X GET $url -H 'Cache-Control: no-cache' --head 
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)


if [ $? -eq 0 ]
then
  color_msg $green "$url $origin"
else
  color_msg $red "$url does not support CORS"
  color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi

maxReceivedMessageSize and maxBufferSize in app.config

The currently accepted answer is incorrect. It is NOT required to set maxBufferSize and maxReceivedMessageSize on the client and the server binding. It depends!

If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.

For the difference between maxBufferSize and maxReceivedMessageSize see MaxBufferSize property?.

Scripting Language vs Programming Language

In Scripting languages like (JavaScript and old PHP versions) we use existing fundamental functions and method for performing our job. Lets take an example in JavaScript we can use ajax or web-sockets only if they are supported by browser or methods exist or them in browser. But in languages like C or C++ , Java we can write that feature from scratch even if any library for that feature is not available but we can't do so in JavaScript.

can you support web-sockets in Internet Explorer 8 or prior with the help of JavaScript But you can write a plugin in C or C++ or Java which may add a feature of web-socket to Internet Explorer 8.

Basically in Scripting languages we write a code in a sequence which execute existing methods in a sequence to complete our job. Entering numbers and formula in a digital calculator to do a operation is also a very example of scripting language.We should note that the compiler/run-time-environment of every scripting language is always written in programming language in which we can add more features and methods and can write new libraries.

PHP This is language which is somewhat b/w programming and scripting. We can add new methods by adding compiled extensions written in another High Level Language. We can't add high level features of networking or creating image processing libraries directly in PHP.

P.S. I am really sorry for revolving my answer around PHP JavaScript only but I use these two because I have a considerable experience in these two.

Can't bind to 'ngModel' since it isn't a known property of 'input'

You need to import FormsModule in your root module if this component is in the root i.e. app.module.ts

Kindly open app.module.ts

Import FormsModule from @angular/forms

Ex:

import { FormsModule } from '@angular/forms';

and

@NgModule({
imports: [
   FormsModule
],
})

How to insert a character in a string at a certain position?

If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:

    for (int i = 1; i < 100000; i *= 2) {
        String s = "00" + i;
        System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
    }

Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)

Does Python have a ternary conditional operator?

<expression 1> if <condition> else <expression 2>

a = 1
b = 2

1 if a > b else -1 
# Output is -1

1 if a > b else -1 if a < b else 0
# Output is -1

How can I wrap or break long text/word in a fixed width span?

By default a span is an inline element... so that's not the default behavior.

You can make the span behave that way by adding display: block; to your CSS.

span {
    display: block;
    width: 100px;
}

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Use:

android:imeActionLabel="Done"
android:singleLine="true" 

sql primary key and index

a PK will become a clustered index unless you specify non clustered

What is the use of static constructors?

you can use static constructor to initializes static fields. It runs at an indeterminate time before those fields are used. Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead.
It is best to avoid static constructors for maximum performance.
update: you can't use more than one static constructor in the same class, however you can use other instance constructors with (maximum) one static constructor.

Toggle show/hide on click with jQuery

Make use of jquery toggle function which do the task for you

.toggle() - Display or hide the matched elements.

$('#myelement').click(function(){
      $('#another-element').toggle('slow');
  });

Angular 5 Scroll to top on every Route click

Angular 6.1 and later:

You can use built in solution available in Angular 6.1+ with option scrollPositionRestoration: 'enabled' to achieve the same.

@NgModule({
  imports: [RouterModule.forRoot(routes,{
    scrollPositionRestoration: 'enabled'
  })],
  exports: [RouterModule]
})

Angular 6.0 and earlier:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {

    private lastPoppedUrl: string;
    private yScrollStack: number[] = [];

    constructor(private router: Router, private location: Location) { }

    ngOnInit() {
        this.location.subscribe((ev:PopStateEvent) => {
            this.lastPoppedUrl = ev.url;
        });
        this.router.events.subscribe((ev:any) => {
            if (ev instanceof NavigationStart) {
                if (ev.url != this.lastPoppedUrl)
                    this.yScrollStack.push(window.scrollY);
            } else if (ev instanceof NavigationEnd) {
                if (ev.url == this.lastPoppedUrl) {
                    this.lastPoppedUrl = undefined;
                    window.scrollTo(0, this.yScrollStack.pop());
                } else
                    window.scrollTo(0, 0);
            }
        });
    }
}

Note: The expected behavior is that when you navigate back to the page, it should remain scrolled down to the same location it was when you clicked on the link, but scrolling to the top when arriving at every page.

Inline elements shifting when made bold on hover

One line in jquery:

$('ul.nav li a').each(function(){
    $(this).parent().width($(this).width() + 4);
});

edit: While this can bring about the solution, one should mention that it does not work in conjunction with the code in the original post. "display:inline" has to be replaced with floating-parameters for a width-setting to be effective and that horizontal menu to work as intended.

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

If it is just single column to delete the below syntax works

ALTER TABLE tablename DROP COLUMN column1;

For deleting multiple columns, using the DROP COLUMN doesnot work, the below syntax works

ALTER TABLE tablename DROP (column1, column2, column3......);

How to generate all permutations of a list?

def permutations(head, tail=''):
    if len(head) == 0:
        print(tail)
    else:
        for i in range(len(head)):
            permutations(head[:i] + head[i+1:], tail + head[i])

called as:

permutations('abc')

How do I format XML in Notepad++?

If you get this error:

Notepad++ Error: Cannot load 32-bit plugin

Cannot load 32-bit plugin, XMLTools.dll is not compatible with the current version of Notepad++

Here you can find a working version for Windows 10 x64: Xml Tools 2.4.9.2 Unicode

Note: It's the only version I've found working on Windows 10 Professional x64.

proper way to sudo over ssh

Assuming you want no password prompt:

ssh $HOST 'echo $PASSWORD | sudo -S $COMMMAND'

Example

ssh me@localhost 'echo secret | sudo -S echo hi' # outputs 'hi'

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Well, for a link, there must be a link tag around. what you can also do is that make a css class for the button and assign that class to the link tag. like,

_x000D_
_x000D_
#btn {_x000D_
  background: url(https://image.flaticon.com/icons/png/128/149/149668.png) no-repeat 0 0;_x000D_
  display: block;_x000D_
  width: 128px;_x000D_
  height: 128px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
}
_x000D_
<a href="btnlink.html" id="btn"></a>
_x000D_
_x000D_
_x000D_

Python error "ImportError: No module named"

In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.

A completely free agile software process tool

Although, I'm a big fan of Kanban Tool service (it has everything you need except free of charge) and therefore it's difficult for me to stay objective, I think that should go for Trello or Kanban Flow. Both are free and both provide basic features that are essential for agile process managers and their teams.

Nginx location priority

It fires in this order.

  1. = (exactly)

    location = /path

  2. ^~ (forward match)

    location ^~ /path

  3. ~ (regular expression case sensitive)

    location ~ /path/

  4. ~* (regular expression case insensitive)

    location ~* .(jpg|png|bmp)

  5. /

    location /path

YouTube: How to present embed video with sound muted

The accepted answer was not working for me, I followed this tutorial instead with success.

Basically:

<div id="muteYouTubeVideoPlayer"></div>
<script async src="https://www.youtube.com/iframe_api"></script>
<script>
 function onYouTubeIframeAPIReady() {
  var player;
  player = new YT.Player('muteYouTubeVideoPlayer', {
    videoId: 'YOUR_VIDEO_ID', // YouTube Video ID
    width: 560,               // Player width (in px)
    height: 316,              // Player height (in px)
    playerVars: {
      autoplay: 1,        // Auto-play the video on load
      controls: 1,        // Show pause/play buttons in player
      showinfo: 0,        // Hide the video title
      modestbranding: 1,  // Hide the Youtube Logo
      loop: 1,            // Run the video in a loop
      fs: 0,              // Hide the full screen button
      cc_load_policy: 0, // Hide closed captions
      iv_load_policy: 3,  // Hide the Video Annotations
      autohide: 0         // Hide video controls when playing
    },
    events: {
      onReady: function(e) {
        e.target.mute();
      }
    }
  });
 }

 // Written by @labnol 
</script>

iOS / Android cross platform development

There is also BatteryTech which we've been using for the past 18 months and have released several games off of it. http://www.batterypoweredgames.com/batterytech

All C++, Android and iOS support, all users get full source. The new v2 includes lua bindings.

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

Passing data from controller to view in Laravel

Can you give this a try,

return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));

While, you can set multiple variables something like this,

$instructors="";
$instituitions="";

$compactData=array('students', 'instructors', 'instituitions');
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions);

return View::make("user/regprofile", compact($compactData));
return View::make("user/regprofile")->with($data);

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

There's a library for conversion:

npm install dateformat

Then write your requirement:

var dateFormat = require('dateformat');

Then bind the value:

var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");

see dateformat

How can I post data as form data instead of a request payload?

The only thin you have to change is to use property "params" rather than "data" when you create your $http object:

$http({
   method: 'POST',
   url: serviceUrl + '/ClientUpdate',
   params: { LangUserId: userId, clientJSON: clients[i] },
})

In the example above clients[i] is just JSON object (not serialized in any way). If you use "params" rather than "data" angular will serialize the object for you using $httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer

Set database from SINGLE USER mode to MULTI USER

The “user is currently connected to it” might be SQL Server Management Studio window itself. Try selecting the master database and running the ALTER query again.

How can I see which Git branches are tracking which remote / upstream branch?

Very much a porcelain command, not good if you want this for scripting:

git branch -vv   # doubly verbose!

Note that with git 1.8.3, that upstream branch is displayed in blue (see "What is this branch tracking (if anything) in git?")


If you want clean output, see arcresu's answer - it uses a porcelain command that I don't believe existed at the time I originally wrote this answer, so it's a bit more concise and works with branches configured for rebase, not just merge.

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

error: command 'gcc' failed with exit status 1 on CentOS

" error: command 'gcc' failed with exit status 1 ". the installation failed because of missing python-devel and some dependencies.

the best way to correct gcc problem:

You need to reinstall gcc , gcc-c++ and dependencies.

For python 2.7

$ sudo yum -y install gcc gcc-c++ kernel-devel
$ sudo yum -y install python-devel libxslt-devel libffi-devel openssl-devel
$ pip install "your python packet"

For python 3.4

$ sudo apt-get install python3-dev
$ pip install "your python packet"

Hope this will help.

how to get login option for phpmyadmin in xampp

Ya, it's working fine, but it can enter into localhost without entering password.

You can do it in another way by following these steps:

  1. In the browser, type: localhost/xampp/

  2. On the left side bar menu, click Security.

  3. Now you can see the subject table, and below the subject table you can see this link:
    http://localhost/security/xamppsecurity.php. Click this link.

  4. Now you can set the password as you want.

  5. Go to the xampp folder where you installed xampp. Open the xampp folder.

  6. Find and open the phpMyAdmin folder.

  7. Find and open the config.inc.php file with Notepad.

  8. Find the code below:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    
  9. Replace it with the code below:

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = false;
    
  10. Save the file and run the localhost/phpmyadmin with the browser.

Count number of tables in Oracle

THIS QUERY WILL FIND ALL THE OBJECTS COUNTS IN A SPECIFIC SCHEMA

select owner, object_type, count(*) from dba_objects where owner='owner_name' group by owner, object_type order by 3 desc;

Preferred way of loading resources in Java

I search three places as shown below. Comments welcome.

public URL getResource(String resource){

    URL url ;

    //Try with the Thread Context Loader. 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if(classLoader != null){
        url = classLoader.getResource(resource);
        if(url != null){
            return url;
        }
    }

    //Let's now try with the classloader that loaded this class.
    classLoader = Loader.class.getClassLoader();
    if(classLoader != null){
        url = classLoader.getResource(resource);
        if(url != null){
            return url;
        }
    }

    //Last ditch attempt. Get the resource from the classpath.
    return ClassLoader.getSystemResource(resource);
}

How do I check the difference, in seconds, between two dates?

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

would that work for you?

Jquery Open in new Tab (_blank)

window.location always refers to the location of the current window. Changing it will affect only the current window.

One thing that can be done is forcing a click on the link after setting its target attribute to _blank:

Check this: http://www.techfoobar.com/2012/jquery-programmatically-clicking-a-link-and-forcing-the-default-action

Disclaimer: Its my blog.

Retrieving Android API version programmatically

As described in the Android documentation, the SDK level (integer) the phone is running is available in:

android.os.Build.VERSION.SDK_INT

The class corresponding to this int is in the android.os.Build.VERSION_CODES class.

Code example:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions
} else{
    // do something for phones running an SDK before lollipop
}

Edit: This SDK_INT is available since Donut (android 1.6 / API4) so make sure your application is not retro-compatible with Cupcake (android 1.5 / API3) when you use it or your application will crash (thanks to Programmer Bruce for the precision).

Corresponding android documentation is here and here

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

How can I make a button redirect my page to another page?

This is here:

 <button onClick="window.location='page_name.php';" value="click here" />

Dictionary with list of strings as value

A simpler way of doing it is:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}

The for loop loops until i=26 (where 26 is total.length) and then your if is executed, going over the bounds of the array. Remove the ; at the end of the for loop.

How to remove rows with any zero value

I prefer a simple adaptation of csgillespie's method, foregoing the need of a function definition:

d[apply(d!=0, 1, all),]

where d is your data frame.

How to run Maven from another directory (without cd to project dir)?

For me, works this way: mvn -f /path/to/pom.xml [goals]

Different CURRENT_TIMESTAMP and SYSDATE in oracle

SYSDATE returns the system date, of the system on which the database resides

CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of datatype TIMESTAMP WITH TIME ZONE

execute this comman

    ALTER SESSION SET TIME_ZONE = '+3:0';

and it will provide you the same result.

Generating UML from C++ code?

UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

Filtering DataSet

You can use DataTable.Select:

var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";

// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);  

Or you can use DataView:

ds.Tables[0].DefaultView.RowFilter = strExpr;  

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I couldn't find an off-the-shelf module that added this function, so I wrote one:

In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:

Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String

Substring_Index = delims

start = 0
test = ""

For i = 1 To intCount
    oldstart = start + 1
    start = InStr(oldstart, strWord, strDelim)
    Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i

End Function

Save the module as module1 (the default). You can now use statements like:

SELECT Substring_Index([fieldname],",",2) FROM table

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

Last Key in Python Dictionary

sorted(dict.keys())[-1]

Otherwise, the keys is just an unordered list, and the "last one" is meaningless, and even can be different on various python versions.

Maybe you want to look into OrderedDict.

Barcode scanner for mobile phone for Website in form

There's a JS QrCode scanner, that works on mobile sites with a camera:

https://github.com/LazarSoft/jsqrcode

I have worked with it for one of my project and it works pretty good !

segmentation fault : 11

Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.

Writing that much data to a file is going to take a while.

You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).

You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?

You should also write a function to do the calculation; you could use an inline function in C99 or later (or C++). The repetition in the code is excruciating to behold.

You should also use C99 notation for main(), with the explicit return type (and preferably void for the argument list when you are not using argc or argv):

int main(void)

Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 }; (thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static in front of the functions, and the main array; file becomes a local to main; error check the fopen(), etc.).

I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.

#include <stdio.h>

#define   lambda   2.0
#define   g        1.0
#define   F0       1.0
#define   h        0.1
#define   e        0.00001

enum { ROWS = 1000, COLS = 10000 };

static double F[ROWS][COLS];

static void Inicio(double D[ROWS][COLS])
{
    for (int i = 399; i < 600; i++) // Magic numbers!!
        D[i][0] = F0;
}

enum { R = ROWS - 1 };

static inline int ko(int k, int n)
{
    int rv = k + n;
    if (rv >= R)
        rv -= R;
    else if (rv < 0)
        rv += R;
    return(rv);
}

static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
    int ks2 = ko(k, -2);
    int ks1 = ko(k, -1);
    int kp1 = ko(k, +1);
    int kp2 = ko(k, +2);

    A[k][i] = A[k][i-1]
            + e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
            + 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
            + e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}

static void Iteration(double A[ROWS][COLS])
{
    for (int i = 1; i < COLS; i++)
    {
        for (int k = 0; k < R; k++)
            calculate_value(i, k, A);
        A[999][i] = A[0][i];
    }
}

int main(void)
{
    FILE *file = fopen("P2.txt","wt");
    if (file == 0)
        return(1);
    Inicio(F);
    Iteration(F);
    for (int i = 0; i < COLS; i++)
    {
        for (int j = 0; j < ROWS; j++)
        {
            fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
        }
    }
    fclose(file);
    return(0);
}

This program writes to P2.txt instead of P1.txt. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:

Original   Modified
6.334s      6.367s
6.241s      6.231s
6.315s     10.778s
6.378s      6.320s
6.388s      6.293s
6.285s      6.268s
6.387s     10.954s
6.377s      6.227s
8.888s      6.347s
6.304s      6.286s
6.258s     10.302s
6.975s      6.260s
6.663s      6.847s
6.359s      6.313s
6.344s      6.335s
7.762s      6.533s
6.310s      9.418s
8.972s      6.370s
6.383s      6.357s

However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for loop became:

for (int i = COLS - 1; i < COLS; i++)

the timings were vastly reduced and very much more consistent:

Original    Modified
0.168s      0.165s
0.145s      0.165s
0.165s      0.166s
0.164s      0.163s
0.151s      0.151s
0.148s      0.153s
0.152s      0.171s
0.165s      0.165s
0.173s      0.176s
0.171s      0.165s
0.151s      0.169s

The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.

gradlew: Permission Denied

Try to set the execution flag on your gradlew file:

chmod +x gradlew

Detach (move) subdirectory into separate Git repository

When running git filter-branch using a newer version of git (2.22+ maybe?), it says to use this new tool git-filter-repo. This tool certainly simplified things for me.

Filtering with filter-repo

Commands to create the XYZ repo from the original question:

# create local clone of original repo in directory XYZ
tmp $ git clone [email protected]:user/original.git XYZ

# switch to working in XYZ
tmp $ cd XYZ

# keep subdirectories XY1 and XY2 (dropping ABC)
XYZ $ git filter-repo --path XY1 --path XY2

# note: original remote origin was dropped
# (protecting against accidental pushes overwriting original repo data)

# XYZ $ ls -1
# XY1
# XY2

# XYZ $ git log --oneline
# last commit modifying ./XY1 or ./XY2
# first commit modifying ./XY1 or ./XY2

# point at new hosted, dedicated repo
XYZ $ git remote add origin [email protected]:user/XYZ.git

# push (and track) remote master
XYZ $ git push -u origin master

assumptions: * remote XYZ repo was new and empty before the push

Filtering and moving

In my case, I also wanted to move a couple of directories for a more consistent structure. Initially, I ran that simple filter-repo command followed by git mv dir-to-rename, but I found I could get a slightly "better" history using the --path-rename option. Instead of seeing last modified 5 hours ago on moved files in the new repo I now see last year (in the GitHub UI), which matches the modified times in the original repo.

Instead of...

git filter-repo --path XY1 --path XY2 --path inconsistent
git mv inconsistent XY3  # which updates last modification time

I ultimately ran...

git filter-repo --path XY1 --path XY2 --path inconsistent --path-rename inconsistent:XY3
Notes:
  • I thought the Git Rev News blog post explained well the reasoning behind creating yet another repo-filtering tool.
  • I initially tried the path of creating a sub-directory matching the target repo name in the original repository and then filtering (using git filter-repo --subdirectory-filter dir-matching-new-repo-name). That command correctly converted that subdirectory to the root of the copied local repo, but it also resulted in a history of only the three commits it took to create the subdirectory. (I hadn't realized that --path could be specified multiple times; thereby, obviating the need to create a subdirectory in the source repo.) Since someone had committed to the source repo by the time I noticed that I'd failed to carry forward the history, I just used git reset commit-before-subdir-move --hard after the clone command, and added --force to the filter-repo command to get it to operate on the slightly modified local clone.
git clone ...
git reset HEAD~7 --hard      # roll back before mistake
git filter-repo ... --force  # tell filter-repo the alterations are expected
  • I was stumped on the install since I was unaware of the extension pattern with git, but ultimately I cloned git-filter-repo and symlinked it to $(git --exec-path):
ln -s ~/github/newren/git-filter-repo/git-filter-repo $(git --exec-path)

MongoDB via Mongoose JS - What is findByID?

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

How to change icon on Google map marker

You have to add the targeted map :

var markers = [
            {
            "title": 'This is title',
            "lat": '-37.801578',
            "lng": '145.060508',
            "map":  map,
            "icon": 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png',
            "description": 'Vikash Rathee. <strong> This is test Description</strong> <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by 

City</a>'
            }
];

JPA Native Query select and cast object

First of all create a model POJO

import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "class_id")
    public int classId;
    @Column(name = "user_name")
    public String userName;
    //getter,setter
}

Controller

import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;

@RestController
public class HomeController {
    @PersistenceUnit
    private EntityManagerFactory emf;

    @GetMapping("/")
    public List<StdUser> actionIndex() {
        EntityManager em = emf.createEntityManager(); // Without parameter
        List<StdUser> arr_cust = (List<StdUser>)em
                .createQuery("SELECT c FROM StdUser c")
                .getResultList();
        return arr_cust;
    }

    @GetMapping("/paramter")
    public List actionJoin() {
        int id = 3;
        String userName = "Suresh Shrestha";
        EntityManager em = emf.createEntityManager(); // With parameter
        List arr_cust = em
                .createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
                .setParameter("Id",id)
                .setParameter("UserName",userName)
                .getResultList();
        return arr_cust;
    }
}

How do I clear inner HTML

Take a look at this. a clean and simple solution using jQuery.

http://jsfiddle.net/ma2Yd/

    <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
    <div id="goy"></div>


    <script type="text/javascript">

    $(function() {
       $("h1").on('mouseover', function() {
          $("#goy").text('The dog is in its shed');
       }).on('mouseout', function() {
          $("#goy").text("");
       });
   });