Programs & Examples On #Open esb

OpenESB is a Java-based open source enterprise service bus. It can be used as a platform for both enterprise application integration and service-oriented applications and supports various Web Services standards. It was formerly developed by Sun Microsystems, but was open sourced in October 2010. It is licensed under CDDL.

Combine hover and click functions (jQuery)?

$("#target").hover(function(){
  $(this).click();
}).click(function(){
  //common function
});

Storing sex (gender) in database

I use char 'f', 'm' and 'u' because I surmise the gender from name, voice and conversation, and sometimes don't know the gender. The final determination is their opinion.

It really depends how well you know the person and whether your criteria is physical form or personal identity. A psychologist might need additional options - cross to female, cross to male, trans to female, trans to male, hermaphrodite and undecided. With 9 options, not clearly defined by a single character, I might go with Hugo's advice of tiny integer.

$.ajax( type: "POST" POST method to php

try this

$(document).on("submit", "#form-data", function(e){
    e.preventDefault()
    $.ajax({
        url: "edit.php",
        method: "POST",
        data: new FormData(this),
        contentType: false,
        processData: false,
        success: function(data){
            $('.center').html(data); 
        }
    })
})

in the form the button needs to be type="submit"

Get all mysql selected rows into an array

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:

while($row = mysql_fetch_assoc($result)){
     $json[] = $row;
}

echo json_encode($json);

If you switched to MySQLi you could do:

$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );

How to convert a string Date to long millseconds

you can use the simpleDateFormat to parse the string date.

Pandas Merge - How to avoid duplicating columns

I'm freshly new with Pandas but I wanted to achieve the same thing, automatically avoiding column names with _x or _y and removing duplicate data. I finally did it by using this answer and this one from Stackoverflow

sales.csv

    city;state;units
    Mendocino;CA;1
    Denver;CO;4
    Austin;TX;2

revenue.csv

    branch_id;city;revenue;state_id
    10;Austin;100;TX
    20;Austin;83;TX
    30;Austin;4;TX
    47;Austin;200;TX
    20;Denver;83;CO
    30;Springfield;4;I

merge.py import pandas

def drop_y(df):
    # list comprehension of the cols that end with '_y'
    to_drop = [x for x in df if x.endswith('_y')]
    df.drop(to_drop, axis=1, inplace=True)


sales = pandas.read_csv('data/sales.csv', delimiter=';')
revenue = pandas.read_csv('data/revenue.csv', delimiter=';')

result = pandas.merge(sales, revenue,  how='inner', left_on=['state'], right_on=['state_id'], suffixes=('', '_y'))
drop_y(result)
result.to_csv('results/output.csv', index=True, index_label='id', sep=';')

When executing the merge command I replace the _x suffix with an empty string and them I can remove columns ending with _y

output.csv

    id;city;state;units;branch_id;revenue;state_id
    0;Denver;CO;4;20;83;CO
    1;Austin;TX;2;10;100;TX
    2;Austin;TX;2;20;83;TX
    3;Austin;TX;2;30;4;TX
    4;Austin;TX;2;47;200;TX

Java ArrayList for integers

You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be

ArrayList<Integer> list = new ArrayList<>();

or better

List<Integer> list = new ArrayList<>();

How can I read large text files in Python, line by line, without loading it into memory?

I demonstrated a parallel byte level random access approach here in this other question:

Getting number of lines in a text file without readlines

Some of the answers already provided are nice and concise. I like some of them. But it really depends what you want to do with the data that's in the file. In my case I just wanted to count lines, as fast as possible on big text files. My code can be modified to do other things too of course, like any code.

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

for bootstrap 3, this is what i used

.carousel-fade .carousel-inner .item {
  opacity: 0;
  -webkit-transition-property: opacity;
  -moz-transition-property: opacity;
  -o-transition-property: opacity;
  transition-property: opacity;
}
.carousel-fade .carousel-inner .active {
  opacity: 1;
}
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  opacity: 0;
  z-index: 1;
}
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-control {
  z-index: 2;
}

How can I pad an integer with zeros on the left?

Use the class DecimalFormat, like so:

NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811)); 

OUTPUT : 0000811

ng-if, not equal to?

This is now possible as of AngularJS 1.5.10, using ng-switch-when-separator

_x000D_
_x000D_
var app = angular.module("app", []); _x000D_
_x000D_
app.controller("ctrl", function($scope) {_x000D_
    $scope.myDataSet = [{Name: 'Michelle', Gender: 'Female', DOB: '01/12/1986', Payment: [{Status: '0'}]},{Name: 'Steve', Gender: 'Male', DOB: '11/12/1982', Payment: [{Status: '1'}]},{Name: 'Dan', Gender: 'Male', DOB: '03/22/1976', Payment: [{Status: '2'}]},{Name: 'Doug', Gender: 'Male', DOB: '02/02/1980', Payment: [{Status: '3'}]},{Name: 'Mary', Gender: 'Female', DOB: '04/02/1976', Payment: [{Status: '4'}]},{Name: 'Cheyenne', Gender: 'Female', DOB: '07/10/1981', Payment: [{Status: '5'}]},{Name: 'Bob', Gender: 'Male', DOB: '02/16/1990', Payment: [{Status: '6'}]},{Name: 'Bad data', Gender: 'Blank', DOB: '01/01/1970', Payment: [{Status: '7'}]}];_x000D_
});
_x000D_
<script src="https://code.angularjs.org/1.5.10/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="ctrl">_x000D_
    <div ng-repeat="details in myDataSet" ng-switch on="details.Payment[0].Status">_x000D_
_x000D_
        <p>{{ details.Name }}</p>_x000D_
        <p>{{ details.DOB  }}</p>_x000D_
_x000D_
        <div ng-switch-when="0">_x000D_
            <p>No payment</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="1|2" ng-switch-when-separator="|">_x000D_
            <p>Late</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="3|4|5" ng-switch-when-separator="|">_x000D_
            <p>Some payment made</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="6">_x000D_
            <p>Late and further taken out</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-default>_x000D_
            <p>Error</p>_x000D_
        </div>_x000D_
        _x000D_
        <p>{{ details.Gender}}</p>_x000D_
_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Lock, mutex, semaphore... what's the difference?

Using C programming on a Linux variant as a base case for examples.

Lock:

• Usually a very simple construct binary in operation either locked or unlocked

• No concept of thread ownership, priority, sequencing etc.

• Usually a spin lock where the thread continuously checks for the locks availability.

• Usually relies on atomic operations e.g. Test-and-set, compare-and-swap, fetch-and-add etc.

• Usually requires hardware support for atomic operation.

File Locks:

• Usually used to coordinate access to a file via multiple processes.

• Multiple processes can hold the read lock however when any single process holds the write lock no other process is allowed to acquire a read or write lock.

• Example : flock, fcntl etc..

Mutex:

• Mutex function calls usually work in kernel space and result in system calls.

• It uses the concept of ownership. Only the thread that currently holds the mutex can unlock it.

• Mutex is not recursive (Exception: PTHREAD_MUTEX_RECURSIVE).

• Usually used in Association with Condition Variables and passed as arguments to e.g. pthread_cond_signal, pthread_cond_wait etc.

• Some UNIX systems allow mutex to be used by multiple processes although this may not be enforced on all systems.

Semaphore:

• This is a kernel maintained integer whose values is not allowed to fall below zero.

• It can be used to synchronize processes.

• The value of the semaphore may be set to a value greater than 1 in which case the value usually indicates the number of resources available.

• A semaphore whose value is restricted to 1 and 0 is referred to as a binary semaphore.

When would you use the different git merge strategies?

With Git 2.30 (Q1 2021), there will be a new merge strategy: ORT ("Ostensibly Recursive's Twin").

git merge -s ort

This comes from this thread from Elijah Newren:

For now, I'm calling it "Ostensibly Recursive's Twin", or "ort" for short. > At first, people shouldn't be able to notice any difference between it and the current recursive strategy, other than the fact that I think I can make it a bit faster (especially for big repos).

But it should allow me to fix some (admittedly corner case) bugs that are harder to handle in the current design, and I think that a merge that doesn't touch $GIT_WORK_TREE or $GIT_INDEX_FILE will allow for some fun new features.
That's the hope anyway.

Problem:

In the ideal world, we should:

  • ask unpack_trees() to do "read-tree -m" without "-u";

  • do all the merge-recursive computations in-core and prepare the resulting index, while keeping the current index intact;

  • compare the current in-core index and the resulting in-core index, and notice the paths that need to be added, updated or removed in the working tree, and ensure that there is no loss of information when the change is reflected to the working tree;
    E.g. the result wants to create a file where the working tree currently has a directory with non-expendable contents in it, the result wants to remove a file where the working tree file has local modification, etc.;
    And then finally

  • carry out the working tree update to make it match what the resulting in-core index says it should look like.

Result:

See commit 14c4586 (02 Nov 2020), commit fe1a21d (29 Oct 2020), and commit 47b1e89, commit 17e5574 (27 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit a1f9595, 18 Nov 2020)

merge-ort: barebones API of new merge strategy with empty implementation

Signed-off-by: Elijah Newren

This is the beginning of a new merge strategy.

While there are some API differences, and the implementation has some differences in behavior, it is essentially meant as an eventual drop-in replacement for merge-recursive.c.

However, it is being built to exist side-by-side with merge-recursive so that we have plenty of time to find out how those differences pan out in the real world while people can still fall back to merge-recursive.
(Also, I intend to avoid modifying merge-recursive during this process, to keep it stable.)

The primary difference noticable here is that the updating of the working tree and index is not done simultaneously with the merge algorithm, but is a separate post-processing step.
The new API is designed so that one can do repeated merges (e.g. during a rebase or cherry-pick) and only update the index and working tree one time at the end instead of updating it with every intermediate result.

Also, one can perform a merge between two branches, neither of which match the index or the working tree, without clobbering the index or working tree.

And:

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

t6423, t6436: note improved ort handling with dirty files

Signed-off-by: Elijah Newren

The "recursive" backend relies on unpack_trees() to check if unstaged changes would be overwritten by a merge, but unpack_trees() does not understand renames -- and once it returns, it has already written many updates to the working tree and index.
As such, "recursive" had to do a special 4-way merge where it would need to also treat the working copy as an extra source of differences that we had to carefully avoid overwriting and resulting in moving files to new locations to avoid conflicts.

The "ort" backend, by contrast, does the complete merge inmemory, and only updates the index and working copy as a post-processing step.
If there are dirty files in the way, it can simply abort the merge.

t6423: expect improved conflict markers labels in the ort backend

Signed-off-by: Elijah Newren

Conflict markers carry an extra annotation of the form REF-OR-COMMIT:FILENAME to help distinguish where the content is coming from, with the :FILENAME piece being left off if it is the same for both sides of history (thus only renames with content conflicts carry that part of the annotation).

However, there were cases where the :FILENAME annotation was accidentally left off, due to merge-recursive's every-codepath-needs-a-copy-of-all-special-case-code format.

t6404, t6423: expect improved rename/delete handling in ort backend

Signed-off-by: Elijah Newren

When a file is renamed and has content conflicts, merge-recursive does not have some stages for the old filename and some stages for the new filename in the index; instead it copies all the stages corresponding to the old filename over to the corresponding locations for the new filename, so that there are three higher order stages all corresponding to the new filename.

Doing things this way makes it easier for the user to access the different versions and to resolve the conflict (no need to manually 'git rm '(man) the old version as well as 'git add'(man) the new one).

rename/deletes should be handled similarly -- there should be two stages for the renamed file rather than just one.
We do not want to destabilize merge-recursive right now, so instead update relevant tests to have different expectations depending on whether the "recursive" or "ort" merge strategies are in use.


With Git 2.30 (Q1 2021), Preparation for a new merge strategy.

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

merge tests: expect improved directory/file conflict handling in ort

Signed-off-by: Elijah Newren

merge-recursive.c is built on the idea of running unpack_trees() and then "doing minor touch-ups" to get the result.
Unfortunately, unpack_trees() was run in an update-as-it-goes mode, leading merge-recursive.c to follow suit and end up with an immediate evaluation and fix-it-up-as-you-go design.

Some things like directory/file conflicts are not well representable in the index data structure, and required special extra code to handle.
But then when it was discovered that rename/delete conflicts could also be involved in directory/file conflicts, the special directory/file conflict handling code had to be copied to the rename/delete codepath.
...and then it had to be copied for modify/delete, and for rename/rename(1to2) conflicts, ...and yet it still missed some.
Further, when it was discovered that there were also file/submodule conflicts and submodule/directory conflicts, we needed to copy the special submodule handling code to all the special cases throughout the codebase.

And then it was discovered that our handling of directory/file conflicts was suboptimal because it would create untracked files to store the contents of the conflicting file, which would not be cleaned up if someone were to run a 'git merge --abort'(man) or 'git rebase --abort'(man).

It was also difficult or scary to try to add or remove the index entries corresponding to these files given the directory/file conflict in the index.
But changing merge-recursive.c to handle these correctly was a royal pain because there were so many sites in the code with similar but not identical code for handling directory/file/submodule conflicts that would all need to be updated.

I have worked hard to push all directory/file/submodule conflict handling in merge-ort through a single codepath, and avoid creating untracked files for storing tracked content (it does record things at alternate paths, but makes sure they have higher-order stages in the index).


With Git 2.31 (Q1 2021), the merge backend "done right" starts to emerge.
Example:

See commit 6d37ca2 (11 Nov 2020) by Junio C Hamano (gitster).
See commit 89422d2, commit ef2b369, commit 70912f6, commit 6681ce5, commit 9fefce6, commit bb470f4, commit ee4012d, commit a9945bb, commit 8adffaa, commit 6a02dd9, commit 291f29c, commit 98bf984, commit 34e557a, commit 885f006, commit d2bc199, commit 0c0d705, commit c801717, commit e4171b1, commit 231e2dd, commit 5b59c3d (13 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit f9d29da, 06 Jan 2021)

merge-ort: add implementation of record_conflicted_index_entries()

Signed-off-by: Elijah Newren

After checkout(), the working tree has the appropriate contents, and the index matches the working copy.
That means that all unmodified and cleanly merged files have correct index entries, but conflicted entries need to be updated.

We do this by looping over the conflicted entries, marking the existing index entry for the path with CE_REMOVE, adding new higher order staged for the path at the end of the index (ignoring normal index sort order), and then at the end of the loop removing the CE_REMOVED-marked cache entries and sorting the index.


With Git 2.31 (Q1 2021), rename detection is added to the "ORT" merge strategy.

See commit 6fcccbd, commit f1665e6, commit 35e47e3, commit 2e91ddd, commit 53e88a0, commit af1e56c (15 Dec 2020), and commit c2d267d, commit 965a7bc, commit f39d05c, commit e1a124e, commit 864075e (14 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 2856089, 25 Jan 2021)

Example:

merge-ort: add implementation of normal rename handling

Signed-off-by: Elijah Newren

Implement handling of normal renames.
This code replaces the following from merge-recurisve.c:

  • the code relevant to RENAME_NORMAL in process_renames()
  • the RENAME_NORMAL case of process_entry()

Also, there is some shared code from merge-recursive.c for multiple different rename cases which we will no longer need for this case (or other rename cases):

  • handle_rename_normal()
  • setup_rename_conflict_info()

The consolidation of four separate codepaths into one is made possible by a change in design: process_renames() tweaks the conflict_info entries within opt->priv->paths such that process_entry() can then handle all the non-rename conflict types (directory/file, modify/delete, etc.) orthogonally.

This means we're much less likely to miss special implementation of some kind of combination of conflict types (see commits brought in by 66c62ea ("Merge branch 'en/merge-tests'", 2020-11-18, Git v2.30.0-rc0 -- merge listed in batch #6), especially commit ef52778 ("merge tests: expect improved directory/file conflict handling in ort", 2020-10-26, Git v2.30.0-rc0 -- merge listed in batch #6) for more details).

That, together with letting worktree/index updating be handled orthogonally in the merge_switch_to_result() function, dramatically simplifies the code for various special rename cases.

(To be fair, the code for handling normal renames wasn't all that complicated beforehand, but it's still much simpler now.)

And, still with Git 2.31 (Q1 2021), With Git 2.31 (Q1 2021), oRT merge strategy learns more support for merge conflicts.

See commit 4ef88fc, commit 4204cd5, commit 70f19c7, commit c73cda7, commit f591c47, commit 62fdec1, commit 991bbdc, commit 5a1a1e8, commit 23366d2, commit 0ccfa4e (01 Jan 2021) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit b65b9ff, 05 Feb 2021)

merge-ort: add handling for different types of files at same path

Signed-off-by: Elijah Newren

Add some handling that explicitly considers collisions of the following types:

  • file/submodule
  • file/symlink
  • submodule/symlink> Leaving them as conflicts at the same path are hard for users to resolve, so move one or both of them aside so that they each get their own path.

Note that in the case of recursive handling (i.e.
call_depth > 0), we can just use the merge base of the two merge bases as the merge result much like we do with modify/delete conflicts, binary files, conflicting submodule values, and so on.

How to increase the distance between table columns in HTML?

If I understand correctly, you want this fiddle.

_x000D_
_x000D_
table {_x000D_
  background: gray;_x000D_
}_x000D_
td {    _x000D_
  display: block;_x000D_
  float: left;_x000D_
  padding: 10px 0;_x000D_
  margin-right:50px;_x000D_
  background: white;_x000D_
}_x000D_
td:last-child {_x000D_
  margin-right: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Hello HTML!</td>_x000D_
    <td>Hello CSS!</td>_x000D_
    <td>Hello JS!</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to add a footer to the UITableView?

Swift 2.1.1 below works:

func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v = UIView()
        v.backgroundColor = UIColor.RGB(53, 60, 62)
        return v
    }

    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 80
    }

If use self.theTable.tableFooterView = tableFooter there is a space between last row and tableFooterView.

How to configure Glassfish Server in Eclipse manually

For Eclipse Mars use the similar approach as harshit.

1) Help -> Install New Software
2) Use url: http://download.oracle.com/otn_software/oepe/mars repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select Glassfish Tools, (Oracle Weblogic Server Tools, Oracle Weblogic Scripting Tools, Oracle patches, Oracle Maven Tools).
4) Install it.
5) Restart eclipse

In point 3) are 4 tools are in braces, I don't know minimal combination, but only install Glassfish Tools has no effect.

During restart Oepe ask for Java 8 JDK if Eclipse run on on older version.

Eclipse 4.5.0 Mars JDK : 1.8

Process.start: how to get the output?

Alright, for anyone who wants both Errors and Outputs read, but gets deadlocks with any of the solutions, provided in other answers (like me), here is a solution that I built after reading MSDN explanation for StandardOutput property.

Answer is based on T30's code:

static void runCommand()
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set ONLY ONE handler here.
    process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHandler);
    //* Start process
    process.Start();
    //* Read one element asynchronously
    process.BeginErrorReadLine();
    //* Read the other one synchronously
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    process.WaitForExit();
}

static void ErrorOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include statement so the preprocessor finds it where it already is.

Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find it while following that search pattern.

Alternatively you can change the #include statement so that the preprocessor can find it. You tell us the xyz.cxx file is is in the 'code' folder but you don't tell us where you've put the xyz.h file. Let's say your file structure looks like this...

<some folder>\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\xyz.h"

On the other hand let's say your file structure looks like this...

<some folder>\include\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\include\xyz.h"

Update: On the other other hand as @In silico points out in the comments, if you are using #include <xyz.h> you should probably change it to #include "xyz.h"

Python SQLite: database is locked

Set the timeout parameter in your connect call, as in:

connection = sqlite.connect('cache.db', timeout=10)

Calculate row means on subset of columns

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
  ID    Means
1  A 3.666667
2  B 4.333333
3  C 3.333333
4  D 4.666667
5  E 4.333333

How to Install pip for python 3.7 on Ubuntu 18?

When i use apt install python3-pip, i get a lot of packages need install, but i donot need them. So, i DO like this:

apt update
apt-get install python3-setuptools
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
rm -f get-pip.py

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

How to create local notifications?

Creating local notifications are pretty easy. Just follow these steps.

  1. On viewDidLoad() function ask user for permission that your apps want to display notifications. For this we can use the following code.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
    })
    
  2. Then you can create a button, and then in the action function you can write the following code to display a notification.

    //creating the notification content
    let content = UNMutableNotificationContent()
    
    //adding title, subtitle, body and badge
    content.title = "Hey this is Simplified iOS"
    content.subtitle = "iOS Development is fun"
    content.body = "We are learning about iOS Local Notification"
    content.badge = 1
    
    //getting the notification trigger
    //it will be called after 5 seconds
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    //getting the notification request
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
    
    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    
  3. Notification will be displayed, just click on home button after tapping the notification button. As when the application is in foreground the notification is not displayed. But if you are using iPhone X. You can display notification even when the app is in foreground. For this you just need to add a delegate called UNUserNotificationCenterDelegate

For more details visit this blog post: iOS Local Notification Tutorial

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

How to modify memory contents using GDB?

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

How to request Administrator access inside a batch file

I used multiple examples to patch this working one liner together.

This will open your batch script as an ADMIN + Maximized Window

Just add one of the following codes to the top of your batch script. Both ways work, just different ways to code it.

I believe the first example responds the quickest due to /d switch disabling my doskey commands that I have enabled..

EXAMPLE ONE

@ECHO OFF
IF NOT "%1"=="MAX" (powershell -WindowStyle Hidden -NoProfile -Command {Start-Process CMD -ArgumentList '/D,/C' -Verb RunAs} & START /MAX CMD /D /C %0 MAX & EXIT /B)
:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

:: Your original batch code here:

:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

EXAMPLE TWO

@ECHO OFF
IF NOT "%1"=="MAX" (powershell -WindowStyle Hidden -NoProfile -Command "Start-Process CMD -ArgumentList '/C' -Verb RunAs" & START /MAX CMD /C "%0" MAX & EXIT /B)
:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

:: Your original batch code here:

:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

See below for recommendations when using your original batch code

Place the original batch code in it's entirety

Just because the first line of code at the very top has @ECHO OFF doesn't mean you should not include it again if your original script has it as well.

This ensures that when the script get's restarted in a new window now running in admin mode that you don't lose your intended script parameters/attributes... Such as the current working directory, your local variables, and so on

You could beginning with the following commands to avoid some of these issues

:: Make sure to use @ECHO OFF if your original code had it
@ECHO OFF
:: Avoid clashing with other active windows variables with SETLOCAL
SETLOCAL
:: Nice color to work with using 0A
COLOR 0A
:: Give your script a name
TITLE NAME IT!

:: Ensure your working directory is set where you want it to be
:: the following code sets the working directory to the script directory folder
PUSHD "%~dp0"

THE REST OF YOUR SCRIPT HERE...

:: Signal the script is finished in the title bar
ECHO.
TITLE Done! NAME IT!
PAUSE
EXIT

Insert text into textarea with jQuery

I know this is an old question but for people searching for this solution it's worth noting that you should not use append() to add content to a textarea. the append() method targets innerHTML not the value of the textarea. The content may appear in the textarea but it will not be added to the element's form value.

As noted above using:

$('#textarea').val($('#textarea').val()+'new content'); 

will work fine.

Spark DataFrame groupBy and sort in the descending order (pyspark)

In PySpark 1.3 sort method doesn't take ascending parameter. You can use desc method instead:

from pyspark.sql.functions import col

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(col("count").desc()))

or desc function:

from pyspark.sql.functions import desc

(group_by_dataframe
    .count()
    .filter("`count` >= 10")
    .sort(desc("count"))

Both methods can be used with with Spark >= 1.3 (including Spark 2.x).

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

Eclipse copy/paste entire line keyboard shortcut

I have to change the assigned key, e.g.

Windows/Preference --> General --> Keys

Select "Duplicate Lines" under command Click on "Binding" Ctrl + Shift + D

Add params to given URL in Python

You want to use URL encoding if the strings can have arbitrary data (for example, characters such as ampersands, slashes, etc. will need to be encoded).

Check out urllib.urlencode:

>>> import urllib
>>> urllib.urlencode({'lang':'en','tag':'python'})
'lang=en&tag=python'

In python3:

from urllib import parse
parse.urlencode({'lang':'en','tag':'python'})

Importing a long list of constants to a Python file

Python doesn't have a preprocessor, nor does it have constants in the sense that they can't be changed - you can always change (nearly, you can emulate constant object properties, but doing this for the sake of constant-ness is rarely done and not considered useful) everything. When defining a constant, we define a name that's upper-case-with-underscores and call it a day - "We're all consenting adults here", no sane man would change a constant. Unless of course he has very good reasons and knows exactly what he's doing, in which case you can't (and propably shouldn't) stop him either way.

But of course you can define a module-level name with a value and use it in another module. This isn't specific to constants or anything, read up on the module system.

# a.py
MY_CONSTANT = ...

# b.py
import a
print a.MY_CONSTANT

Is there a W3C valid way to disable autocomplete in a HTML form?

Not ideal, but you could change the id and name of the textbox each time you render it - you'd have to track it server side too so you could get the data out.

Not sure if this will work or not, was just a thought.

assignment operator overloading in c++

it's right way to use operator overloading now you get your object by reference avoiding value copying.

How to select a column name with a space in MySQL

To each his own but the right way to code this is to rename the columns inserting underscore so there are no gaps. This will ensure zero errors when coding. When printing the column names for public display you could search-and-replace to replace the underscore with a space.

Remove the title bar in Windows Forms

I am sharing my code. form1.cs:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BorderExp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

    }

    private void ExitClick(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void MaxClick(object sender, EventArgs e)
    {
        if (WindowState ==FormWindowState.Normal)
        {
            this.WindowState = FormWindowState.Maximized;
        }
        else
        {
            this.WindowState = FormWindowState.Normal;
        }
    }

    private void MinClick(object sender, EventArgs e)
    {
        this.WindowState = FormWindowState.Minimized;
       }
    }
    }

Now, the designer:-

namespace BorderExp
 {
   partial class Form1
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.button3 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        // 
        // button1
        // 
        this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.button1.BackColor = System.Drawing.SystemColors.ButtonFace;
        this.button1.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.button1.FlatAppearance.BorderSize = 0;
        this.button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
        this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.button1.Location = new System.Drawing.Point(376, 1);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(27, 26);
        this.button1.TabIndex = 0;
        this.button1.Text = "X";
        this.button1.UseVisualStyleBackColor = false;
        this.button1.Click += new System.EventHandler(this.ExitClick);
        // 
        // button2
        // 
        this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.button2.BackColor = System.Drawing.SystemColors.ButtonFace;
        this.button2.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.button2.FlatAppearance.BorderSize = 0;
        this.button2.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
        this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.button2.Location = new System.Drawing.Point(343, 1);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(27, 26);
        this.button2.TabIndex = 1;
        this.button2.Text = "[]";
        this.button2.UseVisualStyleBackColor = false;
        this.button2.Click += new System.EventHandler(this.MaxClick);
        // 
        // button3
        // 
        this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.button3.BackColor = System.Drawing.SystemColors.ButtonFace;
        this.button3.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.button3.FlatAppearance.BorderSize = 0;
        this.button3.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
        this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.button3.Location = new System.Drawing.Point(310, 1);
        this.button3.Name = "button3";
        this.button3.Size = new System.Drawing.Size(27, 26);
        this.button3.TabIndex = 2;
        this.button3.Text = "___";
        this.button3.UseVisualStyleBackColor = false;
        this.button3.Click += new System.EventHandler(this.MinClick);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.ClientSize = new System.Drawing.Size(403, 320);
        this.ControlBox = false;
        this.Controls.Add(this.button3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.button1);
        this.Name = "Form1";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Button button3;
    }
   }

the screenshot:- NoBorderForm

Reading PDF content with itextsharp dll in VB.NET or C#

LGPL / FOSS iTextSharp 4.x

var pdfReader = new PdfReader(path); //other filestream etc
byte[] pageContent = _pdfReader .GetPageContent(pageNum); //not zero based
byte[] utf8 = Encoding.Convert(Encoding.Default, Encoding.UTF8, pageContent);
string textFromPage = Encoding.UTF8.GetString(utf8);

None of the other answers were useful to me, they all seem to target the AGPL v5 of iTextSharp. I could never find any reference to SimpleTextExtractionStrategy or LocationTextExtractionStrategy in the FOSS version.

Something else that might be very useful in conjunction with this:

const string PdfTableFormat = @"\(.*\)Tj";
Regex PdfTableRegex = new Regex(PdfTableFormat, RegexOptions.Compiled);

List<string> ExtractPdfContent(string rawPdfContent)
{
    var matches = PdfTableRegex.Matches(rawPdfContent);

    var list = matches.Cast<Match>()
        .Select(m => m.Value
            .Substring(1) //remove leading (
            .Remove(m.Value.Length - 4) //remove trailing )Tj
            .Replace(@"\)", ")") //unencode parens
            .Replace(@"\(", "(")
            .Trim()
        )
        .ToList();
    return list;
}

This will extract the text-only data from the PDF if the text displayed is Foo(bar) it will be encoded in the PDF as (Foo\(bar\))Tj, this method would return Foo(bar) as expected. This method will strip out lots of additional information such as location coordinates from the raw pdf content.

PowerShell says "execution of scripts is disabled on this system."

In PowerShell 2.0, the execution policy was set to disabled by default.

From then on, the PowerShell team has made a lot of improvements, and they are confident that users will not break things much while running scripts. So from PowerShell 4.0 onward, it is enabled by default.

In your case, type Set-ExecutionPolicy RemoteSigned from the PowerShell console and say yes.

Call to undefined function oci_connect()

try this

in the php.ini file uncomment this

extension_dir = "./" "remove semicolon"

.substring error: "is not a function"

You can use substr

for example:

new Date().getFullYear().toString().substr(-2)

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

Click event doesn't work on dynamically generated elements

Best way to apply event on dynamically generated content by using delegation.

$(document).on("eventname","selector",function(){
    // code goes here
});

so your code is like this now

$(document).on("click",".test",function(){
    // code goes here
});

Css height in percent not working

Make it 100% of the viewport height:

div {
  height: 100vh;
}

Works in all modern browsers and IE>=9, see here for more info.

Converting Python dict to kwargs?

Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

Omitting the first line from any Linux command output

The tail program can do this:

ls -lart | tail -n +2

The -n +2 means “start passing through on the second line of output”.

What are the differences between B trees and B+ trees?

Adegoke A, Amit

I guess one crucial point you people are missing is difference between data and pointers as explained in this section.

Pointer : pointer to other nodes.

Data :- In context of database indexes, data is just another pointer to real data (row) which reside somewhere else.

Hence in case of B tree each node has three information keys, pointers to data associated with the keys and pointer to child nodes.

In B+ tree internal node keep keys and pointers to child node while leaf node keep keys and pointers to associated data. This allows more number of key for a given size of node. Size of node is determined mainly by block size.

Advantage of having more key per node is explained well above so I will save my typing effort.

How do I 'git diff' on a certain directory?

Add Beyond Compare as your difftool in Git and add an alias for diffdir as:

git config --global alias.diffdir = "difftool --dir-diff --tool=bc3 --no-prompt"

Get the gitdiff as:

git diffdir 4bc7ba80edf6  7f566710c7

Reference: Compare entire directories w git difftool + Beyond Compare

How to delete a line from a text file in C#?

To remove an item from a text file, first move all the text to a list and remove whichever item you want. Then write the text stored in the list into a text file:

List<string> quotelist=File.ReadAllLines(filename).ToList();
string firstItem= quotelist[0];
quotelist.RemoveAt(0);
File.WriteAllLines(filename, quotelist.ToArray());
return firstItem;

Linux: where are environment variables stored?

It's stored in the process (shell) and since you've exported it, any processes that process spawns.

Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.

Disable browsers vertical and horizontal scrollbars

Because Firefox has an arrow key short cut, you probably want to put a <div> around it with CSS style: overflow:hidden;.

Batch / Find And Edit Lines in TXT file

This is the kind of stuff sed was made for (of course, you need sed on your system for that).

sed 's/ex3/ex5/g' input.txt > output.txt

You will either need a Unix system or a Windows Cygwin kind of platform for this.
There is also GnuWin32 for sed. (GnuWin32 installation and usage).

Deleting multiple columns based on column names in Pandas

The below worked for me:

for col in df:
    if 'Unnamed' in col:
        #del df[col]
        print col
        try:
            df.drop(col, axis=1, inplace=True)
        except Exception:
            pass

How do I uninstall nodejs installed from pkg (Mac OS X)?

In order to delete the 'native' node.js installation, I have used the method suggested in previous answers sudo npm uninstall npm -g, with additional sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*.

BUT, I had to also delete the following two directories:

sudo rm -rf /usr/local/include/node /Users/$USER/.npm

Only after that I could install node.js with Homebrew.

How to update SQLAlchemy row entry?

Examples to clarify the important issue in accepted answer's comments

I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6 and whose no_of_logins == 30 when you start.

# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

The point

By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?

A caveat

If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:

# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

How do I run a PowerShell script when the computer starts?

I have a script that starts a file system watcher as well, but once the script window is closed the watcher dies. It will run all day if I start it from a powershell window and leave it open, but the minute I close it the script stops doing what it is supposed to.
You need to start the script and have it keep powershell open.
I tried numerous ways to do this, but the one that actually worked was from http://www.methos-it.com/blogs/keep-your-powershell-script-open-when-executed

param ( $Show )
if ( !$Show ) 
{
    PowerShell -NoExit -File $MyInvocation.MyCommand.Path 1
    return
}

Pasting that to the top of the script is what made it work.
I start the script from command line with

powershell.exe -noexit -command "& \path\to\script.ps1"

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

I have used Awesomium.NET. Although I don't like the fact that it's not open-source, and also the fact that it uses a pretty old Webkit rendering engine, it is really easy to use. That's about the only endorsement I can give it.

Checking if a textbox is empty in Javascript

your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

How to compare two double values in Java?

Just use Double.compare() method to compare double values.
Double.compare((d1,d2) == 0)

double d1 = 0.0;
double d2 = 0.0;

System.out.println(Double.compare((d1,d2) == 0))  // true

How do I get the path of a process in Unix / Linux

I use:

ps -ef | grep 786

Replace 786 with your PID or process name.

How to implement "select all" check box in HTML?

<script language="JavaScript">
function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var checkbox in checkboxes)
    checkbox.checked = source.checked;
}
</script>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

UPDATE:

The for each...in construct doesn't seem to work, at least in this case, in Safari 5 or Chrome 5. This code should work in all browsers:

function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}

Taking screenshot on Emulator from Android Studio

Besides using Android Studio, you can also take a screenshot with adb which is faster.

adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png
adb shell rm /sdcard/screen.png

Shorter one line alternative in Unix/OSX

adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > screen.png

Original blog post: Grab Android screenshot to computer via ADB

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

My case, the server was encrypting with padding disabled. But the client was trying to decrypt with the padding enabled.

While using EVP_CIPHER*, by default the padding is enabled. To disable explicitly we need to do

EVP_CIPHER_CTX_set_padding(context, 0);

So non matching padding options can be one reason.

Detect when browser receives file download

If you have download a file, which is saved, as opposed to being in the document, there's no way to determine when the download is complete, since it is not in the scope of the current document, but a separate process in the browser.

Returning first x items from array

A more object oriented way would be to provide a range to the #[] method. For instance:

Say you want the first 3 items from an array.

numbers = [1,2,3,4,5,6]

numbers[0..2] # => [1,2,3]

Say you want the first x items from an array.

numbers[0..x-1]

The great thing about this method is if you ask for more items than the array has, it simply returns the entire array.

numbers[0..100] # => [1,2,3,4,5,6]

Clearing NSUserDefaults

All above answers are very relevant, but if someone still unable to reset the userdefaults for deleted app, then you can reset the content settings of you simulator, and it will work.enter image description here

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

first I had to delete my registry by using npm config delete registry and register new value using npm config set registry "http://registry.npmjs.org"

Get a Windows Forms control by name in C#

One of the best way is a single row of code like this:

In this example we search all PictureBox by name in a form

PictureBox[] picSample = 
                    (PictureBox)this.Controls.Find(PIC_SAMPLE_NAME, true);

Most important is the second paramenter of find.

if you are certain that the control name exists you can directly use it:

  PictureBox picSample = 
                        (PictureBox)this.Controls.Find(PIC_SAMPLE_NAME, true)[0];

Preventing multiple clicks on button

I modified the solution by @Kalyani and so far it's been working beautifully!

$('selector').click(function(event) {
  if(!event.detail || event.detail == 1){ return true; }
  else { return false; }
});

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

Error QApplication: no such file or directory

I suggest you to update your SDK and start new project and recompile everything you have. It seems you have some inner program errors. Or you are missing package.

And ofc do what Abdijeek said.

How to use Visual Studio Code as Default Editor for Git

In the most recent release (v1.0, released in March 2016), you are now able to use VS Code as the default git commit/diff tool. Quoted from the documentations:

  1. Make sure you can run code --help from the command line and you get help.

    • if you do not see help, please follow these steps:

      • Mac: Select Shell Command: Install 'Code' command in path from the Command Palette.

        • Command Palette is what pops up when you press shift + ? + P while inside VS Code. (shift + ctrl + P in Windows)
      • Windows: Make sure you selected Add to PATH during the installation.
      • Linux: Make sure you installed Code via our new .deb or .rpm packages.
  2. From the command line, run git config --global core.editor "code --wait"

Now you can run git config --global -e and use VS Code as editor for configuring Git. enter image description here Add the following to enable support for using VS Code as diff tool:

[diff]
    tool = default-difftool
[difftool "default-difftool"]
    cmd = code --wait --diff $LOCAL $REMOTE

This leverages the new --diff option you can pass to VS Code to compare two files side by side.

To summarize, here are some examples of where you can use Git with VS Code:

  • git rebase HEAD~3 -i allows to interactive rebase using VS Code
  • git commit allows to use VS Code for the commit message
  • git add -p followed by e for interactive add
  • git difftool <commit>^ <commit> allows to use VS Code as diff editor for changes

Why does git say "Pull is not possible because you have unmerged files"?

You are attempting to add one more new commits into your local branch while your working directory is not clean. As a result, Git is refusing to do the pull. Consider the following diagrams to better visualize the scenario:

remote: A <- B <- C <- D
local: A <- B*
(*indicates that you have several files which have been modified but not committed.)

There are two options for dealing with this situation. You can either discard the changes in your files, or retain them.

Option one: Throw away the changes
You can either use git checkout for each unmerged file, or you can use git reset --hard HEAD to reset all files in your branch to HEAD. By the way, HEAD in your local branch is B, without an asterisk. If you choose this option, the diagram becomes:

remote: A <- B <- C <- D
local: A <- B

Now when you pull, you can fast-forward your branch with the changes from master. After pulling, you branch would look like master:

local: A <- B <- C <- D

Option two: Retain the changes
If you want to keep the changes, you will first want to resolve any merge conflicts in each of the files. You can open each file in your IDE and look for the following symbols:

<<<<<<< HEAD
// your version of the code
=======
// the remote's version of the code
>>>>>>>

Git is presenting you with two versions of code. The code contained within the HEAD markers is the version from your current local branch. The other version is what is coming from the remote. Once you have chosen a version of the code (and removed the other code along with the markers), you can add each file to your staging area by typing git add. The final step is to commit your result by typing git commit -m with an appropriate message. At this point, our diagram looks like this:

remote: A <- B <- C <- D
local: A <- B <- C'

Here I have labelled the commit we just made as C' because it is different from the commit C on the remote. Now, if you try to pull you will get a non-fast forward error. Git cannot play the changes in remote on your branch, because both your branch and the remote have diverged from the common ancestor commit B. At this point, if you want to pull you can either do another git merge, or git rebase your branch on the remote.

Getting a mastery of Git requires being able to understand and manipulate uni-directional linked lists. I hope this explanation will get you thinking in the right direction about using Git.

Array to String PHP?

implode():

<?php
$string = implode('|',$types);

However, Incognito is right, you probably don't want to store it that way -- it's a total waste of the relational power of your database.

If you're dead-set on serializing, you might also consider using json_encode()

Bootstrap Carousel : Remove auto slide

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: 40000,
  });
});

By using the above script, you will be able to move the images automaticaly

$(document).ready(function() {
  $('#media').carousel({
    pause: true,
    interval: false,
  });
});

By using the above script, auto-rotation will be blocked because interval is false

'POCO' definition

To add the the other answers, the POxx terms all appear to stem from POTS (Plain old telephone services).

The POX, used to define simple (plain old) XML, rather than the complex multi-layered stuff associated with REST, SOAP etc, was a useful, and vaguely amusing, term. PO(insert language of choice)O terms have rather worn the joke thin.

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop

Auto highlight text in a textbox control

I think the easiest way is using TextBox.SelectAll like in an Enter event:

private void TextBox_Enter(object sender, EventArgs e)
{
    ((TextBox)sender).SelectAll();
}

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

This issue is created due to name="iSetPointId" make "i" capital and corresponding model class changes.

Does "git fetch --tags" include "git fetch"?

The general problem here is that git fetch will fetch +refs/heads/*:refs/remotes/$remote/*. If any of these commits have tags, those tags will also be fetched. However if there are tags not reachable by any branch on the remote, they will not be fetched.

The --tags option switches the refspec to +refs/tags/*:refs/tags/*. You could ask git fetch to grab both. I'm pretty sure to just do a git fetch && git fetch -t you'd use the following command:

git fetch origin "+refs/heads/*:refs/remotes/origin/*" "+refs/tags/*:refs/tags/*"

And if you wanted to make this the default for this repo, you can add a second refspec to the default fetch:

git config --local --add remote.origin.fetch "+refs/tags/*:refs/tags/*"

This will add a second fetch = line in the .git/config for this remote.


I spent a while looking for the way to handle this for a project. This is what I came up with.

git fetch -fup origin "+refs/*:refs/*"

In my case I wanted these features

  • Grab all heads and tags from the remote so use refspec refs/*:refs/*
  • Overwrite local branches and tags with non-fast-forward + before the refspec
  • Overwrite currently checked out branch if needed -u
  • Delete branches and tags not present in remote -p
  • And force to be sure -f

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

Creating Unicode character from its number

Remember that char is an integral type, and thus can be given an integer value, as well as a char constant.

char c = 0x2202;//aka 8706 in decimal. \u codepoints are in hex.
String s = String.valueOf(c);

Python: Find in list

You may want to use one of two possible searches while working with list of strings:

  1. if list element is equal to an item ('example' is in ['one','example','two']):

    if item in your_list: some_function_on_true()

    'ex' in ['one','ex','two'] => True

    'ex_1' in ['one','ex','two'] => False

  2. if list element is like an item ('ex' is in ['one,'example','two'] or 'example_1' is in ['one','example','two']):

    matches = [el for el in your_list if item in el]

    or

    matches = [el for el in your_list if el in item]

    then just check len(matches) or read them if needed.

using stored procedure in entity framework

// Add some tenants to context so we have something for the procedure to return! AddTenentsToContext(Context);

    // ACT
    // Get the results by calling the stored procedure from the context extention method 
    var results = Context.ExecuteStoredProcedure(procedure);

    // ASSERT
    Assert.AreEqual(expectedCount, results.Count);
}

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

This answer assumes you understand implementing the perfect algorithm for P1 and discusses how to achieve a win in conditions against ordinary human players, who will make some mistakes more commonly than others.

The game of course should end in a draw if both players play optimally. At a human level, P1 playing in a corner produces wins far more often. For whatever psychological reason, P2 is baited into thinking that playing in the center is not that important, which is unfortunate for them, since it's the only response that does not create a winning game for P1.

If P2 does correctly block in the center, P1 should play the opposite corner, because again, for whatever psychological reason, P2 will prefer the symmetry of playing a corner, which again produces a losing board for them.

For any move P1 may make for the starting move, there is a move P2 may make that will create a win for P1 if both players play optimally thereafter. In that sense P1 may play wherever. The edge moves are weakest in the sense that the largest fraction of possible responses to this move produce a draw, but there are still responses that will create a win for P1.

Empirically (more precisely, anecdotally) the best P1 starting moves seem to be first corner, second center, and last edge.

The next challenge you can add, in person or via a GUI, is not to display the board. A human can definitely remember all the state but the added challenge leads to a preference for symmetric boards, which take less effort to remember, leading to the mistake I outlined in the first branch.

I'm a lot of fun at parties, I know.

Converting SVG to PNG using C#

I'm using Batik for this. The complete Delphi code:

procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
  StartInfo : TStartupInfo;
  ProcInfo : TProcessInformation;
  CreateOK : Boolean;
begin
  FillChar(StartInfo, SizeOf(TStartupInfo), #0);
  FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
              CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);
  if CreateOK then begin
    //may or may not be needed. Usually wait for child processes
    if Wait then
      WaitForSingleObject(ProcInfo.hProcess, INFINITE);
  end else
    ShowMessage('Unable to run ' + ProgramName);

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
end;

procedure ConvertSVGtoPNG(aFilename: String);
const
  ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
  ExecNewProcess(ExecLine + aFilename, True);
end;

Add table row in jQuery

<table id=myTable>
    <tr><td></td></tr>
    <style="height=0px;" tfoot></tfoot>
</table>

You can cache the footer variable and reduce access to DOM (Note: may be it will be better to use a fake row instead of footer).

var footer = $("#mytable tfoot")
footer.before("<tr><td></td></tr>")

How to disable spring security for particular url

I have a better way:

http
    .authorizeRequests()
    .antMatchers("/api/v1/signup/**").permitAll()
    .anyRequest().authenticated()

Can not connect to local PostgreSQL

Try uninstalling the pg gem (gem uninstall pg) then reinstalling -- if you use bundler, then bundle install, else gem install pg. Also, make sure path picks up the right version: Lion has a version of posgresql (prior versions didn't) and it may be in the path before your locally installed version (e.g. MacPorts, homebrew).

In my case: homebrew install of postgresql, updated postgresql, rails, etc. and then got this error. Uninstalling and reinstalling the pg gem did it for me.

Can my enums have friendly names?

After reading many resources regarding this topic, including StackOverFlow, I find that not all solutions are working properly. Below is our attempt to fix this.

Basically, We take the friendly name of an Enum from a DescriptionAttribute if it exists.
If it does not We use RegEx to determine the words within the Enum name and add spaces.

Next version, we will use another Attribute to flag whether we can/should take the friendly name from a localizable resource file.

Below are the test cases. Please report if you have another test case that do not pass.

public static class EnumHelper
{
    public static string ToDescription(Enum value)
    {
        if (value == null)
        {
            return string.Empty;
        }

        if (!Enum.IsDefined(value.GetType(), value))
        {
            return string.Empty;
        }

        FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
        if (fieldInfo != null)
        {
            DescriptionAttribute[] attributes =
                fieldInfo.GetCustomAttributes(typeof (DescriptionAttribute), false) as DescriptionAttribute[];
            if (attributes != null && attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }

        return StringHelper.ToFriendlyName(value.ToString());
    }
}

public static class StringHelper
{
    public static bool IsNullOrWhiteSpace(string value)
    {
        return value == null || string.IsNullOrEmpty(value.Trim());
    }

    public static string ToFriendlyName(string value)
    {
        if (value == null) return string.Empty;
        if (value.Trim().Length == 0) return string.Empty;

        string result = value;

        result = string.Concat(result.Substring(0, 1).ToUpperInvariant(), result.Substring(1, result.Length - 1));

        const string pattern = @"([A-Z]+(?![a-z])|\d+|[A-Z][a-z]+|(?![A-Z])[a-z]+)+";

        List<string> words = new List<string>();
        Match match = Regex.Match(result, pattern);
        if (match.Success)
        {
            Group group = match.Groups[1];
            foreach (Capture capture in group.Captures)
            {
                words.Add(capture.Value);
            }
        }

        return string.Join(" ", words.ToArray());
    }
}


    [TestMethod]
    public void TestFriendlyName()
    {
        string[][] cases =
            {
                new string[] {null, string.Empty},
                new string[] {string.Empty, string.Empty},
                new string[] {" ", string.Empty}, 
                new string[] {"A", "A"},
                new string[] {"z", "Z"},

                new string[] {"Pascal", "Pascal"},
                new string[] {"camel", "Camel"},

                new string[] {"PascalCase", "Pascal Case"}, 
                new string[] {"ABCPascal", "ABC Pascal"}, 
                new string[] {"PascalABC", "Pascal ABC"}, 
                new string[] {"Pascal123", "Pascal 123"}, 
                new string[] {"Pascal123ABC", "Pascal 123 ABC"}, 
                new string[] {"PascalABC123", "Pascal ABC 123"}, 
                new string[] {"123Pascal", "123 Pascal"}, 
                new string[] {"123ABCPascal", "123 ABC Pascal"}, 
                new string[] {"ABC123Pascal", "ABC 123 Pascal"}, 

                new string[] {"camelCase", "Camel Case"}, 
                new string[] {"camelABC", "Camel ABC"}, 
                new string[] {"camel123", "Camel 123"}, 
            };

        foreach (string[] givens in cases)
        {
            string input = givens[0];
            string expected = givens[1];
            string output = StringHelper.ToFriendlyName(input);

            Assert.AreEqual(expected, output);
        }
    }
}

"Conversion to Dalvik format failed with error 1" on external JAR

None of the answers here helped in my case.

For me the problem was that mvn eclipse:eclipse was generating a classpath entry that was a project reference to an Android library project, however, it was not showing up in the Eclipse build path settings! This meant that the library classes ended up in the dexer twice, once from the hidden project reference, and once from the linked library JAR.

I had to open the .classpath with a text editor and remove the projects element manually. This fixed the issue.

Conversion between UTF-8 ArrayBuffer and String

If you are doing this in browser there are no character encoding libraries built-in, but you can get by with:

function pad(n) {
    return n.length < 2 ? "0" + n : n;
}

var array = new Uint8Array(data);
var str = "";
for( var i = 0, len = array.length; i < len; ++i ) {
    str += ( "%" + pad(array[i].toString(16)))
}

str = decodeURIComponent(str);

Here's a demo that decodes a 3-byte UTF-8 unit: http://jsfiddle.net/Z9pQE/

What's the difference between a Future and a Promise?

Not sure if this can be an answer but as I see what others have said for someone it may look like you need two separate abstractions for both of these concepts so that one of them (Future) is just a read-only view of the other (Promise) ... but actually this is not needed.

For example take a look at how promises are defined in javascript:

https://promisesaplus.com/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

The focus is on the composability using the then method like:

asyncOp1()
.then(function(op1Result){
  // do something
  return asyncOp2();
})
.then(function(op2Result){
  // do something more
  return asyncOp3();
})
.then(function(op3Result){
  // do something even more
  return syncOp4(op3Result);
})
...
.then(function(result){
  console.log(result);
})
.catch(function(error){
  console.log(error);
})

which makes asynchronous computation to look like synchronous:

try {
  op1Result = syncOp1();
  // do something
  op1Result = syncOp2();
  // do something more
  op3Result = syncOp3();
  // do something even more
  syncOp4(op3Result);
  ...
  console.log(result);
} catch(error) {
  console.log(error);
}

which is pretty cool. (Not as cool as async-await but async-await just removes the boilerplate ....then(function(result) {.... from it).

And actually their abstraction is pretty good as the promise constructor

new Promise( function(resolve, reject) { /* do it */ } );

allows you to provide two callbacks which can be used to either complete the Promise successfully or with an error. So that only the code that constructs the Promise can complete it and the code that receives an already constructed Promise object has the read-only view.

With inheritance the above can be achieved if resolve and reject are protected methods.

Instagram API - How can I retrieve the list of people a user is following on Instagram

I've been working on some Instagram extension for chrome last few days and I got this to workout:

First, you need to know that this can work if the user profile is public or you are logged in and you are following that user.

I am not sure why does it work like this, but probably some cookies are set when you log in that are checked on the backend while fetching private profiles.

Now I will share with you an ajax example but you can find other ones that suit you better if you are not using jquery.

Also, you can notice that we have two query_hash values for followers and followings and for other queries different ones.

let config = {
  followers: {
    hash: 'c76146de99bb02f6415203be841dd25a',
    path: 'edge_followed_by'
  },
  followings: {
    hash: 'd04b0a864b4b54837c0d870b0e77e076',
    path: 'edge_follow'
  }
};

The user ID you can get from https://www.instagram.com/user_name/?__a=1 as response.graphql.user.id

After is just response from first part of users that u are getting since the limit is 50 users per request:

let after = response.data.user[list].page_info.end_cursor

let data = {followers: [], followings: []};

function getFollows (user, list = 'followers', after = null) {
  $.get(`https://www.instagram.com/graphql/query/?query_hash=${config[list].hash}&variables=${encodeURIComponent(JSON.stringify({
    "id": user.id,
    "include_reel": true,
    "fetch_mutual": true,
    "first": 50,
    "after": after
  }))}`, function (response) {
    data[list].push(...response.data.user[config[list].path].edges);
    if (response.data.user[config[list].path].page_info.has_next_page) {
      setTimeout(function () {
        getFollows(user, list, response.data.user[config[list].path].page_info.end_cursor);
      }, 1000);
    } else if (list === 'followers') {
      getFollows(user, 'followings');
    } else {
      alert('DONE!');
      console.log(followers);
      console.log(followings);
    }
  });
}

You could probably use this off instagram website but I did not try, you would probably need some headers to match those from instagram page.

And if you need for those headers some additional data you could maybe find that within window._sharedData JSON that comes from backend with csrf token etc.

You can catch this by using:

let $script = JSON.parse(document.body.innerHTML.match(/<script type="text\/javascript">window\._sharedData = (.*)<\/script>/)[1].slice(0, -1));

Thats all from me!

Hope it helps you out!

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

<system.web>
  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>
</system.web>

Print page numbers on pages when printing html

As @page with pagenumbers don't work in browsers for now I was looking for alternatives.
I've found an answer posted by Oliver Kohll.
I'll repost it here so everyone could find it more easily:
For this answer we are not using @page, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the link of an example.
The CSS is:

#content {
    display: table;
}

#pageFooter {
    display: table-footer-group;
}

#pageFooter:after {
    counter-increment: page;
    content: counter(page);
}

And the HTML code is:

<div id="content">
  <div id="pageFooter">Page </div>
  multi-page content here...
</div>

This way you can customize your page number by editing parametrs to #pageFooter. My example:

#pageFooter:after {
    counter-increment: page;
    content:"Page " counter(page);
    left: 0; 
    top: 100%;
    white-space: nowrap; 
    z-index: 20;
    -moz-border-radius: 5px; 
    -moz-box-shadow: 0px 0px 4px #222;  
    background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);  
  }

This trick worked for me fine. Hope it will help you.

How to view the list of compile errors in IntelliJ?

the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.

Is it possible to have placeholders in strings.xml for runtime values?

Was looking for the same and finally found the following very simple solution. Best: it works out of the box.
1. alter your string ressource:

<string name="welcome_messages">Hello, <xliff:g name="name">%s</xliff:g>! You have 
<xliff:g name="count">%d</xliff:g> new messages.</string>

2. use string substitution:

c.getString(R.string.welcome_messages,name,count);

where c is the Context, name is a string variable and count your int variable

You'll need to include

<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">

in your res/strings.xml. Works for me. :)

Is there a timeout for idle PostgreSQL connections?

There is a timeout on broken connections (i.e. due to network errors), which relies on the OS' TCP keepalive feature. By default on Linux, broken TCP connections are closed after ~2 hours (see sysctl net.ipv4.tcp_keepalive_time).

There is also a timeout on abandoned transactions, idle_in_transaction_session_timeout and on locks, lock_timeout. It is recommended to set these in postgresql.conf.

But there is no timeout for a properly established client connection. If a client wants to keep the connection open, then it should be able to do so indefinitely. If a client is leaking connections (like opening more and more connections and never closing), then fix the client. Do not try to abort properly established idle connections on the server side.

Is it possible to get an Excel document's row count without loading the entire document into memory?

This might be extremely convoluted and I might be missing the obvious, but without OpenPyXL filling in the column_dimensions in Iterable Worksheets (see my comment above), the only way I can see of finding the column size without loading everything is to parse the xml directly:

from xml.etree.ElementTree import iterparse
from openpyxl import load_workbook
wb=load_workbook("/path/to/workbook.xlsx", use_iterators=True)
ws=wb.worksheets[0]
xml = ws._xml_source
xml.seek(0)

for _,x in iterparse(xml):

    name= x.tag.split("}")[-1]
    if name=="col":
        print "Column %(max)s: Width: %(width)s"%x.attrib # width = x.attrib["width"]

    if name=="cols":
        print "break before reading the rest of the file"
        break

Uint8Array to string in Javascript

The solution given by Albert works well as long as the provided function is invoked infrequently and is only used for arrays of modest size, otherwise it is egregiously inefficient. Here is an enhanced vanilla JavaScript solution that works for both Node and browsers and has the following advantages:

• Works efficiently for all octet array sizes

• Generates no intermediate throw-away strings

• Supports 4-byte characters on modern JS engines (otherwise "?" is substituted)

var utf8ArrayToStr = (function () {
    var charCache = new Array(128);  // Preallocate the cache for the common single byte chars
    var charFromCodePt = String.fromCodePoint || String.fromCharCode;
    var result = [];

    return function (array) {
        var codePt, byte1;
        var buffLen = array.length;

        result.length = 0;

        for (var i = 0; i < buffLen;) {
            byte1 = array[i++];

            if (byte1 <= 0x7F) {
                codePt = byte1;
            } else if (byte1 <= 0xDF) {
                codePt = ((byte1 & 0x1F) << 6) | (array[i++] & 0x3F);
            } else if (byte1 <= 0xEF) {
                codePt = ((byte1 & 0x0F) << 12) | ((array[i++] & 0x3F) << 6) | (array[i++] & 0x3F);
            } else if (String.fromCodePoint) {
                codePt = ((byte1 & 0x07) << 18) | ((array[i++] & 0x3F) << 12) | ((array[i++] & 0x3F) << 6) | (array[i++] & 0x3F);
            } else {
                codePt = 63;    // Cannot convert four byte code points, so use "?" instead
                i += 3;
            }

            result.push(charCache[codePt] || (charCache[codePt] = charFromCodePt(codePt)));
        }

        return result.join('');
    };
})();

How to start mongodb shell?

Just right click on your terminal icon, and select open a new window. Now you'll have two terminal windows open. In the new window, type, mongo and hit enter. Boom, that'll work like it's supposed to.

Run a Docker image as a container

$ docker images
REPOSITORY                TAG                 IMAGE ID            CREATED            
jamesmedice/marketplace   latest              e78c49b5f380        2 days ago          
jamesmedice/marketplace   v1.0.0              *e78c49b5f380*        2 days ago          


$ docker run -p 6001:8585 *e78c49b5f380*

Set formula to a range of cells

I would update the formula in C1. Then copy the formula from C1 and paste it till C10...

Not sure about a more elegant solution

Range("C1").Formula = "=A1+B1"
Range("C1").Copy
Range("C1:C10").Pastespecial(XlPasteall)

How to delete multiple pandas (python) dataframes from memory to save RAM?

del statement does not delete an instance, it merely deletes a name.

When you do del i, you are deleting just the name i - but the instance is still bound to some other name, so it won't be Garbage-Collected.

If you want to release memory, your dataframes has to be Garbage-Collected, i.e. delete all references to them.

If you created your dateframes dynamically to list, then removing that list will trigger Garbage Collection.

>>> lst = [pd.DataFrame(), pd.DataFrame(), pd.DataFrame()]
>>> del lst     # memory is released

If you created some variables, you have to delete them all.

>>> a, b, c = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
>>> lst = [a, b, c]
>>> del a, b, c # dfs still in list
>>> del lst     # memory release now

How can I make a div stick to the top of the screen once it's been scrolled to?

I used some of the work above to create this tech. I improved it a bit and thought I would share my work. Hope this helps.

jsfiddle Code

function scrollErrorMessageToTop() {
    var flash_error = jQuery('#flash_error');
    var flash_position = flash_error.position();

    function lockErrorMessageToTop() {
        var place_holder = jQuery("#place_holder");
        if (jQuery(this).scrollTop() > flash_position.top && flash_error.attr("position") != "fixed") {
            flash_error.css({
                'position': 'fixed',
                'top': "0px",
                "width": flash_error.width(),
                "z-index": "1"
            });
            place_holder.css("display", "");
        } else {
            flash_error.css('position', '');
            place_holder.css("display", "none");
        }

    }
    if (flash_error.length > 0) {
        lockErrorMessageToTop();

        jQuery("#flash_error").after(jQuery("<div id='place_holder'>"));
        var place_holder = jQuery("#place_holder");
        place_holder.css({
            "height": flash_error.height(),
            "display": "none"
        });
        jQuery(window).scroll(function(e) {
            lockErrorMessageToTop();
        });
    }
}
scrollErrorMessageToTop();?

This is a little bit more dynamic of a way to do the scroll. It does need some work and I will at some point turn this into a pluging but but this is what I came up with after hour of work.

How to add jQuery to an HTML page?

You need this code wrap in tags and put on the end of page. Or create JS file (for example test.js), write this code on it and put on the end of page this tag

Upload Image using POST form data in Python-requests

From wechat api doc:

curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

JSON Stringify changes time of date because of UTC

Got around this issue by using the moment.js library (the non-timezone version).

var newMinDate = moment(datePicker.selectedDates[0]);
var newMaxDate = moment(datePicker.selectedDates[1]);

// Define the data to ask the server for
var dataToGet = {"ArduinoDeviceIdentifier":"Temperatures",
                "StartDate":newMinDate.format('YYYY-MM-DD HH:mm'),
                "EndDate":newMaxDate.format('YYYY-MM-DD HH:mm')
};

alert(JSON.stringify(dataToGet));

I was using the flatpickr.min.js library. The time of the resulting JSON object created matches the local time provided but the date picker.

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:

tcp:name.cloudapp.net,1433

Class file has wrong version 52.0, should be 50.0

Select "File" -> "Project Structure".

Under "Project Settings" select "Project"

From there you can select the "Project SDK".

Log4j output not displayed in Eclipse console

A simple log4j.properties file can look like this:

log4j.rootCategory=debug,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.immediateFlush=true
log4j.appender.console.encoding=UTF-8
log4j.appender.console.threshold=info

log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d [%t] %-5p %c - %m%n

Place it in your class path (target/classes folder). Or you if you have a Maven project, place it under your src/main/resources and Eclipse will copy it to your class path.

Without a configuration file, you should see an Eclipse warning in the console like this:

log4j:WARN No appenders could be found for logger.
log4j:WARN Please initialize the log4j system properly.

iOS 8 UITableView separator inset 0 not working

Adding this snippet, simple elegant in Swift works for me in iOS8 :)

    // tableview single line
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.preservesSuperviewLayoutMargins = false
    cell.layoutMargins = UIEdgeInsetsZero
}

Running two projects at once in Visual Studio

Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.

This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).

Remove multiple whitespaces

I use this code and pattern:

preg_replace('/\\s+/', ' ',$data)

$data = 'This is   a Text 
   and so on         Text text on multiple lines and with        whitespaces';
$data= preg_replace('/\\s+/', ' ',$data);
echo $data;

You may test this on http://writecodeonline.com/php/

Show just the current branch in Git

I'm using

/etc/bash_completion.d/git

It came with Git and provides a prompt with branch name and argument completion.

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.

My example code

$rexpenditure = <<<Expenditure
                  <tr>
                      <td>$row->payment_referencenumber</td>
                      <td>$row->payment_requestdate</td>
                      <td>$row->payment_description</td>
                      <td>$row->payment_fundingsource</td>
                      <td>$row->payment_agencyulo</td>
                      <td>$row->payment_agencyproject</td>
                      <td>$$row->payment_disbustment</td>
                      <td>$row->payment_payeename</td>
                      <td>$row->payment_processpayment</td>
                  </tr>
Expenditure;

It will error if there is a space on PHP 7.0.33.

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

IntelliJ show JavaDocs tooltip on mouse over

In 2020.1 there is in editor javadocs rendering has been added. Screen shots borrowed from intellij documentation.

enter image description here

enter image description here enter image description here

enter image description here

Using underscores in Java variables and method names

Personally, I think a language shouldn't make rules about coding style. It is a matter of preferences, usage, convenience, concept about readability.
Now, a project must set coding rules, for consistency across listings. You might not agree with these rules, but you should stick to them if you want to contribute (or work in a team).

At least, IDEs like Eclispe are agnostic, allowing to set rules like variable prefixes or suffixes, various styles of brace placement and space management, etc. So you can use it to reformat code along your guidelines.

Note: I am among those keeping their old habits from C/C++, coding Java with m_ prefixes for member variables (and s_ for static ones), prefixing booleans with an initial b, using an initial uppercase letter for function names and aligning braces... The horror for Java fundamentalists! ;-)
Funnily, that's the conventions used where I work... probably because the main initial developer comes from MFC world! :-D

Change Project Namespace in Visual Studio

Right click properties, Application tab, then see the assembly name and default namespace

How do MySQL indexes work?

Basically an index is a map of all your keys that is sorted in order. With a list in order, then instead of checking every key, it can do something like this:

1: Go to middle of list - is higher or lower than what I'm looking for?

2: If higher, go to halfway point between middle and bottom, if lower, middle and top

3: Is higher or lower? Jump to middle point again, etc.

Using that logic, you can find an element in a sorted list in about 7 steps, instead of checking every item.

Obviously there are complexities, but that gives you the basic idea.

Use dynamic variable names in JavaScript

eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:

function createVariable(varName,varContent)
{
  var scriptStr = "var "+varName+"= \""+varContent+"\""

  var node_scriptCode = document.createTextNode( scriptStr )
  var node_script = document.createElement("script");
  node_script.type = "text/javascript"
  node_script.appendChild(node_scriptCode);

  var node_head = document.getElementsByTagName("head")[0]
  node_head.appendChild(node_script);
}

createVariable("dynamicVar", "some content")
console.log(dynamicVar)

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

"document.getElementByClass is not a function"

As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.

If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById(), then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.

If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:

var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
    // list[i] is a node with the desired class name
}

and it will return a list of nodes that have that class name.

In Sizzle, it would be this:

var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
    // list[i] is a node with the desired class name
}

In jQuery, it would be this:

$(".myButton").each(function(index, element) {
    // element is a node with the desired class name
});

In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:

$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
    // element is a node that matches the selector
});

Read a file in Node.js

Use path.join(__dirname, '/start.html');

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (!err) {
        console.log('received data: ' + data);
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    } else {
        console.log(err);
    }
});

Getting the name of the currently executing method

Just in case the method which name you want to know is a junit test method, then you can use junit TestName rule: https://stackoverflow.com/a/1426730/3076107

Replacing Spaces with Underscores

As of others have explained how to do it using str_replace, you can also use regex to achieve this.

$name = preg_replace('/\s+/', '_', $name);

Activating Anaconda Environment in VsCode

If you need an independent environment for your project: Install your environment to your project folder using the --prefix option:

conda create --prefix C:\your\workspace\root\awesomeEnv\ python=3

In VSCode launch.json configuration set your "pythonPath" to:

"pythonPath":"${workspaceRoot}/awesomeEnv/python.exe"

Java: Finding the highest value in an array

It's printing out a number every time it finds one that is higher than the current max (which happens to occur three times in your case.) Move the print outside of the for loop and you should be good.

for (int counter = 1; counter < decMax.length; counter++)
{
     if (decMax[counter] > max)
     {
      max = decMax[counter];
     }
}

System.out.println("The highest maximum for the December is: " + max);

Hadoop "Unable to load native-hadoop library for your platform" warning

I'm not using CentOS. Here is what I have in Ubuntu 16.04.2, hadoop-2.7.3, jdk1.8.0_121. Run start-dfs.sh or stop-dfs.sh successfully w/o error:

# JAVA env
#
export JAVA_HOME=/j01/sys/jdk
export JRE_HOME=/j01/sys/jdk/jre

export PATH=${JAVA_HOME}/bin:${JRE_HOME}/bin:${PATH}:.

# HADOOP env
#
export HADOOP_HOME=/j01/srv/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME

export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin

Replace /j01/sys/jdk, /j01/srv/hadoop with your installation path

I also did the following for one time setup on Ubuntu, which eliminates the need to enter passwords for multiple times when running start-dfs.sh:

sudo apt install openssh-server openssh-client
ssh-keygen -t rsa
ssh-copy-id user@localhost

Replace user with your username

HTTP error 403 in Python 3 Web Scraping

You can try in two ways. The detail is in this link.

1) Via pip

pip install --upgrade certifi

2) If it doesn't work, try to run a Cerificates.command that comes bundled with Python 3.* for Mac:(Go to your python installation location and double click the file)

open /Applications/Python\ 3.*/Install\ Certificates.command

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

Docker compose port mapping

If you want to bind to the redis port from your nodejs container you will have to expose that port in the redis container:

version: '2'
services:
  nodejs:
    build:
      context: .
      dockerfile: DockerFile
    ports:
      - "4000:4000"
    links:
      - redis

  redis:
    build:
      context: .
      dockerfile: Dockerfile-redis
    expose:
      - "6379"

The expose tag will let you expose ports without publishing them to the host machine, but they will be exposed to the containers networks.

https://docs.docker.com/compose/compose-file/#expose

The ports tag will be mapping the host port with the container port HOST:CONTAINER

https://docs.docker.com/compose/compose-file/#ports

Efficient way to Handle ResultSet in Java

Here is the code little modified that i got it from google -

 List data_table = new ArrayList<>();
    Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(conn_url, user_id, password);
            Statement stmt = con.createStatement();
            System.out.println("query_string: "+query_string);
            ResultSet rs = stmt.executeQuery(query_string);
            ResultSetMetaData rsmd = rs.getMetaData();


            int row_count = 0;
            while (rs.next()) {
                HashMap<String, String> data_map = new HashMap<>();
                if (row_count == 240001) {
                    break;
                }
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    data_map.put(rsmd.getColumnName(i), rs.getString(i));
                }
                data_table.add(data_map);
                row_count = row_count + 1;
            }
            rs.close();
            stmt.close();
            con.close();

How to make readonly all inputs in some div in Angular2?

All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.

// template
<your-input [readonly]="!childmessage"></your-input>

// component value
childmessage = false;

How to set maximum height for table-cell?

Try something like this:-

 table {
    width: 50%;
    height: 50%;
    border-spacing: 0;
    position:absolute;
}
td {
    border: 1px solid black;
}
#content {
    position:absolute;
    width:100%;
    left:0px;
    top:20px;
    bottom:20px;
    overflow: hidden;
}

How to delete all files and folders in a directory?

System.IO.Directory.Delete(installPath, true);
System.IO.Directory.CreateDirectory(installPath);

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How to fix apt-get: command not found on AWS EC2?

Try replacing apt-get with yum as Amazon Linux based AMI uses the yum command instead of apt-get.

Failure during conversion to COFF: file invalid or corrupt

I am using Visual Studio 2010.

This happened to me when I installed .NET 4.5. Uninstall of .NET 4.5 and install of .NET 4.0 helped me and error messages disappeared.

C# DataTable.Select() - How do I format the filter criteria to include null?

The way to check for null is to check for it:

DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");

You can use and and or in the Select statement.

Sending HTML mail using a shell script

So far I have found two quick ways in cmd linux

  1. Use old school mail

mail -s "$(echo -e "This is Subject\nContent-Type: text/html")" [email protected] < mytest.html

  1. Use mutt

mutt -e "my_hdr Content-Type: text/html" [email protected] -s "subject" < mytest.html

How do I delete an entity from symfony2

DELETE FROM ... WHERE id=...;

protected function templateRemove($id){
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));

            if ($entity != null){
                $em->remove($entity);
                $em->flush();
            }
        }

How to merge many PDF files into a single one?

There are lots of free tools that can do this.

I use PDFTK (a open source cross-platform command-line tool) for things like that.

Fit Image in ImageButton in Android

I want them to cover 75% of the button area.

Use android:padding="20dp" (adjust the padding as needed) to control how much the image takes up on the button.

but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?

Use a android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling.

All of these attributes can be set in code on each ImageButton at runtime. However, it is much easier to set and preview in xml in my opinion.

Also, do not use sp for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp dimensions will be larger than your intended if the user has a "large" text setting. Use dp instead, as it is not scaled by the user's text size preference.

Here's a snippet of what each button should look like:

    <ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:scaleType="fitCenter" />

Sample Button

Laravel - check if Ajax request

public function index()
{
    if(!$this->isLogin())
        return Redirect::to('login');

    if(Request::ajax()) // This is check ajax request
    {
      return $JSON;
    }

    $data = array();
    $data['records'] = $this->table->fetchAll();

    $this->setLayout(compact('data'));
}

Java String array: is there a size of method?

Not really the answer to your question, but if you want to have something like an array that can grow and shrink you should not use an array in java. You are probably best of by using ArrayList or another List implementation.

You can then call size() on it to get it's size.

How to implement a binary search tree in Python?

Here is a compact, object oriented, recursive implementation:

    class BTreeNode(object):
        def __init__(self, data):
            self.data = data
            self.rChild = None
            self.lChild = None

    def __str__(self):
        return (self.lChild.__str__() + '<-' if self.lChild != None else '') + self.data.__str__() + ('->' + self.rChild.__str__() if self.rChild != None else '')

    def insert(self, btreeNode):
        if self.data > btreeNode.data: #insert left
            if self.lChild == None:
                self.lChild = btreeNode
            else:
                self.lChild.insert(btreeNode)
        else: #insert right
            if self.rChild == None:
                self.rChild = btreeNode
            else:
                self.rChild.insert(btreeNode)


def main():
    btreeRoot = BTreeNode(5)
    print 'inserted %s:' %5, btreeRoot

    btreeRoot.insert(BTreeNode(7))
    print 'inserted %s:' %7, btreeRoot

    btreeRoot.insert(BTreeNode(3))
    print 'inserted %s:' %3, btreeRoot

    btreeRoot.insert(BTreeNode(1))
    print 'inserted %s:' %1, btreeRoot

    btreeRoot.insert(BTreeNode(2))
    print 'inserted %s:' %2, btreeRoot

    btreeRoot.insert(BTreeNode(4))
    print 'inserted %s:' %4, btreeRoot

    btreeRoot.insert(BTreeNode(6))
    print 'inserted %s:' %6, btreeRoot

The output of the above main() is:

inserted 5: 5
inserted 7: 5->7
inserted 3: 3<-5->7
inserted 1: 1<-3<-5->7
inserted 2: 1->2<-3<-5->7
inserted 4: 1->2<-3->4<-5->7
inserted 6: 1->2<-3->4<-5->6<-7

Wordpress plugin install: Could not create directory

CentOS7 or Ubuntu 16


1.

WordPress uses ftp to install themes and plugins.
So the ftpd should have been configured to create-directory

vim /etc/pure-ftpd.confg

and if it is no then should be yes

# Are anonymous users allowed to create new directories?
AnonymousCanCreateDirs       yes

lastly

sudo systemctl restart pure-ftpd

2.

Maybe there is an ownership issue with the parent directories. Find the Web Server user name and group name if it is Apache Web Server

apachectl -S

it will print

...
...
User: name="apache" id=997
Group: name="apache" id=1000

on Ubuntu it is

User: name="www-data" id=33 not_used
Group: name="www-data" id=33 not_used

then

sudo chown -R apache:apache directory-name

3.

Sometimes it is because of directories permissions. So try

sudo chmod -R 755 directory-name

in some cases 755 does not work. (It should & I do not no why) so try

sudo chmod -R 777 directory-name

4.

Maybe it is because of php safe mode. So turn it off in the root of your domain

vim php.ini

then add

safe_mode = Off

NOTE:
For not entering FTP username and password each time installing a theme we can configure WordPress to use it directly by adding

define('FS_METHOD','direct');

to the wp-config.php file.

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Entity
@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @Id
    @Column(name="useranswer_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

Does Python have an argc argument?

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

Dynamically creating keys in a JavaScript associative array

All modern browsers support a Map, which is a key/value data structure. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

How can I increment a date by one day in Java?

long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);

This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.

Extract source code from .jar file

You can extract a jar file with the command :

jar xf filename.jar

References : Oracle's JAR documentation

IF...THEN...ELSE using XML

Faced with a similar problem sometime ago, I decided to go for a generalized "switch ... case ... break ... default" type solution together with an arm-style instruction set with conditional execution. A custom interpreter using a nesting stack was used to parse these "programs". This solution completely avoids id's or labels. All my XML language elements or "instructions" support a "condition" attribute which if not present or if it evaluates to true then the element's instruction is executed. If there is an "exit" attribute evaluating to true and the condition is also true, then the following group of elements/instructions at the same nesting level will neither be evaluated nor executed and the execution will continue with the next element/instruction at the parent level. If there is no "exit" or it evaluates to false, then the program will proceed with the next element/instruction. For example you can write this type of program (it will be useful to provide a noop "statement" and a mechanism/instruction to assign values and/or expressions to "variables" will prove very handy):

<ins-1>
    <ins-11 condition="expr-a" exit="true">
        <ins-111 />
        ...
    </ins11>
    <ins-12 condition="expr-b" exit="true" />
    <ins-13 condition="expr-c" />
    <ins-14>
        ...
    </ins14>
</ins-1>
<ins-2>
    ...
</ins-2>

If expr-a is true then the execution sequence will be:

ins-1
ins-11
ins-111
ins-2

if expr-a is false and expr-b is true then it will be:

ins-1
ins-12
ins-2

If both expr-a and expr-b are false then we'll have:

ins-1
ins-13 (only if expr-c evaluates to true)
ins-14
ins-2

PS. I used "exit" instead of "break" because I used "break" to implement "breakpoints". Such programs are very hard to debug without some kind of breakpointing/tracing mechanism.

PS2. Because I had similar date-time conditions as your example along with the other types of conditions, I also implemented two special attributes: "from" and "until", that also had to evaluate to true if present, just like "condition", and which used special fast date-time checking logic.

How to hide Bootstrap modal with javascript?

With the modal open in the browser window, use the browser's console to try

$('#myModal').modal('hide');

If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.

If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?

Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.

How to declare and add items to an array in Python?

You can also do:

array = numpy.append(array, value)

Note that the numpy.append() method returns a new object, so if you want to modify your initial array, you have to write: array = ...

How to pass values arguments to modal.show() function in Bootstrap

Here's how i am calling my modal

<a data-toggle="modal" data-id="190" data-target="#modal-popup">Open</a>

Here's how i am obtaining value in the modal

$('#modal-popup').on('show.bs.modal', function(e) {
    console.log($(e.relatedTarget).data('id')); // 190 will be printed
});

How can I add a background thread to flask?

In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:

https://github.com/viniciuschiele/flask-apscheduler

A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:

from flask import Flask
from flask_apscheduler import APScheduler


class Config(object):
    JOBS = [
        {
            'id': 'job1',
            'func': 'jobs:job1',
            'args': (1, 2),
            'trigger': 'interval',
            'seconds': 10
        }
    ]

    SCHEDULER_API_ENABLED = True


def job1(a, b):
    print(str(a) + ' ' + str(b))

if __name__ == '__main__':
    app = Flask(__name__)
    app.config.from_object(Config())

    scheduler = APScheduler()
    # it is also possible to enable the API directly
    # scheduler.api_enabled = True
    scheduler.init_app(app)
    scheduler.start()

    app.run()

Failed to allocate memory: 8

Referring to Android: failed to allocate memory and its first comment under accepted answer, changing "1024" to "1024MB" helped me. Pathetic, but works.

SQLite Reset Primary Key Field

You can reset by update sequence after deleted rows in your-table

UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';

I want to exception handle 'list index out of range.'

for i in range (1, len(list))
    try:
        print (list[i])

    except ValueError:
        print("Error Value.")
    except indexError:
        print("Erorr index")
    except :
        print('error ')

C# Clear all items in ListView

listView.Items.Clear()
listView.Refresh() 

/e Updating due to lack of explanation. Often times, Clear() isn't suffice in the event of immediate events / methods following. It's best to update the view with Refresh() following a Clear() for an instant reflection of the listView clearing. This, anyhow had solved my related issues.

Difference between `constexpr` and `const`

As @0x499602d2 already pointed out, const only ensures that a value cannot be changed after initialization where as constexpr (introduced in C++11) guarantees the variable is a compile time constant.
Consider the following example(from LearnCpp.com):

cout << "Enter your age: ";
int age;
cin >> age;

const int myAge{age};        // works
constexpr int someAge{age};  // error: age can only be resolved at runtime

refresh both the External data source and pivot tables together within a time schedule

Under the connection properties, uncheck "Enable background refresh". This will make the connection refresh when told to, not in the background as other processes happen.

With background refresh disabled, your VBA procedure will wait for your external data to refresh before moving to the next line of code.

Then you just modify the following code:

ActiveWorkbook.Connections("CONNECTION_NAME").Refresh
Sheets("SHEET_NAME").PivotTables("PIVOT_TABLE_NAME").PivotCache.Refresh

You can also turn off background refresh in VBA:

ActiveWorkbook.Connections("CONNECTION_NAME").ODBCConnection.BackgroundQuery = False

"The page has expired due to inactivity" - Laravel 5.5

I have figured out two solution to avoid these error 1)by adding protected $except = ['/yourroute'] possible disable csrf token inspection from defined root. 2)just comment \App\Http\Middleware\VerifyCsrfToken::class line in protected middleware group in kernel

Understanding the set() function

As +Volatility and yourself pointed out, sets are unordered. If you need the elements to be in order, just call sorted on the set:

>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> sorted(set(y))
[1, 6, 8]

Run function in script from command line (Node JS)

Update 2020 - CLI

As @mix3d pointed out you can just run a command where file.js is your file and someFunction is your function optionally followed by parameters separated with spaces

npx run-func file.js someFunction "just some parameter"

That's it.

file.js called in the example above

const someFunction = (param) => console.log('Welcome, your param is', param)

// exporting is crucial
module.exports = { someFunction }

More detailed description

Run directly from CLI (global)

Install

npm i -g run-func

Usage i.e. run function "init", it must be exported, see the bottom

run-func db.js init

or

Run from package.json script (local)

Install

npm i -S run-func

Setup

"scripts": {
   "init": "run-func db.js init"
}

Usage

npm run init

Params

Any following arguments will be passed as function parameters init(param1, param2)

run-func db.js init param1 param2

Important

the function (in this example init) must be exported in the file containing it

module.exports = { init };

or ES6 export

export { init };

XPath - Difference between node() and text()

For me it was a big difference when I faced this scenario (here my story:)

<?xml version="1.0" encoding="UTF-8"?>
<sentence id="S1.6">When U937 cells were infected with HIV-1, 
        
    <xcope id="X1.6.3">
        <cue ref="X1.6.3" type="negation">no</cue> 
                        
                        induction of NF-KB factor was detected
        
    </xcope>
                    
, whereas high level of progeny virions was produced, 
        
    <xcope id="X1.6.2">
        <cue ref="X1.6.2" type="speculation">suggesting</cue> that this factor was 
        <xcope id="X1.6.1">
            <cue ref="X1.6.1" type="negation">not</cue> required for viral replication
        </xcope>
    </xcope>.

</sentence>

I needed to extract text between tags and aggregate (by concat) the text including in innner tags.

/node() did the job, while /text() made half job

/text() only returned text not included in inner tags, because inner tags are not "text nodes". You may think, "just extract text included in the inner tags in an additional xpath", however, it becomes challenging to sort the text in this original order because you dont know where to place the aggregated text from the inner tags!because you dont know where to place the aggregated text from the inner nodes.

  1. When U937 cells were infected with HIV-1,
  2. no induction of NF-KB factor was detected
  3. , whereas high level of progeny virions was produced,
  4. suggesting that this factor was not required for viral replication
  5. .

Finally, /node() did exactly what I wanted, because it gets the text from inner tags too.

How to install MySQLi on MacOS

For Windows: 3 steps

Step1: Just need to give the ext folder path in php.ini

Here

; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
 extension_dir = "C:\php7\ext"

Step 2: Remove the comment from

extension=php_mysqli.dll

Step 3: restart the Apache server.

how to fire event on file select

You could subscribe for the onchange event on the input field:

<input type="file" id="file" name="file" />

and then:

document.getElementById('file').onchange = function() {
    // fire the upload here
};

Java: Add elements to arraylist with FOR loop where element name has increasing number

Thomas's solution is good enough for this matter.

If you want to use loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So loop is used for operating on an array-like data structure, not just simply to simplify typing task. And you cannot use FOR loop by simply just giving increasing-number-names to the elements.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Refresh a page using JavaScript or HTML

try this working fine

jQuery("body").load(window.location.href);

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

How can I disable mod_security in .htaccess file?

With some web hosts including NameCheap, it's not possible to disable ModSecurity using .htaccess. The only option is to contact tech support and ask them to alter the configuration for you.

Python Regex - How to Get Positions and Values of Matches

note that the span & group are indexed for multi capture groups in a regex

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

PG::ConnectionBad - could not connect to server: Connection refused

I just had this problem and none of the suggested solutions worked for me. After a lot of googling, I did find a solution. This is what worked for me.

First, I had to run this command to start the server and I am guessing set the location of config file.

pg_ctl -D /usr/local/var/postgres start && brew services start postgresql

Then I ran this command to access postgres

psql postgres

And at the postgres prompt then I typed "\du" to list the roles

postgres=# \du

The postgres role was missing so I had to create it with this command

CREATE ROLE POSTGRES WITH SUPERUSER CREATEDB CREATEUSER CREATEROLE REPLICATION BYPASSRLS ;

That solved my problem and I hope this helps someone else.

Visual Studio : short cut Key : Duplicate Line

In visual studio code (WebMatrix):

Copy Lines Down: Shift + Alt + down

Copy Lines Up: Shift + Alt + up

Delete Lines: Ctrl + Shift + k

Generate a dummy-variable

For the usecase as presented in the question, you can also just multiply the logical condition with 1 (or maybe even better, with 1L):

# example data
df1 <- data.frame(yr = 1951:1960)

# create the dummies
df1$is.1957 <- 1L * (df1$yr == 1957)
df1$after.1957 <- 1L * (df1$yr >= 1957)

which gives:

> df1
     yr is.1957 after.1957
1  1951       0          0
2  1952       0          0
3  1953       0          0
4  1954       0          0
5  1955       0          0
6  1956       0          0
7  1957       1          1
8  1958       0          1
9  1959       0          1
10 1960       0          1

For the usecases as presented in for example the answers of @zx8754 and @Sotos, there are still some other options which haven't been covered yet imo.

1) Make your own make_dummies-function

# example data
df2 <- data.frame(id = 1:5, year = c(1991:1994,1992))

# create a function
make_dummies <- function(v, prefix = '') {
  s <- sort(unique(v))
  d <- outer(v, s, function(v, s) 1L * (v == s))
  colnames(d) <- paste0(prefix, s)
  d
}

# bind the dummies to the original dataframe
cbind(df2, make_dummies(df2$year, prefix = 'y'))

which gives:

  id year y1991 y1992 y1993 y1994
1  1 1991     1     0     0     0
2  2 1992     0     1     0     0
3  3 1993     0     0     1     0
4  4 1994     0     0     0     1
5  5 1992     0     1     0     0

2) use the dcast-function from either or

 dcast(df2, id + year ~ year, fun.aggregate = length)

which gives:

  id year 1991 1992 1993 1994
1  1 1991    1    0    0    0
2  2 1992    0    1    0    0
3  3 1993    0    0    1    0
4  4 1994    0    0    0    1
5  5 1992    0    1    0    0

However, this will not work when there are duplicate values in the column for which the dummies have to be created. In the case a specific aggregation function is needed for dcast and the result of of dcast need to be merged back to the original:

# example data
df3 <- data.frame(var = c("B", "C", "A", "B", "C"))

# aggregation function to get dummy values
f <- function(x) as.integer(length(x) > 0)

# reshape to wide with the cumstom aggregation function and merge back to the original
merge(df3, dcast(df3, var ~ var, fun.aggregate = f), by = 'var', all.x = TRUE)

which gives (note that the result is ordered according to the by column):

  var A B C
1   A 1 0 0
2   B 0 1 0
3   B 0 1 0
4   C 0 0 1
5   C 0 0 1

3) use the spread-function from (with mutate from )

library(dplyr)
library(tidyr)

df2 %>% 
  mutate(v = 1, yr = year) %>% 
  spread(yr, v, fill = 0)

which gives:

  id year 1991 1992 1993 1994
1  1 1991    1    0    0    0
2  2 1992    0    1    0    0
3  3 1993    0    0    1    0
4  4 1994    0    0    0    1
5  5 1992    0    1    0    0

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

HTTPS connection Python

import requests
r = requests.get("https://stackoverflow.com") 
data = r.content  # Content of response

print r.status_code  # Status code of response
print data

Unable to generate an explicit migration in entity framework

Just my two cents:

My scenario:

  1. I restored my local database to a working state.
  2. Already had migrations already applied to it.
  3. Whenever I tried adding a new migration i got the error about pending migrations as mentioned my the OP.

Solution:

To get around this i just provided more explicit parameters:

Add-Migration -ConnectionString "Server=localhost\SQLEXPRESS;Database=YourDataBase;Trusted_Connection=True;" -ConnectionProviderName "System.Data.SqlClient" -verbose

I am lead to believe that you can set a setting in your app.config folder to allow you to default this behaviour so you don't have to provide explicit parameters everytime. However I am not sure on how to do this.

H2 in-memory database. Table not found

When opening the h2-console, the JDBC URL must match the one specified in the properties:

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb

spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true

spring.h2.console.enabled=true

enter image description here

Which seems obvious, but I spent hours figuring this out..

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

Best solution that i found is create a new database role i.e.

CREATE ROLE db_executor;

and then grant that role exec permission.

GRANT EXECUTE TO db_executor;

Now when you go to the properties of the user and go to User Mapping and select the database where you have added new role,now new role will be visible in the Database role membership for: section

For more detail read full article

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

#!upstart
description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown

respawn

env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

Testing Private method using mockito

  1. By using reflection, private methods can be called from test classes. In this case,

    //test method will be like this ...

    public class TestA {
    
      @Test
        public void testMethod() {
    
        A a= new A();
        Method privateMethod = A.class.getDeclaredMethod("method1", null);
        privateMethod.setAccessible(true);
        // invoke the private method for test
        privateMethod.invoke(A, null);
    
        }
    }
    
  2. If the private method calls any other private method, then we need to spy the object and stub the another method.The test class will be like ...

    //test method will be like this ...

    public class TestA {
    
      @Test
        public void testMethod() {
    
        A a= new A();
        A spyA = spy(a);
        Method privateMethod = A.class.getDeclaredMethod("method1", null);
        privateMethod.setAccessible(true);
        doReturn("Test").when(spyA, "method2"); // if private method2 is returning string data
        // invoke the private method for test
        privateMethod.invoke(spyA , null);
    
        }
    }
    

**The approach is to combine reflection and spying the object. **method1 and **method2 are private methods and method1 calls method2.

How to set True as default value for BooleanField on Django?

from django.db import models

class Foo(models.Model):
    any_field = models.BooleanField(default=True)

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

I'm using this script by Adam Anderson, updated to support objects in other schemas than dbo.

declare @n char(1)
set @n = char(10)

declare @stmt nvarchar(max)

-- procedures
select @stmt = isnull( @stmt + @n, '' ) +
    'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures


-- check constraints
select @stmt = isnull( @stmt + @n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + ']    drop constraint [' + name + ']'
from sys.check_constraints

-- functions
select @stmt = isnull( @stmt + @n, '' ) +
    'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )

-- views
select @stmt = isnull( @stmt + @n, '' ) +
    'drop view [' + schema_name(schema_id) + '].[' + name + ']'
from sys.views

-- foreign keys
select @stmt = isnull( @stmt + @n, '' ) +
    'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys

-- tables
select @stmt = isnull( @stmt + @n, '' ) +
    'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables

-- user defined types
select @stmt = isnull( @stmt + @n, '' ) +
    'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1


exec sp_executesql @stmt

Source: an Adam Anderson blog post

SQLite with encryption/password protection

Keep in mind, the following is not intended to be a substitute for a proper security solution.

After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.

using System.Data.SQLite;

namespace EncryptDB
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = @"C:\Programming\sqlite3\db.db";
            string passwordString = "password";
            byte[] passwordBytes = GetBytes(passwordString);
            SQLiteConnection.CreateFile(connectionString);
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
            conn.SetPassword(passwordBytes);
            conn.Open();
            SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
            sqlCmd.ExecuteNonQuery();
            sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
            sqlCmd.ExecuteNonQuery();
            conn.Close();
        }
        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            bytes = System.Text.Encoding.Default.GetBytes(str);
            return bytes;
        }
    }
}

Optionally, you can remove conn.SetPassword(passwordBytes);, and replace it with conn.ChangePassword("password"); which needs to be placed after conn.Open(); instead of before. Then you won't need the GetBytes method.

To decrypt, it's just a matter of putting the password in your connection string before the call to open.

        string filename = @"C:\Programming\sqlite3\db.db";
        string passwordString = "password";
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
        conn.Open();

Python error when trying to access list by index - "List indices must be integers, not str"

Were you expecting player to be a dict rather than a list?

>>> player=[1,2,3]
>>> player["score"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> player={'score':1, 'age': 2, "foo":3}
>>> player['score']
1

Print a file's last modified date in Bash

If file name has no spaces:

ls -l <dir> | awk '{print $6, " ", $7, " ", $8, " ", $9 }'

This prints as the following format:

 Dec   21   20:03   a1.out
 Dec   21   20:04   a.cpp

If file names have space (you can use the following command for file names with no spaces too, just it looks complicated/ugly than the former):

 ls -l <dir> | awk '{printf ("%s %s %s ",  $6,  $7, $8); for (i=9;   i<=NF; i++){ printf ("%s ", $i)}; printf ("\n")}'