Programs & Examples On #Noncopyable

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

Android Studio with Google Play Services

  1. Go to File -> Project Structure
  2. Select 'Project Settings'
  3. Select 'Dependencies' Tab
  4. Click '+' and select '1.Library Dependencies'
  5. Search for : com.google.android.gms:play-services
  6. Select the latest version and click 'OK'

Voila! No need to fight with Gradle :)

What does $@ mean in a shell script?

Meaning.

In brief, $@ expands to the positional arguments passed from the caller to either a function or a script. Its meaning is context-dependent: Inside a function, it expands to the arguments passed to such function. If used in a script (not inside the scope a function), it expands to the arguments passed to such script.

$ cat my-sh
#! /bin/sh
echo "$@"

$ ./my-sh "Hi!"
Hi!
$ put () ( echo "$@" )
$ put "Hi!"
Hi!

Word splitting.

Now, another topic that is of paramount importance when understanding how $@ behaves in the shell is word splitting. The shell splits tokens based on the contents of the IFS variable. Its default value is \t\n; i.e., whitespace, tab, and newline.

Expanding "$@" gives you a pristine copy of the arguments passed. However, expanding $@ will not always. More specifically, if the arguments contain characters from IFS, they will split.


Most of the time what you will want to use is "$@", not $@.

Moment JS start and end of given month

That's because endOf mutates the original value.

Relevant quote:

Mutates the original moment by setting it to the end of a unit of time.

Here's an example function that gives you the output you want:

function getMonthDateRange(year, month) {
    var moment = require('moment');

    // month in moment is 0 based, so 9 is actually october, subtract 1 to compensate
    // array is 'year', 'month', 'day', etc
    var startDate = moment([year, month - 1]);

    // Clone the value before .endOf()
    var endDate = moment(startDate).endOf('month');

    // just for demonstration:
    console.log(startDate.toDate());
    console.log(endDate.toDate());

    // make sure to call toDate() for plain JavaScript date type
    return { start: startDate, end: endDate };
}

References:

Cannot find "Package Explorer" view in Eclipse

For Eclipse version 4.3.0.v20130605-2000. You can use the Java (default) perspective. In this perspective, it provides the Package Explorer view.

To use the Java (default) perspective: Window -> Open Perspective -> Other... -> Java (default) -> Ok

If you already use the Java (default) perspective but accidentally close the Package Explorer view, you can open it by; Window -> Show View -> Package Explorer (Alt+Shift+Q,P)

If the Package Explorer still doesn't appear in the Java (default) perspective, I suggest you to right-click on the Java (default) perspective button that is located in the top-right of the Eclipse IDE and then select Reset. The Java (default) perspective will show the Package Explorer view, Code pane, Outline view, Problems, JavaDoc and Declaration View.

how to write an array to a file Java

private static void saveArrayToFile(String fileName, int[] array) throws IOException {
    Files.write( // write to file
        Paths.get(fileName), // get path from file
        Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
        Charset.forName("UTF-8") // formatting
    );
}

Pivoting rows into columns dynamically in Oracle

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

Oracle 11g solution

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

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

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

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

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

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

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

How to exit git log or git diff

You can press q to exit.

git hist is using a pager tool so you can scroll up and down the results before returning to the console.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Culprit is preflight request using OPTIONS method

For HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.

Web specification refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

I resolved the problem by adding following lines in Nginx conf.

    location / {
               if ($request_method = OPTIONS ) {
                   add_header Access-Control-Allow-Origin  "*";
                   add_header Access-Control-Allow-Methods "POST, GET, PUT, UPDATE, DELETE, OPTIONS";
                   add_header Access-Control-Allow-Headers "Authorization";
                   add_header Access-Control-Allow-Credentials  "true";
                   add_header Content-Length 0;
                   add_header Content-Type text/plain;
                   return 200;
               }
    location ~ ^/(xxxx)$ {
                if ($request_method = OPTIONS) {
                    rewrite ^(.*)$ / last;
                }
    }

How to convert JSON to XML or XML to JSON?

You can do these conversions also with the .NET Framework:

JSON to XML: by using System.Runtime.Serialization.Json

var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));

XML to JSON: by using System.Web.Script.Serialization

var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));

private static Dictionary<string, object> GetXmlData(XElement xml)
{
    var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
    if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
    else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

    return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}

How to increase the gap between text and underlining in CSS

just use

{
   text-decoration-line: underline;
   text-underline-offset: 2px;
}


Number of occurrences of a character in a string

Because LINQ can do everything...:

string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();

Or if you like, you can use the Count overload that takes a predicate :

var count = test.Count(x => x == '&');

HTML form with side by side input fields

For the sake of bandwidth saving, we shouldn't include <div> for each of <label> and <input> pair

This solution may serve you better and may increase readability

<div class="form">
            <label for="product_name">Name</label>
            <input id="product_name" name="product[name]" size="30" type="text" value="4">
            <label for="product_stock">Stock</label>
            <input id="product_stock" name="product[stock]" size="30" type="text" value="-1">
            <label for="price_amount">Amount</label>
            <input id="price_amount" name="price[amount]" size="30" type="text" value="6.0">
</div>

The css for above form would be

.form > label
{
  float: left;
  clear: right;
}

.form > input
{
  float: right;
}

I believe the output would be as following:

Demo

APK signing error : Failed to read key from keystore

Most likely that your key alias does not exist for your keystore file.

This answer should fix your signing issue ;)

Resizable table columns with jQuery

Here's a short complete html example. See demo http://jsfiddle.net/CU585/

<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>

SHA1 vs md5 vs SHA256: which to use for a PHP login?

Use argon2i. The argon2 password hashing function has won the Password Hashing Competition.

Other reasonable choices, if using argon2 is not available, are scrypt, bcrypt and PBKDF2. Wikipedia has pages for these functions:

MD5, SHA1 and SHA256 are message digests, not password-hashing functions. They are not suitable for this purpose.

Switching from MD5 to SHA1 or SHA512 will not improve the security of the construction so much. Computing a SHA256 or SHA512 hash is very fast. An attacker with common hardware could still try tens of millions (with a single CPU) or even billions (with a single GPU) of hashes per second. Good password hashing functions include a work factor to slow down dictionary attacks.

Here is a suggestion for PHP programmers: read the PHP FAQ then use password_hash().

for each inside a for each - Java

most simple solution would be to set a boolean var. if to true where you do the insert statement and then in the outter loop check this and insert the tweet there if the boolean is true...

jQuery load more data on scroll

If not all of your document scrolls, say, when you have a scrolling div within the document, then the above solutions won't work without adaptations. Here's how to check whether the div's scrollbar has hit the bottom:

$('#someScrollingDiv').on('scroll', function() {
    let div = $(this).get(0);
    if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
        // do the lazy loading here
    }
});

Possible to extend types in Typescript?

You can also do:

export type UserEvent = Event & { UserId: string; };

How can I validate a string to only allow alphanumeric characters in it?

Based on cletus's answer you may create new extension.

public static class StringExtensions
{        
    public static bool IsAlphaNumeric(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;

        Regex r = new Regex("^[a-zA-Z0-9]*$");
        return r.IsMatch(str);
    }
}

Converting two lists into a matrix

The standard numpy function for what you want is np.column_stack:

>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
       [2, 5],
       [3, 6]])

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

would yield something like:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]

Visual Studio Code pylint: Unable to import 'protorpc'

First I will check the python3 path where it lives

enter image description here

And then in the VS Code settings just add that path, for example:

"python.pythonPath": "/usr/local/bin/python3"

Pass Parameter to Gulp Task

There's an official gulp recipe for this using minimist.

https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md

The basics are using minimist to separate the cli arguments and combine them with known options:

var options = minimist(process.argv.slice(2), knownOptions);

Which would parse something like

$ gulp scripts --env development

More complete info in the recipe.

Getting the error "Missing $ inserted" in LaTeX

I had this symbol _ in the head of one table and the code didn't run, so I had to delete.

Change "on" color of a Switch

Create your own 9-patch image and set it as the background of the toggle button.

http://radleymarx.com/2011/simple-guide-to-9-patch/

Linking static libraries to other static libraries

Static libraries do not link with other static libraries. The only way to do this is to use your librarian/archiver tool (for example ar on Linux) to create a single new static library by concatenating the multiple libraries.

Edit: In response to your update, the only way I know to select only the symbols that are required is to manually create the library from the subset of the .o files that contain them. This is difficult, time consuming and error prone. I'm not aware of any tools to help do this (not to say they don't exist), but it would make quite an interesting project to produce one.

How to print last two columns using awk

@jim mcnamara: try using parentheses for around NF, i. e. $(NF-1) and $(NF) instead of $NF-1 and $NF (works on Mac OS X 10.6.8 for FreeBSD awkand gawk).

echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'

# output:
# 1 2
# 2 3
# two three

How do you clear the SQL Server transaction log?

DISCLAIMER: Please read comments below carefully, and I assume you've already read the accepted answer. As I said nearly 5 years ago:

if anyone has any comments to add for situations when this is NOT an adequate or optimal solution then please comment below


  • Right click on the database name.

  • Select Tasks ? Shrink ? Database

  • Then click OK!

I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.

I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17 GB in 10 seconds

In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]

--

PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!

Python, remove all non-alphabet chars from string

You can use the re.sub() function to remove these characters:

>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'

re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)

  • "[^a-zA-Z]+" - look for any group of characters that are NOT a-zA-z.
  • "" - Replace the matched characters with ""

How to HTML encode/escape a string? Is there a built-in?

You can use either h() or html_escape(), but most people use h() by convention. h() is short for html_escape() in rails.

In your controller:

@stuff = "<b>Hello World!</b>"

In your view:

<%=h @stuff %>

If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as &lt;b&gt;Hello World!&lt;/b&gt;.

It will appear an be displayed as <b>Hello World!</b>

Open existing file, append a single line

//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
   stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
   stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
   stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
   stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}

How to hide reference counts in VS2013?

I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators or CodeLens, and can be located under

Tools ? Options ? Text Editor ? All Languages ? CodeLens

(for RC/final version)

or

Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators

(for preview version)

That was according to this link. It seems to be pretty well hidden.

In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:

editor options

documented in the Q&A section of the msdn CodeLens documentation

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

At its simplest, the difference is one of plurality:

  • Backout backs out of a single changelist (whether the most recent or not). i.e. it undoes a single changelist.
  • Rollback rolls back changes as much as it needs to in order to get to a previous changelist. i.e. it undoes multiple changelists.

I used to forget which one is which and end up having to look it up many times. To fix this problem, imagine rolling back as several rotations then hopefully the fact that rollback is plural will help you (and me!) remember which one is which. Backout sounds 'less plural' than rollback to me. Imagine backing out of a single parking space.

So, the mnemonic is:

  • Rollback → multiple rotations
  • Backout → back out of a single car parking space

I hope this helps!

ModuleNotFoundError: No module named 'sklearn'

The other name of sklearn in anaconda is scikit-learn. simply open your anaconda navigator, go to the environments, select your environment, for example tensorflow or whatever you want to work with, search for scikit_learn in the list of uninstalled packages, apply it and then you can import sklearn in your jupyter.

How do I make a JAR from a .java file?

Simply with command line:

javac MyApp.java
jar -cf myJar.jar MyApp.class

Sure IDEs avoid using command line terminal

Creating/writing into a new file in Qt

#include <QFile>
#include <QCoreApplication>
#include <QTextStream>

int main(int argc, char *argv[])
{
    // Create a new file     
    QFile file("out.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out << "This file is generated by Qt\n";

    // optional, as QFile destructor will already do it:
    file.close(); 

    //this would normally start the event loop, but is not needed for this
    //minimal example:
    //return app.exec();

    return 0;
}

How do I remove version tracking from a project cloned from git?

From root folder run

find . | grep .git

Review the matches and confirm it only contains those files you want to delete and adjust to suit. Once satisfied, run

find . | grep .git | xargs rm -rf

Remove all whitespace from C# string with regex

Regex.Replace does not modify its first argument (recall that strings are immutable in .NET) so the call

Regex.Replace(LastName, @"\s+", "");

leaves the LastName string unchanged. You need to call it like this:

LastName = Regex.Replace(LastName, @"\s+", "");

All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.

ReportViewer Client Print Control "Unable to load client print control"?

Found a Fix:

  1. First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).

  2. If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.

  3. Download and install the following update:

URL Encode a string in jQuery for an AJAX request

encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:

  $.ajax({
    cache: false,
    type: "POST",
    url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
    data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
    dataType: "HTML",
    success: function (data) {
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
  });

embedding image in html email

It may be of interest that both Outlook and Outlook Express can generate these multipart image email formats, if you insert the image files using the Insert / Picture menu function.

Obviously the email type must be set to HTML (not plain text).

Any other method (e.g. drag/drop, or any command-line invocation) results in the image(s) being sent as an attachment.

If you then send such an email to yourself, you can see how it is formatted! :)

FWIW, I am looking for a standalone windows executable which does inline images from the command line mode, but there seem to be none. It's a path which many have gone up... One can do it with say Outlook Express, by passing it an appropriately formatted .eml file.

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

In my experience, these errors happen this way:

try:
    code_that_executes_bad_query()
    # transaction on DB is now bad
except:
    pass

# transaction on db is still bad
code_that_executes_working_query() # raises transaction error

There nothing wrong with the second query, but since the real error was caught, the second query is the one that raises the (much less informative) error.

edit: this only happens if the except clause catches IntegrityError (or any other low level database exception), If you catch something like DoesNotExist this error will not come up, because DoesNotExist does not corrupt the transaction.

The lesson here is don't do try/except/pass.

Mysql - delete from multiple tables with one query

You can also use following query :

DELETE FROM Student, Enrollment USING Student INNER JOIN Enrollment ON Student.studentId = Enrollment.studentId WHERE Student.studentId= 51;

Streaming video from Android camera to server

Here is complete article about streaming android camera video to a webpage.

Android Streaming Live Camera Video to Web Page

  1. Used libstreaming on android app
  2. On server side Wowza Media Engine is used to decode the video stream
  3. Finally jWplayer is used to play the video on a webpage.

git: undo all working dir changes including new files

The following works:

git add -A .
git stash
git stash drop stash@{0}

Please note that this will discard both your unstaged and staged local changes. So you should commit anything you want to keep, before you run these commands.

A typical use case: You moved a lot of files or directories around, and then want to get back to the original state.

Credits: https://stackoverflow.com/a/52719/246724

How do I create an iCal-type .ics file that can be downloaded by other users?

That will work just fine. You can export an entire calendar with File > Export…, or individual events by dragging them to the Finder.

iCalendar (.ics) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN: and end with END:. You'll mostly find VEVENT sections (each of which represents an event) and VTIMEZONE sections, each of which represents a time zone that's referenced from one or more events.

Constructors in JavaScript objects

Yes, you can define a constructor inside a class declaration like this:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

PHPMyAdmin Default login password

This is asking for your MySQL username and password.

You should enter these details, which will default to "root" and "" (i.e.: nothing) if you've not specified a password.

How do I rename a local Git branch?

All of the previous answers are talking about git branch -m. Of course, it's easy to operate, but for me, it may be a little hard to remember another Git command. So I tried to get the work done by the command I was familiar with. Yeah, you may guessed it.

I use git branch -b <new_branch_name>. And if you don't want to save the old branch now you can execute git branch -D <old_branch_name> to remove it.

I know it may be a little tedious, but it's easier to understand and remember. I hope it‘s helpful for you.

python: create list of tuples from lists

You're looking for the zip builtin function. From the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

How to create an Array, ArrayList, Stack and Queue in Java?

Without more details as to what the question is exactly asking, I am going to answer the title of the question,

Create an Array:

String[] myArray = new String[2];
int[] intArray = new int[2];

// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};

Create an ArrayList:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");

ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);

This means, create an ArrayList of String and Integer objects. You cannot use int because thats a primitive data types, see the link for a list of primitive data types.

Create a Stack:

Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);

Create an Queue: (using LinkedList)

Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);

Same thing as an ArrayList, this declaration means create an Queue of String and Integer objects.


Update:

In response to your comment from the other given answer,

i am pretty confused now, why are using string. and what does <String> means

We are using String only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.

I have posted some links to explain the difference between the two, but here are a list of primitive types

  • byte
  • short
  • char
  • int
  • long
  • boolean
  • double
  • float

Which means, you are not allowed to make an ArrayList of integer's like so:

ArrayList<int> numbers = new ArrayList<int>(); 
           ^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
            ^ perfectly valid

Also, you can use your own objects, here is my Monster object I created,

public class Monster {
   String name = null;
   String location = null;
   int age = 0;

public Monster(String name, String loc, int age) { 
   this.name = name;
   this.loc = location;
   this.age = age;
 }

public void printDetails() {
   System.out.println(name + " is from " + location +
                                     " and is " + age + " old.");
 }
} 

Here we have a Monster object, but now in our Main.java class we want to keep a record of all our Monster's that we create, so let's add them to an ArrayList

public class Main {
    ArrayList<Monster> myMonsters = new ArrayList<Monster>();

public Main() {
    Monster yetti = new Monster("Yetti", "The Mountains", 77);
    Monster lochness = new Monster("Lochness Monster", "Scotland", 20);

    myMonsters.add(yetti); // <-- added Yetti to our list
    myMonsters.add(lochness); // <--added Lochness to our list
  
    for (Monster m : myMonsters) {
        m.printDetails();
     }
   }

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

(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)

Singleton: How should it be used

The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.

Java 8: Difference between two LocalDateTime in multiple units

It should be simpler!

Duration.between(startLocalDateTime, endLocalDateTime).toMillis();

You can convert millis to whatever unit you like:

String.format("%d minutes %d seconds", 
  TimeUnit.MILLISECONDS.toMinutes(millis),
  TimeUnit.MILLISECONDS.toSeconds(millis) - 
  TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

JavaFX Location is not set error message

I was getting this exception and the "solution" I found was through Netbeans IDE, simply:

  1. Right-click -> "Clean and Build"
  2. Run project again

I don't know WHY this worked, but it did!

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Authentication plugin 'caching_sha2_password' cannot be loaded

For Windows 10,

  1. Modify my.ini file in C:\ProgramData\MySQL\MySQL Server 8.0\

    [mysqld]
    default_authentication_plugin=mysql_native_password
    
  2. Restart the MySQL Service.

  3. Login to MySQL on the command line, and execute the following commands in MySQL:

    • Create a new user.

      CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
      
    • Grant all privileges.

      GRANT ALL PRIVILEGES ON * .* TO 'user'@'localhost';
      
  4. Open MySQL workbench, and open a new connection using the new user credentials.

I was facing the same issue and this worked.

What is cardinality in Databases?

In database, Cardinality number of rows in the table.

enter image description here img source


enter image description here img source


  • Relationships are named and classified by their cardinality (i.e. number of elements of the set).
  • Symbols which appears closes to the entity is Maximum cardinality and the other one is Minimum cardinality.
  • Entity relation, shows end of the relationship line as follows:
    enter image description here

enter image description here

image source

How to get relative path from absolute path

As Alex Brault points out, especially on Windows, the absolute path (with drive letter and all) is unambiguous and often better.

Shouldn't your OpenFileDialog use a regular tree-browser structure?

To get some nomenclature in place, the RefDir is the directory relative to which you want to specify the path; the AbsName is the absolute path name that you want to map; and the RelPath is the resulting relative path.

Take the first of these options that matches:

  • If you have different drive letters, there is no relative path from RefDir to AbsName; you must use the AbsName.
  • If the AbsName is in a sub-directory of RefDir or is a file within RefDir then simply remove the RefDir from the start of AbsName to create RelPath; optionally prepend "./" (or ".\" since you are on Windows).
  • Find the longest common prefix of RefDir and AbsName (where D:\Abc\Def and D:\Abc\Default share D:\Abc as the longest common prefix; it has to be a mapping of name components, not a simple longest common substring); call it LCP. Remove LCP from AbsName and RefDir. For each path component left in (RefDir - LCP), prepend "..\" to (AbsName - LCP) to yield RelPath.

To illustrate the last rule (which is, of course, by far the most complex), start with:

RefDir = D:\Abc\Def\Ghi
AbsName = D:\Abc\Default\Karma\Crucible

Then

LCP = D:\Abc
(RefDir - LCP) = Def\Ghi
(Absname - LCP) = Default\Karma\Crucible
RelPath = ..\..\Default\Karma\Crucible

While I was typing, DavidK produced an answer which suggests that you are not the first to need this feature and that there is a standard function to do this job. Use it. But there's no harm in being able to think your way through from first principles, either.

Except that Unix systems do not support drive letters (so everything is always located under the same root directory, and the first bullet therefore is irrelevant), the same technique could be used on Unix.

CSS Box Shadow - Top and Bottom Only

As Kristian has pointed out, good control over z-values will often solve your problems.

If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.

I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:

box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;

This will give you some control over the "amount" of shadow in each direction.

Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.

Hope this was what you were looking for!

"register" keyword in C?

It's a hint to the compiler that the variable will be heavily used and that you recommend it be kept in a processor register if possible.

Most modern compilers do that automatically, and are better at picking them than us humans.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

How do I read the source code of shell commands?

You can have it on github using the command

git clone https://github.com/coreutils/coreutils.git

You can find all the source codes in the src folder.

You need to have git installed.

Things have changed since 2012, ls source code has now 5309 lines

Rotate an image in image source in html

This might be your script-free solution: http://davidwalsh.name/css-transform-rotate

It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.

That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms- and -moz- prefixes to economize space.

However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-, and there's a still-big cult following of pre-Next Opera and using -o- is sensate.

Get first letter of a string from column

Cast the dtype of the col to str and you can perform vectorised slicing calling str:

In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df

Out[29]:
   First  Second new_col
0    123     234       1
1     22    4353       2
2     32     355       3
3    453     453       4
4     45     345       4
5    453     453       4
6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

Setting dropdownlist selecteditem programmatically

ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :

ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));

return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.

How do I create my own URL protocol? (e.g. so://...)

A Protocol?

I found this, it appears to be a local setting for a computer...

http://kb.mozillazine.org/Register_protocol

Android Layout Weight

It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.

Mockito : how to verify method was called on an object created within a method?

If you don't want to use DI or Factories. You can refactor your class in a little tricky way:

public class Foo {
    private Bar bar;

    public void foo(Bar bar){
        this.bar = (bar != null) ? bar : new Bar();
        bar.someMethod();
        this.bar = null;  // for simulating local scope
    }
}

And your test class:

@RunWith(MockitoJUnitRunner.class)
public class FooTest {
    @Mock Bar barMock;
    Foo foo;

    @Test
    public void testFoo() {
       foo = new Foo();
       foo.foo(barMock);
       verify(barMock, times(1)).someMethod();
    }
}

Then the class that is calling your foo method will do it like this:

public class thirdClass {

   public void someOtherMethod() {
      Foo myFoo = new Foo();
      myFoo.foo(null);
   }
}

As you can see when calling the method this way, you don't need to import the Bar class in any other class that is calling your foo method which is maybe something you want.

Of course the downside is that you are allowing the caller to set the Bar Object.

Hope it helps.

How to set UICollectionViewCell Width and Height programmatically

Swift 4

You have 2 ways in order to change the size of CollectionView.
First way -> add this protocol UICollectionViewDelegateFlowLayout
for In my case I want to divided cell into 3 part in one line. I did this code below

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
            // In this function is the code you must implement to your code project if you want to change size of Collection view
            let width  = (view.frame.width-20)/3
            return CGSize(width: width, height: width)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = collectionData[indexPath.row]
        }
        return cell
    }
}

Second way -> you don't have to add UICollectionViewDelegateFlowLayout but you have to write some code in viewDidload function instead as code below

class ViewController: UIViewController {
@IBOutlet weak var collectionView1: UICollectionView!
        var collectionData = ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10.", "11.", "12."]

    override func viewDidLoad() {
        super.viewDidLoad()
        let width = (view.frame.width-20)/3
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: width, height: width) 
    }
}

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
   

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = collectionData[indexPath.row]
        }
   
        return cell
    }
}

Whatever you write a code as the first way or second way you will get the same result as above. I wrote it. It worked for me

enter image description here

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

How can I add a volume to an existing Docker container?

The best way is to copy all the files and folders inside a directory on your local file system by: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH

SRC_PATH is on container DEST_PATH is on localhost

Then do docker-compose down attach a volume to the same DEST_PATH and run Docker containers by using docker-compose up -d

Add volume by following in docker-compose.yml

volumes:
 - DEST_PATH:SRC_PATH

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

Check the nginx folder permission and set appache permission for that:

chown -R www-data:www-data /var/lib/nginx

Change class on mouseover in directive

This is my solution for my scenario:

<div class="btn-group btn-group-justified">
    <a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
        {{ song.name }}
    </a>
    <a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
        {{ match.name }}
    </a>
</div>

default state: enter image description here

on hover: enter image description here

How to group by month from Date field using sql

Use the DATEPART function to extract the month from the date.

So you would do something like this:

SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

How can I programmatically determine if my app is running in the iphone simulator?

Not pre-processor directive, but this was what I was looking for when i came to this question;

NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:@"iPhone Simulator"]) {
    //device is simulator
}

Kill Attached Screen in Linux

screen -X -S SCREENID kill

alternatively, you can use the following command

screen -S SCREENNAME -p 0 -X quit

You can view the list of the screen sessions by executing screen -ls

C program to check little vs. big endian

Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:


The following program would determine that:

#include <stdio.h>
#include <stdint.h>

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } e = { 0x01000000 };

    return e.c[0];
}

int main(void)
{
    printf("System is %s-endian.\n",
        is_big_endian() ? "big" : "little");

    return 0;
}

You also have this approach; from Quake II:

byte    swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
    bigendien = false;

And !is_big_endian() is not 100% to be little as it can be mixed/middle.

Believe this can be checked using same approach only change value from 0x01000000 to i.e. 0x01020304 giving:

switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE

But not entirely sure about that one ...

How do I remove a single file from the staging area (undo git add)?

I think you probably got confused with the concept of index, as @CB Bailey commented:

The staging area is the index.

You can simply consider staging directory and index as the same thing.
So, just like @Tim Henigan's answer, I guess:

you simply want to "undo" the git add that was done for that file.



Here is my answer:

Commonly, there are two ways to undo a stage operation, as other answers already mentioned:

git reset HEAD <file>

and

git rm --cached <file>

But what is the difference?

Assume the file has been staged and exists in working directory too, use git rm --cached <file> if you want to remove it from staging directory, and keep the file in working directory. But notice that this operation will not only remove the file from staging directory but also mark the file as deleted in staging directory, if you use

git status

after this operation, you will see this :

        deleted:    <file>

It's a record of removing the file from staging directory. If you don't want to keep that record and just simply want to undo a previous stage operation of a file, use git reset HEAD <file> instead.


-------- END OF ANSWER --------

PS: I have noticed some answers mentioned:

git checkout -- <file>

This command is for the situation when the file has been staged, but the file has been modified in working directory after it was staged, use this operation to restore the file in working directory from staging directory. In other words, after this operation, changes happen in your working directory, NOT your staging directory.

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details. https://stackoverflow.com/a/17231361/1419668

Converting list to *args when calling function

You can use the * operator before an iterable to expand it within the function call. For example:

timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)

(notice the * before timeseries_list)

From the python documentation:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the ** operator.

Setting Camera Parameters in OpenCV/Python

To avoid using integer values to identify the VideoCapture properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS in OpenCV 2.4 and cv2.CAP_PROP_FPS in OpenCV 3.0. (See also Stefan's comment below.)

Here a utility function that works for both OpenCV 2.4 and 3.0:

# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
  return getattr(cv2 if OPCV3 else cv2.cv,
    ("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)

OPCV3 is set earlier in my utilities code like this:

from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')

jQuery set checkbox checked

If you're wanting to use this functionality for a GreaseMonkey script to automatically check a checkbox on a page, keep in mind that simply setting the checked property may not trigger the associated action. In that case, "clicking" the checkbox probably will (and set the checked property as well).

$("#id").click()

How to pull remote branch from somebody else's repo

git remote add coworker git://path/to/coworkers/repo.git
git fetch coworker
git checkout --track coworker/foo

This will setup a local branch foo, tracking the remote branch coworker/foo. So when your co-worker has made some changes, you can easily pull them:

git checkout foo
git pull

Response to comments:

Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?

You don't need to create a new branch, even though I recommend it. You might as well commit directly to foo and have your co-worker pull your branch. But that branch already exists and your branch foo need to be setup as an upstream branch to it:

git branch --set-upstream foo colin/foo

assuming colin is your repository (a remote to your co-workers repository) defined in similar way:

git remote add colin git://path/to/colins/repo.git

How to use If Statement in Where Clause in SQL?

select * from xyz where (1=(CASE WHEN @AnnualFeeType = 'All' THEN 1 ELSE 0 END) OR AnnualFeeType = @AnnualFeeType)

How to tell if node.js is installed or not

Please try this command node --version or node -v, either of which should return something like v4.4.5.

Git "error: The branch 'x' is not fully merged"

Note Wording changed in response to the commments. Thanks @slekse
That is not an error, it is a warning. It means the branch you are about to delete contains commits that are not reachable from any of: its upstream branch, or HEAD (currently checked out revision). In other words, when you might lose commits¹.

In practice it means that you probably amended, rebased or filtered commits and they don't seem identical.

Therefore you could avoid the warning by checking out a branch that does contain the commits that you're about un-reference by deleting that other branch.²

You will want to verify that you in fact aren't missing any vital commits:

git log --graph --left-right --cherry-pick --oneline master...experiment

This will give you a list of any nonshared between the branches. In case you are curious, there might be a difference without --cherry-pick and this difference could well be the reason for the warning you get:

--cherry-pick

Omit any commit that introduces the same change as another commit on the "other side" when the set of commits are limited with symmetric difference. For example, if you have two branches, A and B, a usual way to list all commits on only one side of them is with --left-right, like the example above in the description of that option. It however shows the commits that were cherry-picked from the other branch (for example, "3rd on b" may be cherry-picked from branch A). With this option, such pairs of commits are excluded from the output.


¹ they're really only garbage collected after a while, by default. Also, the git-branch command does not check the revision tree of all branches. The warning is there to avoid obvious mistakes.

² (My preference here is to just force the deletion instead, but you might want to have the extra reassurance).

Using ls to list directories and their total sizes

The following is easy to remember

ls -ltrapR

list directory contents

-l use a long listing format

-t sort by modification time, newest first

-r, --reverse reverse order while sorting

-a, --all do not ignore entries starting with .

-p, --indicator-style=slash append / indicator to directories

-R, --recursive list subdirectories recursively

https://explainshell.com/explain?cmd=ls+-ltrapR

Oracle's default date format is YYYY-MM-DD, WHY?

This is a "problem" on the client side, not really an Oracle problem.

It's the client application which formats and displays the date this way.

In your case it's SQL*Plus which does this formatting.
Other SQL clients have other defaults.

How to show the Project Explorer window in Eclipse

  1. Window -> Perspective -> Reset

  2. Reset the IDE

  3. Window -> Show View -> Project Explorer

enter image description here

Datatable to html Table

I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#

using System.Data;
using System.Web.UI.HtmlControls;

public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
    Table tbl = new Table();
    TableRow tr = null;
    TableCell cell = null;

    int rows = dt.Rows.Count;
    int cols = dt.Columns.Count;

    if (includeHeaders)
    {
        TableHeaderRow htr = new TableHeaderRow();
        TableHeaderCell hcell = null;
        for (int i = 0; i < cols; i++)
        {
            hcell = new TableHeaderCell();
            hcell.Text = dt.Columns[i].ColumnName.ToString();
            htr.Cells.Add(hcell);
        }
        tbl.Rows.Add(htr);
    }

    for (int j = 0; j < rows; j++)
    {
        tr = new TableRow();
        for (int k = 0; k < cols; k++)
        {
            cell = new TableCell();
            cell.Text = dt.Rows[j][k].ToString();
            tr.Cells.Add(cell);
        }
        tbl.Rows.Add(tr);
    }
    return tbl;
}

why this solution? Because you can easily just add this to a panel ie:

panel.Controls.Add(DataTableToHTMLTable(dtExample,true));

Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):

public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
    int dt2ColsCount = dt2.Columns.Count;
    int dt1lRowsCount = dt1.Rows.Count;

    DataColumn column;
    for (int i = 0; i < dt2ColsCount; i++)
    {
        column = new DataColumn();
        string colName = dt2.Columns[i].ColumnName;
        System.Type colType = dt2.Columns[i].DataType;
        column.ColumnName = colName;
        column.DataType = colType;
        dt1.Columns.Add(column);

        for (int j = 0; j < dt1lRowsCount; j++)
        {
            dt1.Rows[j][colName] = dt2.Rows[j][colName];
        }
    }
    return dt1;
}

and your solution would look something like:

panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));

interpret the rest, and have fun.

LINQ Inner-Join vs Left-Join

I the following error message when faced this same problem:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.

Solved when I used the same property name, it worked.

(...)

join enderecoST in db.PessoaEnderecos on 
    new 
      {  
         CD_PESSOA          = nf.CD_PESSOA_ST, 
         CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST 
      } equals 
    new 
    { 
         enderecoST.CD_PESSOA, 
         enderecoST.CD_ENDERECO_PESSOA 
    } into eST

(...)

How to install and run Typescript locally in npm?

tsc requires a config file or .ts(x) files to compile.

To solve both of your issues, create a file called tsconfig.json with the following contents:

{
    "compilerOptions": {
        "outFile": "../../built/local/tsc.js"
    },
    "exclude": [
        "node_modules"
    ]
}

Also, modify your npm run with this

tsc --config /path/to/a/tsconfig.json

Join two sql queries

Here's what worked for me:

select visits, activations, simulations, simulations/activations
   as sims_per_visit, activations/visits*100
   as adoption_rate, simulations/activations*100
   as completion_rate, duration/60
   as minutes, m1 as month, Wk1 as week, Yr1 as year 

from
(
    (select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
    as m1 from sessions group by week(stamp), year(stamp)) as t3

    join

    (select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
    month(stamp) as m2 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t4

    join

    (select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
    month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
    year(stamp)) as t5

    join

    (select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
    month(stamp) as m4 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4

I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.

Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.

Is it possible to specify condition in Count()?

@Guffa 's answer is excellent, just point out that maybe is cleaner with an IF statement

select count(IF(Position = 'Manager', 1, NULL)) as ManagerCount
from ...

Spring RestTemplate GET with parameters

I take different approach, you may agree or not but I want to control from .properties file instead of compiled Java code

Inside application.properties file

endpoint.url = https://yourHost/resource?requestParam1={0}&requestParam2={1}

Java code goes here, you can write if or switch condition to find out if endpoint URL in .properties file has @PathVariable (contains {}) or @RequestParam (yourURL?key=value) etc... then invoke method accordingly... that way its dynamic and not need to code change in future one stop shop...

I'm trying to give more of idea than actual code here ...try to write generic method each for @RequestParam, and @PathVariable etc... then call accordingly when needed

  @Value("${endpoint.url}")
  private String endpointURL;
  // you can use variable args feature in Java
  public String requestParamMethodNameHere(String value1, String value2) {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate
           .getMessageConverters()
           .add(new MappingJackson2HttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<String> entity = new HttpEntity<>(headers);

    try {
      String formatted_URL = MessageFormat.format(endpointURL, value1, value2);
      ResponseEntity<String> response = restTemplate.exchange(
                    formatted_URL ,
                    HttpMethod.GET,
                    entity,
                    String.class);
     return response.getBody();
    } catch (Exception e) { e.printStackTrace(); }

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

convert from Color to brush

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

Break a previous commit into multiple commits

Use git rebase --interactive to edit that earlier commit, run git reset HEAD~, and then git add -p to add some, then make a commit, then add some more and make another commit, as many times as you like. When you're done, run git rebase --continue, and you'll have all the split commits earlier in your stack.

Important: Note that you can play around and make all the changes you want, and not have to worry about losing old changes, because you can always run git reflog to find the point in your project that contains the changes you want, (let's call it a8c4ab), and then git reset a8c4ab.

Here's a series of commands to show how it works:

mkdir git-test; cd git-test; git init

now add a file A

vi A

add this line:

one

git commit -am one

then add this line to A:

two

git commit -am two

then add this line to A:

three

git commit -am three

now the file A looks like this:

one
two
three

and our git log looks like the following (well, I use git log --pretty=oneline --pretty="%h %cn %cr ---- %s"

bfb8e46 Rose Perrone 4 seconds ago ---- three
2b613bc Rose Perrone 14 seconds ago ---- two
9aac58f Rose Perrone 24 seconds ago ---- one

Let's say we want to split the second commit, two.

git rebase --interactive HEAD~2

This brings up a message that looks like this:

pick 2b613bc two
pick bfb8e46 three

Change the first pick to an e to edit that commit.

git reset HEAD~

git diff shows us that we just unstaged the commit we made for the second commit:

diff --git a/A b/A
index 5626abf..814f4a4 100644
--- a/A
+++ b/A
@@ -1 +1,2 @@
 one
+two

Let's stage that change, and add "and a third" to that line in file A.

git add .

This is usually the point during an interactive rebase where we would run git rebase --continue, because we usually just want to go back in our stack of commits to edit an earlier commit. But this time, we want to create a new commit. So we'll run git commit -am 'two and a third'. Now we edit file A and add the line two and two thirds.

git add . git commit -am 'two and two thirds' git rebase --continue

We have a conflict with our commit, three, so let's resolve it:

We'll change

one
<<<<<<< HEAD
two and a third
two and two thirds
=======
two
three
>>>>>>> bfb8e46... three

to

one
two and a third
two and two thirds
three

git add .; git rebase --continue

Now our git log -p looks like this:

commit e59ca35bae8360439823d66d459238779e5b4892
Author: Rose Perrone <[email protected]>
Date:   Sun Jul 7 13:57:00 2013 -0700

    three

diff --git a/A b/A
index 5aef867..dd8fb63 100644
--- a/A
+++ b/A
@@ -1,3 +1,4 @@
 one
 two and a third
 two and two thirds
+three

commit 4a283ba9bf83ef664541b467acdd0bb4d770ab8e
Author: Rose Perrone <[email protected]>
Date:   Sun Jul 7 14:07:07 2013 -0700

    two and two thirds

diff --git a/A b/A
index 575010a..5aef867 100644
--- a/A
+++ b/A
@@ -1,2 +1,3 @@
 one
 two and a third
+two and two thirds

commit 704d323ca1bc7c45ed8b1714d924adcdc83dfa44
Author: Rose Perrone <[email protected]>
Date:   Sun Jul 7 14:06:40 2013 -0700

    two and a third

diff --git a/A b/A
index 5626abf..575010a 100644
--- a/A
+++ b/A
@@ -1 +1,2 @@
 one
+two and a third

commit 9aac58f3893488ec643fecab3c85f5a2f481586f
Author: Rose Perrone <[email protected]>
Date:   Sun Jul 7 13:56:40 2013 -0700

    one

diff --git a/A b/A
new file mode 100644
index 0000000..5626abf
--- /dev/null
+++ b/A
@@ -0,0 +1 @@
+one

Using <style> tags in the <body> with other HTML

The <style> tag belongs in the <head> section, separate from all the content.

References: W3C Specs and W3Schools

Auto line-wrapping in SVG text

Here's an alternative:

<svg ...>
  <switch>
    <g requiredFeatures="http://www.w3.org/Graphics/SVG/feature/1.2/#TextFlow">
      <textArea width="200" height="auto">
       Text goes here
      </textArea>
    </g>
    <foreignObject width="200" height="200" 
     requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">
      <p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
    </foreignObject>
    <text x="20" y="20">No automatic linewrapping.</text>
  </switch>
</svg>

Noting that even though foreignObject may be reported as being supported with that featurestring, there's no guarantee that HTML can be displayed because that's not required by the SVG 1.1 specification. There is no featurestring for html-in-foreignobject support at the moment. However, it is still supported in many browsers, so it's likely to become required in the future, perhaps with a corresponding featurestring.

Note that the 'textArea' element in SVG Tiny 1.2 supports all the standard svg features, e.g advanced filling etc, and that you can specify either of width or height as auto, meaning that the text can flow freely in that direction. ForeignObject acts as clipping viewport.

Note: while the above example is valid SVG 1.1 content, in SVG 2 the 'requiredFeatures' attribute has been removed, which means the 'switch' element will try to render the first 'g' element regardless of having support for SVG 1.2 'textArea' elements. See SVG2 switch element spec.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

I happened to run with the same issue in iOS 7 (with some devices no simulators).

Looks like Safari in iOS 7 has a lower storage quota, which apparently is reached by having a long history log.

I guess the best practice will be to catch the exception.

The Modernizr project has an easy patch, you should try something similar: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

Concatenate multiple files but include filename as section headers

This should do the trick as well:

find . -type f -print -exec cat {} \;

Means:

find    = linux `find` command finds filenames, see `man find` for more info
.       = in current directory
-type f = only files, not directories
-print  = show found file
-exec   = additionally execute another linux command
cat     = linux `cat` command, see `man cat`, displays file contents
{}      = placeholder for the currently found filename
\;      = tell `find` command that it ends now here

You further can combine searches trough boolean operators like -and or -or. find -ls is nice, too.

switch case statement error: case expressions must be constant expression

Unchecking "Is Library" in the project Properties worked for me.

What are ABAP and SAP?

SAP is a company and offers a full Enterprise Resource Planning (ERP) system, business platform, and the associated modules (financials, general ledger, &c).

ABAP is the primary programming language used to write SAP software and customizations. It would do it injustice to think of it as COBOL and SQL on steroids, but that gives you an idea. ABAP runs within the SAP system.

SAP and ABAP abstract the DB and run atop various underlying DBMSs.

SAP produces other things as well and even publicly says they dabble in Java and even produce a J2EE container, but tried-and-true SAP is ABAP through-and-through.

get size of json object

use this one

//for getting length of object
 int length = jsonObject.length();

or

//for getting length of array
 int length = jsonArray.length();

413 Request Entity Too Large - File Upload Issue

sudo nano /etc/nginx/nginx.conf

Then add a line in the http section

http {
    client_max_body_size 100M;
}

don't use MB only M.

systemctl restart nginx

then for php location

sudo gedit /etc/php5/fpm/php.ini

for nowdays maximum use php 7.0 or higher

sudo nano /etc/php/7.2/fpm/php.ini     //7.3,7.2 or 7.1 which php you use

check those increasing by your desire .

memory_limit = 128M 
post_max_size = 20M  
upload_max_filesize = 10M

restart php-fpm

service php-fpm restart 

Static variables in C++

Static variable in a header file:

say 'common.h' has

static int zzz;

This variable 'zzz' has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h' has it's own unique object of name 'zzz'.

Static variable in a class:

Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.

$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."

So let's say 'myclass.h' has

struct myclass{
   static int zzz;        // this is only a declaration
};

and myclass.cpp has

#include "myclass.h"

int myclass::zzz = 0           // this is a definition, 
                               // should be done once and only once

and "hisclass.cpp" has

#include "myclass.h"

void f(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

and "ourclass.cpp" has

#include "myclass.h"
void g(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.

Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate

Tomcat Servlet: Error 404 - The requested resource is not available

Writing Java servlets is easy if you use Java EE 7

@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("Hello World");
   out.flush();
  }
}

Since servlet 3.0

The good news is the deployment descriptor is no longer required!

Read the tutorial for Java Servlets.

How to change Label Value using javascript

very simple

$('#label-ID').text("label value which you want to set");

CSS text-align: center; is not centering things

This worked for me :

  e.Row.Cells["cell no "].HorizontalAlign = HorizontalAlign.Center;

But 'css text-align = center ' didn't worked for me

hope it will help you

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

How to define a List bean in Spring?

Use the util namespace, you will be able to register the list as a bean in your application context. You can then reuse the list to inject it in other bean definitions.

ASP.NET Bundles how to disable minification

If you have debug="true" in web.config and are using Scripts/Styles.Render to reference the bundles in your pages, that should turn off both bundling and minification. BundleTable.EnableOptimizations = false will always turn off both bundling and minification as well (irrespective of the debug true/false flag).

Are you perhaps not using the Scripts/Styles.Render helpers? If you are directly rendering references to the bundle via BundleTable.Bundles.ResolveBundleUrl() you will always get the minified/bundled content.

What is %0|%0 and how does it work?

This is known as a fork bomb. It keeps splitting itself until there is no option but to restart the system. http://en.wikipedia.org/wiki/Fork_bomb

How do you hide the Address bar in Google Chrome for Chrome Apps?

2016-05-04-03:59A - Windows 7 - Google Chrome [Version 50.0.2661.94]

wanted this done for a 'YouTube Pop-out Player' without Chrome Address / Toolbar or Bookmarks Bar; solution ended up being a small edit of MarkHu's answer (because of new updates, i guess?)

Go to the page you want altered, select Chrome Toolbar's 'Hamburger button' (3 horizontal lines).

From there: More tools > Add to desktop... > Open as window (tick box) > Add (button).

... and, simply open your page from the new desktop shortcut, adjust as needed, and enjoy!

Laravel Check If Related Model Exists

Not sure if this has changed in Laravel 5, but the accepted answer using count($data->$relation) didn't work for me, as the very act of accessing the relation property caused it to be loaded.

In the end, a straightforward isset($data->$relation) did the trick for me.

Convert ASCII number to ASCII Character in C

You can assign int to char directly.

int a = 65;
char c = a;
printf("%c", c);

In fact this will also work.

printf("%c", a);  // assuming a is in valid range

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

How to set the component size with GridLayout? Is there a better way?

You need to try one of the following:

  1. GridBagLayout
  2. MigLayout
  3. SpringLayout

They offer many more features and will be easier to get what you are looking for.

Google Maps Api v3 - find nearest markers

Use computeDistanceBetween() Google map API method to calculate near marker between your location and markers list on google map.

Steps:-

  1. Create marker on google map.
    function addMarker(location) { var marker = new google.maps.Marker({ title: 'User added marker', icon: { path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW, scale: 5 }, position: location, map: map }); }

  2. On Mouse click create event for getting lat, long of your location and pass that to find_closest_marker().

    function find_closest_marker(event) {
          var distances = [];
          var closest = -1;
          for (i = 0; i < markers.length; i++) {
            var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].position, event.latLng);
            distances[i] = d;
            if (closest == -1 || d < distances[closest]) {
              closest = i;
            }
          }
          alert('Closest marker is: ' + markers[closest].getTitle());
        }
    

visit this link follow the steps. You will able to get nearer marker to your location.

set the width of select2 input (through Angular-ui directive)

This is an old question but new info is still worth posting...

Starting with Select2 version 3.4.0 there is an attribute dropdownAutoWidth which solves the problem and handles all the odd cases. Note it is not on by default. It resizes dynamically as the user makes selections, it adds width for allowClear if that attribute is used, and it handles placeholder text properly too.

$("#some_select_id").select2({
    dropdownAutoWidth : true
});

HTML Input="file" Accept Attribute File Type (CSV)

These days you can just use the file extension

<input type="file" ID="fileSelect" accept=".xlsx, .xls, .csv"/>

How can foreign key constraints be temporarily disabled using T-SQL?

Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, set Enforce foreign key constraint to 'Yes' (to enable foreign key constraints) or 'No' (to disable it). enter image description here

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

How to export MySQL database with triggers and procedures?

mysqldump will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:

  • --routines – FALSE by default
  • --triggers – TRUE by default

so in mysqldump command , add --routines like :

mysqldump <other mysqldump options> --routines > outputfile.sql

See the MySQL documentation about mysqldump arguments.

How does Git handle symbolic links?

Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.

When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.

If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

This is what i've implemented:

$(window).resize(function(){ setTimeout(someFunction, 500); });

we can clear the setTimeout if we expect resize to happen less than 500ms

Good Luck...

If Else If In a Sql Server Function

Look at these lines:

If yes_ans > no_ans and yes_ans > na_ans

and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.

Consider assigning those values to variables you can then use for your conditional flow below. Thus,

if exists (some record)
begin
   set @var = column, @var2 = column2, ...

   if (@var1 > @var2)
      -- do something

end

The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

Color not work, if you use for bootstrap font png image, as i.

[class^="icon-"],
[class*=" icon-"] {
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-top: 1px;
  *margin-right: .3em;
  line-height: 14px;
  vertical-align: text-top;
  background-image: url("../img/glyphicons-halflings.png");
  background-position: 14px 14px;
  background-repeat: no-repeat;
}

HTML5 use css filter to colorize image, example

filter: invert(100%)  contrast(2) brightness(50%) sepia(40%) saturate(450%) hue-rotate(-50deg);

Writing unit tests in Python: How do I start?

nosetests is brilliant solution for unit-testing in python. It supports both unittest based testcases and doctests, and gets you started with it with just simple config file.

Eclipse/Maven error: "No compiler is provided in this environment"

  1. Uninstall older Java(JDK/JRE) from the system( Keep one (latest) java version), Also remove if any old java jre/jdk entries in environment variables PATH/CLASSPATH
  2. Eclipse->Window->Preferences->Installed JREs->Add/Edit JDK from the latest installation
  3. Eclipse->Window->Preferences->Installed JREs->Execution Environment->Select the desired java version on left and click the check box on right
  4. If you are using maven include the following tag in pom.xml (update versions as needed) inside plugins tag.

    <plugin>  
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    
  5. Right click on eclipse project Maven - > Update Project

What is getattr() exactly and how do I use it?

A pretty common use case for getattr is mapping data to functions.

For instance, in a web framework like Django or Pylons, getattr makes it straightforward to map a web request's URL to the function that's going to handle it. If you look under the hood of Pylons's routing, for instance, you'll see that (by default, at least) it chops up a request's URL, like:

http://www.example.com/customers/list

into "customers" and "list". Then it searches for a controller class named CustomerController. Assuming it finds the class, it creates an instance of the class and then uses getattr to get its list method. It then calls that method, passing it the request as an argument.

Once you grasp this idea, it becomes really easy to extend the functionality of a web application: just add new methods to the controller classes, and then create links in your pages that use the appropriate URLs for those methods. All of this is made possible by getattr.

Sorting arrays in NumPy by column

It is an old question but if you need to generalize this to a higher than 2 dimension arrays, here is the solution than can be easily generalized:

np.einsum('ij->ij', a[a[:,1].argsort(),:])

This is an overkill for two dimensions and a[a[:,1].argsort()] would be enough per @steve's answer, however that answer cannot be generalized to higher dimensions. You can find an example of 3D array in this question.

Output:

[[7 0 5]
 [9 2 3]
 [4 5 6]]

Git: can't undo local changes (error: path ... is unmerged)

I find git stash very useful for temporal handling of all 'dirty' states.

Git merge reports "Already up-to-date" though there is a difference

Say you have a branch master with the following commit history:

A -- B -- C -- D

Now, you create a branch test, work on it, and do 4 commits:


                 E -- F -- G -- H
                /
A -- B -- C -- D

master's head points to D, and test's head points to H.

The "Already up-to-date" message shows up when the HEAD of the branch you are merging into is a parent of the chain of commits of the branch you want to merge. That's the case, here: D is a parent of E.

There is nothing to merge from test to master, since nothing has changed on master since then. What you want to do here is literally to tell Git to have master's head to point to H, so master's branch has the following commits history:

A -- B -- C -- D -- E -- F -- G -- H

This is a job for Git command reset. You also want the working directory to reflect this change, so you'll do a hard reset:

git reset --hard H

How to import existing Git repository into another?

If you want to retain the exact commit history of the second repository and therefore also retain the ability to easily merge upstream changes in the future then here is the method you want. It results in unmodified history of the subtree being imported into your repo plus one merge commit to move the merged repository to the subdirectory.

git remote add XXX_remote <path-or-url-to-XXX-repo>
git fetch XXX_remote
git merge -s ours --no-commit --allow-unrelated-histories XXX_remote/master
git read-tree --prefix=ZZZ/ -u XXX_remote/master
git commit -m "Imported XXX as a subtree."

You can track upstream changes like so:

git pull -s subtree XXX_remote master

Git figures out on its own where the roots are before doing the merge, so you don't need to specify the prefix on subsequent merges.

The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a will show you all the changes (if any) except those in the merged history. You can do:

git log --follow -- a

but that won't show the changes other then in the merged history.

In other words, if you don't change ZZZ's files in repository XXX, then you need to specify --follow and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.

Git versions before 2.9: You don’t need to pass the --allow-unrelated-histories option to git merge.

The method in the other answer that uses read-tree and skips the merge -s ours step is effectively no different than copying the files with cp and committing the result.

Original source was from github's "Subtree Merge" help article. And another useful link.

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

Displaying output of a remote command with Ansible

Prints pubkey and avoid the changed status by adding changed_when: False to cat task:

- name: Generate SSH keys for vagrant user   
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048

- name: Check SSH public key   
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
  changed_when: False

- name: Print SSH public key
  debug: var=cat.stdout

- name: Wait for user to copy SSH public key   
  pause: prompt="Please add the SSH public key above to your GitHub account"

SQLite in Android How to update a specific row

just try this way

  String strFilter = "_id=" + Id;
  ContentValues args = new ContentValues();
  args.put(KEY_TITLE, title);
  myDB.update("titles", args, strFilter, null);**

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

For me it was "Prefer 32bit": clearing the checkbox allowed CLR to load Crystal Reports 64bit runtime (the only one installed).

Best way to format integer as string with leading zeros?

One-liner alternative to the built-in zfill.

This function takes x and converts it to a string, and adds zeros in the beginning only and only if the length is too short:

def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )

To sum it up - build-in: zfill is good enough, but if someone is curious on how to implement this by hand, here is one more example.

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

I found the best way to fix this error: Bootstrap’s JavaScript requires jQuery version 1.9.1 or higher

In Wordpress..just ran this plugin and it fixed it. Thought I'd share jQuery Updater

Is there a "between" function in C#?

There is no built in construct in C#/.NET, but you can easily add your own extension method for this:

public static class ExtensionsForInt32
{
    public static bool IsBetween (this int val, int low, int high)
    {
           return val > low && val < high;
    }
}

Which can be used like:

if (5.IsBetween (0, 10)) { /* Do something */ }

Django - after login, redirect user to his custom page --> mysite.com/username

Got into django recently and been looking into a solution to that and found a method that might be useful.

So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:

def profile(request):
    name=request.user.username
    return redirect('-----choose where-----' + name + '/')

Then create a view that captures it in one of your apps, for example:

def profile(request, name):
    user = get_object_or_404(User, username=name)
    return render(request, 'myproject/user.html', {'profile': user})

Where the urlpatterns capture would look like this:

url(r'^(?P<name>.+)/$', views.profile, name='user')

Works well for me.

Selenium WebDriver: Wait for complex page with JavaScript to load

Thanks Ashwin !

In my case I should need wait for a jquery plugin execution in some element.. specifically "qtip"

based in your hint, it worked perfectly for me :

wait.until( new Predicate<WebDriver>() {
            public boolean apply(WebDriver driver) {
                return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
            }
        }
    );

Note: I'm using Webdriver 2

Environment variable substitution in sed

Your two examples look identical, which makes problems hard to diagnose. Potential problems:

  1. You may need double quotes, as in sed 's/xxx/'"$PWD"'/'

  2. $PWD may contain a slash, in which case you need to find a character not contained in $PWD to use as a delimiter.

To nail both issues at once, perhaps

sed 's@xxx@'"$PWD"'@'

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

What's the difference between Perl's backticks, system, and exec?

exec

executes a command and never returns. It's like a return statement in a function.

If the command is not found exec returns false. It never returns true, because if the command is found it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.

system

executes a command and your Perl script is continued after the command has finished.

The return value is the exit status of the command. You can find documentation about it in perlfunc.

backticks

like system executes a command and your perl script is continued after the command has finished.

In contrary to system the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and execit is an operator.


Other ways

What is missing from the above is a way to execute a command asynchronously. That means your perl script and your command run simultaneously. This can be accomplished with open. It allows you to read STDOUT/STDERR and write to STDIN of your command. It is platform dependent though.

There are also several modules which can ease this tasks. There is IPC::Open2 and IPC::Open3 and IPC::Run, as well as Win32::Process::Create if you are on windows.

Assigning variables with dynamic names in Java

Dynamic Variable Names in Java
There is no such thing.

In your case you can use array:

int[] n = new int[3];
for() {
 n[i] = 5;
}

For more general (name, value) pairs, use Map<>

How can I stop Chrome from going into debug mode?

For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.

For me it was the "breakOnLoad": true line in VS Code launch.json config.

Hide password with "•••••••" in a textField

in Swift 3.0 or Later

passwordTextField.isSecureTextEntry = true

Function to return only alpha-numeric characters from string?

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

How to render a DateTime object in a Twig template

you can render in following way

{{ post.published_at|date("m/d/Y") }}

For more details can visit http://twig.sensiolabs.org/doc/filters/date.html

validation of input text field in html using javascript

function hasValue( val ) { // Return true if text input is valid/ not-empty
    return val.replace(/\s+/, '').length; // boolean
}

For multiple elements you can pass inside your input elements loop their value into that function argument.

If a user inserted one or more spaces, thanks to the regex s+ the function will return false.

Where to download visual studio express 2005?

You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?

How to redirect and append both stdout and stderr to a file with Bash?

There are two ways to do this, depending on your Bash version.

The classic and portable (Bash pre-4) way is:

cmd >> outfile 2>&1

A nonportable way, starting with Bash 4 is

cmd &>> outfile

(analog to &> outfile)

For good coding style, you should

  • decide if portability is a concern (then use classic way)
  • decide if portability even to Bash pre-4 is a concern (then use classic way)
  • no matter which syntax you use, not change it within the same script (confusion!)

If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.

Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.

The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Converting binary to decimal integer output

You can use int and set the base to 2 (for binary):

>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>

However, if you cannot use int like that, then you could always do this:

binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
    decimal = decimal*2 + int(digit)
print decimal

Below is a demonstration:

>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
...     decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

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

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

When should I use the new keyword in C++?

There is an important difference between the two.

Everything not allocated with new behaves much like value types in C# (and people often say that those objects are allocated on the stack, which is probably the most common/obvious case, but not always true. More precisely, objects allocated without using new have automatic storage duration Everything allocated with new is allocated on the heap, and a pointer to it is returned, exactly like reference types in C#.

Anything allocated on the stack has to have a constant size, determined at compile-time (the compiler has to set the stack pointer correctly, or if the object is a member of another class, it has to adjust the size of that other class). That's why arrays in C# are reference types. They have to be, because with reference types, we can decide at runtime how much memory to ask for. And the same applies here. Only arrays with constant size (a size that can be determined at compile-time) can be allocated with automatic storage duration (on the stack). Dynamically sized arrays have to be allocated on the heap, by calling new.

(And that's where any similarity to C# stops)

Now, anything allocated on the stack has "automatic" storage duration (you can actually declare a variable as auto, but this is the default if no other storage type is specified so the keyword isn't really used in practice, but this is where it comes from)

Automatic storage duration means exactly what it sounds like, the duration of the variable is handled automatically. By contrast, anything allocated on the heap has to be manually deleted by you. Here's an example:

void foo() {
  bar b;
  bar* b2 = new bar();
}

This function creates three values worth considering:

On line 1, it declares a variable b of type bar on the stack (automatic duration).

On line 2, it declares a bar pointer b2 on the stack (automatic duration), and calls new, allocating a bar object on the heap. (dynamic duration)

When the function returns, the following will happen: First, b2 goes out of scope (order of destruction is always opposite of order of construction). But b2 is just a pointer, so nothing happens, the memory it occupies is simply freed. And importantly, the memory it points to (the bar instance on the heap) is NOT touched. Only the pointer is freed, because only the pointer had automatic duration. Second, b goes out of scope, so since it has automatic duration, its destructor is called, and the memory is freed.

And the barinstance on the heap? It's probably still there. No one bothered to delete it, so we've leaked memory.

From this example, we can see that anything with automatic duration is guaranteed to have its destructor called when it goes out of scope. That's useful. But anything allocated on the heap lasts as long as we need it to, and can be dynamically sized, as in the case of arrays. That is also useful. We can use that to manage our memory allocations. What if the Foo class allocated some memory on the heap in its constructor, and deleted that memory in its destructor. Then we could get the best of both worlds, safe memory allocations that are guaranteed to be freed again, but without the limitations of forcing everything to be on the stack.

And that is pretty much exactly how most C++ code works. Look at the standard library's std::vector for example. That is typically allocated on the stack, but can be dynamically sized and resized. And it does this by internally allocating memory on the heap as necessary. The user of the class never sees this, so there's no chance of leaking memory, or forgetting to clean up what you allocated.

This principle is called RAII (Resource Acquisition is Initialization), and it can be extended to any resource that must be acquired and released. (network sockets, files, database connections, synchronization locks). All of them can be acquired in the constructor, and released in the destructor, so you're guaranteed that all resources you acquire will get freed again.

As a general rule, never use new/delete directly from your high level code. Always wrap it in a class that can manage the memory for you, and which will ensure it gets freed again. (Yes, there may be exceptions to this rule. In particular, smart pointers require you to call new directly, and pass the pointer to its constructor, which then takes over and ensures delete is called correctly. But this is still a very important rule of thumb)

Loop through columns and add string lengths as new columns

For the sake of completeness, there is also a data.table solution:

library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
#      col1     col2 col1_length col2_length
#1:     abc adf qqwe           3           8
#2:    abcd        d           4           1
#3:       a        e           1           1
#4: abcdefg        f           7           1

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

... right now it happens only to the website I'm testing. I can't post it here because it's confidential.

Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use --secure-protocol=TLSv1. If this does not help check if you can access the site with openssl s_client -connect ... (probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ....

Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.

The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.

Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?

The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.

How to correctly catch change/focusOut event on text input in React.js?

If you want to only trigger validation when the input looses focus you can use onBlur

Trivia: React <17 listens to blur event and >=17 listens to focusout event.

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

int to string in MySQL

select t2.* 
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar)  + '%/more' 
where t1.id > 9000

Using concat like suggested is even better though

Best way to do multi-row insert in Oracle?

you can insert using loop if you want to insert some random values.

BEGIN 
    FOR x IN 1 .. 1000 LOOP
         INSERT INTO MULTI_INSERT_DEMO (ID, NAME)
         SELECT x, 'anyName' FROM dual;
    END LOOP;
END;

What is the Python equivalent for a case/switch statement?

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

Convert MySql DateTime stamp into JavaScript's Date format

A quick search in google provided this:

 function mysqlTimeStampToDate(timestamp) {
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
  }

Source:http://snippets.dzone.com/posts/show/4132

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

What is the best way to dump entire objects to a log in C#?

You can write your own WriteLine method-

public static void WriteLine<T>(T obj)
    {
        var t = typeof(T);
        var props = t.GetProperties();
        StringBuilder sb = new StringBuilder();
        foreach (var item in props)
        {
            sb.Append($"{item.Name}:{item.GetValue(obj,null)}; ");
        }
        sb.AppendLine();
        Console.WriteLine(sb.ToString());
    }

Use it like-

WriteLine(myObject);

To write a collection we can use-

 var ifaces = t.GetInterfaces();
        if (ifaces.Any(o => o.Name.StartsWith("ICollection")))
        {

            dynamic lst = t.GetMethod("GetEnumerator").Invoke(obj, null);
            while (lst.MoveNext())
            {
                WriteLine(lst.Current);
            }
        }   

The method may look like-

 public static void WriteLine<T>(T obj)
    {
        var t = typeof(T);
        var ifaces = t.GetInterfaces();
        if (ifaces.Any(o => o.Name.StartsWith("ICollection")))
        {

            dynamic lst = t.GetMethod("GetEnumerator").Invoke(obj, null);
            while (lst.MoveNext())
            {
                WriteLine(lst.Current);
            }
        }            
        else if (t.GetProperties().Any())
        {
            var props = t.GetProperties();
            StringBuilder sb = new StringBuilder();
            foreach (var item in props)
            {
                sb.Append($"{item.Name}:{item.GetValue(obj, null)}; ");
            }
            sb.AppendLine();
            Console.WriteLine(sb.ToString());
        }
    }

Using if, else if and checking interfaces, attributes, base type, etc. and recursion (as this is a recursive method) in this way we may achieve an object dumper, but it is tedious for sure. Using the object dumper from Microsoft's LINQ Sample would save your time.

Javascript to sort contents of select element

This will do the trick. Just pass it your select element a la: document.getElementById('lstALL') when you need your list sorted.

function sortSelect(selElem) {
    var tmpAry = new Array();
    for (var i=0;i<selElem.options.length;i++) {
        tmpAry[i] = new Array();
        tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][1] = selElem.options[i].value;
    }
    tmpAry.sort();
    while (selElem.options.length > 0) {
        selElem.options[0] = null;
    }
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElem.options[i] = op;
    }
    return;
}

Can't start Eclipse - Java was started but returned exit code=13

  1. Under system environment variables, make sure "C:\ProgramData\Oracle\Java\javapath" is removed.

  2. Under system environment variables, make sure "C:\Program Files\Java\jdk1.8.0_131\bin" is added.

enter image description here

Beautiful way to remove GET-variables with PHP?

If the URL that you are trying to remove the query string from is the current URL of the PHP script, you can use one of the previously mentioned methods. If you just have a string variable with a URL in it and you want to strip off everything past the '?' you can do:

$pos = strpos($url, "?");
$url = substr($url, 0, $pos);

"Sources directory is already netbeans project" error when opening a project from existing sources

  1. Go to the folder containing your project
  2. Delete the folder named nbproject
  3. Restart Netbeans
  4. Try creating your project again from the original folder

MongoDB relationships: embed or reference?

If I want to edit a specified comment, how to get its content and its question?

You can query by sub-document: db.question.find({'comments.content' : 'xxx'}).

This will return the whole Question document. To edit the specified comment, you then have to find the comment on the client, make the edit and save that back to the DB.

In general, if your document contains an array of objects, you'll find that those sub-objects will need to be modified client side.

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

JavaScript or jQuery browser back button click detector

In case of HTML5 this will do the trick

window.onpopstate = function() {
   alert("clicked back button");
}; history.pushState({}, '');

Why can't static methods be abstract in Java?

As abstract methods belong to the class and cannot be overridden by the implementing class.Even if there is a static method with same signature , it hides the method ,does not override it. So it is immaterial to declare the abstract method as static as it will never get the body.Thus, compile time error.

How to unpackage and repackage a WAR file

Non programmatically, you can just open the archive using the 7zip UI to add/remove or extract/replace files without the structure changing. I didn't know it was a problem using other things until now :)

Doctrine 2: Update query with query builder

Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.

An update could be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
            ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
            ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()
            ->getSingleScalarResult()
        ;
    }

AJAX action handling:

# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
        ->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
    # Row updated
}

Working example using Doctrine 2.5 (on top of Symfony3).

List of special characters for SQL LIKE clause

For SQL Server, from http://msdn.microsoft.com/en-us/library/ms179859.aspx :

  • % Any string of zero or more characters.

    WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title.

  • _ Any single character.

    WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).

  • [ ] Any single character within the specified range ([a-f]) or set ([abcdef]).

    WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.

  • [^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

    WHERE au_lname LIKE 'de[^l]%' all author last names starting with de and where the following letter is not l.

how to remove the first two columns in a file using shell (awk, sed, whatever)

Here's one way to do it with Awk that's relatively easy to understand:

awk '{print substr($0, index($0, $3))}'

This is a simple awk command with no pattern, so action inside {} is run for every input line.

The action is to simply prints the substring starting with the position of the 3rd field.

  • $0: the whole input line
  • $3: 3rd field
  • index(in, find): returns the position of find in string in
  • substr(string, start): return a substring starting at index start

If you want to use a different delimiter, such as comma, you can specify it with the -F option:

awk -F"," '{print substr($0, index($0, $3))}'

You can also operate this on a subset of the input lines by specifying a pattern before the action in {}. Only lines matching the pattern will have the action run.

awk 'pattern{print substr($0, index($0, $3))}'

Where pattern can be something such as:

  • /abcdef/: use regular expression, operates on $0 by default.
  • $1 ~ /abcdef/: operate on a specific field.
  • $1 == blabla: use string comparison
  • NR > 1: use record/line number
  • NF > 0: use field/column number

How do I remove a MySQL database?

From the MySQL prompt:

mysql> drop database <db_name>;

How to get current date & time in MySQL?

$rs = $db->Insert('register',"'$fn','$ln','$email','$pass','$city','$mo','$fil'","'f_name','l_name=','email','password','city','contact','image'");

git pull while not in a git directory

For anyone like me that was trying to do this via a drush (Drupal shell) command on a remote server, you will not be able to use the solution that requires you to CD into the working directory:

Instead you need to use the solution that breaks up the pull into a fetch & merge:

drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH fetch origin
drush @remote exec git --git-dir=/REPO/PATH --work-tree=/REPO/WORKDIR-PATH merge origin/branch

MySQL OPTIMIZE all tables?

You can use mysqlcheck to do this at the command line.

One database:

mysqlcheck -o <db_schema_name>

All databases:

mysqlcheck -o --all-databases

SQL Error: ORA-12899: value too large for column

example : 1 and 2 table is available

1 table delete entry and select nor 2 table records and insert to no 1 table . when delete time no 1 table dont have second table records example emp id not available means this errors appeared

Removing Spaces from a String in C?

I assume the C string is in a fixed memory, so if you replace spaces you have to shift all characters.

The easiest seems to be to create new string and iterate over the original one and copy only non space characters.

How do relative file paths work in Eclipse?

This is really similar to another question. How should I load files into my Java application?

How should I load my files into my Java Application?

You do not want to load your files in by:

C:\your\project\file.txt

this is bad!

You should use getResourceAsStream.

InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);

And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.

Detect if page has finished loading

Another option you can check the document.readyState like,

var chkReadyState = setInterval(function() {
    if (document.readyState == "complete") {
        // clear the interval
        clearInterval(chkReadyState);
        // finally your page is loaded.
    }
}, 100);

From the documentation of readyState Page the summary of complete state is

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

Nodejs cannot find installed module on Windows

if you are using windows , it takes some steps , 1) create a file called package.json

 {
  "name": "hello"
, "version": "0.0.1"
, "dependencies": {
    "express": "*"
  }
}

where hello is the name of the package and * means the latest version of your dependency

2) code to you project directory and run the following command

npm install

It installs the dependencies

No Network Security Config specified, using platform default - Android Log

I have a same problem, with volley, but this is my solution:

  1. In Android Manifiest, in tag application add:

    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"
    
  2. create in folder xml this file network_security_config.xml and write this:

    <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
      </network-security-config>
    
  3. inside tag application add this tag:

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    

Possible to iterate backwards through a foreach?

Before using foreach for iteration, reverse the list by the reverse method:

    myList.Reverse();
    foreach( List listItem in myList)
    {
       Console.WriteLine(listItem);
    }

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:

$ ps -ef|grep httpd
0     681     1   0 10:38pm ??         0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501   690   681   0 10:38pm ??         0:00.02 /Applications/MAMP/Library/bin/httpd -k start

...

Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)

$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.

Wait for crash... then:

(gdb) backtrace

Or

(gdb) backtrace full

Should give you some clue what's going on. If you file a bug report you should include the backtrace.

If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:

StartServers 1
MinSpareServers 1
MaxSpareServers 1