Programs & Examples On #Integration

The process of linking together different computing systems and software applications physically or functionally, to act as a coordinated whole. For numerical integration problem, please use tag [numerical-integration].

How to insert table values from one database to another database?

How about this:

USE TargetDatabase
GO

INSERT INTO dbo.TargetTable(field1, field2, field3)
   SELECT field1, field2, field3
     FROM SourceDatabase.dbo.SourceTable
     WHERE (some condition)

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.

I use this

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2</version>
</plugin>

Call Python function from JavaScript code

From the document.getElementsByTagName I guess you are running the javascript in a browser.

The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.

For example, using jQuery you can do something like:

$.getJSON('http://example.com/your/webservice?param1=x&param2=y', 
    function(data, textStatus, jqXHR) {
        alert(data);
    }
)

You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.

A typical implementation looks like:

@app.route("/your/webservice")
def my_webservice():
    return jsonify(result=some_function(**request.args)) 

You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.

Escape double quotes in Java

Use Java's replaceAll(String regex, String replacement)

For example, Use a substitution char for the quotes and then replace that char with \"

String newstring = String.replaceAll("%","\"");

or replace all instances of \" with \\\"

String newstring = String.replaceAll("\"","\\\"");

Custom UITableViewCell from nib in Swift

Here's my approach using Swift 2 and Xcode 7.3. This example will use a single ViewController to load two .xib files -- one for a UITableView and one for the UITableCellView.

enter image description here

For this example you can drop a UITableView right into an empty TableNib.xib file. Inside, set the file's owner to your ViewController class and use an outlet to reference the tableView.

enter image description here

and

enter image description here

Now, in your view controller, you can delegate the tableView as you normally would, like so

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Table view delegate
        self.tableView.delegate = self
        self.tableView.dataSource = self

        ...

To create your Custom cell, again, drop a Table View Cell object into an empty TableCellNib.xib file. This time, in the cell .xib file you don't have to specify an "owner" but you do need to specify a Custom Class and an identifier like "TableCellId"

enter image description here enter image description here

Create your subclass with whatever outlets you need like so

class TableCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!

}

Finally... back in your View Controller, you can load and display the entire thing like so

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // First load table nib
    let bundle = NSBundle(forClass: self.dynamicType)
    let tableNib = UINib(nibName: "TableNib", bundle: bundle)
    let tableNibView = tableNib.instantiateWithOwner(self, options: nil)[0] as! UIView

    // Then delegate the TableView
    self.tableView.delegate = self
    self.tableView.dataSource = self

    // Set resizable table bounds
    self.tableView.frame = self.view.bounds
    self.tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

    // Register table cell class from nib
    let cellNib = UINib(nibName: "TableCellNib", bundle: bundle)
    self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId)

    // Display table with custom cells
    self.view.addSubview(tableNibView)

}

The code shows how you can simply load and display a nib file (the table), and second how to register a nib for cell use.

Hope this helps!!!

Why em instead of px?

The main reason for using em or percentages is to allow the user to change the text size without breaking the design. If you design with fonts specified in px, they do not change size (in IE 6 and others) if the user chooses text size - larger. This is very bad for users with visual handicaps.

For several examples of and articles on designs like this (there are a myriad to choose from), see the latest issue of A List Apart: Fluid Grids, the older article How to Size Text in CSS or Dan Cederholm's Bulletproof Web Design.

Your images should still be displayed with px sizes, but, in general, it is not considered good form to size your text with px.

As much as I personally despise IE6, it is currently the only browser approved for the bulk of the users in our Fortune 200 company.

MySQL, update multiple tables with one query

Take the case of two tables, Books and Orders. In case, we increase the number of books in a particular order with Order.ID = 1002 in Orders table then we also need to reduce that the total number of books available in our stock by the same number in Books table.

UPDATE Books, Orders
SET Orders.Quantity = Orders.Quantity + 2,
    Books.InStock = Books.InStock - 2
WHERE
    Books.BookID = Orders.BookID
    AND Orders.OrderID = 1002;

iPhone: How to get current milliseconds?

// Timestamp after converting to milliseconds.

NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];

The source was not found, but some or all event logs could not be searched

I recently experienced the error, and none of the solutions worked for me. What resolved the error for me was adding the Application pool user to the Power Users group in computer management. I couldn't use the Administrator group due to a company policy.

Check a radio button with javascript

Today, in the year 2016, it is save to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):

document.querySelector("input[name=main-categories]:checked").value

Make browser window blink in task Bar

this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab.

newExcitingAlerts = (function () {
    var oldTitle = document.title;
    var msg = "New!";
    var timeoutId;
    var blink = function() { document.title = document.title == msg ? ' ' : msg; };
    var clear = function() {
        clearInterval(timeoutId);
        document.title = oldTitle;
        window.onmousemove = null;
        timeoutId = null;
    };
    return function () {
        if (!timeoutId) {
            timeoutId = setInterval(blink, 1000);
            window.onmousemove = clear;
        }
    };
}());

Update: You may want to look at using HTML5 notifications.

What is the standard naming convention for html/css ids and classes?

tl;dr;

There is no one true answer. You can pick one of the many out there, or create your own standards based on what makes sense, depending upon who you're working with. And it is 100% dependent upon the platform.


Original Post

Just one more alternative standard to consider:

<div id="id_name" class="class-name"></div>

And in your script:

var variableName = $("#id_name .class-name");

This just uses a camelCase, under_score, and hyphen-ation respectively for variables, ids, and classes. I've read about this standard on a couple of different websites. Although a little redundant in css/jquery selectors, redundancies make it easier to catch errors. eg: If you see .unknown_name or #unknownName in your CSS file, you know you need to figure out what that's actually referring to.


UPDATE 2019

(Hyphens are called 'kebab-case', underscores are called 'snake_case', and then you have 'TitleCase', 'pascalCase')

I personally dislike hyphens. I originally posted this as one alternative (because the rules are simple). However, Hyphens make selection shortcuts very difficult (double click, ctrl/option + left/right, and ctrl/cmd+D in vsCode. Also, class names and file names are the only place where hyphens work, because they're almost always in quotes or in css, etc. But the shortcut thing still applies.

In addition to variables, class names, and ids, you also want to look at file name conventions. And Git Branches.

My office's coding group actually had a meeting a month or two ago to discuss how we were going to name things. For git branches, we couldn't decide between 321-the_issue_description or 321_the-issue-description. (I wanted 321_theIssueDescription, but my coworkers didn't like that.)

An Example, to demonstrate working with other peoples' standards...

Vue.js does have a standard. Actually they have two alternate standards for several of their items. I dislike both of their versions for filenames. They recommend either "/path/kebab-case.vue" or "/path/TitleCase.Vue". The former is harder to rename, unless you're specifically trying to rename part of it. The latter is not good for cross-platform compatibility. I would prefer "/path/snake_case.vue". However, when working with other people or existing projects, it's important to follow whatever standard was already laid out. Therefore I go with kebab-case for filenames in Vue, even though I'll totally complain about it. Because not following that means changing a lot of files that vue-cli sets up.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Does Eclipse have line-wrap

As mentioned in the post by VonC on this same page. Eclipse now has this capability as of 06/2016 Neon.

Try this plugin Eclipse platform plugin

It looks like eclipse only has the ability to do it manually on its own and here are the commands. At that point you must reformat the highlighted text manually.

It's not terribly obvious how to control Eclipse line width and line wrapping in your Java source files. Here's how and where:

Comment width and line wrapping is set in Preferences->Java->Code Style->Formatter, then click on the Edit button and select the Comments tab. I like Line Width for Comments to be 120.

Code line wrapping is set nearby, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Line Wrapping tab. I like a line width of 120 and indent size of 4.

Indentation is set separately, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Indentation tab. I like an indent size of 4, consistent with the Line Wrapping indent setting.

As if that's not enough, you can also set printer margins, tab size, etc, in Preferences>General>Editors>Text Editors where I set the Displayed Tab Width to 4 and Print Margin Column to 120 or more.

You can also check the Show Print Margin box to get a faint vertical line at the printer margin column

@Autowired - No qualifying bean of type found for dependency at least 1 bean

You forgot @Service annotation in your service class.

git push says "everything up-to-date" even though I have local changes

We need to add the files and commit the already changed/added files execute below commands

git add . or git add nameoffile #it will add the existing files in the project

git commit -m "first commit" #commiting all the files in the project

git push origin master

Does return stop a loop?

The return statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:

Uncaught SyntaxError: Illegal return statement(…)

To terminate a loop you should use break.

Update Rows in SSIS OLEDB Destination

You can't do a bulk-update in SSIS within a dataflow task with the OOB components.

The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.

Stage data

http://www.sqlservercentral.com/Images/11369.png

Set based updates

enter image description here

You'll get much better performance with a pattern like this versus using the OLE DB Command transformation for anything but trivial amounts of data.

If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If this is a personal script, rather than one you're planning on distributing, it might be simpler to write a shell function for this:

function warextract { jar xf $1 $2 && mv $2 $3 }

which you could then call from python like so:

warextract /home/foo/bar/Portal.ear Binaries.war /home/foo/bar/baz/

If you really feel like it, you could use sed to parse out the filename from the path, so that you'd be able to call it with

warextract /home/foo/bar/Portal.ear /home/foo/bar/baz/Binaries.war

I'll leave that as an excercise to the reader, though.

Of course, since this will extract the .war out into the current directory first, and then move it, it has the possibility of overwriting something with the same name where you are.

Changing directory, extracting it, and cd-ing back is a bit cleaner, but I find myself using little one-line shell functions like this all the time when I want to reduce code clutter.

How to get JSON object from Razor Model object in javascript

In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

It should be as simple as:

<script>
  var json = @Json.Serialize(Model.CollegeInformationlist);
</script>

Git submodule update

Git 1.8.2 features a new option ,--remote, that will enable exactly this behavior. Running

git submodule update --rebase --remote

will fetch the latest changes from upstream in each submodule, rebase them, and check out the latest revision of the submodule. As the documentation puts it:

--remote

This option is only valid for the update command. Instead of using the superproject’s recorded SHA-1 to update the submodule, use the status of the submodule’s remote-tracking branch.

This is equivalent to running git pull in each submodule, which is generally exactly what you want.

(This was copied from this answer.)

Converting stream of int's to char's in java

If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the String constructor and provide a Charset, or use InputStreamReader with the appropriate Charset instead.

Simply casting from int to char only works if you want ISO-8859-1, if you're reading bytes from a stream directly.

EDIT: If you are already using a Reader, then casting the return value of read() to char is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call read(char[], int, int) to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.

React-Router External link

Here's a one-liner for using React Router to redirect to an external link:

<Route path='/privacy-policy' component={() => { 
     window.location.href = 'https://example.com/1234'; 
     return null;
}}/>

It uses React pure component concept to reduce the component's code to a single function that, instead of rendering anything, redirects browser to an external URL.

Works both on React Router 3 and 4.

How do you run a SQL Server query from PowerShell?

Invoke-Sqlcmd -Query "sp_who" -ServerInstance . -QueryTimeout 3

RegEx - Match Numbers of Variable Length

You can specify how many times you want the previous item to match by using {min,max}.

{[0-9]{1,3}:[0-9]{1,3}}

Also, you can use \d for digits instead of [0-9] for most regex flavors:

{\d{1,3}:\d{1,3}}

You may also want to consider escaping the outer { and }, just to make it clear that they are not part of a repetition definition.

Why is 2 * (i * i) faster than 2 * i * i in Java?

I got similar results:

2 * (i * i): 0.458765943 s, n=119860736
2 * i * i: 0.580255126 s, n=119860736

I got the SAME results if both loops were in the same program, or each was in a separate .java file/.class, executed on a separate run.

Finally, here is a javap -c -v <.java> decompile of each:

     3: ldc           #3                  // String 2 * (i * i):
     5: invokevirtual #4                  // Method java/io/PrintStream.print:(Ljava/lang/String;)V
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
    11: lstore_1
    12: iconst_0
    13: istore_3
    14: iconst_0
    15: istore        4
    17: iload         4
    19: ldc           #6                  // int 1000000000
    21: if_icmpge     40
    24: iload_3
    25: iconst_2
    26: iload         4
    28: iload         4
    30: imul
    31: imul
    32: iadd
    33: istore_3
    34: iinc          4, 1
    37: goto          17

vs.

     3: ldc           #3                  // String 2 * i * i:
     5: invokevirtual #4                  // Method java/io/PrintStream.print:(Ljava/lang/String;)V
     8: invokestatic  #5                  // Method java/lang/System.nanoTime:()J
    11: lstore_1
    12: iconst_0
    13: istore_3
    14: iconst_0
    15: istore        4
    17: iload         4
    19: ldc           #6                  // int 1000000000
    21: if_icmpge     40
    24: iload_3
    25: iconst_2
    26: iload         4
    28: imul
    29: iload         4
    31: imul
    32: iadd
    33: istore_3
    34: iinc          4, 1
    37: goto          17

FYI -

java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Package doesn't exist error in intelliJ

I had the same problem and it was fixed for me by changing the "Maven home directory" in Settings from "Bundled" to my locally installed maven. Perhaps this triggered some kind of refresh somewhere since I had not changed this setting for months without any issue.

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

There is a change in syntax from Python 2 to Python 3. In Python 2,

print "Hello, World!" 

will work but in Python 3, use parentheses as

print("Hello, World!")

This is equivalent syntax to Scala and near to Java.

How to convert JSON data into a Python object

Python3.x

The best aproach I could reach with my knowledge was this.
Note that this code treat set() too.
This approach is generic just needing the extension of class (in the second example).
Note that I'm just doing it to files, but it's easy to modify the behavior to your taste.

However this is a CoDec.

With a little more work you can construct your class in other ways. I assume a default constructor to instance it, then I update the class dict.

import json
import collections


class JsonClassSerializable(json.JSONEncoder):

    REGISTERED_CLASS = {}

    def register(ctype):
        JsonClassSerializable.REGISTERED_CLASS[ctype.__name__] = ctype

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in self.REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = self.REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


JsonClassSerializable.register(C)


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


JsonClassSerializable.register(B)


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()

JsonClassSerializable.register(A)

A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
print(b.b)
print(b.c.a)

Edit

With some more of research I found a way to generalize without the need of the SUPERCLASS register method call, using a metaclass

import json
import collections

REGISTERED_CLASS = {}

class MetaSerializable(type):

    def __call__(cls, *args, **kwargs):
        if cls.__name__ not in REGISTERED_CLASS:
            REGISTERED_CLASS[cls.__name__] = cls
        return super(MetaSerializable, cls).__call__(*args, **kwargs)


class JsonClassSerializable(json.JSONEncoder, metaclass=MetaSerializable):

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()


A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
# 1
print(b.b)
# {1, 2}
print(b.c.a)
# 1230
print(b.c.c.mill)
# s

Using an array as needles in strpos

If you just want to check if certain characters are actually in the string or not, use strtok:

$string = 'abcdefg';
if (strtok($string, 'acd') === $string) {
    // not found
} else {
    // found
}

How to replace all occurrences of a string in Javascript?

If the string contain similar pattern like abccc, you can use this:

str.replace(/abc(\s|$)/g, "")

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

How do I migrate an SVN repository with history to a new Git repository?

First, credit to the answer from @cmcginty. It was a great starting point for me, and much of what I'll post here borrowed heavily from it. However, the repos that I was moving have years of history which led to a few issues following that answer to the letter (hundreds of branches and tags that would need to be manually moved for one; read more later).

So after hours of searching and trial and error I was able to put together a script which allowed me to easily move several projects from SVN to GIT, and I've decided to share my findings here in case anyone else is in my shoes.

<tl;dr> Let's get started


First, create an 'Authors' file which will translate basic svn users to more complex git users. The easiest way to do this is using a command to extract all users from the svn repo you are going to move.

svn log -q | awk -F '|' '/^r/ {sub("^ ", "", $2); sub(" $", "", $2); print $2" = "$2" <"$2">"}' | sort -u > authors-transform.txt

This will produce a file called authors-transform.txt with a line for each user that has made a change in the svn repo it was ran from.

someuser = someuser <someuser>

Update to include full name and email for git

someuser = Some User <[email protected]>

Now start the clone using your authors file

git svn clone --stdlayout --no-metadata -r854:HEAD --authors-file=authors-transform.txt https://somesvnserver/somerepo/ temp
  • --stdlayout indicates that the svn repo follows the standard /trunk /branches /tags layout
  • --no-metadata tells git not to stamp metadata relating to the svn commits on each git commit. If this is not a one-way conversion remove this tag
  • -r854:HEAD only fetches history from revision 854 up. This is where I hit my first snag; the repo I was converting had a 'corrupted' commit at revision 853 so it would not clone. Using this parameter allows you to only clone part of the history.
  • temp is the name of the directory that will be created to initialize the new git repo

This step can take awhile, particularly on a large or old repo (roughly 18 hours for one of ours). You can also use that -r switch to only take a small history to see the clone, and fetch the rest later.

Move to the new directory

cd temp

Fetch any missing history if you only pulled partial in clone

git svn fetch

Tags are created as branches during cloning. If you only have a few you can convert them one at a time.

git 1.0.0 origin/tags/1.0.0

However, this is tedious if you have hundreds of tags, so the following script worked for me.

for brname in `git branch -r | grep tags | awk '{gsub(/^[^\/]+\//,"",$1); print $1}'`; do echo $brname; tname=${brname:5}; echo $tname; git tag $tname origin/tags/$tname; done

You also need to checkout all branches you want to keep

git checkout -b branchname origin/branches/branchname

And if you have a lot of branches as well, this script may help

for brname in `git branch -r | grep -v master | grep -v HEAD | grep -v trunk | grep -v tags | awk '{gsub(/^[^\/]+\//,"",$1); print $1}'`; do echo $brname; git checkout -b $brname origin/$brname; done

This will ignore the trunk branch, as it will already be checked out as master and save a step later deleting the duplicate branch, as well as ignoring the /tags that we already converted.

Now is a good time to take a look at the new repo and make sure you have a local branch or tag for anything you want to keep as remote branches will be dropped in a moment.

Ok, now lets clone everything we've checked out to a clean repo (named temp2 here)

cd ..
git clone temp temp2
cd temp2

Now we'll need to checkout all of the branches one more time before pushing them to their final remote, so follow your favorite method from above.

If you're following gitflow you can rename your working branch to develop.

git checkout -b WORKING
git branch -m develop
git push origin --delete WORKING
git push origin -u develop

Now, if everything looks good, you're ready to push to your git repository

git remote set-url origin https://somebitbucketserver/somerepo.git
git push -u origin --all
git push origin --tags

I did run into one final issue which was that Control Freak initially blocked me from pushing tags that I didn't create, so if your team uses Control Freak you may need to disable or adjust that setting for your initial push.

How is malloc() implemented internally?

Simplistically malloc and free work like this:

malloc provides access to a process's heap. The heap is a construct in the C core library (commonly libc) that allows objects to obtain exclusive access to some space on the process's heap.

Each allocation on the heap is called a heap cell. This typically consists of a header that hold information on the size of the cell as well as a pointer to the next heap cell. This makes a heap effectively a linked list.

When one starts a process, the heap contains a single cell that contains all the heap space assigned on startup. This cell exists on the heap's free list.

When one calls malloc, memory is taken from the large heap cell, which is returned by malloc. The rest is formed into a new heap cell that consists of all the rest of the memory.

When one frees memory, the heap cell is added to the end of the heap's free list. Subsequent malloc's walk the free list looking for a cell of suitable size.

As can be expected the heap can get fragmented and the heap manager may from time to time, try to merge adjacent heap cells.

When there is no memory left on the free list for a desired allocation, malloc calls brk or sbrk which are the system calls requesting more memory pages from the operating system.

Now there are a few modification to optimize heap operations.

  • For large memory allocations (typically > 512 bytes, the heap manager may go straight to the OS and allocate a full memory page.
  • The heap may specify a minimum size of allocation to prevent large amounts of fragmentation.
  • The heap may also divide itself into bins one for small allocations and one for larger allocations to make larger allocations quicker.
  • There are also clever mechanisms for optimizing multi-threaded heap allocation.

Regex to match alphanumeric and spaces

The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.

How to INNER JOIN 3 tables using CodeIgniter

you can modiv your coding like this

 $this->db->select('a.nik,b.nama,a.inv,c.cekin,c.cekout,a.tunai,a.nontunai,a.id');
 $this->db->select('DATEDIFF (c.cekout, c.cekin) as lama');
 $this->db->select('(DATEDIFF (c.cekout, c.cekin)*c.total) as tagihan');
 $this->db->from('bayar as a');
 $this->db->join('pelanggan as b', 'a.nik = b.nik');
 $this->db->join('pesankamar_h as c', 'a.inv = c.id');
 $this->db->where('a.user_id',$id);
 $query = $this->db->get();
 return $query->result();

i hope can be resolve your SQL

How to convert a HTMLElement to a string

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

<div id="new-element-1">Hello world.</div>

<script type="text/javascript"><!--

var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>

--></script>

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

  1. outerHTML - Javascript Property
  2. Javascript Reference - Elements

Ascii/Hex convert in bash

For the first part, try

echo Aa | od -t x1

It prints byte-by-byte

$ echo Aa | od -t x1
0000000 41 61 0a
0000003

The 0a is the implicit newline that echo produces.

Use echo -n or printf instead.

$ printf Aa | od -t x1
0000000 41 61
0000002

Using group by and having clause

Having: It applies filter conditions to each group of rows. Where: It applies a filter of individual rows.

Getting permission denied (public key) on gitlab

I solved like this..

Generated a key for Windows using this command:

ssh-keygen -t rsa -C "[email protected]" -b 4096

but the problem was that after running this command, it popped a line: "Enter file in which to save the key (/c/Users/xxx/.ssh/id_rsa): " Here, I was giving only file name because of which my key was getting saved in my pwd and not in the given location. When I did "git clone ", it was assuming the key to be at "/c/Users/xxx/.ssh/id_rsa" location but it was not found, hence it was throwing error.

At the time of key generation 2 files were generated say "file1" & "file1.pub". I renamed both these files as

file1 -> id_rsa 

and

file1.pub -> id_rsa.pub

and placed both in the location "/c/Users/xxx/.ssh/"

How to select lines between two marker patterns which may occur multiple times with awk/sed

sed '/^abc$/,/^mno$/!d;//d' file

golfs two characters better than ppotong's {//!b};d

The empty forward slashes // mean: "reuse the last regular expression used". and the command does the same as the more understandable:

sed '/^abc$/,/^mno$/!d;/^abc$/d;/^mno$/d' file

This seems to be POSIX:

If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.

This project references NuGet package(s) that are missing on this computer

In my case it had to do with the Microsoft.Build.Bcl version. My nuget package version was 1.0.21, but my project files were still pointing to version 1.0.14

So I changed my .csproj files from:

  <Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
   <Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
    <Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
    <Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
  </Target>

to:

 <Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />
  <Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
    <Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
    <Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />

And the build was working again.

How to create a dotted <hr/> tag?

hr {
    border-top:1px dotted #000;
    /*Rest of stuff here*/
}

Access Enum value using EL with JSTL

I do it this way when there are many points to use...

public enum Status { 

    VALID("valid"), OLD("old");

    private final String val;

    Status(String val) {
        this.val = val;
    }

    public String getStatus() {
        return val;
    }

    public static void setRequestAttributes(HttpServletRequest request) {
        Map<String,String> vals = new HashMap<String,String>();
        for (Status val : Status.values()) {
            vals.put(val.name(), val.value);
        }
        request.setAttribute("Status", vals);
    }

}

JSP

<%@ page import="...Status" %>
<% Status.setRequestAttributes(request) %>

<c:when test="${dp.status eq Status.VALID}">
...

Get current batchfile directory

System read-only variable %CD% keeps the path of the caller of the batch, not the batch file location.

You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch.bat). Parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\) and %~f0 will return the full pathname (e.g. W:\scripts\mybatch.cmd).

You can refer to other files in the same folder as the batch script by using this syntax:

CALL %0\..\SecondBatch.cmd

This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will give you the filename of the batch script.

When the %0 variable is expanded, the result is enclosed in quotation marks.

More on batch parameters.

insert datetime value in sql database with c#

INSERT INTO <table> (<date_column>) VALUES ('1/1/2010 12:00')

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

There is an option in the Virtual Box itself. If you look in the Oracle VM Virtual Box Manager. Select the Virtual Box you want to start. Go to System, the second from above item in the right pane. In System go to the third tab called acceleration. In that tab the first check box is called something like: 'VT-x/AMD-V' (I have the Dutch version, so I don't know the exact string) UNCHECK And then start. That worked for me.

I also got this problem after an upgrade. And I did not have the problem before. But I fail to see the exact connection between the update and the check/unchecking of that option.

By the way, I have no idea where the hell that 'virtualization tab' should be in my 'BIOS'. Maybe I was looking in my PC's BIOS not the System page here which is the BIOS of the VM Machine maybe and that is what you meant Veer7? If it was, it was pretty unclear you meant this. Maybe it's because I have OVM in Dutch not English. But there was nothing called BIOS in the Oracle VM Virtual Box Manager I could find.

Dynamically load a JavaScript file

There is no import / include / require in javascript, but there are two main ways to achieve what you want:

1 - You can load it with an AJAX call then use eval.

This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks.

2 - Add a script tag with the script URL in the HTML.

Definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the tag in the head of the web page, or at the bottom of the body.

Both of these solutions are discussed and illustrated here.

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performances.

It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

E.G : my_lovely_script.js contains MySuperObject

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. E.G :

function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function :

var myPrettyCode = function() {
    // here, do what ever you want
};

Then you run all that :

loadScript("my_lovely_script.js", myPrettyCode);

Ok, I got it. But it's a pain to write all this stuff.

Well, in that case, you can use as always the fantastic free jQuery framework, which let you do the very same thing in one line :

$.getScript("my_lovely_script.js", function() {
    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script
});

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

first delete all tables of the database in the localhost

Change Laravel default database (utf8mb4) properties in file config/database.php to:

'charset' => 'utf8', 'collation' => 'utf8_unicode_ci',

after then Changing my local database properties utf8_unicode_ci. php artisan migrate it is ok.

How to change the icon of an Android app in Eclipse?

In your AndroidManifest.xml file

<application
        android:name="ApplicationClass"
        android:icon="@drawable/ic_launcher"  <--------
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Detecting sheet of paper is kinda old school. If you want to tackle skew detection then it is better if you straightaway aim for text line detection. With this you will get the extremas left, right, top and bottom. Discard any graphics in the image if you dont want and then do some statistics on the text line segments to find the most occurring angle range or rather angle. This is how you will narrow down to a good skew angle. Now after this you put these parameters the skew angle and the extremas to deskew and chop the image to what is required.

As for the current image requirement, it is better if you try CV_RETR_EXTERNAL instead of CV_RETR_LIST.

Another method of detecting edges is to train a random forests classifier on the paper edges and then use the classifier to get the edge Map. This is by far a robust method but requires training and time.

Random forests will work with low contrast difference scenarios for example white paper on roughly white background.

Spark - repartition() vs coalesce()

In a simple way COALESCE :- is only for decreases the no of partitions , No shuffling of data it just compress the partitions

REPARTITION:- is for both increase and decrease the no of partitions , But shuffling takes place

Example:-

val rdd = sc.textFile("path",7)
rdd.repartition(10)
rdd.repartition(2)

Both works fine

But we go generally for this two things when we need to see output in one cluster,we go with this.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are synonyms, no difference at all.Decimal and Numeric data types are numeric data types with fixed precision and scale.

-- Initialize a variable, give it a data type and an initial value

declare @myvar as decimal(18,8) or numeric(18,8)----- 9 bytes needed

-- Increse that the vaue by 1

set @myvar = 123456.7

--Retrieve that value

select @myvar as myVariable

Select columns from result set of stored procedure

Can you split up the query? Insert the stored proc results into a table variable or a temp table. Then, select the 2 columns from the table variable.

Declare @tablevar table(col1 col1Type,..
insert into @tablevar(col1,..) exec MyStoredProc 'param1', 'param2'

SELECT col1, col2 FROM @tablevar

Passing additional variables from command line to make

From the manual:

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.

So you can do (from bash):

FOOBAR=1 make

resulting in a variable FOOBAR in your Makefile.

IPython/Jupyter Problems saving notebook as PDF

To convert notebooks to PDF you first need to have nbconvert installed.

pip install nbconvert
# OR
conda install nbconvert

Next, if you aren't using Anaconda or haven't already, you must install pandoc either by following the instructions on their website or, on Linux, as follows:

sudo apt-get install pandoc

After that you need to have XeTex installed on your machine:

You can now navigate to the folder that holds your IPython Notebook and run the following command:

jupyter nbconvert --to pdf MyNotebook.ipynb

for further reference, please check out this link.

How do I make an html link look like a button?

You may do it with JavaScript:

  1. Get CSS styles of real button with getComputedStyle(realButton).
  2. Apply the styles to all your links.

_x000D_
_x000D_
/* javascript, after body is loaded */_x000D_
'use strict';_x000D_
_x000D_
{ // Namespace starts (to avoid polluting root namespace)._x000D_
  _x000D_
  const btnCssText = window.getComputedStyle(_x000D_
    document.querySelector('.used-for-btn-css-class')_x000D_
  ).cssText;_x000D_
  document.querySelectorAll('.btn').forEach(_x000D_
    (btn) => {_x000D_
      _x000D_
      const _d = btn.style.display; // Hidden buttons should stay hidden._x000D_
      btn.style.cssText = btnCssText;_x000D_
      btn.style.display = _d;_x000D_
      _x000D_
    }_x000D_
  );_x000D_
  _x000D_
} // Namespace ends.
_x000D_
<body>_x000D_
  <h3>Button Styled Links</h3>_x000D_
  <button class="used-for-btn-css-class" style="display: none"></button>_x000D_
  <a href="//github.io" class="btn">first</a>_x000D_
  <a href="//github.io" class="btn">second</a>_x000D_
  <button>real button</button>_x000D_
  <script>/* You may put JS here. */</script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

'const string' vs. 'static readonly string' in C#

const

public const string MyStr;

is a compile time constant (you can use it as the default parameter for a method parameter for example), and it will not be obfuscated if you use such technology

static readonly

public static readonly string MyStr;

is runtime constant. It means that it is evaluated when the application is launched and not before. This is why it can't be used as the default parameter for a method (compilation error) for example. The value stored in it can be obfuscated.

what is the multicast doing on 224.0.0.251?

Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.

The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.

mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.

If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.

REST API Best practices: Where to put parameters?

"Pack" and POST your data against the "context" that universe-resource-locator provides, which means #1 for the sake of the locator.

Mind the limitations with #2. I prefer POSTs to #1.

note: limitations are discussed for

POST in Is there a max size for POST parameter content?

GET in Is there a limit to the length of a GET request? and Max size of URL parameters in _GET

p.s. these limits are based on the client capabilities (browser) and server(configuration).

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Synchronizing with threads. 1) NEVER use synchronized(this) in a thread it doesn't work. Synchronizing with (this) uses the current thread as the locking thread object. Since each thread is independent of other threads, there is NO coordination of synchronization. 2) Tests of code show that in Java 1.6 on a Mac the method synchronization does not work. 3) synchronized(lockObj) where lockObj is a common shared object of all threads synchronizing on it will work. 4) ReenterantLock.lock() and .unlock() work. See Java tutorials for this.

The following code shows these points. It also contains the thread-safe Vector which would be substituted for the ArrayList, to show that many threads adding to a Vector do not lose any information, while the same with an ArrayList can lose information. 0) Current code shows loss of information due to race conditions A) Comment the current labeled A line, and uncomment the A line above it, then run, method loses data but it shouldn't. B) Reverse step A, uncomment B and // end block }. Then run to see results no loss of data C) Comment out B, uncomment C. Run, see synchronizing on (this) loses data, as expected. Don't have time to complete all the variations, hope this helps. If synchronizing on (this), or the method synchronization works, please state what version of Java and OS you tested. Thank you.

import java.util.*;

/** RaceCondition - Shows that when multiple threads compete for resources 
     thread one may grab the resource expecting to update a particular 
     area but is removed from the CPU before finishing.  Thread one still 
     points to that resource.  Then thread two grabs that resource and 
     completes the update.  Then thread one gets to complete the update, 
     which over writes thread two's work.
     DEMO:  1) Run as is - see missing counts from race condition, Run severa times, values change  
            2) Uncomment "synchronized(countLock){ }" - see counts work
            Synchronized creates a lock on that block of code, no other threads can 
            execute code within a block that another thread has a lock.
        3) Comment ArrayList, unComment Vector - See no loss in collection
            Vectors work like ArrayList, but Vectors are "Thread Safe"
         May use this code as long as attribution to the author remains intact.
     /mf
*/ 

public class RaceCondition {
    private ArrayList<Integer> raceList = new ArrayList<Integer>(); // simple add(#)
//  private Vector<Integer> raceList = new Vector<Integer>(); // simple add(#)

    private String countLock="lock";    // Object use for locking the raceCount
    private int raceCount = 0;        // simple add 1 to this counter
    private int MAX = 10000;        // Do this 10,000 times
    private int NUM_THREADS = 100;    // Create 100 threads

    public static void main(String [] args) {
    new RaceCondition();
    }

    public RaceCondition() {
    ArrayList<Thread> arT = new ArrayList<Thread>();

    // Create thread objects, add them to an array list
    for( int i=0; i<NUM_THREADS; i++){
        Thread rt = new RaceThread( ); // i );
        arT.add( rt );
    }

    // Start all object at once.
    for( Thread rt : arT ){
        rt.start();
    }

    // Wait for all threads to finish before we can print totals created by threads
    for( int i=0; i<NUM_THREADS; i++){
        try { arT.get(i).join(); }
        catch( InterruptedException ie ) { System.out.println("Interrupted thread "+i); }
    }

    // All threads finished, print the summary information.
    // (Try to print this informaiton without the join loop above)
    System.out.printf("\nRace condition, should have %,d. Really have %,d in array, and count of %,d.\n",
                MAX*NUM_THREADS, raceList.size(), raceCount );
    System.out.printf("Array lost %,d. Count lost %,d\n",
             MAX*NUM_THREADS-raceList.size(), MAX*NUM_THREADS-raceCount );
    }   // end RaceCondition constructor



    class RaceThread extends Thread {
    public void run() {
        for ( int i=0; i<MAX; i++){
        try {
            update( i );        
        }    // These  catches show when one thread steps on another's values
        catch( ArrayIndexOutOfBoundsException ai ){ System.out.print("A"); }
        catch( OutOfMemoryError oome ) { System.out.print("O"); }
        }
    }

    // so we don't lose counts, need to synchronize on some object, not primitive
    // Created "countLock" to show how this can work.
    // Comment out the synchronized and ending {, see that we lose counts.

//    public synchronized void update(int i){   // use A
    public void update(int i){                  // remove this when adding A
//      synchronized(countLock){            // or B
//      synchronized(this){             // or C
        raceCount = raceCount + 1;
        raceList.add( i );      // use Vector  
//          }           // end block for B or C
    }   // end update

    }   // end RaceThread inner class


} // end RaceCondition outter class

Access to file download dialog in Firefox

Web Applications generate 3 different types of pop-ups; namely,

 1| JavaScript PopUps
 2| Browser PopUps
 3| Native OS PopUps [e.g., Windows Popup like Upload/Download]

In General, the JavaScript pop-ups are generated by the web application code. Selenium provides an API to handle these JavaScript pop-ups, such as Alert.

Eventually, the simplest way to ignore Browser pop-up and download files is done by making use of Browser profiles; There are couple of ways to do this:

  • Manually involve changes on browser properties (or)
  • Customize browser properties using profile setPreference

Method1

Before you start working with pop-ups on Browser profiles, make sure that the Download options are set default to Save File.

(Open Firefox) Tools > Options > Applications

enter image description here

Method2

Make use of the below snippet and do edits whenever necessary.

FirefoxProfile profile = new FirefoxProfile();

String path = "C:\\Test\\";
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", path);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);  
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
       
driver = new FirefoxDriver(profile);

SQL: How to perform string does not equal

Another way of getting the results

SELECT * from table WHERE SUBSTRING(tester, 1, 8)  <> 'username' or tester is null

open a url on click of ok button in android

    Button imageLogo = (Button)findViewById(R.id.iv_logo);
    imageLogo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String url = "http://www.gobloggerslive.com";

            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }
    });

Correct way of looping through C++ arrays

sizeof tells you the size of a thing, not the number of elements in it. A more C++11 way to do what you are doing would be:

#include <array>
#include <string>
#include <iostream>

int main()
{
    std::array<std::string, 3> texts { "Apple", "Banana", "Orange" };
    for (auto& text : texts) {
        std::cout << text << '\n';
    }
    return 0;
}

ideone demo: http://ideone.com/6xmSrn

Cannot find the declaration of element 'beans'

For me the problem was my file encoding...I used powershell to write the xml file and this was not UTF-8 ... It seems that spring requires UTF8 because as soon as I changed the encoding (using notepad++) it works again without any errors

Now i Use in my powershellscript the following line to output the xml file in UTF-8: [IO.File]::WriteAllLines($fname_dataloader_xml_config_file, $dataloader_configfile)

instead of using the redirection operator > to create my file

Note: I didn't put any xml parameters in my beans tag and it works

How to use subprocess popen Python

Use sh, it'll make things a lot easier:

import sh
print sh.swfdump("/tmp/filename.swf", "-d")

Does Enter key trigger a click event?

Here is the correct SOLUTION! Since the button doesn't have a defined attribute type, angular maybe attempting to issue the keyup event as a submit request and triggers the click event on the button.

<button type="button" ...></button>

Big thanks to DeborahK!

Angular2 - Enter Key executes first (click) function present on the form

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

Why does Java's hashCode() in String use 31 as a multiplier?

Goodrich and Tamassia computed from over 50,000 English words (formed as the union of the word lists provided in two variants of Unix) that using the constants 31, 33, 37, 39, and 41 will produce fewer than 7 collisions in each case. This may be the reason that so many Java implementations choose such constants.

See section 9.2 Hash Tables (page 522) of Data Structures and Algorithms in Java.

Read a file in Node.js

To read the html file from server using http module. This is one way to read file from server. If you want to get it on console just remove http module declaration.

_x000D_
_x000D_
var http = require('http');_x000D_
var fs = require('fs');_x000D_
var server = http.createServer(function(req, res) {_x000D_
  fs.readFile('HTMLPage1.html', function(err, data) {_x000D_
    if (!err) {_x000D_
      res.writeHead(200, {_x000D_
        'Content-Type': 'text/html'_x000D_
      });_x000D_
      res.write(data);_x000D_
      res.end();_x000D_
    } else {_x000D_
      console.log('error');_x000D_
    }_x000D_
  });_x000D_
});_x000D_
server.listen(8000, function(req, res) {_x000D_
  console.log('server listening to localhost 8000');_x000D_
});
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <h1>My Header</h1>_x000D_
  <p>My paragraph.</p>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

In Laravel, the best way to pass different types of flash messages in the session

You could use Laravel Macros.

You can create macros.php in app/helpers and include it routes.php.

if you wish to put your macros in a class file instead, you can look at this tutorial: http://chrishayes.ca/blog/code/laravel-4-object-oriented-form-html-macros-classes-service-provider

HTML::macro('alert', function($class='alert-danger', $value="",$show=false)
{

    $display = $show ? 'display:block' : 'display:none';

    return
        '<div class="alert '.$class.'" style="'.$display.'">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <strong><i class="fa fa-times"></i></strong>'.$value.'
        </div>';
});

In your controller:

Session::flash('message', 'This is so dangerous!'); 
Session::flash('alert', 'alert-danger');

In your View

@if(Session::has('message') && Session::has('alert') )
  {{HTML::alert($class=Session::get('alert'), $value=Session::get('message'), $show=true)}}
@endif

Foreign keys in mongo?

Short answer: You should to use "weak references" between collections, using ObjectId properties:

References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.

https://docs.mongodb.com/manual/core/data-modeling-introduction/#references

This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

json_encode sparse PHP array as JSON array, not JSON object

json_decode($jsondata, true);

true turns all properties to array (sequential or not)

Checking during array iteration, if the current element is the last element

I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:

$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
    if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
                            // just to use this `hasNext()` method to see
                            // if this is the last element
       echo $each;
    }
}

Are HTTP headers case-sensitive?

They are not case sensitive. In fact NodeJS web server explicitly converts them to lower-case, before making them available in the request object.

It's important to note here that all headers are represented in lower-case only, regardless of how the client actually sent them. This simplifies the task of parsing headers for whatever purpose.

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

is there any PHP function for open page in new tab

You can use both PHP and javascript. Perform your php codes in the backend and redirect to a php page. On the php page you redirected to add the code below:

<?php if(condition_to_check_for){ ?>

    <script type="text/javascript">
       window.open('url_goes_here', '_blank');
    </script>

<?  } ?>

Can I access variables from another file?

I may be doing this a little differently. I'm not sure why I use this syntax, copied it from some book a long time ago. But each of my js files defines a variable. The first file, for no reason at all, is called R:

    var R = 
    { 
        somevar: 0,
        othervar: -1,

        init: function() {
          ...
        } // end init function

        somefunction: function(somearg) {
          ...
        }  // end somefunction

        ...

    }; // end variable R definition


    $( window ).load(function() {
       R.init();
    })

And then if I have a big piece of code that I want to segregate, I put it in a separate file and a different variable name, but I can still reference the R variables and functions. I called the new one TD for no good reason at all:

    var TD = 
    { 
        xvar: 0,
        yvar: -1,

        init: function() {
           ...
        } // end init function

        sepfunction: function() {
           ...
           R.somefunction(xvar);
           ...
        }  // end somefunction

        ...

    }; // end variable TD definition


    $( window ).load(function() {
       TD.init();
    })

You can see that where in the TD 'sepfunction' I call the R.somefunction. I realize this doesn't give any runtime efficiencies because both scripts to need to load, but it does help me keep my code organized.

Accessing a local website from another computer inside the local network in IIS 7

Add two bindings to your website, one for local access and another for LAN access like so:

Open IIS and select your local website (that you want to access from your local network) from the left panel:

Connections > server (user-pc) > sites > local site

Open Bindings on the right panel under Actions tab add these bindings:

  1. Local:

    Type: http
    Ip Address: All Unassigned
    Port: 80
    Host name: samplesite.local
    
  2. LAN:

    Type: http
    Ip Address: <Network address of the hosting machine ex. 192.168.0.10>
    Port: 80
    Host name: <Leave it blank>
    

Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.

NOTE:

if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):

192.168.0.10 samplesite.local

How do I convert ticks to minutes?

The clearest way in my view is to use TimeSpan.FromTicks and then convert that to minutes:

TimeSpan ts = TimeSpan.FromTicks(ticks);
double minutes = ts.TotalMinutes;

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

Network tools that simulate slow network connection

I love Charles.

The free version works fine for me.

Throttling, rerwiting, breakpoints are all awesome features.

How to post query parameters with Axios?

axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

Add Bootstrap Glyphicon to Input Box

Here is a non-bootstrap solution that keeps your markup simple by embedding the image representation of the glyphicon directly in the CSS using base64 URI encoding.

_x000D_
_x000D_
input {_x000D_
  border:solid 1px #ddd;_x000D_
}_x000D_
input.search {_x000D_
 padding-left:20px;_x000D_
 background-repeat: no-repeat;_x000D_
 background-position-y: 1px;_x000D_
 background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAYAAABb0P4QAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADbSURBVDhP5ZI9C4MwEIb7//+BEDgICA6C4OQgBJy6dRIEB6EgCNkEJ4e3iT2oHzH9wHbpAwfyJvfkJDnhYH4kHDVKlSAigSAQoCiBKjVGXvaxFXZnxBQYkSlBICII+22K4jM63rbHSthCSdsskVX9Y6KxR5XJSSpVy6GbpbBKp6aw0BzM0ShCe1iKihMXC6EuQtMQwukzPFu3fFd4+C+/cimUNxy6WQkNnmdzL3NYPfDmLVuhZf2wZYz80qDkKX1St3CXAfVMqq4cz3hTaGEpmctxDPmB0M/fCYEbAwZYyVKYcroAAAAASUVORK5CYII=);_x000D_
}
_x000D_
<input class="search">
_x000D_
_x000D_
_x000D_

Custom pagination view in Laravel 5

In Laravel 5.4

The easiest way I found, by exporting them to your resources/views/vendor directory using the vendor:publish command

php artisan vendor:publish --tag=laravel-pagination

and than go to resources\views\vendor\pagination\default.blade.php

and do your customization there.

Full documentation about this can be found here

Date formatting in WPF datagrid

first select datagrid and then go to properties find Datagrid_AutoGeneratingColumn and the double click And then use this code

   Datagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
            {
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
            }

I try it it works on WPF

How to receive serial data using android bluetooth

I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.

My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

How do you run a single query through mysql from the command line?

echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production

Convert a RGB Color Value to a Hexadecimal String

Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<%
String session_val = (String)session.getAttribute("sessionval"); 
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>

What's better at freeing memory with PHP: unset() or $var = null

I still doubt about this, but I've tried it at my script and I'm using xdebug to know how it will affect my app memory usage. The script is set on my function like this :

function gen_table_data($serv, $coorp, $type, $showSql = FALSE, $table = 'ireg_idnts') {
    $sql = "SELECT COUNT(`operator`) `operator` FROM $table WHERE $serv = '$coorp'";
    if($showSql === FALSE) {
        $sql = mysql_query($sql) or die(mysql_error());
        $data = mysql_fetch_array($sql);
        return $data[0];
    } else echo $sql;
}

And I add unset just before the return code and it give me : 160200 then I try to change it with $sql = NULL and it give me : 160224 :)

But there is something unique on this comparative when I am not using unset() or NULL, xdebug give me 160144 as memory usage

So, I think giving line to use unset() or NULL will add process to your application and it will be better to stay origin with your code and decrease the variable that you are using as effective as you can .

Correct me if I'm wrong, thanks

CSS table-cell equal width

Here you go:

http://jsfiddle.net/damsarabi/gwAdA/

You cannot use width: 100px, because the display is table-cell. You can however use Max-width: 100px. then your box will never get bigger than 100px. but you need to add overflow:hidden to make sure the contect don't bleed to other cells. you can also add white-space: nowrap if you wish to keep the height from increasing.

How can you determine a point is between two other points on a line segment?

The length of the segment is not important, thus using a square root is not required and should be avoided since we could lose some precision.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Segment:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def is_between(self, c):
        # Check if slope of a to c is the same as a to b ;
        # that is, when moving from a.x to c.x, c.y must be proportionally
        # increased than it takes to get from a.x to b.x .

        # Then, c.x must be between a.x and b.x, and c.y must be between a.y and b.y.
        # => c is after a and before b, or the opposite
        # that is, the absolute value of cmp(a, b) + cmp(b, c) is either 0 ( 1 + -1 )
        #    or 1 ( c == a or c == b)

        a, b = self.a, self.b             

        return ((b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y) and 
                abs(cmp(a.x, c.x) + cmp(b.x, c.x)) <= 1 and
                abs(cmp(a.y, c.y) + cmp(b.y, c.y)) <= 1)

Some random example of usage :

a = Point(0,0)
b = Point(50,100)
c = Point(25,50)
d = Point(0,8)

print Segment(a,b).is_between(c)
print Segment(a,b).is_between(d)

Java URLConnection Timeout

You can manually force disconnection by a Thread sleep. This is an example:

URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();

then

public class InterruptThread implements Runnable {

    HttpURLConnection con;
    public InterruptThread(HttpURLConnection con) {
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
        } catch (InterruptedException e) {

        }
        con.disconnect();
        System.out.println("Timer thread forcing to quit connection");
    }
}

Clear an input field with Reactjs?

Also after React v 16.8+ you have an ability to use hooks

import React, {useState} from 'react';

const ControlledInputs = () => {
  const [firstName, setFirstName] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (firstName) {
      console.log('firstName :>> ', firstName);
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
          <label htmlFor="firstName">Name: </label>
          <input
            type="text"
            id="firstName"
            name="firstName"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
          />
        <button type="submit">add person</button>
      </form>
    </>
  );
};

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

Express: How to pass app-instance to routes from a different file?

If you want to pass an app-instance to others in Node-Typescript :

Option 1: With the help of import (when importing)

//routes.ts
import { Application } from "express";
import { categoryRoute } from './routes/admin/category.route'
import { courseRoute } from './routes/admin/course.route';

const routing = (app: Application) => {
    app.use('/api/admin/category', categoryRoute)
    app.use('/api/admin/course', courseRoute)
}
export { routing }

Then import it and pass app:

import express, { Application } from 'express';

const app: Application = express();
import('./routes').then(m => m.routing(app))

Option 2: With the help of class

// index.ts
import express, { Application } from 'express';
import { Routes } from './routes';


const app: Application = express();
const rotues = new Routes(app)
...

Here we will access the app in the constructor of Routes Class

// routes.ts
import { Application } from 'express'
import { categoryRoute } from '../routes/admin/category.route'
import { courseRoute } from '../routes/admin/course.route';

class Routes {
    constructor(private app: Application) {
        this.apply();
    }

    private apply(): void {
       this.app.use('/api/admin/category', categoryRoute)
       this.app.use('/api/admin/course', courseRoute)
    }
}

export { Routes }

Find the item with maximum occurrences in a list

I obtained the best results with groupby from itertools module with this function using Python 3.5.2:

from itertools import groupby

a = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]

def occurrence():
    occurrence, num_times = 0, 0
    for key, values in groupby(a, lambda x : x):
        val = len(list(values))
        if val >= occurrence:
            occurrence, num_times =  key, val
    return occurrence, num_times

occurrence, num_times = occurrence()
print("%d occurred %d times which is the highest number of times" % (occurrence, num_times))

Output:

4 occurred 6 times which is the highest number of times

Test with timeit from timeit module.

I used this script for my test with number= 20000:

from itertools import groupby

def occurrence():
    a = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
    occurrence, num_times = 0, 0
    for key, values in groupby(a, lambda x : x):
        val = len(list(values))
        if val >= occurrence:
            occurrence, num_times =  key, val
    return occurrence, num_times

if __name__ == '__main__':
    from timeit import timeit
    print(timeit("occurrence()", setup = "from __main__ import occurrence",  number = 20000))

Output (The best one):

0.1893607140000313

Remove characters after specific character in string, then remove substring?

The Uri class is generally your best bet for manipulating Urls.

Java - ignore exception and continue

You are actually ignoring exception in your code. But I suggest you to reconsider.

Here is a quote from Coding Crimes: Ignoring Exceptions

For a start, the exception should be logged at the very least, not just written out to the console. Also, in most cases, the exception should be thrown back to the caller for them to deal with. If it doesn't need to be thrown back to the caller, then the exception should be handled. And some comments would be nice too.

The usual excuse for this type of code is "I didn't have time", but there is a ripple effect when code is left in this state. Chances are that most of this type of code will never get out in the final production. Code reviews or static analysis tools should catch this error pattern. But that's no excuse, all this does is add time to the maintainance and debugging of the software.

Even if you are ignoring it I suggest you to use specific exception names instead of superclass name. ie., Use NullPointerException instead of Exception in your catch clause.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Go to your config.php. I had the same problem. Verify the username and the password, and also sql select is the same name as the config.

Using momentjs to convert date to epoch then back to date

There are a few things wrong here:

  • First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".

  • .unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.

  • You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:

    moment("10/15/2014 9:00", "M/D/YYYY H:mm")
    
  • .calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.

  • To answer your questions in comments, No - you don't need to call .local() or .utc().

Putting it all together:

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);

On my machine, in the US Pacific time zone, it results in:

Values are: ts = 1413388800000, s = 10/15/2014 9:00

Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.

Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);

How do I round a double to two decimal places in Java?

Are you working with money? Creating a String and then converting it back is pretty loopy.

Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.

Even if you're not working with money, consider BigDecimal.

Making an svg image object clickable with onclick, avoiding absolute positioning

Assuming you don't need cross browser support (which is impossible without a plugin for IE), have you tried using svg as a background image?

Experimental stuff for sure, but thought I would mention it.

How do you use https / SSL on localhost?

If you have IIS Express (with Visual Studio):

To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.

See the steps and pictures at this code project.

IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.

From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.

enter image description here

Document directory path of Xcode Device Simulator

If your app uses CoreData, a nifty trick is to search for the name of the sqlite file using terminal.

find ~ -name my_app_db_name.sqlite

The results will list the full file paths to any simulators that have run your app.

I really wish Apple would just add a button to the iOS Simulator file menu like "Reveal Documents folder in Finder".

How do I hide the PHP explode delimiter from submitted form results?

Instead of adding the line breaks with nl2br() and then removing the line breaks with explode(), try using the line break character '\r' or '\n' or '\r\n'.

<?php     $options= file_get_contents("employees.txt");     $options=explode("\n",$options);        // try \r as well.      foreach ($options as $singleOption){         echo "<option value='".$singleOption."'>".$singleOption."</option>";     }   ?> 

This could also fix the issue if the problem was due to Google Spreadsheets reading the line breaks.

jQuery trigger file input

i had problems with custom client side validation for <input type="file"/> while using a fake button to trigger it and @Guillaume Bodi's solution worked for me (also with opacity: 0; on chrome)

$("#MyForm").on("click", "#fake-button", function () {
        $("#uploadInput").focus().trigger("click");
    });

and css style for upload input

#uploadInput {
opacity: 0.0; 
filter: alpha(opacity=0); /* IE lt 8 */
-ms-filter: "alpha(opacity=0)"; /* IE 8 */
-khtml-opacity: 0.0; /* Safari 1.x */
-moz-opacity: 0.0;
}

Call a Javascript function every 5 seconds continuously

You can use setInterval(), the arguments are the same.

const interval = setInterval(function() {
   // method to be executed;
 }, 5000);

clearInterval(interval); // thanks @Luca D'Amico

how to save and read array of array in NSUserdefaults in swift?

Here is an example of reading and writing a list of objects of type SNStock that implements NSCoding - we have an accessor for the entire list, watchlist, and two methods to add and remove objects, that is addStock(stock: SNStock) and removeStock(stock: SNStock).

import Foundation

class DWWatchlistController {

  private let kNSUserDefaultsWatchlistKey: String = "dw_watchlist_key"

  private let userDefaults: NSUserDefaults

  private(set) var watchlist:[SNStock] {

    get {
      if let watchlistData : AnyObject = userDefaults.objectForKey(kNSUserDefaultsWatchlistKey) {
        if let watchlist : AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(watchlistData as! NSData) {
          return watchlist as! [SNStock]
        }
      }
      return []
    }

    set(watchlist) {
      let watchlistData = NSKeyedArchiver.archivedDataWithRootObject(watchlist)
      userDefaults.setObject(watchlistData, forKey: kNSUserDefaultsWatchlistKey)
      userDefaults.synchronize()
    }
  }

  init() {
    userDefaults = NSUserDefaults.standardUserDefaults()
  }

  func addStock(stock: SNStock) {
    var watchlist = self.watchlist
    watchlist.append(stock)
    self.watchlist = watchlist
  }

  func removeStock(stock: SNStock) {
    var watchlist = self.watchlist
    if let index = find(watchlist, stock) {
      watchlist.removeAtIndex(index)
      self.watchlist = watchlist
    }
  }

}

Remember that your object needs to implement NSCoding or else the encoding won't work. Here is what SNStock looks like:

import Foundation

class SNStock: NSObject, NSCoding
{
  let ticker: NSString
  let name: NSString

  init(ticker: NSString, name: NSString)
  {
    self.ticker = ticker
    self.name = name
  }

  //MARK: NSCoding

  required init(coder aDecoder: NSCoder) {
    self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString
    self.name = aDecoder.decodeObjectForKey("name") as! NSString
  }

  func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(ticker, forKey: "ticker")
    aCoder.encodeObject(name, forKey: "name")
  }

  //MARK: NSObjectProtocol

  override func isEqual(object: AnyObject?) -> Bool {
    if let object = object as? SNStock {
      return self.ticker == object.ticker &&
        self.name == object.name
    } else {
      return false
    }
  }

  override var hash: Int {
    return ticker.hashValue
  }
}

Hope this helps!

How can I add to a List's first position?

 myList.Insert(0, item);

         

Android scale animation on view

Here is a code snip to do exactly that.

public void scaleView(View v, float startScale, float endScale) {
    Animation anim = new ScaleAnimation(
            1f, 1f, // Start and end values for the X axis scaling
            startScale, endScale, // Start and end values for the Y axis scaling
            Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
            Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
    anim.setFillAfter(true); // Needed to keep the result of the animation
    anim.setDuration(1000);
    v.startAnimation(anim);
}

The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...).

The other 4 args are for the Y-scaling we do care about.

startScale, endScale - In your case, you'd use 0f, 0.6f.

Animation.RELATIVE_TO_SELF, 1f - This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f.

Finally, and equally important, is the call to anim.setFillAfter(true). If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.

So in your case, you can do something like this:

View v = findViewById(R.id.viewContainer);
scaleView(v, 0f, .6f);

Codesign error: Provisioning profile cannot be found after deleting expired profile

Just spent a hour or so doing this and with the help of Brad's advice and a few additional changes it all worked.

I've done this using the following: 10.7.3, Xcode 4.3.2, iOS 5.1 btw.

1) Right click on your myapp.xcodeproj and select package contents

2) open project.pbxproj with a text editor (don't recommend textedit as it may screw up the formatting)

3) Scroll all the way down until you find /* Begin XCBuildConfiguration section */

4) Notice that you have a debug and release sections

5) In the release section take a look at CODE_SIGN_IDENTITY & "CODE_SIGN_IDENTITY[sdk=iphoneos*]" it should look something like this:

CODE_SIGN_IDENTITY = "iPhone Distribution: MyCompany LLC";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution: MyCompany LLC";

6) Take a look at PROVISIONING_PROFILE and "PROVISIONING_PROFILE[sdk=iphoneos*]" they should look like this:

PROVISIONING_PROFILE = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";

This should match your provisioning profile in Xcode. To see if they match open Xcode > Window > Organizer > Devices > Provisioning Profiles > Right click on the profile > Reveal in Finder > The filename of the .mobileprovision is your profile id.

7) Scroll down in the project.pbxproj and find a second instance of the release section. The second instance of the release section should end with a comment saying /* End XCBuildConfiguration section */

8) make sure that the second section matches the first section so that CODE_SIGN_IDENTITY, "CODE_SIGN_IDENTITY[sdk=iphoneos*], and PROVISIONING_PROFILE are all filled in.

What is trunk, branch and tag in Subversion?

A trunk is considered your main code base, a branch offshoot of the trunk. Like, you create a branch if you want to implement a new feature, but don't want to affect the main trunk.

TortoiseSVN has good documentation, and a great diff tool.

I use Visual studio, and I use VisualSVN and TortoiseSVN.

Save file/open file dialog box, using Swing & Netbeans GUI editor

I think you face three problems:

  1. understanding the FileChooser
  2. writing/reading files
  3. understanding extensions and file formats

ad 1. Are you sure you've connected the FileChooser to a correct panel/container? I'd go for a simple tutorial on this matter and see if it works. That's the best way to learn - by making small but large enough steps forward. Breaking down an issue into such parts might be tricky sometimes ;)

ad. 2. After you save or open the file you should have methods to write or read the file. And again there are pretty neat examples on this matter and it's easy to understand topic.

ad. 3. There's a difference between a file having extension and file format. You can change the format of any file to anything you want but that doesn't affect it's contents. It might just render the file unreadable for the application associated with such extension. TXT files are easy - you read what you write. XLS, DOCX etc. require more work and usually framework is the best way to tackle these.

Delete all but the most recent X files in bash

find . -maxdepth 1 -type f -printf '%T@ %p\0' | sort -r -z -n | awk 'BEGIN { RS="\0"; ORS="\0"; FS="" } NR > 5 { sub("^[0-9]*(.[0-9]*)? ", ""); print }' | xargs -0 rm -f

Requires GNU find for -printf, and GNU sort for -z, and GNU awk for "\0", and GNU xargs for -0, but handles files with embedded newlines or spaces.

Calculate row means on subset of columns

(Another solution using pivot_longer & pivot_wider from latest Tidyr update)

You should try using pivot_longer to get your data from wide to long form Read latest tidyR update on pivot_longer & pivot_wider (https://tidyr.tidyverse.org/articles/pivot.html)

library(tidyverse)
C1<-c(3,2,4,4,5)
C2<-c(3,7,3,4,5)
C3<-c(5,4,3,6,3)
DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)

Output here

  ID     mean
  <fct> <dbl>
1 A      3.67
2 B      4.33
3 C      3.33
4 D      4.67
5 E      4.33

How to specify Memory & CPU limit in docker compose version 3

I know the topic is a bit old and seems stale, but anyway I was able to use these options:

    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M

when using 3.7 version of docker-compose

What helped in my case, was using this command:

docker-compose --compatibility up

--compatibility flag stands for (taken from the documentation):

If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent

Think it's great, that I don't have to revert my docker-compose file back to v2.

git pull fails "unable to resolve reference" "unable to update local ref"

Had the same msg but with a directory, got a failed msg on pull.

git --prone did not help me either. Turns out there was a file with the same name as a directory created remotely.

Had to go to .git\logs\refs\remotes\origin and erase the locale file - then pull again, all good.

AngularJS: ng-model not binding to ng-checked for checkboxes

ngModel and ngChecked are not meant to be used together.

ngChecked is expecting an expression, so by saying ng-checked="true", you're basically saying that the checkbox will always be checked by default.

You should be able to just use ngModel, tied to a boolean property on your model. If you want something else, then you either need to use ngTrueValue and ngFalseValue (which only support strings right now), or write your own directive.

What is it exactly that you're trying to do? If you just want the first checkbox to be checked by default, you should change your model -- item1: true,.

Edit: You don't have to submit your form to debug the current state of the model, btw, you can just dump {{testModel}} into your HTML (or <pre>{{testModel|json}}</pre>). Also your ngModel attributes can be simplified to ng-model="testModel.item1".

http://plnkr.co/edit/HtdOok8aieBjT5GFZOb3?p=preview

Postgres manually alter sequence

I don't try changing sequence via setval. But using ALTER I was issued how to write sequence name properly. And this only work for me:

  1. Check required sequence name using SELECT * FROM information_schema.sequences;

  2. ALTER SEQUENCE public."table_name_Id_seq" restart {number};

    In my case it was ALTER SEQUENCE public."Services_Id_seq" restart 8;

Also there is a page on wiki.postgresql.org where describes a way to generate sql script to fix sequences in all database tables at once. Below the text from link:

Save this to a file, say 'reset.sql'

SELECT 'SELECT SETVAL(' ||
       quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
       ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
       quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
     pg_depend AS D,
     pg_class AS T,
     pg_attribute AS C,
     pg_tables AS PGT
WHERE S.relkind = 'S'
    AND S.oid = D.objid
    AND D.refobjid = T.oid
    AND D.refobjid = C.attrelid
    AND D.refobjsubid = C.attnum
    AND T.relname = PGT.tablename
ORDER BY S.relname;

Run the file and save its output in a way that doesn't include the usual headers, then run that output. Example:

psql -Atq -f reset.sql -o temp
psql -f temp
rm temp

And the output will be a set of sql commands which look exactly like this:

SELECT SETVAL('public."SocialMentionEvents_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."SocialMentionEvents";
SELECT SETVAL('public."Users_Id_seq"', COALESCE(MAX("Id"), 1) ) FROM public."Users";

Node.js Best Practice Exception Handling

nodejs domains is the most up to date way of handling errors in nodejs. Domains can capture both error/other events as well as traditionally thrown objects. Domains also provide functionality for handling callbacks with an error passed as the first argument via the intercept method.

As with normal try/catch-style error handling, is is usually best to throw errors when they occur, and block out areas where you want to isolate errors from affecting the rest of the code. The way to "block out" these areas are to call domain.run with a function as a block of isolated code.

In synchronous code, the above is enough - when an error happens you either let it be thrown through, or you catch it and handle there, reverting any data you need to revert.

try {  
  //something
} catch(e) {
  // handle data reversion
  // probably log too
}

When the error happens in an asynchronous callback, you either need to be able to fully handle the rollback of data (shared state, external data like databases, etc). OR you have to set something to indicate that an exception has happened - where ever you care about that flag, you have to wait for the callback to complete.

var err = null;
var d = require('domain').create();
d.on('error', function(e) {
  err = e;
  // any additional error handling
}
d.run(function() { Fiber(function() {
  // do stuff
  var future = somethingAsynchronous();
  // more stuff

  future.wait(); // here we care about the error
  if(err != null) {
    // handle data reversion
    // probably log too
  }

})});

Some of that above code is ugly, but you can create patterns for yourself to make it prettier, eg:

var specialDomain = specialDomain(function() {
  // do stuff
  var future = somethingAsynchronous();
  // more stuff

  future.wait(); // here we care about the error
  if(specialDomain.error()) {
    // handle data reversion
    // probably log too
  } 
}, function() { // "catch"
  // any additional error handling
});

UPDATE (2013-09):

Above, I use a future that implies fibers semantics, which allow you to wait on futures in-line. This actually allows you to use traditional try-catch blocks for everything - which I find to be the best way to go. However, you can't always do this (ie in the browser)...

There are also futures that don't require fibers semantics (which then work with normal, browsery JavaScript). These can be called futures, promises, or deferreds (I'll just refer to futures from here on). Plain-old-JavaScript futures libraries allow errors to be propagated between futures. Only some of these libraries allow any thrown future to be correctly handled, so beware.

An example:

returnsAFuture().then(function() {
  console.log('1')
  return doSomething() // also returns a future

}).then(function() {
  console.log('2')
  throw Error("oops an error was thrown")

}).then(function() {
  console.log('3')

}).catch(function(exception) {
  console.log('handler')
  // handle the exception
}).done()

This mimics a normal try-catch, even though the pieces are asynchronous. It would print:

1
2
handler

Note that it doesn't print '3' because an exception was thrown that interrupts that flow.

Take a look at bluebird promises:

Note that I haven't found many other libraries other than these that properly handle thrown exceptions. jQuery's deferred, for example, don't - the "fail" handler would never get the exception thrown an a 'then' handler, which in my opinion is a deal breaker.

Image, saved to sdcard, doesn't appear in Android's Gallery app

Use this after saving the image

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

None of the other answeres worked for me. My imports were not being resolved because IntelliJ pointed to wrong .m2 file.

IntelliJ Version: IntelliJ Idea 2018.1.5

My location for the .m2 directory was pointed to the wrong path. All I did to fix it was re-point IntelliJ to the right .m2 directory and update it.

First, go to: File->Settings->Build, Execution, Deployment->Build Tools->Maven

I had to change the User settings file: and the Local repository: to the correct location of my .m2 directory.

After this go to: File->Settings->Build, Execution, Deployment->Build Tools->Maven->Repositories

and click the Update button.

Calculating the sum of two variables in a batch script

You can solve any equation including adding with this code:

@echo off

title Richie's Calculator 3.0

:main

echo Welcome to Richie's Calculator 3.0

echo Press any key to begin calculating...

pause>nul

echo Enter An Equation

echo Example: 1+1

set /p 

set /a sum=%equation%

echo.

echo The Answer Is:

echo %sum%

echo.

echo Press any key to return to the main menu

pause>nul

cls

goto main

React - Component Full Screen (with height 100%)

<div style={{ height: "100vh", background: "#2d405f" }}>
   <Component 1 />
   <Component 2 />
</div>

Create a div with full screen with background color #2d405f

Java Hashmap: How to get key from value?

Decorate map with your own implementation

class MyMap<K,V> extends HashMap<K, V>{

    Map<V,K> reverseMap = new HashMap<V,K>();

    @Override
    public V put(K key, V value) {
        // TODO Auto-generated method stub
        reverseMap.put(value, key);
        return super.put(key, value);
    }

    public K getKey(V value){
        return reverseMap.get(value);
    }
}

How do I check if an integer is even or odd?

You guys are waaaaaaaay too efficient. What you really want is:

public boolean isOdd(int num) {
  int i = 0;
  boolean odd = false;

  while (i != num) {
    odd = !odd;
    i = i + 1;
  }

  return odd;
}

Repeat for isEven.

Of course, that doesn't work for negative numbers. But with brilliance comes sacrifice...

Count occurrences of a char in a string using Bash

Building on everyone's great answers and comments, this is the shortest and sweetest version:

grep -o "$needle" <<< "$haystack" | wc -l

Set environment variables on Mac OS X Lion

Your .profile or .bash_profile are simply files that are present in your "home" folder. If you open a Finder window and click your account name in the Favorites pane, you won't see them. If you open a Terminal window and type ls to list files you still won't see them. However, you can find them by using ls -a in the terminal. Or if you open your favorite text editor (say TextEdit since it comes with OS X) and do File->Open and then press Command+Shift+. and click on your account name (home folder) you will see them as well. If you do not see them, then you can create one in your favorite text editor.

Now, adding environment variables is relatively straightforward and remarkably similar to windows conceptually. In your .profile just add, one per line, the variable name and its value as follows:

export JAVA_HOME=/Library/Java/Home
export JRE_HOME=/Library/Java/Home

etc.

If you are modifying your "PATH" variable, be sure to include the system's default PATH that was already set for you:

export PATH=$PATH:/path/to/my/stuff

Now here is the quirky part, you can either open a new Terminal window to have the new variables take effect, or you will need to type .profile or .bash_profile to reload the file and have the contents be applied to your current Terminal's environment.

You can check that your changes took effect using the "set" command in your Terminal. Just type set (or set | more if you prefer a paginated list) and be sure what you added to the file is there.

As for adding environment variables to GUI apps, that is normally not necessary and I'd like to hear more about what you are specifically trying to do to better give you an answer for it.

How can I pipe stderr, and not stdout?

I just came up with a solution for sending stdout to one command and stderr to another, using named pipes.

Here goes.

mkfifo stdout-target
mkfifo stderr-target
cat < stdout-target | command-for-stdout &
cat < stderr-target | command-for-stderr &
main-command 1>stdout-target 2>stderr-target

It's probably a good idea to remove the named pipes afterward.

CSS div element - how to show horizontal scroll bars only?

I also had to add white-space: nowrap; to the style, otherwise elements would wrap down into the area that we're removing the ability to scroll to.

Difference in Months between two dates in JavaScript

You could also consider this solution, this function returns the month difference in integer or number

Passing the start date as the first or last param, is fault tolerant. Meaning, the function would still return the same value.

_x000D_
_x000D_
const diffInMonths = (end, start) => {_x000D_
   var timeDiff = Math.abs(end.getTime() - start.getTime());_x000D_
   return Math.round(timeDiff / (2e3 * 3600 * 365.25));_x000D_
}_x000D_
_x000D_
const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));_x000D_
_x000D_
// shows month difference as integer/number_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Importing .py files in Google Colab

In case anyone else is interested to know how to import files/packages from gdrive inside a google colab. The following procedure worked for me:

1) Mount your google drive in google colab:

from google.colab import drive
drive.mount('/content/gdrive/')

2) Append the directory to your python path using sys:

import sys
sys.path.append('/content/gdrive/mypythondirectory')

Now you should be able to import stuff from that directory!

What does 'corrupted double-linked list' mean

Heap overflow should be blame (but not always) for corrupted double-linked list, malloc(): memory corruption, double free or corruption (!prev)-like glibc warnings.

It should be reproduced by the following code:

#include <vector>

using std::vector;


int main(int argc, const char *argv[])
{
    int *p = new int[3];
    vector<int> vec;
    vec.resize(100);
    p[6] = 1024;
    delete[] p;
    return 0;
}

if compiled using g++ (4.5.4):

$ ./heapoverflow
*** glibc detected *** ./heapoverflow: double free or corruption (!prev): 0x0000000001263030 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7af26)[0x7f853f5d3f26]
./heapoverflow[0x40138e]
./heapoverflow[0x400d9c]
./heapoverflow[0x400bd9]
./heapoverflow[0x400aa6]
./heapoverflow[0x400a26]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x7f853f57b4bd]
./heapoverflow[0x4008f9]
======= Memory map: ========
00400000-00403000 r-xp 00000000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
00602000-00603000 r--p 00002000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
00603000-00604000 rw-p 00003000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
01263000-01284000 rw-p 00000000 00:00 0                                  [heap]
7f853f559000-7f853f6fa000 r-xp 00000000 09:01 201329536                  /lib64/libc-2.15.so
7f853f6fa000-7f853f8fa000 ---p 001a1000 09:01 201329536                  /lib64/libc-2.15.so
7f853f8fa000-7f853f8fe000 r--p 001a1000 09:01 201329536                  /lib64/libc-2.15.so
7f853f8fe000-7f853f900000 rw-p 001a5000 09:01 201329536                  /lib64/libc-2.15.so
7f853f900000-7f853f904000 rw-p 00000000 00:00 0
7f853f904000-7f853f919000 r-xp 00000000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853f919000-7f853fb19000 ---p 00015000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb19000-7f853fb1a000 r--p 00015000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1a000-7f853fb1b000 rw-p 00016000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1b000-7f853fc11000 r-xp 00000000 09:01 201329538                  /lib64/libm-2.15.so
7f853fc11000-7f853fe10000 ---p 000f6000 09:01 201329538                  /lib64/libm-2.15.so
7f853fe10000-7f853fe11000 r--p 000f5000 09:01 201329538                  /lib64/libm-2.15.so
7f853fe11000-7f853fe12000 rw-p 000f6000 09:01 201329538                  /lib64/libm-2.15.so
7f853fe12000-7f853fefc000 r-xp 00000000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f853fefc000-7f85400fb000 ---p 000ea000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f85400fb000-7f8540103000 r--p 000e9000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540103000-7f8540105000 rw-p 000f1000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540105000-7f854011a000 rw-p 00000000 00:00 0
7f854011a000-7f854013c000 r-xp 00000000 09:01 201328977                  /lib64/ld-2.15.so
7f854031c000-7f8540321000 rw-p 00000000 00:00 0
7f8540339000-7f854033b000 rw-p 00000000 00:00 0
7f854033b000-7f854033c000 r--p 00021000 09:01 201328977                  /lib64/ld-2.15.so
7f854033c000-7f854033d000 rw-p 00022000 09:01 201328977                  /lib64/ld-2.15.so
7f854033d000-7f854033e000 rw-p 00000000 00:00 0
7fff92922000-7fff92943000 rw-p 00000000 00:00 0                          [stack]
7fff929ff000-7fff92a00000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
[1]    18379 abort      ./heapoverflow

and if compiled using clang++(6.0 (clang-600.0.56)):

$  ./heapoverflow
[1]    96277 segmentation fault  ./heapoverflow

If you thought you might have written a bug like that, here is some hints to trace it out.

First, compile the code with debug flag(-g):

g++ -g foo.cpp

And then, run it using valgrind:

$ valgrind ./a.out
==12693== Memcheck, a memory error detector
==12693== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12693== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==12693== Command: ./a.out
==12693==
==12693== Invalid write of size 4
==12693==    at 0x400A25: main (foo.cpp:11)
==12693==  Address 0x5a1c058 is 12 bytes after a block of size 12 alloc'd
==12693==    at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12693==    by 0x4009F6: main (foo.cpp:8)
==12693==
==12693==
==12693== HEAP SUMMARY:
==12693==     in use at exit: 0 bytes in 0 blocks
==12693==   total heap usage: 2 allocs, 2 frees, 412 bytes allocated
==12693==
==12693== All heap blocks were freed -- no leaks are possible
==12693==
==12693== For counts of detected and suppressed errors, rerun with: -v
==12693== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

The bug is located in ==12693== at 0x400A25: main (foo.cpp:11)

Is there a simple way that I can sort characters in a string in alphabetical order

Yes; copy the string to a char array, sort the char array, then copy that back into a string.

static string SortString(string input)
{
    char[] characters = input.ToArray();
    Array.Sort(characters);
    return new string(characters);
}

Make more than one chart in same IPython Notebook cell

Make the multiple axes first and pass them to the Pandas plot function, like:

fig, axs = plt.subplots(1,2)

df['korisnika'].plot(ax=axs[0])
df['osiguranika'].plot(ax=axs[1])

It still gives you 1 figure, but with two different plots next to each other.

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

Jenkins: Is there any way to cleanup Jenkins workspace?

There is a way to cleanup workspace in Jenkins. You can clean up the workspace before build or after build.

First, install Workspace Cleanup Plugin.

To clean up the workspace before build: Under Build Environment, check the box that says Delete workspace before build starts.

To clean up the workspace after the build: Under the heading Post-build Actions select Delete workspace when build is done from the Add Post-build Actions drop down menu.

Function to calculate distance between two coordinates

Calculate the Distance between Two Points in javascript

function distance(lat1, lon1, lat2, lon2, unit) {
        var radlat1 = Math.PI * lat1/180
        var radlat2 = Math.PI * lat2/180
        var theta = lon1-lon2
        var radtheta = Math.PI * theta/180
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist)
        dist = dist * 180/Math.PI
        dist = dist * 60 * 1.1515
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return dist
}

For more details refer this: Reference Link

System.Data.SqlClient.SqlException: Login failed for user

Check the properties of SQL Sever from the Object explorer.

If Integrated Security is set to true, make the same changes in connection string as well.

check the screenshot of the property grid

It worked in case of ASP.NET Core Web Api...

The request failed or the service did not respond in a timely fashion?

Just disable the VIA protocol in sql server configuration manager

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I faced this issue moment ago, after migrating from android.support to androidx.

The problem was renderscript.

Solution: I removed from my build.gradle those two lines:

renderscriptTargetApi 21
renderscriptSupportModeEnabled true

after that project building failed, because of unresolved references:

import androidx.renderscript.Allocation;
import androidx.renderscript.Element;
import androidx.renderscript.RenderScript;
import androidx.renderscript.ScriptIntrinsicBlur;

so I've changed them to:

import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;

After that all problems were gone.

Rounding SQL DateTime to midnight

In SQL Server 2008 and newer you can cast the DateTime to a Date, which removes the time element.

WHERE Orders.OrderStatus = 'Shipped'  
AND Orders.ShipDate >= (cast(GETDATE()-6 as date))  

In SQL Server 2005 and below you can use:

WHERE Orders.OrderStatus = 'Shipped'  
AND Orders.ShipDate >= DateAdd(Day, Datediff(Day,0, GetDate() -6), 0)

What's the difference between MyISAM and InnoDB?

MYISAM:

  1. MYISAM supports Table-level Locking
  2. MyISAM designed for need of speed
  3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
  4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
  5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
  6. MYISAM supports fulltext search
  7. You can use MyISAM, if the table is more static with lots of select and less update and delete.

INNODB:

  1. InnoDB supports Row-level Locking
  2. InnoDB designed for maximum performance when processing high volume of data
  3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
  4. InnoDB stores its tables and indexes in a tablespace
  5. InnoDB supports transaction. You can commit and rollback with InnoDB

Could not find or load main class

I faced a similar problem in Eclipse. Whenever I clicked on the Run button it gave me the message, "Error: Could not find or load main class". But when I right click on the java file in the project explorer and Run As Java configuration, it works perfectly.

I think this is because it tries by default to run it in some other configuration which causes problems.

Hope this answer helps some.

How to cherry-pick from a remote branch?

After merging a development branch to master, I usually delete the development branch. However, if I want to cherry pick the commits in the development branch, I have to use the merge commit hash to avoid "bad object" error.

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

How to forward declare a template class in namespace std?

The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:

namespace std {
  template<class T, class Allocator = std::allocator<T>>
  class list;
}

But to make even such a forward declaration in namespace std is explicitly prohibited by the standard: the only thing you're allowed to put in std is a template specialisation, commonly std::less on a user-defined type. Someone else can cite the relevant text if necessary.

Just #include <list> and don't worry about it.

Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H instead of __TEST__. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.

How do I install a Python package with a .whl file?

EDIT: THIS NO LONGER IS A PART OF PIP

To avoid having to download such files, you can try:

pip install --use-wheel pillow

For more information, see this.

SQL SELECT WHERE field contains words

If you just want to find a match.

SELECT * FROM MyTable WHERE INSTR('word1 word2 word3',Column1)<>0

SQL Server :

CHARINDEX(Column1, 'word1 word2 word3', 1)<>0

To get exact match. Example (';a;ab;ac;',';b;') will not get a match.

SELECT * FROM MyTable WHERE INSTR(';word1;word2;word3;',';'||Column1||';')<>0

Assign an initial value to radio button as checked

Note that if you have two radio button with same "name" attribute and they have "required" attribute, then adding "checked" attribute to them won't make them checked.

Example: This makes both radio button remain unchecked.

<input type="radio" name="gender" value="male" required <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" required />

This will makes the "male" radio button checked.

<input type="radio" name="gender" value="male" <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" />

Assign keyboard shortcut to run procedure

For assigning a keyboard key to button on the sheet you can use this code, just copy this code to the sheet which contain the button.

Here Return specifies the key and get_detail is the procedure name.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.OnKey "{RETURN}", "get_detail"

End Sub

Now within this sheet whenever you press Enter button the assigned macro will be called.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

Use this

 from tensorflow.keras.datasets import imdb

instead of this

 from keras.datasets import imdb

Eventviewer eventid for lock and unlock

Using Windows 10 Home edition. I was unable to get my event viewer to capture events 4800 and 4801, even after installing the Windows Group Policy Editor, enabling auditing on all the relevant events, and restarting the computer. However, I was able to discover other events that are tied to locking and unlocking that you can use as accurate and reliable indicators of when the PC was locked. See configurations below - the first is for PC Locked (the event connected to displaying C:\Windows\System32\LogonUI.exe) - and the second is for PC Unlocked (the event for successful logon).

enter image description here

enter image description here

How to reset Jenkins security settings from the command line?

One other way would be to manually edit the configuration file for your user (e.g. /var/lib/jenkins/users/username/config.xml) and update the contents of passwordHash:

<passwordHash>#jbcrypt:$2a$10$razd3L1aXndFfBNHO95aj.IVrFydsxkcQCcLmujmFQzll3hcUrY7S</passwordHash>

Once you have done this, just restart Jenkins and log in using this password:

test

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

For AMPPS, I have to add this is my phpMyAdmin/config.inc.php

$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Note: In Ubuntu, I had to locate where the file is and I used locate config.inc.php

This answer is only meant for local, development purposes :)

Multiline TextView in Android?

I just thought I'd add that if you use :

android:inputType="textMultiLine"

Then the view stops being clickable. I was trying to get multi line textviews in my slide-drawer menu which obviously needs to respond to clicks.

The android:singleLine="false" worked fine though.

How to send an email using PHP?

For most projects, I use Swift mailer these days. It's a very flexible and elegant object-oriented approach to sending emails, created by the same people who gave us the popular Symfony framework and Twig template engine.


Basic usage :

require 'mail/swift_required.php';

$message = Swift_Message::newInstance()
    // The subject of your email
    ->setSubject('Jane Doe sends you a message')
    // The from address(es)
    ->setFrom(array('[email protected]' => 'Jane Doe'))
    // The to address(es)
    ->setTo(array('[email protected]' => 'Frank Stevens'))
    // Here, you put the content of your email
    ->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');

if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
    echo json_encode([
        "status" => "OK",
        "message" => 'Your message has been sent!'
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        "status" => "error",
        "message" => 'Oops! Something went wrong!'
    ], JSON_PRETTY_PRINT);
}

See the official documentation for more info on how to use Swift mailer.

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I fixed this problem by running this in terminal. Full writeup is available over here

rvm install 2.2.0 --disable-binary

AngularJS UI Router - change url without reloading state

Try something like this

$state.go($state.$current.name, {... $state.params, 'key': newValue}, {notify: false})

Any way to declare an array in-line?

I'd like to add that the array initialization syntax is very succinct and flexible. I use it a LOT to extract data from my code and place it somewhere more usable.

As an example, I've often created menus like this:

Menu menu=initMenus(menuHandler, new String[]{"File", "+Save", "+Load", "Edit", "+Copy", ...});

This would allow me to write come code to set up a menu system. The "+" is enough to tell it to place that item under the previous item.

I could bind it to the menuHandler class either by a method naming convention by naming my methods something like "menuFile, menuFileSave, menuFileLoad, ..." and binding them reflectively (there are other alternatives).

This syntax allows AMAZINGLY brief menu definition and an extremely reusable "initMenus" method. (Yet I don't bother reusing it because it's always fun to write and only takes a few minutes+a few lines of code).

any time you see a pattern in your code, see if you can replace it with something like this, and always remember how succinct the array initialization syntax is!.

Return value from exec(@sql)

On the one hand you could use sp_executesql:

exec sp_executesql N'select @rowcount=count(*) from anytable', 
                    N'@rowcount int output', @rowcount output;

On the other hand you could use a temporary table:

declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);

d3.select("#element") not working when code above the html element

Use jQuery $(document) function...

$(document).ready(function(){

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x0 = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var x1 = d3.scale.ordinal();

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.ordinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var xAxis = d3.svg.axis()
    .scale(x0)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

//d3.select('#chart svg')
//d3.select("body").append("svg")


    //var svg = d3.select("#chart").append("svg:svg");

    var svg = d3.select("#BarChart").append("svg:svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var updateData = function(getData){

    d3.selectAll('svg > g > *').remove();

    d3.csv(getData, function(error, data) {
      if (error) throw error;

      var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });

      data.forEach(function(d) {
        d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
      });

      x0.domain(data.map(function(d) { return d.State; }));
      x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
      y.domain([0, d3.max(data, function(d) { return d3.max(d.ages, function(d) { return d.value; }); })]);

      svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis);

      svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Population");

      var state = svg.selectAll(".state")
          .data(data)
        .enter().append("g")
          .attr("class", "state")
          .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });

      state.selectAll("rect")
          .data(function(d) { return d.ages; })
        .enter().append("rect")
          .attr("width", x1.rangeBand())
          .attr("x", function(d) { return x1(d.name); })
          .attr("y", function(d) { return y(d.value); })
          .attr("height", function(d) { return height - y(d.value); })
          .style("fill", function(d) { return color(d.name); });

      var legend = svg.selectAll(".legend")
          .data(ageNames.slice().reverse())
        .enter().append("g")
          .attr("class", "legend")
          .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

      legend.append("rect")
          .attr("x", width - 18)
          .attr("width", 18)
          .attr("height", 18)
          .style("fill", color);

      legend.append("text")
          .attr("x", width - 24)
          .attr("y", 9)
          .attr("dy", ".35em")
          .style("text-anchor", "end")
          .text(function(d) { return d; });

    });

}

updateData('data1.csv');

});

how to convert current date to YYYY-MM-DD format with angular 2

Try this below code it is also works well in angular 2

<span>{{current_date | date: 'yyyy-MM-dd'}}</span>

How might I schedule a C# Windows Service to perform a task daily?

I wouldn't use Thread.Sleep(). Either use a scheduled task (as others have mentioned), or set up a timer inside your service, which fires periodically (every 10 minutes for example) and check if the date changed since the last run:

private Timer _timer;
private DateTime _lastRun = DateTime.Now.AddDays(-1);

protected override void OnStart(string[] args)
{
    _timer = new Timer(10 * 60 * 1000); // every 10 minutes
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    _timer.Start();
    //...
}


private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    // ignore the time, just compare the date
    if (_lastRun.Date < DateTime.Now.Date)
    {
        // stop the timer while we are running the cleanup task
        _timer.Stop();
        //
        // do cleanup stuff
        //
        _lastRun = DateTime.Now;
        _timer.Start();
    }
}

Unable to load script from assets index.android.bundle on windows

I was also facing this problem because when I run projects on the emulator its working fine but on a real device it gives this error. So I resolve this problem by the following solution

1st step: First of all open cmd and go to your SDK manager Platform-tools folder

cd C:Development\Android\Sdk\Platform-tools

2nd step: now run this command :

adb devices

after this command check your device listed in command prompt

3rd step: now run this

adb reverse tcp:8081 tcp:8081

Now your setup is done

4th step: Go to your project directory and run this command

react-native run-android

How do I get the parent directory in Python?

The Pathlib method (Python 3.4+)

from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object

The traditional method

import os.path
os.path.dirname('C:\Program Files')
# Returns a string


Which method should I use?

Use the traditional method if:

  • You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)

  • Your Python version is less than 3.4.

  • You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.

If none of the above apply, use Pathlib.



What is Pathlib?

If you don't know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I've highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.

Navigating inside a directory tree:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

Querying path properties:

>>> q.exists()
True
>>> q.is_dir()
False

Warning: A non-numeric value encountered

$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
{
$sn++;
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy 
$notes = "some notes here";//any notes about the jobs

$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";


/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";

echo $$job_no;//and then echo each job

}

that's the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.

After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to

/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows

Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.

How to construct a std::string from a std::vector<char>?

With C++11, you can do std::string(v.data()) or, if your vector does not contain a '\0' at the end, std::string(v.data(), v.size()).

Sending HTML mail using a shell script

The tags include 'sendmail' so here's a solution using that:

(
echo "From: [email protected] "
echo "To: [email protected] "
echo "MIME-Version: 1.0"
echo "Content-Type: multipart/alternative; " 
echo ' boundary="some.unique.value.ABC123/server.xyz.com"' 
echo "Subject: Test HTML e-mail." 
echo "" 
echo "This is a MIME-encapsulated message" 
echo "" 
echo "--some.unique.value.ABC123/server.xyz.com" 
echo "Content-Type: text/html" 
echo "" 
echo "<html> 
<head>
<title>HTML E-mail</title>
</head>
<body>
<a href='http://www.google.com'>Click Here</a>
</body>
</html>"
echo "------some.unique.value.ABC123/server.xyz.com--"
) | sendmail -t

A wrapper for sendmail can make this job easier, for example, mutt:

mutt -e 'set content_type="text/html"' [email protected] -s "subject" <  message.html

List files in local git repo?

Try this command:

git ls-files 

This lists all of the files in the repository, including those that are only staged but not yet committed.

http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.

You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:

sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
  abstract erubis activesupport mime-types mail text-hyphen text-format   \
  thor i18n rake bundler arel railties rails --prerelease --force

JavaScript: remove event listener

element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();


HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
    this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};


HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
    for (var i = 0; i < this.myListeners.length; i++) {
        this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
    };
   delete this.myListeners;
};
};

Best practices for API versioning?

This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.

Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.

On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.

Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.

This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).

Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.

Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.

A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.

From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.

From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.

However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!

The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:

  • develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).

  • bind to a specific version of the API (which becomes apparent) but only for a limited time

For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):

http://shonzilla/api/customers/1234
http://shonzilla/api/v3.0/customers/1234
http://shonzilla/api/v3/customers/1234

In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:

http://shonzilla/api/v2.2/customers/1234
http://shonzilla/api/v2.0/customers/1234
http://shonzilla/api/v2/customers/1234
http://shonzilla/api/v1.1/customers/1234
http://shonzilla/api/v1/customers/1234

should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location HTTP header that redirects to the appropriate version of resource URI which remain to be this one:

http://shonzilla/api/customers/1234

There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:

  • 301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.

  • 302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).

  • other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification

Difference between a View's Padding and Margin

Below image will let you understand the padding and margin-

enter image description here

How to search a specific value in all tables (PostgreSQL)?

to search every column of every table for a particular value

This does not define how to match exactly.
Nor does it define what to return exactly.

Assuming:

  • Find any row with any column containing the given value in its text representation - as opposed to equaling the given value.
  • Return the table name (regclass) and the tuple ID (ctid), because that's simplest.

Here is a dead simple, fast and slightly dirty way:

CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
  RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
   FOR _tbl IN
      SELECT c.oid::regclass
      FROM   pg_class c
      JOIN   pg_namespace n ON n.oid = relnamespace
      WHERE  c.relkind = 'r'                           -- only tables
      AND    n.nspname !~ '^(pg_|information_schema)'  -- exclude system schemas
      ORDER BY n.nspname, c.relname
   LOOP
      RETURN QUERY EXECUTE format(
         'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
       , _tbl, '%' || _like_pattern || '%')
      USING _tbl;
   END LOOP;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM search_whole_db('mypattern');

Provide the search pattern without enclosing %.

Why slightly dirty?

If separators and decorators for the row in text representation can be part of the search pattern, there can be false positives:

  • column separator: , by default
  • whole row is enclosed in parentheses:()
  • some values are enclosed in double quotes "
  • \ may be added as escape char

And the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.

Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).

This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.

The regclass object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path:

What is the ctid?

You might want to escape characters with special meaning in the search pattern. See:

How do I force a favicon refresh?

ON MAC: ? + Shift-R or hold down Ctrl and click the reload button in the browser.

window.open(url, '_blank'); not working on iMac/Safari

You can't rely on window.open because browsers may have different policies. I had the same issue and I used the code below instead.

let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = <your_url>;
a.download = <your_fileName>;
a.click();
document.body.removeChild(a);

How to vertically center a <span> inside a div?

Quick answer for single line span

Make the child (in this case a span) the same line-height as the parent <div>'s height

<div class="parent">
  <span class="child">Yes mom, I did my homework lol</span>
</div>

You should then add the CSS rules

.parent { height: 20px; }
.child { line-height: 20px; vertical-align: middle; }



Or you can target it with a child selector

.parent { height: 20px; }
.parent > span { line-height: 20px; vertical-align: middle; }

Background on my own use of this

I ran into this similar issue where I needed to vertically center items in a mobile menu. I made the div and spans inside the same line height. Note that this is for a meteor project and therefore not using inline css ;)

HTML

<div class="international">        
  <span class="intlFlag">
    {{flag}}        
  </span>

  <span class="intlCurrent">
    {{country}}
  </span>

  <span class="intlButton">
    <i class="fa fa-globe"></i>
  </span> 
</div>

CSS (option for multiple spans in a div)

.international {
  height: 42px;
}

.international > span {
  line-height: 42px;
}

In this case if I just had one span I could have added the CSS rule directly to that span.

CSS (option for one specific span)

.intlFlag { line-height: 42px; }

Here is how it displayed for me

enter image description here

PowerShell: Run command from script's directory

There are answers with big number of votes, but when I read your question, I thought you wanted to know the directory where the script is, not that where the script is running. You can get the information with powershell's auto variables

$PSScriptRoot - the directory where the script exists, not the target directory the script is running in
$PSCommandPath - the full path of the script

For example, I have $profile script that finds visual studio solution file and start it. I wanted to store the full path, once a solution file is started. But I wanted to save the file where the original script exists. So I used $PsScriptRoot.

Nested attributes unpermitted parameters

or you can simply use

def question_params

  params.require(:question).permit(team_ids: [])

end

How to overwrite the output directory in spark

UPDATE: Suggest using Dataframes, plus something like ... .write.mode(SaveMode.Overwrite) ....

Handy pimp:

implicit class PimpedStringRDD(rdd: RDD[String]) {
    def write(p: String)(implicit ss: SparkSession): Unit = {
      import ss.implicits._
      rdd.toDF().as[String].write.mode(SaveMode.Overwrite).text(p)
    }
  }

For older versions try

yourSparkConf.set("spark.hadoop.validateOutputSpecs", "false")
val sc = SparkContext(yourSparkConf)

In 1.1.0 you can set conf settings using the spark-submit script with the --conf flag.

WARNING (older versions): According to @piggybox there is a bug in Spark where it will only overwrite files it needs to to write it's part- files, any other files will be left unremoved.

How to get a parent element to appear above child

Fortunately a solution exists. You must add a wrapper for parent and change z-index of this wrapper for example 10, and set z-index for child to -1:

_x000D_
_x000D_
.parent {_x000D_
    position: relative;_x000D_
    width: 750px;_x000D_
    height: 7150px;_x000D_
    background: red;_x000D_
    border: solid 1px #000;_x000D_
    z-index: initial;_x000D_
}_x000D_
_x000D_
.child {_x000D_
    position: relative;_x000D_
    background-color: blue;_x000D_
    z-index: -1;_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
    position: relative;_x000D_
    background: green;_x000D_
    z-index: 10;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="parent">parent parent_x000D_
        <div class="child">child child child</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Print JSON parsed object?

The following code will display complete json data in alert box

var data= '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

json = JSON.parse(data);
window.alert(JSON.stringify(json));

Google Maps API v3: How do I dynamically change the marker icon?

The GMaps Utility Library has a plugin called MapIconMaker that makes it easy to generate different marker styles on the fly. It uses Google Charts to draw the markers.

There's a good demo here that shows what kind of markers you can make with it.

Commenting in a Bash script inside a multiline command

$IFS comment hacks

This hack uses parameter expansion on $IFS, which is used to separate words in commands:

$ echo foo${IFS}bar
foo bar

Similarly:

$ echo foo${IFS#comment}bar
foo bar

Using this, you can put a comment on a command line with contination:

$ echo foo${IFS# Comment here} \
> bar
foo bar

but the comment will need to be before the \ continuation.

Note that parameter expansion is performed inside the comment:

$ ls file
ls: cannot access 'file': No such file or directory
$ echo foo${IFS# This command will create file: $(touch file)}bar
foo bar
$ ls file
file

Rare exception

The only rare case this fails is if $IFS previously started with the exact text which is removed via the expansion (ie, after the # character):

$ IFS=x
$ echo foo${IFS#y}bar
foo bar
$ echo foo${IFS#x}bar
foobar

Note the final foobar has no space, illustrating the issue.

Since $IFS contains only whitespace by default, it's extremely unlikely you'll run into this problem.


Credit to @pjh's comment which sparked off this answer.

vim - How to delete a large block of text without counting the lines?

I'm no vim guru, but what I use in this circumstance is "visual mode". In command mode, type V (capital). Then move up/down to highlight the block you want deleted (all the usual movement commands work). Then remove it with x or d.

java.util.regex - importance of Pattern.compile()?

It is matter of performance and memory usage, compile and keep the complied pattern if you need to use it a lot. A typical usage of regex is to validated user input (format), and also format output data for users, in these classes, saving the complied pattern, seems quite logical as they usually called a lot.

Below is a sample validator, which is really called a lot :)

public class AmountValidator {
    //Accept 123 - 123,456 - 123,345.34
    private static final String AMOUNT_REGEX="\\d{1,3}(,\\d{3})*(\\.\\d{1,4})?|\\.\\d{1,4}";
    //Compile and save the pattern  
    private static final Pattern AMOUNT_PATTERN = Pattern.compile(AMOUNT_REGEX);


    public boolean validate(String amount){

         if (!AMOUNT_PATTERN.matcher(amount).matches()) {
            return false;
         }    
        return true;
    }    
}

As mentioned by @Alan Moore, if you have reusable regex in your code, (before a loop for example), you must compile and save pattern for reuse.

xpath find if node exists

I work in Ruby and using Nokogiri I fetch the element and look to see if the result is nil.

require 'nokogiri'

url = "http://somthing.com/resource"

resp = Nokogiri::XML(open(url))

first_name = resp.xpath("/movies/actors/actor[1]/first-name")

puts "first-name not found" if first_name.nil?

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Running .sh scripts in Git Bash

If you wish to execute a script file from the git bash prompt on Windows, just precede the script file with sh

sh my_awesome_script.sh

Convert bytes to a string

From sys — System-specific parameters and functions:

To write or read binary data from/to the standard streams, use the underlying binary buffer. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc').

jQuery Clone table row

Try this code, I used the following code for cloning and removing the cloned element, i have also used new class (newClass) which can be added automatically with the newly cloned html

for cloning..

 $(".tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var newClass='newClass';
    var $clone = $tr.clone().addClass(newClass);
    $clone.find(':text').val('');
    $tr.after($clone);
});

for removing the clone element.

$(".tr_clone_remove").live('click', function() { //Once remove button is clicked
    $(".newClass:last").remove(); //Remove field html
    x--; //Decrement field counter
});

html is as followinng

<tr class="tr_clone">
                       <!-- <td>1</td>-->
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span10" readonly>
                        <span><a href="javascript:void(0);" class="tr_clone_add" title="Add field"><span><i class="icon-plus-sign"></i></span></a> <a href="javascript:void(0);" class="tr_clone_remove" title="Remove field"><span style="color: #D63939;"><i class="icon-remove-sign"></i></span></a> </span> </td> </tr>

chrome undo the action of "prevent this page from creating additional dialogs"

Turning Hardware Acceleration OFF seems to be the setting that affects popups & dialogs.

Chrome was continually hiding Dialog Windows when I needed to respond Yes or No to things, also when I needed to Rename folders in my bookmarks panel. After weeks of doing this. I disabled all the Chrome helpers in Settings, Also In windows 10 I switched Window Snapping off. It has done something to put the popups and dialogs back in the Viewport.

When this bug is happening, I was able to shut a tab by first pressing Enter before clicking the tab close X button. The browser had an alert box, hidden which needed a response from the user.

Switching Hardware Accleration Off and back On, Killing the Chrome process and switching all the other Helpers Off and back has fixed it for me... It must be in chrome itself because Ive just gone into a Chrome window in the Mac and it has now stopped the problem, without any intervention. Im guessing flicking the chrome settings on/off/on has caused it to reposition the dialogs. I cant get the browser to repeat the fault now...