Programs & Examples On #Svnadmin

svnadmin is the administrative tool for monitoring and repairing your Subversion repository.

Getting realtime output using subprocess

You may use an iterator over each byte in the output of the subprocess. This allows inline update (lines ending with '\r' overwrite previous output line) from the subprocess:

from subprocess import PIPE, Popen

command = ["my_command", "-my_arg"]

# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)


# read each byte of subprocess
while subprocess.poll() is None:
    for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
        c = c.decode('ascii')
        sys.stdout.write(c)
sys.stdout.flush()

if subprocess.returncode != 0:
    raise Exception("The subprocess did not terminate correctly.")

How to vertically center a <span> inside a div?

To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.

Creating a chart in Excel that ignores #N/A or blank cells

This is what I found as I was plotting only 3 cells from each 4 columns lumped together. My chart has a merged cell with the date which is my x axis. The problem: BC26-BE27 are plotting as ZERO on my chart. enter image description here

I click on the filter on the side of the chart and found where it is showing all the columns for which the data points are charted. I unchecked the boxes that do not have values. enter image description here

It worked for me.

What's the difference between interface and @interface in java?

interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example:

@interface MyAnnotation {

    String   value();

    String   name();
    int      age();
    String[] newNames();

}

This example defines an annotation called MyAnnotation which has four elements. Notice the @interface keyword. This signals to the Java compiler that this is a Java annotation definition.

Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.

To use the above annotation, you could use code like this:

@MyAnnotation(
    value="123",
    name="Jakob",
    age=37,
    newNames={"Jenkov", "Peterson"}
)
public class MyClass {


}

Reference - http://tutorials.jenkov.com/java/annotations.html

How to build an android library with Android Studio and gradle?

Here is my solution for mac users I think it work for window also:

First go to your Android Studio toolbar

Build > Make Project (while you guys are online let it to download the files) and then

Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then

Run your app that is done it will launch your emulator and configure it then run it!

That is it!!! Happy Coding guys!!!!!!!

Can I install Python 3.x and 2.x on the same Windows computer?

Easy-peasy ,after installing both the python versions add the paths to the environment variables ;seeenvironment variable settings. Then go to python 2 and python 3 folders and rename them to python2 and python3 respectively as shown here for python2 and here for python3. Now in cmd type python2 or python3 to use your required version see here.

Throw away local commits in Git

Use any number of times, to revert back to the last commit without deleting any files that you have recently created.

git reset --soft HEAD~1

Then use

git reset HEAD <name-of-file/files*>

to unstage, or untrack.

JavaScript to scroll long page to DIV

There is a jQuery plugin for the general case of scrolling to a DOM element, but if performance is an issue (and when is it not?), I would suggest doing it manually. This involves two steps:

  1. Finding the position of the element you are scrolling to.
  2. Scrolling to that position.

quirksmode gives a good explanation of the mechanism behind the former. Here's my preferred solution:

function absoluteOffset(elem) {
    return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);
}

It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses window.scroll. So the rest of the solution is:

function scrollToElement(elem) {
    window.scroll(absoluteOffset(elem));
}

Voila!

How to select top n rows from a datatable/dataview in ASP.NET

I just used Midhat's answer but appended CopyToDataTable() on the end.

The code below is an extension to the answer that I used to quickly enable some paging.

int pageNum = 1;
int pageSize = 25;

DataTable dtPage = dt.Rows.Cast<System.Data.DataRow>().Skip((pageNum - 1) * pageSize).Take(pageSize).CopyToDataTable();

Show Hide div if, if statement is true

A fresh look at this(possibly)
in your php:

else{
      $hidemydiv = "hide";
}

And then later in your html code:

<div class='<?php echo $hidemydiv ?>' > maybe show or hide this</div>

in this way your php remains quite clean

Why does Math.Round(2.5) return 2 instead of 3?

That's called rounding to even (or banker's rounding), which is a valid rounding strategy for minimizing accrued errors in sums (MidpointRounding.ToEven). The theory is that, if you always round a 0.5 number in the same direction, the errors will accrue faster (round-to-even is supposed to minimize that) (a).

Follow these links for the MSDN descriptions of:

  • Math.Floor, which rounds down towards negative infinity.
  • Math.Ceiling, which rounds up towards positive infinity.
  • Math.Truncate, which rounds up or down towards zero.
  • Math.Round, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)" becoming 3).

The following diagram and table may help:

-3        -2        -1         0         1         2         3
 +--|------+---------+----|----+--|------+----|----+-------|-+
    a                     b       c           d            e

                       a=-2.7  b=-0.5  c=0.3  d=1.5  e=2.8
                       ======  ======  =====  =====  =====
Floor                    -3      -1      0      1      2
Ceiling                  -2       0      1      2      3
Truncate                 -2       0      0      1      2
Round(ToEven)            -3       0      0      2      3
Round(AwayFromZero)      -3      -1      0      2      3

Note that Round is a lot more powerful than it seems, simply because it can round to a specific number of decimal places. All the others round to zero decimals always. For example:

n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven);       // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15

With the other functions, you have to use multiply/divide trickery to achieve the same effect:

c = System.Math.Truncate (n * 100) / 100;                    // 3.14
d = System.Math.Ceiling (n * 100) / 100;                     // 3.15

(a) Of course, that theory depends on the fact that your data has an fairly even spread of values across the even halves (0.5, 2.5, 4.5, ...) and odd halves (1.5, 3.5, ...).

If all the "half-values" are evens (for example), the errors will accumulate just as fast as if you always rounded up.

How do I get hour and minutes from NSDate?

If you only need it for presenting as a string the following code is much easier

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];

NSString *startTimeString = [formatter stringFromDate:startTimePicker.date];

Stop node.js program from command line

My use case: on MacOS, run/rerun multiple node servers on different ports from a script

run: "cd $PATH1 && node server1.js & cd $PATH2 && node server2.js & ..."

stop1: "kill -9 $(lsof -nP -i4TCP:$PORT1 | grep LISTEN | awk '{print $2}')"

stop2, stop3...

rerun: "stop1 & stop2 & ... & stopN ; run

for more info about finding a process by a port: Who is listening on a given TCP port on Mac OS X?

How to filter by object property in angularJS

We have Collection as below:


enter image description here

Syntax:

{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}

Example:

{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}

-OR-

Syntax:

ng-bind="(input | filter)"

Example:

ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"

Request Monitoring in Chrome

I know this is an old thread but I thought I would chime in.

Chrome currently has a solution built in.

  1. Use CTRL+SHIFT+I (or navigate to Current Page Control > Developer > Developer Tools. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools.
  2. From within the developer tools click on the Network button. If it isn't already, enable it for the session or always.
  3. Click the "XHR" sub-button.
  4. Initiate an AJAX call.
  5. You will see items begin to show up in the left column under "Resources".
  6. Click the resource and there are 2 tabs showing the headers and return content.

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

Inline JavaScript onclick function

Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:

<a href="#" onClick="(function(e){
    console.log(e);
    alert('Hey i am calling');
    return false;
})(arguments[0]);return false;">click here</a>

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

How to add font-awesome to Angular 2 + CLI project

Accepted answer is outdated.

For angular 9 and Fontawesome 5

  1. Install FontAwesome

    npm install @fortawesome/fontawesome-free --save

  2. Register it on angular.json under styles

    "node_modules/@fortawesome/fontawesome-free/css/all.min.css"

  3. Use it on your application

SHA-256 or MD5 for file integrity

  1. Yes, on most CPUs, SHA-256 is two to three times slower than MD5, though not primarily because of its longer hash. See other answers here and the answers to this Stack Overflow questions.
  2. Here's a backup scenario where MD5 would not be appropriate:
    • Your backup program hashes each file being backed up. It then stores each file's data by its hash, so if you're backing up the same file twice you only end up with one copy of it.
    • An attacker can cause the system to backup files they control.
    • The attacker knows the MD5 hash of a file they want to remove from the backup.
    • The attacker can then use the known weaknesses of MD5 to craft a new file that has the same hash as the file to remove. When that file is backed up, it will replace the file to remove, and that file's backed up data will be lost.
    • This backup system could be strengthened a bit (and made more efficient) by not replacing files whose hash it has previously encountered, but then an attacker could prevent a target file with a known hash from being backed up by preemptively backing up a specially constructed bogus file with the same hash.
    • Obviously most systems, backup and otherwise, do not satisfy the conditions necessary for this attack to be practical, but I just wanted to give an example of a situation where SHA-256 would be preferable to MD5. Whether this would be the case for the system you're creating depends on more than just the characteristics of MD5 and SHA-256.
  3. Yes, cryptographic hashes like the ones generated by MD5 and SHA-256 are a type of checksum.

Happy hashing!

How do I crop an image in Java?

This question has not enough information to answer. A general solution (depending on your GUI framework): add a mouse event handler that will catch clicks and mouse movements. This will give you your (x, y) coordinates. Next use these coordinates to crop your image.

How to display Wordpress search results?

Check whether your template in theme folder contains search.php and searchform.php or not.

Why do I get a warning icon when I add a reference to an MEF plugin project?

Also happens if you explicitly reference a project that was already implicitly referenced.

i.e

  • project a references project b
  • project c references project a (which adds implicit ref. Expand and see)
  • project c references project b

you will see an exclamation mark next to b under project references.

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

How to simulate POST request?

Postman is the best application to test your APIs !

You can import or export your routes and let him remember all your body requests ! :)

EDIT : This comment is 5 yea's old and deprecated :D

Here's the new Postman App : https://www.postman.com/

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

How to find day of week in php in a specific timezone

Another quick way:

date_default_timezone_set($userTimezone);
echo date("l");

Share data between html pages

Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)

I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.

But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.

These two links might help you, it shows the example via Node backend, but you get the point how it works:

Link 1

And, of course, the CORS spec:

Link 2

~Cheers

C programming: Dereferencing pointer to incomplete type error

You haven't defined struct stasher_file by your first definition. What you have defined is an nameless struct type and a variable stasher_file of that type. Since there's no definition for such type as struct stasher_file in your code, the compiler complains about incomplete type.

In order to define struct stasher_file, you should have done it as follows

struct stasher_file {
 char name[32];
 int  size;
 int  start;
 int  popularity;
};

Note where the stasher_file name is placed in the definition.

Multiple Updates in MySQL

All of the following applies to InnoDB.

I feel knowing the speeds of the 3 different methods is important.

There are 3 methods:

  1. INSERT: INSERT with ON DUPLICATE KEY UPDATE
  2. TRANSACTION: Where you do an update for each record within a transaction
  3. CASE: In which you a case/when for each different record within an UPDATE

I just tested this, and the INSERT method was 6.7x faster for me than the TRANSACTION method. I tried on a set of both 3,000 and 30,000 rows.

The TRANSACTION method still has to run each individually query, which takes time, though it batches the results in memory, or something, while executing. The TRANSACTION method is also pretty expensive in both replication and query logs.

Even worse, the CASE method was 41.1x slower than the INSERT method w/ 30,000 records (6.1x slower than TRANSACTION). And 75x slower in MyISAM. INSERT and CASE methods broke even at ~1,000 records. Even at 100 records, the CASE method is BARELY faster.

So in general, I feel the INSERT method is both best and easiest to use. The queries are smaller and easier to read and only take up 1 query of action. This applies to both InnoDB and MyISAM.

Bonus stuff:

The solution for the INSERT non-default-field problem is to temporarily turn off the relevant SQL modes: SET SESSION sql_mode=REPLACE(REPLACE(@@SESSION.sql_mode,"STRICT_TRANS_TABLES",""),"STRICT_ALL_TABLES",""). Make sure to save the sql_mode first if you plan on reverting it.

As for other comments I've seen that say the auto_increment goes up using the INSERT method, this does seem to be the case in InnoDB, but not MyISAM.

Code to run the tests is as follows. It also outputs .SQL files to remove php interpreter overhead

<?php
//Variables
$NumRows=30000;

//These 2 functions need to be filled in
function InitSQL()
{

}
function RunSQLQuery($Q)
{

}

//Run the 3 tests
InitSQL();
for($i=0;$i<3;$i++)
    RunTest($i, $NumRows);

function RunTest($TestNum, $NumRows)
{
    $TheQueries=Array();
    $DoQuery=function($Query) use (&$TheQueries)
    {
        RunSQLQuery($Query);
        $TheQueries[]=$Query;
    };

    $TableName='Test';
    $DoQuery('DROP TABLE IF EXISTS '.$TableName);
    $DoQuery('CREATE TABLE '.$TableName.' (i1 int NOT NULL AUTO_INCREMENT, i2 int NOT NULL, primary key (i1)) ENGINE=InnoDB');
    $DoQuery('INSERT INTO '.$TableName.' (i2) VALUES ('.implode('), (', range(2, $NumRows+1)).')');

    if($TestNum==0)
    {
        $TestName='Transaction';
        $Start=microtime(true);
        $DoQuery('START TRANSACTION');
        for($i=1;$i<=$NumRows;$i++)
            $DoQuery('UPDATE '.$TableName.' SET i2='.(($i+5)*1000).' WHERE i1='.$i);
        $DoQuery('COMMIT');
    }
    
    if($TestNum==1)
    {
        $TestName='Insert';
        $Query=Array();
        for($i=1;$i<=$NumRows;$i++)
            $Query[]=sprintf("(%d,%d)", $i, (($i+5)*1000));
        $Start=microtime(true);
        $DoQuery('INSERT INTO '.$TableName.' VALUES '.implode(', ', $Query).' ON DUPLICATE KEY UPDATE i2=VALUES(i2)');
    }
    
    if($TestNum==2)
    {
        $TestName='Case';
        $Query=Array();
        for($i=1;$i<=$NumRows;$i++)
            $Query[]=sprintf('WHEN %d THEN %d', $i, (($i+5)*1000));
        $Start=microtime(true);
        $DoQuery("UPDATE $TableName SET i2=CASE i1\n".implode("\n", $Query)."\nEND\nWHERE i1 IN (".implode(',', range(1, $NumRows)).')');
    }
    
    print "$TestName: ".(microtime(true)-$Start)."<br>\n";

    file_put_contents("./$TestName.sql", implode(";\n", $TheQueries).';');
}

What is the difference between `throw new Error` and `throw someObject`?

throw "I'm Evil"

throw will terminate the further execution & expose message string on catch the error.

_x000D_
_x000D_
try {
  throw "I'm Evil"
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e); // I'm Evil
}
_x000D_
_x000D_
_x000D_

Console after throw will never be reached cause of termination.


throw new Error("I'm Evil")

throw new Error exposes an error event with two params name & message. It also terminate further execution

_x000D_
_x000D_
try {
  throw new Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}
_x000D_
_x000D_
_x000D_

throw Error("I'm Evil")

And just for completeness, this works also, though is not technically the correct way to do it -

_x000D_
_x000D_
try {
  throw Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}

console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function
_x000D_
_x000D_
_x000D_

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

How can I see the entire HTTP request that's being sent by my Python application?

The verbose configuration option might allow you to see what you want. There is an example in the documentation.

NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.

Python, remove all non-alphabet chars from string

Try:

s = ''.join(filter(str.isalnum, s))

This will take every char from the string, keep only alphanumeric ones and build a string back from them.

CSS: fixed to bottom and centered

revised code by Daniel Kanis:

just change the following lines in CSS

.problem {text-align:center}
.enclose {position:fixed;bottom:0px;width:100%;}

and in html:

<p class="enclose problem">
Your footer text here.
</p>

Node.js/Express.js App Only Works on Port 3000

In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.

How to change legend size with matplotlib.pyplot

you can reduce the legend size setting:

plt.legend(labelspacing=y, handletextpad=x,fontsize)  

labelspacing is the vertical space between each label.

handletextpad is the distance between the actual legend and your label.

And fontsize is self-explanatory

align images side by side in html

Try using this format

<figure>
   <img src="img" alt="The Pulpit Rock" width="304" height="228">
   <figcaption>Fig1. - A view of the pulpit rock in Norway.</figcaption>
</figure>

This will give you a real caption (just add the 2nd and 3rd imgs using Float:left like others suggested)

Reimport a module in python while interactive

Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:

# Python >= 3.5
import importlib
import types


def walk_reload(module: types.ModuleType) -> None:
    if hasattr(module, "__all__"):
        for submodule_name in module.__all__:
            walk_reload(getattr(module, submodule_name))
    importlib.reload(module)


walk_reload(my_module)

The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.

How to import other Python files?

You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type

from root.parent.folder.file import variable, class, whatever

ClassNotFoundException com.mysql.jdbc.Driver

You should download MariaDB connector.
Then:

  1. Expand your project.
  2. Right-click on Libraries.
  3. Select Add Jar/Folder.
  4. Add mariadb-java-client-2.0.2.jar which you just downloaded.

Get a UTC timestamp

You can use Date.UTC method to get the time stamp at the UTC timezone.

Usage:

var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , 
      now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());

Live demo here http://jsfiddle.net/naryad/uU7FH/1/

CardView Corner Radius

There is an example how to achieve it, when the card is at the very bottom of the screen. If someone has this kind of problem just do something like that:

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="-5dp"
    card_view:cardCornerRadius="4dp">

    <SomeView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp">

    </SomeView>

</android.support.v7.widget.CardView>

Card View has a negative bottom margin. The view inside a Card View has the same, but positive bottom margin. This way rounded parts are hidden below the screen, but everything looks exactly the same, because the inner view has a counter margin.

Relative path to absolute path in C#?

This worked for me.

//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat"; 
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);

NSAttributedString add text alignment

Swift 4.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [.font: titleFont,    
    .foregroundColor: UIColor.red, 
    .paragraphStyle: titleParagraphStyle])

Swift 3.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center

let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered", 
    attributes: [NSFontAttributeName:titleFont,    
    NSForegroundColorAttributeName:UIColor.red, 
    NSParagraphStyleAttributeName: titleParagraphStyle])

(original answer below)

Swift 2.0+

let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .Center

let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let title = NSMutableAttributedString(string: "You Are Registered",
    attributes:[NSFontAttributeName:titleFont,   
    NSForegroundColorAttributeName:UIColor.redColor(), 
    NSParagraphStyleAttributeName: titleParagraphStyle])

Are there benefits of passing by pointer over passing by reference in C++?

Passing by pointer

  • Caller has to take the address -> not transparent
  • A 0 value can be provided to mean nothing. This can be used to provide optional arguments.

Pass by reference

  • Caller just passes the object -> transparent. Has to be used for operator overloading, since overloading for pointer types is not possible (pointers are builtin types). So you can't do string s = &str1 + &str2; using pointers.
  • No 0 values possible -> Called function doesn't have to check for them
  • Reference to const also accepts temporaries: void f(const T& t); ... f(T(a, b, c));, pointers cannot be used like that since you cannot take the address of a temporary.
  • Last but not least, references are easier to use -> less chance for bugs.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Which version of SQL Server?

For SQL Server 2005 and later, you can obtain the SQL script used to create the view like this:

select definition
from sys.objects     o
join sys.sql_modules m on m.object_id = o.object_id
where o.object_id = object_id( 'dbo.MyView')
  and o.type      = 'V'

This returns a single row containing the script used to create/alter the view.

Other columns in the table tell about about options in place at the time the view was compiled.

Caveats

  • If the view was last modified with ALTER VIEW, then the script will be an ALTER VIEW statement rather than a CREATE VIEW statement.

  • The script reflects the name as it was created. The only time it gets updated is if you execute ALTER VIEW, or drop and recreate the view with CREATE VIEW. If the view has been renamed (e.g., via sp_rename) or ownership has been transferred to a different schema, the script you get back will reflect the original CREATE/ALTER VIEW statement: it will not reflect the objects current name.

  • Some tools truncate the output. For example, the MS-SQL command line tool sqlcmd.exe truncates the data at 255 chars. You can pass the parameter -y N to get the result with N chars.

How to delete from multiple tables in MySQL?

Use this

DELETE FROM `articles`, `comments` 
USING `articles`,`comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

or

DELETE `articles`, `comments` 
FROM `articles`, `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

I got same issue on Catalina mac. I also installed the R from the source in following diretory. ./Documents/R-4.0.3

Now from the terminal type

 ls -a 

and open

 vim .bash_profile 

type

export LANG="en_US.UTF-8"

save with :wq

then type

source .bash_profile 

and then open

./Documents/R-4.0.3/bin/R 
./Documents/R-4.0.3/bin/Rscript 

I always have to run "source /Users/yourComputerName/.bash_profile" before running R scripts.

Android LinearLayout Gradient Background

My problem was the .xml extension was not added to the filename of the newly created XML file. Adding the .xml extension fixed my problem.

Why is &#65279; appearing in my HTML?

An old stupid trick that works in this case... paste code from your editor to ms notepad, then viceversa, and evil character will disappears ! I take inspiration from wyisyg/msword copypaste problem. Notepad++ utf-8 w/out BOM works as well.

Check if enum exists in Java

I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:

public static MyEnum asMyEnum(String str) {
    for (MyEnum me : MyEnum.values()) {
        if (me.name().equalsIgnoreCase(str))
            return me;
    }
    return null;
}

Edit: As Jon Skeet notes, values() works by cloning a private backing array every time it is called. If performance is critical, you may want to call values() only once, cache the array, and iterate through that.

Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.

How to determine if a String has non-alphanumeric characters?

string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.

How to convert NSData to byte array in iPhone?

You could also just use the bytes where they are, casting them to the type you need.

unsigned char *bytePtr = (unsigned char *)[data bytes];

jQuery scroll to ID from different page

function scroll_down(){
    $.noConflict();
    jQuery(document).ready(function($) {
        $('html, body').animate({
            scrollTop : $("#bottom").offset().top
        }, 1);
    });
    return false;
}

here "bottom" is the div tag id where you want to scroll to. For changing the animation effects, you can change the time from '1' to a different value

What is the "Temporary ASP.NET Files" folder for?

Thats where asp.net puts dynamically compiled assemblies.

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

Ok, I figured it out. I just wrapped it in a try catch and send back null.

    public String test() {
            String cert=null;
            String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN 
                     where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
            try {
                Object o = (String) jdbc.queryForObject(sql, String.class);
                cert = (String) o;
            } catch (EmptyResultDataAccessException e) {
                e.printStackTrace();
            }
            return cert;
    }

How do I modify fields inside the new PostgreSQL JSON datatype?

With Postgresql 9.5 it can be done by following-

UPDATE test
SET data = data - 'a' || '{"a":5}'
WHERE data->>'b' = '2';

OR

UPDATE test
SET data = jsonb_set(data, '{a}', '5'::jsonb);

Somebody asked how to update many fields in jsonb value at once. Suppose we create a table:

CREATE TABLE testjsonb ( id SERIAL PRIMARY KEY, object JSONB );

Then we INSERT a experimental row:

INSERT INTO testjsonb
VALUES (DEFAULT, '{"a":"one", "b":"two", "c":{"c1":"see1","c2":"see2","c3":"see3"}}');

Then we UPDATE the row:

UPDATE testjsonb SET object = object - 'b' || '{"a":1,"d":4}';

Which does the following:

  1. Updates the a field
  2. Removes the b field
  3. Add the d field

Selecting the data:

SELECT jsonb_pretty(object) FROM testjsonb;

Will result in:

      jsonb_pretty
-------------------------
 {                      +
     "a": 1,            +
     "c": {             +
         "c1": "see1",  +
         "c2": "see2",  +
         "c3": "see3",  +
     },                 +
     "d": 4             +
 }
(1 row)

To update field inside, Dont use the concat operator ||. Use jsonb_set instead. Which is not simple:

UPDATE testjsonb SET object =
jsonb_set(jsonb_set(object, '{c,c1}','"seeme"'),'{c,c2}','"seehim"');

Using the concat operator for {c,c1} for example:

UPDATE testjsonb SET object = object || '{"c":{"c1":"seedoctor"}}';

Will remove {c,c2} and {c,c3}.

For more power, seek power at postgresql json functions documentation. One might be interested in the #- operator, jsonb_set function and also jsonb_insert function.

How to use paths in tsconfig.json?

This can be set up on your tsconfig.json file, as it is a TS feature.

You can do like this:

"compilerOptions": {
        "baseUrl": "src", // This must be specified if "paths" is.
         ...
        "paths": {
            "@app/*": ["app/*"],
            "@config/*": ["app/_config/*"],
            "@environment/*": ["environments/*"],
            "@shared/*": ["app/_shared/*"],
            "@helpers/*": ["helpers/*"]
        },
        ...

Have in mind that the path where you want to refer to, it takes your baseUrl as the base of the route you are pointing to and it's mandatory as described on the doc.

The character '@' is not mandatory.

After you set it up on that way, you can easily use it like this:

import { Yo } from '@config/index';

the only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

How to check the maximum number of allowed connections to an Oracle database?

The sessions parameter is derived from the processes parameter and changes accordingly when you change the number of max processes. See the Oracle docs for further info.

To get only the info about the sessions:

    select current_utilization, limit_value 
    from v$resource_limit 
    where resource_name='sessions';
CURRENT_UTILIZATION LIMIT_VALUE
------------------- -----------
                110         792

Try this to show info about both:

    select resource_name, current_utilization, max_utilization, limit_value 
    from v$resource_limit 
    where resource_name in ('sessions', 'processes');
RESOURCE_NAME CURRENT_UTILIZATION MAX_UTILIZATION LIMIT_VALUE
------------- ------------------- --------------- -----------
processes                      96             309         500
sessions                      104             323         792

How to test multiple variables against a value?

It can be done easily as

for value in [var1,var2,var3]:
     li.append("targetValue")

How to find patterns across multiple lines using grep?

awk one-liner:

awk '/abc/,/efg/' [file-with-content]

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

public static void main(String[] args) throws ParseException {
    java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    Date date;
    date = (Date)formatter.parse(fecha.toString());
    System.out.println(date);        

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String formatedDate = cal.get(Calendar.DATE) + "/" + 
            (cal.get(Calendar.MONTH) + 1) + 
            "/" +         cal.get(Calendar.YEAR);
    System.out.println("formatedDate : " + formatedDate);
}

BigDecimal equals() versus compareTo()

I believe that the correct answer would be to make the two numbers (BigDecimals), have the same scale, then we can decide about their equality. For example, are these two numbers equal?

1.00001 and 1.00002

Well, it depends on the scale. On the scale 5 (5 decimal points), no they are not the same. but on smaller decimal precisions (scale 4 and lower) they are considered equal. So I suggest make the scale of the two numbers equal and then compare them.

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

Casting interfaces for deserialization in JSON.NET

Suppose an autofac setting like the following:

public class AutofacContractResolver : DefaultContractResolver
{
    private readonly IContainer _container;

    public AutofacContractResolver(IContainer container)
    {
        _container = container;
    }

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        JsonObjectContract contract = base.CreateObjectContract(objectType);

        // use Autofac to create types that have been registered with it
        if (_container.IsRegistered(objectType))
        {
           contract.DefaultCreator = () => _container.Resolve(objectType);
        }  

        return contract;
    }
}

Then, suppose your class is like this:

public class TaskController
{
    private readonly ITaskRepository _repository;
    private readonly ILogger _logger;

    public TaskController(ITaskRepository repository, ILogger logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public ITaskRepository Repository
    {
        get { return _repository; }
    }

    public ILogger Logger
    {
        get { return _logger; }
    }
}

Therefore, the usage of the resolver in deserialization could be like:

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<TaskRepository>().As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogService(new DateTime(2000, 12, 12))).As<ILogger>();

IContainer container = builder.Build();

AutofacContractResolver contractResolver = new AutofacContractResolver(container);

string json = @"{
      'Logger': {
        'Level':'Debug'
      }
}";

// ITaskRespository and ILogger constructor parameters are injected by Autofac 
TaskController controller = JsonConvert.DeserializeObject<TaskController>(json, new JsonSerializerSettings
{
    ContractResolver = contractResolver
});

Console.WriteLine(controller.Repository.GetType().Name);

You can see more details in http://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm

Fixed header table with horizontal scrollbar and vertical scrollbar on

This has been driving me crazy for literally weeks. I found a solution that will work for me that includes:

  1. Non-fixed column widths - they shrink and grow on window resizing.
  2. Table has a horizontal scroll-bar when needed, but not when it isn't.
  3. Number of columns is irrelevant - it will size to however many columns you need it to.
  4. Not all columns need to be the same width.
  5. Header goes all the way to the end of the right scrollbar.
  6. No javascript!

...but there are a couple of caveats:

  1. The vertical scrollbar is not visible until you scroll all the way to the right. Given that most people have scroll wheels, this was an acceptable sacrifice.

  2. The width of the scrollbar must be known. On my website I set the scrollbar widths (I'm not overly concerned with older, incompatible browsers), so I can then calculate div and table widths that adjust based on the scrollbar.

Instead of posting my code here, I'll post a link to the jsFiddle.

Fixed header table + scroll left/right.

How to determine an interface{} value's "real" type?

I'm going to offer up a way to return a boolean based on passing an argument of a reflection Kinds to a local type receiver (because I couldn't find anything like this).

First, we declare our anonymous type of type reflect.Value:

type AnonymousType reflect.Value

Then we add a builder for our local type AnonymousType which can take in any potential type (as an interface):

func ToAnonymousType(obj interface{}) AnonymousType {
    return AnonymousType(reflect.ValueOf(obj))
}

Then we add a function for our AnonymousType struct which asserts against a reflect.Kind:

func (a AnonymousType) IsA(typeToAssert reflect.Kind) bool {
    return typeToAssert == reflect.Value(a).Kind()
}

This allows us to call the following:

var f float64 = 3.4

anon := ToAnonymousType(f)

if anon.IsA(reflect.String) {
    fmt.Println("Its A String!")
} else if anon.IsA(reflect.Float32) {
    fmt.Println("Its A Float32!")
} else if anon.IsA(reflect.Float64) {
    fmt.Println("Its A Float64!")
} else {
    fmt.Println("Failed")
}

Can see a longer, working version here:https://play.golang.org/p/EIAp0z62B7

XML parsing of a variable string in JavaScript

I've always used the approach below which works in IE and Firefox.

Example XML:

<fruits>
  <fruit name="Apple" colour="Green" />
  <fruit name="Banana" colour="Yellow" />
</fruits>

JavaScript:

function getFruits(xml) {
  var fruits = xml.getElementsByTagName("fruits")[0];
  if (fruits) {
    var fruitsNodes = fruits.childNodes;
    if (fruitsNodes) {
      for (var i = 0; i < fruitsNodes.length; i++) {
        var name = fruitsNodes[i].getAttribute("name");
        var colour = fruitsNodes[i].getAttribute("colour");
        alert("Fruit " + name + " is coloured " + colour);
      }
    }
  }
}

convert string to number node.js

Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

Git credential helper - update password

On my first attempt to Git fetch after my password change, I was told that my username/password combination was invalid. This was correct as git-credential helper had cached my old values.

However, I attempted another git fetch after restarting my terminal/command-prompt and this time the credential helper prompted me to enter in my GitHub username and password.

I suspect the initial failed Git fetch request in combination with restarting my terminal/command-prompt resolved this for me.

I hope this answer helps anybody else in a similar position in the future!

How can the default node version be set using NVM?

This will set the default to be the most current version of node

nvm alias default node

and then you'll need to run

nvm use default

or exit and open a new tab

How to vertically align text inside a flexbox?

Using display: flex you can control the vertical alignment of HTML elements.

_x000D_
_x000D_
.box {_x000D_
  height: 100px;_x000D_
  display: flex;_x000D_
  align-items: center; /* Vertical */_x000D_
  justify-content: center; /* Horizontal */_x000D_
  border:2px solid black;_x000D_
}_x000D_
_x000D_
.box div {_x000D_
  width: 100px;_x000D_
  height: 20px;_x000D_
  border:1px solid;_x000D_
}
_x000D_
<div class="box">_x000D_
  <div>Hello</div>_x000D_
  <p>World</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java 8 Streams FlatMap method example

A very simple example: Split a list of full names to get a list of names, regardless of first or last

 List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");

 fullNames.stream()
            .flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
            .forEach(System.out::println);

This prints out:

Barry
Allen
Bruce
Wayne
Clark
Kent

What is correct media query for IPad Pro?

Too late but may this save you from headache! All of these is because we have to detect the target browser is a mobile!

Is this a mobile then combine it with min/max-(width/height)'s

So Just this seems works:

@media (hover: none) {
    /* ... */
}

If the primary input mechanism system of the device cannot hover over elements with ease or they can but not easily (for example a long touch is performed to emulate the hover) or there is no primary input mechanism at all, we use none! There are many cases that you can read from bellow links.

Described as well Also for browser Support See this from MDN

HTML5 Canvas and Anti-aliasing

I haven't needed to turn on anti-alias because it's on by default but I have needed to turn it off. And if it can be turned off it can also be turned on.

ctx.imageSmoothingEnabled = true;

I usually shut it off when I'm working on my canvas rpg so when I zoom in the images don't look blurry.

Convert datetime object to a String of date only in Python

type-specific formatting can be used as well:

t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)

Output:

'02/23/2012'

Detecting negative numbers

if ( $profitloss < 0 ) {
   echo "negative";
};

Optimal way to DELETE specified rows from Oracle

Store all the to be deleted ID's into a table. Then there are 3 ways. 1) loop through all the ID's in the table, then delete one row at a time for X commit interval. X can be a 100 or 1000. It works on OLTP environment and you can control the locks.

2) Use Oracle Bulk Delete

3) Use correlated delete query.

Single query is usually faster than multiple queries because of less context switching, and possibly less parsing.

Imply bit with constant 1 or 0 in SQL Server

Enjoy this :) Without cast each value individually.

SELECT ...,
  IsCoursedBased = CAST(
      CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
    AS BIT
  )
FROM fc

Does JavaScript guarantee object property order?

From the JSON standard:

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

(emphasis mine).

So, no you can't guarantee the order.

Cast object to T

First check to see if it can be cast.

if (readData is T) {
    return (T)readData;
} 
try {
   return (T)Convert.ChangeType(readData, typeof(T));
} 
catch (InvalidCastException) {
   return default(T);
}

Default keystore file does not exist?

For Mac Users: The debug.keystore file exists in ~/.android directory. Sometimes, due to the relative path, the above mentioned error keeps on popping up.

How to extract the substring between two markers?

You can find first substring with this function in your code (by character index). Also, you can find what is after a substring.

def FindSubString(strText, strSubString, Offset=None):
    try:
        Start = strText.find(strSubString)
        if Start == -1:
            return -1 # Not Found
        else:
            if Offset == None:
                Result = strText[Start+len(strSubString):]
            elif Offset == 0:
                return Start
            else:
                AfterSubString = Start+len(strSubString)
                Result = strText[AfterSubString:AfterSubString + int(Offset)]
            return Result
    except:
        return -1

# Example:

Text = "Thanks for contributing an answer to Stack Overflow!"
subText = "to"

print("Start of first substring in a text:")
start = FindSubString(Text, subText, 0)
print(start); print("")

print("Exact substring in a text:")
print(Text[start:start+len(subText)]); print("")

print("What is after substring \"%s\"?" %(subText))
print(FindSubString(Text, subText))

# Your answer:

Text = "gfgfdAAA1234ZZZuijjk"
subText1 = "AAA"
subText2 = "ZZZ"

AfterText1 = FindSubString(Text, subText1, 0) + len(subText1)
BeforText2 = FindSubString(Text, subText2, 0) 

print("\nYour answer:\n%s" %(Text[AfterText1:BeforText2]))

How to change Named Range Scope

You can download the free Name Manager addin developed by myself and Jan Karel Pieterse from http://www.decisionmodels.com/downloads.htm This enables many name operations that the Excel 2007 Name manager cannot handle, including changing scope of names.

In VBA:

Sub TestName()
Application.Calculation = xlManual
Names("TestName").Delete
Range("Sheet1!$A$1:$B$2").Name = "Sheet1!TestName"
Application.Calculation = xlAutomatic
End Sub

How to Extract Year from DATE in POSTGRESQL

Try

select date_part('year', your_column) from your_table;

or

select extract(year from your_column) from your_table;

How to run vi on docker container?

If you need to change a file just once. You should prefer making the change locally and build a new docker image with this file.

Say in a docker image, you need to change a file named myFile.xml under /path/to/docker/image/. So, you need to do.

  1. Copy myFile.xml in your local filesystem and make necessary changes.
  2. Create a file named 'Dockerfile' with the following content-
FROM docker-repo:tag
ADD myFile.xml /path/to/docker/image/

Then build your own docker image with docker build -t docker-repo:v-x.x.x .

Then use your newly build docker image.

How to do join on multiple criteria, returning all combinations of both criteria

select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)

Preferred way to create a Scala list

To create a list of string, use the following:

val l = List("is", "am", "are", "if")

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

MySQL ODBC 3.51 Driver is that special characters in the password aren't handled.

"Warning – You might have a serious headache with MySQL ODBC 3.51 if the password in your GRANT command contains special characters, such as ! @ # $ % ^ ?. MySQL ODBC 3.51 ODBC Driver does not support these special characters in the password box. The only error message you would receive is “Access denied” (using password: YES)" - from http://www.plaintutorials.com/install-and-create-mysql-odbc-connector-on-windows-7/

Unpacking a list / tuple of pairs into two lists / tuples

list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)

Set cURL to use local virtual hosts

EDIT: While this is currently accepted answer, readers might find this other answer by user John Hart more adapted to their needs. It uses an option which, according to user Ken, was introduced in version 7.21.3 (which was released in December 2010, i.e. after this initial answer).


In your edited question, you're using the URL as the host name, whereas it needs to be the host name only.

Try:

curl -H 'Host: project1.loc' http://127.0.0.1/something

where project1.loc is just the host name and 127.0.0.1 is the target IP address.

(If you're using curl from a library and not on the command line, make sure you don't put http:// in the Host header.)

jquery $(this).id return Undefined

use this actiion

$(document).ready(function () {
var a = this.id;

alert (a);
});

How do I create and store md5 passwords in mysql

Please don't use MD5 for password hashing. Such passwords can be cracked in milliseconds. You're sure to be pwned by cybercriminals.

PHP offers a high-quality and future proof password hashing subsystem based on a reliable random salt and multiple rounds of Rijndael / AES encryption.

When a user first provides a password you can hash it like this:

 $pass = 'whatever the user typed in';
 $hashed_password = password_hash( "secret pass phrase", PASSWORD_DEFAULT );

Then, store $hashed_password in a varchar(255) column in MySQL. Later, when the user wants to log in, you can retrieve the hashed password from MySQL and compare it to the password the user offered to log in.

 $pass = 'whatever the user typed in';
 $hashed_password = 'what you retrieved from MySQL for this user';
 if ( password_verify ( $pass , $hashed_password )) {
    /* future proof the password */
    if ( password_needs_rehash($hashed_password , PASSWORD_DEFAULT)) {
       /* recreate the hash */
       $rehashed_password = password_hash($pass, PASSWORD_DEFAULT );
       /* store the rehashed password in MySQL */
     }
     /* password verified, let the user in */
 }
 else {
     /* password not verified, tell the intruder to get lost */
 }

How does this future-proofing work? Future releases of PHP will adapt to match faster and easier to crack encryption. If it's necessary to rehash passwords to make them harder to crack, the future implementation of the password_needs_rehash() function will detect that.

Don't reinvent the flat tire. Use professionally designed and vetted open source code for security.

Execute a large SQL script (with GO commands)

I had the same problem in java and I solved it with a bit of logic and regex. I believe the same logic can be applied.First I read from the slq file into memory. Then I apply the following logic. It's pretty much what has been said before however I believe that using regex word bound is safer than expecting a new line char.

String pattern = "\\bGO\\b|\\bgo\\b";

String[] splitedSql = sql.split(pattern);
for (String chunk : splitedSql) {
  getJdbcTemplate().update(chunk);
}

This basically splits the sql string into an array of sql strings. The regex is basically to detect full 'go' words either lower case or upper case. Then you execute the different querys sequentially.

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

ASP.NET MVC ActionLink and post method

Here was an answer baked into the default ASP.NET MVC 5 project I believe that accomplishes my styling goals nicely in the UI. Form submit using pure javascript to some containing form.

@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
   <a href="javascript:document.getElementById('logoutForm').submit()">
      <span>Sign out</span>
   </a>
}

The fully shown use case is a logout dropdown in the navigation bar of a web app.

@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
    @Html.AntiForgeryToken()

    <div class="dropdown">
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            <span class="ma-nav-text ma-account-name">@User.Identity.Name</span>
            <i class="material-icons md-36 text-inverse">person</i>
        </button>

        <ul class="dropdown-menu dropdown-menu-right ma-dropdown-tray">
            <li>
                <a href="javascript:document.getElementById('logoutForm').submit()">
                    <i class="material-icons">system_update_alt</i>
                    <span>Sign out</span>
                </a>
            </li>
        </ul>
    </div>
}

How to write a unit test for a Spring Boot Controller endpoint

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

An example test for your controller can be something as simple as

public class DemoApplicationTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception {
        this.mockMvc.perform(get("/")
           .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
           .andExpect(status().isOk())
           .andExpect(content().contentType("application/json"));

    }
}

Retrieving the output of subprocess.call()

For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess object, from which you can easily obtain the output as well as return code.

from subprocess import PIPE, run

command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)

What is the best comment in source code you have ever encountered?

There was some old javascript code, quite well written tho. Then was a comment line

// and there is where the dragon lives

followed by a function 4 people spent a day to understand what it's doing. Finally we realised it's not even used and does nothing.

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.

(The strange thing was that all ssh-* commands were valid, (bash could execute as program) but the openssh package wasn't installed.)

Checkout Jenkins Pipeline Git SCM with credentials?

It solved for me using

checkout scm: ([
                    $class: 'GitSCM',
                    userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
                    branches: [[name: 'refs/tags/${project_tag}']]
            ])

How do I check whether input string contains any spaces?

To check if a string does not contain any whitespaces, you can use

string.matches("^\\S*$")

Example:

"name"        -> true
"  "          -> false
"name xxname" -> false

Stopping python using ctrl+c

  • Forcing the program to close using Alt+F4 (shuts down current program)
  • Spamming the X button on CMD for e.x.
  • Taskmanager (first Windows+R and then "taskmgr") and then end the task.

Those may help.

C++ display stack trace on exception

I recommend http://stacktrace.sourceforge.net/ project. It support Windows, Mac OS and also Linux

Saving lists to txt file

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString() defines the default behavior you're seeing here.

Android Studio does not show layout preview

I also go through same problem and do this simple work just go to res->values->style.xml and change

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 

to

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

onCreateOptionsMenu inside Fragments

I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:

Add setSupportActionBar(toolbar) in my Activity, like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

I hope this answer can be helpful for someone with the same problem.

How to convert string to integer in C#

If you're sure it'll parse correctly, use

int.Parse(string)

If you're not, use

int i;
bool success = int.TryParse(string, out i);

Caution! In the case below, i will equal 0, not 10 after the TryParse.

int i = 10;
bool failure = int.TryParse("asdf", out i);

This is because TryParse uses an out parameter, not a ref parameter.

How to checkout a specific Subversion revision from the command line?

It seems that you can use the repository browser. Click the revision button at top-right and change it to the revision you want. Then right-click your file in the browser and use 'Copy to working copy...' but change the filename it will check out, to avoid a clash.

Could not insert new outlet connection: Could not find any information for the class named

For me it worked when on the right tab > Localization, I checked English check box. Initially only Base was checked. After that I had no more problems. Hope this helps!

Populate nested array in mongoose

That works for me:

 Project.find(query)
  .lean()
  .populate({ path: 'pages' })
  .exec(function(err, docs) {

    var options = {
      path: 'pages.components',
      model: 'Component'
    };

    if (err) return res.json(500);
    Project.populate(docs, options, function (err, projects) {
      res.json(projects);
    });
  });

Documentation: Model.populate

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

How to convert a NumPy array to PIL image applying matplotlib colormap

  • input = numpy_image
  • np.unit8 -> converts to integers
  • convert('RGB') -> converts to RGB
  • Image.fromarray -> returns an image object

    from PIL import Image
    import numpy as np
    
    PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
    
    PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
    

bootstrap responsive table content wrapping

So you can use the following :

td {
  white-space: normal !important; // To consider whitespace.
}

If this doesn't work:

td {
  white-space: normal !important; 
  word-wrap: break-word;  
}
table {
  table-layout: fixed;
}

Transparent background on winforms?

I've tried the solutions above (and also) many other solutions from other posts.

In my case, I did it with the following setup:

public partial class WaitingDialog : Form
{
    public WaitingDialog()
    {
        InitializeComponent();

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;

        // Other stuff
    }

    protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}

As you can see, this is a mix of previously given answers.

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Run: python -c "import ssl; print(ssl.get_default_verify_paths())" to check the current paths which are used to verify the certificate. Add your company's root certificate to one of those.

The path openssl_capath_env points to the environment variable: SSL_CERT_DIR.

If SSL_CERT_DIR doesn't exist, you will need to create it and point it to a valid folder within your filesystem. You can then add your certificate to this folder to use it.

Finding the length of an integer in C

sprintf(s, "%d", n);
length_of_int = strlen(s);

webpack command not working

webpack is not only in your node-modules/webpack/bin/ directory, it's also linked in node_modules/.bin.

You have the npm bin command to get the folder where npm will install executables.

You can use the scripts property of your package.json to use webpack from this directory which will be exported.

"scripts": {
  "scriptName": "webpack --config etc..."
}

For example:

"scripts": {
  "build": "webpack --config webpack.config.js"
}

You can then run it with:

npm run build

Or even with arguments:

npm run build -- <args>

This allow you to have you webpack.config.js in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules folder.

What is the current directory in a batch file?

It is the directory from where you run the command to execute your batch file.

As mentioned in the above answers you can add the below command to your script to verify:

> set current_dir=%cd%
> echo %current_dir%  

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

How can you debug a CORS request with cURL?

Updated answer that covers most cases

curl -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost" --head http://www.example.com/
  1. Replace http://www.example.com/ with URL you want to test.
  2. If response includes Access-Control-Allow-* then your resource supports CORS.

Rationale for alternative answer

I google this question every now and then and the accepted answer is never what I need. First it prints response body which is a lot of text. Adding --head outputs only headers. Second when testing S3 URLs we need to provide additional header -H "Access-Control-Request-Method: GET".

Hope this will save time.

How to convert TimeStamp to Date in Java?

Assuming you have a pre-existing java.util.Date date:

Timestamp timestamp = new Timestamp(long);
date.setTime( l_timestamp.getTime() );

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

Select2 open dropdown on focus

The problem is, that the internal focus event is not transformed to jQuery event, so I've modified the plugin and added the focus event to the EventRelay on line 2063 of Select2 4.0.3:

EventRelay.prototype.bind = function (decorated, container, $container) {
    var self = this;
    var relayEvents = [
      'open', 'opening',
      'close', 'closing',
      'select', 'selecting',
      'unselect', 'unselecting',
      'focus'
    ]};

Then it is enough to open the select2 when the focus occurs:

$('#select2').on('select2:focus', function(evt){
    $(this).select2('open');
});

Works well on Chrome 54, IE 11, FF 49, Opera 40

How can I start an Activity from a non-Activity class?

I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.

Try this: ((Activity) mContext).startActivity(...)

Post an object as data using Jquery Ajax

All arrays passed to php must be object literals. Here's an example from JS/jQuery:

var myarray = {};  //must be declared as an object literal first

myarray[fld1] = val;  // then you can add elements and values
myarray[fld2] = val;
myarray[fld3] = Array();  // array assigned to an element must also be declared as object literal

etc...`

It can now be sent via Ajax in the data: parameter as follows:

data: { new_name: myarray },

php picks this up and reads it as a normal array without any decoding necessary. Here's an example:

$array = $_POST['new_name'];  // myarray became new_name (see above)
$fld1 = array['fld1'];
$fld2 = array['fld2'];
etc...

However, when you return an array to jQuery via Ajax it must first be encoded using json. Here's an example in php:

$return_array = json_encode($return_aray));
print_r($return_array);

And the output from that looks something like this:

{"fname":"James","lname":"Feducia","vip":"true","owner":"false","cell_phone":"(801) 666-0909","email":"[email protected]", "contact_pk":"","travel_agent":""}

{again we see the object literal encoding tags} now this can be read by JS/jQuery as an array without any further action inside JS/JQuery... Here's an example in jquery ajax:

success: function(result) {
console.log(result);
alert( "Return Values: " + result['fname'] + " " + result['lname'] );
}

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Activity class is the basic class. (The original) It supports Fragment management (Since API 11). Is not recommended anymore its pure use because its specializations are far better.

ActionBarActivity was in a moment the replacement to the Activity class because it made easy to handle the ActionBar in an app.

AppCompatActivity is the new way to go because the ActionBar is not encouraged anymore and you should use Toolbar instead (that's currently the ActionBar replacement). AppCompatActivity inherits from FragmentActivity so if you need to handle Fragments you can (via the Fragment Manager). AppCompatActivity is for ANY API, not only 16+ (who said that?). You can use it by adding compile 'com.android.support:appcompat-v7:24:2.0' in your Gradle file. I use it in API 10 and it works perfect.

Suppress output of a function

In case anyone's arriving here looking for a solution applicable to RMarkdown, this will suppress all output:

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({

# Your code goes here
2 * 2
# etc
# etc


})})
```

The code will run, but the output will not be printed to the HTML document

WSDL validator?

You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools

These will check both WSDL validity and Basic Profile 1.1 compliance.

Android YouTube app Play Video Intent

EDIT: The below implementation proved to have problems on at least some HTC devices (they crashed). For that reason I don't use setclassname and stick with the action chooser menu. I strongly discourage using my old implementation.

Following is the old implementation:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(youtubelink));
if(Utility.isAppInstalled("com.google.android.youtube", getActivity())) {
    intent.setClassName("com.google.android.youtube", "com.google.android.youtube.WatchActivity");
}
startActivity(intent);

Where Utility is my own personal utility class with following methode:

public static boolean isAppInstalled(String uri, Context context) {
    PackageManager pm = context.getPackageManager();
    boolean installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        installed = false;
    }
    return installed;
}

First I check if youtube is installed, if it is installed, I tell android which package I prefer to open my intent.

Installed SSL certificate in certificate store, but it's not in IIS certificate list

This happens when the installed certificate does not contain your private key.

In order to check if the certificate contains the private key and how to repair it use this nice tutorial provided by Entrust

Set default syntax to different filetype in Sublime Text 2

Go to a Packages/User, create (or edit) a .sublime-settings file named after the Syntax where you want to add the extensions, Ini.sublime-settings in your case, then write there something like this:

{
    "extensions":["cfg"]
}

And then restart Sublime Text

What tool can decompile a DLL into C++ source code?

I think a C++ DLL is a machine code file. Therefore decompiling will only result in assembler code. If you can read that and create C++ from that you're good to go.

Is there a way to get rid of accents and convert a whole string to regular letters?

I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.

C++ Redefinition Header Files (winsock2.h)

#pragma once is based on the full path of the filename. So what you likely have is there are two identical copies of either MyClass.h or Winsock2.h in different directories.

The remote end hung up unexpectedly while git cloning

For shared bandwidth try to clone when load is less. Otherwise, try with a high speed connection. If still does not work, please use below command,

git config --global http.postBuffer 2048M
git config --global http.maxRequestBuffer 1024M
git config --global core.compression 9

git config --global ssh.postBuffer 2048M
git config --global ssh.maxRequestBuffer 1024M

git config --global pack.windowMemory 256m 
git config --global pack.packSizeLimit 256m

And try to clone again. You might need to change those settings according to your available memory size.

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

Why am I getting a NoClassDefFoundError in Java?

I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.

set classpath=%classpath%;axis.jar

I was able to get it to pick up the proper version by using:

set classpath=axis.jar;%classpath%;

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

"Application tried to present modally an active controller"?

Just remove

[tabBarController presentModalViewController:viewController animated:YES];

and keep

[self dismissModalViewControllerAnimated:YES];

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

Webkit browsers (not sure about FireBug) allow you to copy the HTML of an element easily, so that's one part of the process out of the way.

Running this (in the javascript console) prior to copying the HTML for an element will move all the computed styles for the parent element given, as well as all child elements, into the inline style attribute which will then be available as part of the HTML.

var el = document.querySelector("#someid");
var els = el.getElementsByTagName("*");

for(var i = -1, l = els.length; ++i < l;){

    els[i].setAttribute("style", window.getComputedStyle(els[i]).cssText);

}

It's a total hack and you'll have alot of "junk" css attributes to wade through, but should at least get your started.

Select single item from a list

SingleOrDefault() is what you need

cheers

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

How to show the text on a ImageButton?

you can use a regular Button and the android:drawableTop attribute (or left, right, bottom) instead.

Web Service vs WCF Service

The major difference is time-out, WCF Service has timed-out when there is no response, but web-service does not have this property.

How to convert date in to yyyy-MM-dd Format?

UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..

Joda-Time

The accepted answer by NidhishKrishnan is correct.

For fun, here is the same kind of code in Joda-Time 2.3.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

java.util.Date date = new Date(); // A Date object coming from other code.

// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );

When run…

dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

filter items in a python dictionary where keys contain a specific string

How about a dict comprehension:

filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}

One you see it, it should be self-explanatory, as it reads like English pretty well.

This syntax requires Python 2.7 or greater.

In Python 3, there is only dict.items(), not iteritems() so you would use:

filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}

How to automatically update your docker containers, if base-images are updated

I'm not going into the whole question of whether or not you want unattended updates in production (I think not). I'm just leaving this here for reference in case anybody finds it useful. Update all your docker images to the latest version with the following command in your terminal:

# docker images | awk '(NR>1) && ($2!~/none/) {print $1":"$2}' | xargs -L1 docker pull

How many characters can a Java String have?

Have you considered using BigDecimal instead of String to hold your numbers?

asynchronous vs non-blocking

Blocking: control returns to invoking precess after processing of primitive(sync or async) completes

Non blocking: control returns to process immediately after invocation

What is the correct syntax of ng-include?

For those who are looking for the shortest possible "item renderer" solution from a partial, so a combo of ng-repeat and ng-include:

<div ng-repeat="item in items" ng-include src="'views/partials/item.html'" />

Actually, if you use it like this for one repeater, it will work, but won't for 2 of them! Angular (v1.2.16) will freak out for some reason if you have 2 of these one after another, so it is safer to close the div the pre-xhtml way:

<div ng-repeat="item in items" ng-include src="'views/partials/item.html'"></div>

AngularJS: how to implement a simple file upload with multipart form?

I just wrote a simple directive (from existing one ofcourse) for a simple uploader in AngularJs.

(The exact jQuery uploader plugin is https://github.com/blueimp/jQuery-File-Upload)

A Simple Uploader using AngularJs (with CORS Implementation)

(Though the server side is for PHP, you can simple change it node also)

Get current scroll position of ScrollView in React Native

The above answers tell how to get the position using different API, onScroll, onMomentumScrollEnd etc; If you want to know the page index, you can calculate it using the offset value.

 <ScrollView 
    pagingEnabled={true}
    onMomentumScrollEnd={this._onMomentumScrollEnd}>
    {pages}
 </ScrollView> 

  _onMomentumScrollEnd = ({ nativeEvent }: any) => {
   // the current offset, {x: number, y: number} 
   const position = nativeEvent.contentOffset; 
   // page index 
   const index = Math.round(nativeEvent.contentOffset.x / PAGE_WIDTH);

   if (index !== this.state.currentIndex) {
     // onPageDidChanged
   }
 };

enter image description here

In iOS, the relationship between ScrollView and the visible region is as follow: The picture comes from https://www.objc.io/issues/3-views/scroll-view/

ref: https://www.objc.io/issues/3-views/scroll-view/

how to change language for DataTable

It is indeed

language: {
 url: '//URL_TO_CDN'
}

The problem is not all of the DataTables (As of this writing) are valid JSON. The Traditional Chinese file for instance is one of them.

To get around this I wrote the following code in JavaScript:

  var dataTableLanguages = {
    'es': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json',
    'fr': '//cdn.datatables.net/plug-ins/1.10.21/i18n/French.json',
    'ar': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Arabic.json',
    'zh-TW': {
      "processing": "???...",
      "loadingRecords": "???...",
      "lengthMenu": "?? _MENU_ ???",
      "zeroRecords": "???????",
      "info": "??? _START_ ? _END_ ???,? _TOTAL_ ?",
      "infoEmpty": "??? 0 ? 0 ???,? 0 ?",
      "infoFiltered": "(? _MAX_ ??????)",
      "infoPostFix": "",
      "search": "??:",
      "paginate": {
        "first": "???",
        "previous": "???",
        "next": "???",
        "last": "????"
      },
      "aria": {
        "sortAscending": ": ????",
        "sortDescending": ": ????"
      }
    }
  };
  var language = dataTableLanguages[$('html').attr('lang')];

  var opts = {...};
  
  if (language) {
    if (typeof language === 'string') {
       opts.language = {
         url: language
       };
    } else {
       opts.language = language;
    }
  }

Now use the opts as option object for data table like

$('#list-table').DataTable(opts)

Centering a Twitter Bootstrap button

Wrap in a div styled with "text-center" class.

Are one-line 'if'/'for'-statements good Python style?

I've found that in the majority of cases doing block clauses on one line is a bad idea.

It will, again as a generality, reduce the quality of the form of the code. High quality code form is a key language feature for python.

In some cases python will offer ways todo things on one line that are definitely more pythonic. Things such as what Nick D mentioned with the list comprehension:

newlist = [splitColon.split(a) for a in someList]

although unless you need a reusable list specifically you may want to consider using a generator instead

listgen = (splitColon.split(a) for a in someList)

note the biggest difference between the two is that you can't reiterate over a generator, but it is more efficient to use.

There is also a built in ternary operator in modern versions of python that allow you to do things like

string_to_print = "yes!" if "exam" in "example" else ""
print string_to_print

or

iterator = max_value if iterator > max_value else iterator

Some people may find these more readable and usable than the similar if (condition): block.

When it comes down to it, it's about code style and what's the standard with the team you're working on. That's the most important, but in general, i'd advise against one line blocks as the form of the code in python is so very important.

Date Conversion from String to sql Date in Java giving different output?

You need to use MM as mm stands for minutes.

There are two ways of producing month pattern.

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01

Full coding snippet:

        String startDate="01-Feb-2013"; // Input String
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
        java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
        java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
        System.out.println(sqlStartDate); // Outputs : 2013-02-01

How to change the color of the axis, ticks and labels for a plot in matplotlib

As a quick example (using a slightly cleaner method than the potentially duplicate question):

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()

alt text

Alternatively

[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]

Recursive Fibonacci

My solution is:

#include <iostream>


    int fib(int number);

    void call_fib(void);

    int main()
    {
    call_fib();
    return 0;
    }

    void call_fib(void)
    {
      int input;
      std::cout<<"enter a number\t";
      std::cin>> input;
      if (input <0)
      {
        input=0;
        std::cout<<"that is not a valid input\n"   ;
        call_fib();
     }
     else 
     {
         std::cout<<"the "<<input <<"th fibonacci number is "<<fib(input);
     }

    }





    int fib(int x)
    {
     if (x==0){return 0;}
     else if (x==2 || x==1)
    {
         return 1;   
    }

    else if (x>0)
   {
        return fib(x-1)+fib(x-2);
    }
    else 
     return -1;
    }

it returns fib(0)=0 and error if negitive

PHPDoc type hinting for array of objects?

Netbeans hints:

You get code completion on $users[0]-> and for $this-> for an array of User classes.

/**
 * @var User[]
 */
var $users = array();

You also can see the type of the array in a list of class members when you do completion of $this->...

Set today's date as default date in jQuery UI datepicker

You need to make the call to setDate separately from the initialization call. So to create the datepicker and set the date in one go:

$("#mydate").datepicker().datepicker("setDate", new Date());

Why it is like this I do not know. If anyone did, that would be interesting information.

PHP Date Time Current Time Add Minutes

In addition to Khriz's answer.

If you need to add 5 minutes to the current time in Mysql format you can do:

$cur_time=date("Y-m-d H:i:s");
$duration='+5 minutes';
echo date('Y-m-d H:i:s', strtotime($duration, strtotime($cur_time)));

Do conditional INSERT with SQL?

I dont know about SmallSQL, but this works for MSSQL:

IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
    UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
    INSERT INTO Table1 VALUES (...)

Based on the where-condition, this updates the row if it exists, else it will insert a new one.

I hope that's what you were looking for.

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

How to highlight cell if value duplicate in same column for google spreadsheet?

While zolley's answer is perfectly right for the question, here's a more general solution for any range, plus explanation:

    =COUNTIF($A$1:$C$50, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))) > 1

Please note that in this example I will be using the range A1:C50. The first parameter ($A$1:$C$50) should be replaced with the range on which you would like to highlight duplicates!


to highlight duplicates:

  1. Select the whole range on which the duplicate marking is wanted.
  2. On the menu: Format > Conditional formatting...
  3. Under Apply to range, select the range to which the rule should be applied.
  4. In Format cells if, select Custom formula is on the dropdown.
  5. In the textbox insert the given formula, adjusting the range to match step (3).

Why does it work?

COUNTIF(range, criterion), will compare every cell in range to the criterion, which is processed similarly to formulas. If no special operators are provided, it will compare every cell in the range with the given cell, and return the number of cells found to be matching the rule (in this case, the comparison). We are using a fixed range (with $ signs) so that we always view the full range.

The second block, INDIRECT(ADDRESS(ROW(), COLUMN(), 4)), will return current cell's content. If this was placed inside the cell, docs will have cried about circular dependency, but in this case, the formula is evaluated as if it was in the cell, without changing it.

ROW() and COLUMN() will return the row number and column number of the given cell respectively. If no parameter is provided, the current cell will be returned (this is 1-based, for example, B3 will return 3 for ROW(), and 2 for COLUMN()).

Then we use: ADDRESS(row, column, [absolute_relative_mode]) to translate the numeric row and column to a cell reference (like B3. Remember, while we are inside the cell's context, we don't know it's address OR content, and we need the content in order to compare with). The third parameter takes care for the formatting, and 4 returns the formatting INDIRECT() likes.

INDIRECT(), will take a cell reference and return its content. In this case, the current cell's content. Then back to the start, COUNTIF() will test every cell in the range against ours, and return the count.

The last step is making our formula return a boolean, by making it a logical expression: COUNTIF(...) > 1. The > 1 is used because we know there's at least one cell identical to ours. That's our cell, which is in the range, and thus will be compared to itself. So to indicate a duplicate, we need to find 2 or more cells matching ours.


Sources:

How do I add 1 day to an NSDate?

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSLog(@"StartDate = %@", startDate);

components.day += 1;
NSDate *endDate = [calendar dateFromComponents:components];
NSLog(@"EndDate = %@", endDate);

Sum values in a column based on date

If the second row has the same pattern as the first row, you just need edit first row manually, then you position your mouse pointer to the bottom-right corner, in the mean time, press ctrl key to drag the cell down. the pattern should be copied automatically.

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

How to get previous page url using jquery

Use can use one of below this

history.back();     // equivalent to clicking back button
history.go(-1);     // equivalent to history.back();

I am using as below for back button

<a class="btn btn-info float-right" onclick="history.back();" >Back</a>

Uploading Laravel Project onto Web Server

I believe - your Laravel files/folders should not be placed in root directory.

e.g. If your domain is pointed to public_html directory then all content should placed in that directory. How ? let me tell you

  1. Copy all files and folders ( including public folder ) in public html
  2. Copy all content of public folder and paste it in document root ( i.e. public_html )
  3. Remove the public folder
  4. Open your bootstrap/paths.php and then changed 'public' => __DIR__.'/../public', into 'public' => __DIR__.'/..',

  5. and finally in index.php,

    Change

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/start.php';

into

require __DIR__.'/bootstrap/autoload.php';

$app = require_once __DIR__.'/bootstrap/start.php';

Your Laravel application should work now.

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

How can I check if my Element ID has focus?

Compare document.activeElement with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn't.

// dummy element
var dummyEl = document.getElementById('myID');

// check for focus
var isFocused = (document.activeElement === dummyEl);

hasFocus is part of the document; there's no such method for DOM elements.

Also, document.getElementById doesn't use a # at the beginning of myID. Change this:

var dummyEl = document.getElementById('#myID');

to this:

var dummyEl = document.getElementById('myID');

If you'd like to use a CSS query instead you can use querySelector (and querySelectorAll).

How can I get current date in Android?

try this,

SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);

How can I force users to access my page over HTTPS instead of HTTP?

Using this is NOT enough:

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

If you have any http content (like an external http image source), the browser will detect a possible threat. So be sure all your ref and src inside your code are https

SQL Server: use CASE with LIKE

One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.

You should create another table and store one value per row.

This will make your querying easier, and your database structure better.

select 
    case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end
from yourtable

Getting attributes of a class

I don't know if something similar has been made by now or not, but I made a nice attribute search function using vars(). vars() creates a dictionary of the attributes of a class you pass through it.

class Player():
    def __init__(self):
        self.name = 'Bob'
        self.age = 36
        self.gender = 'Male'

s = vars(Player())
#From this point if you want to print all the attributes, just do print(s)

#If the class has a lot of attributes and you want to be able to pick 1 to see
#run this function
def play():
    ask = input("What Attribute?>: ")
    for key, value in s.items():
        if key == ask:
            print("self.{} = {}".format(key, value))
            break
    else:
        print("Couldn't find an attribute for self.{}".format(ask))

I'm developing a pretty massive Text Adventure in Python, my Player class so far has over 100 attributes. I use this to search for specific attributes I need to see.

Exec : display stdout "live"

I have found it helpful to add a custom exec script to my utilities that do this.

utilities.js

const { exec } = require('child_process')

module.exports.exec = (command) => {
  const process = exec(command)

  process.stdout.on('data', (data) => {
    console.log('stdout: ' + data.toString())
  })

  process.stderr.on('data', (data) => {
    console.log('stderr: ' + data.toString())
  })

  process.on('exit', (code) => {
    console.log('child process exited with code ' + code.toString())
  })
}

app.js

const { exec } = require('./utilities.js')

exec('coffee -cw my_file.coffee')

How do I remove accents from characters in a PHP string?

I just created a removeAccents method based on the reading of this thread and this other one too (How to remove accents and turn letters into "plain" ASCII characters?).

The method is here: https://github.com/lingtalfi/Bat/blob/master/StringTool.md#removeaccents

Tests are here: https://github.com/lingtalfi/Bat/blob/master/btests/StringTool/removeAccents/stringTool.removeAccents.test.php,

and here is what was tested so far:

$a = [
    // easy
    '',
    'a',
    'après',
    'dédé fait la fête ?',
    // hard
    'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',
    'ZZCNASLEÓzzcnasleó',
    'qqqqZZCNASLEÓzzcnasleóqqq',
    'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöøùúûüýÿ',       
    'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ',
    'AaAaAaCcCcCcCcDdÐdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIJjKk',
    'LlLlLl??LlNnNnNn?OoOoOoRrRrRrSsSsSsŠšTtTtTtUuUuUuUuUuUuWwYyŸZzZzŽž',
    '?ƒOoUuAaIiOoUuUuUuUuUu????',
    '??',
];

and it converts only accentuated things (letters/ligatures/cédilles/some letters with a line through/...?).

Here is the content of the method: (https://github.com/lingtalfi/Bat/blob/master/StringTool.php#L83)

public static function removeAccents($str)
{
    static $map = [
        // single letters
        'à' => 'a',
        'á' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'ä' => 'a',
        'a' => 'a',
        'å' => 'a',
        'a' => 'a',
        'a' => 'a',
        'a' => 'a',
        '?' => 'a',
        'À' => 'A',
        'Á' => 'A',
        'Â' => 'A',
        'Ã' => 'A',
        'Ä' => 'A',
        'A' => 'A',
        'Å' => 'A',
        'A' => 'A',
        'A' => 'A',
        'A' => 'A',
        '?' => 'A',


        'ç' => 'c',
        'c' => 'c',
        'c' => 'c',
        'c' => 'c',
        'c' => 'c',
        'Ç' => 'C',
        'C' => 'C',
        'C' => 'C',
        'C' => 'C',
        'C' => 'C',

        'd' => 'd',
        'd' => 'd',
        'Ð' => 'D',
        'D' => 'D',
        'Ð' => 'D',


        'è' => 'e',
        'é' => 'e',
        'ê' => 'e',
        'ë' => 'e',
        'e' => 'e',
        'e' => 'e',
        'e' => 'e',
        'e' => 'e',
        'e' => 'e',
        'È' => 'E',
        'É' => 'E',
        'Ê' => 'E',
        'Ë' => 'E',
        'E' => 'E',
        'E' => 'E',
        'E' => 'E',
        'E' => 'E',
        'E' => 'E',

        'ƒ' => 'f',


        'g' => 'g',
        'g' => 'g',
        'g' => 'g',
        'g' => 'g',
        'G' => 'G',
        'G' => 'G',
        'G' => 'G',
        'G' => 'G',


        'h' => 'h',
        'h' => 'h',
        'H' => 'H',
        'H' => 'H',

        'ì' => 'i',
        'í' => 'i',
        'î' => 'i',
        'ï' => 'i',
        'i' => 'i',
        'i' => 'i',
        'i' => 'i',
        'i' => 'i',
        '?' => 'i',
        'i' => 'i',
        'Ì' => 'I',
        'Í' => 'I',
        'Î' => 'I',
        'Ï' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',

        'j' => 'j',
        'J' => 'J',

        'k' => 'k',
        'K' => 'K',


        'l' => 'l',
        'l' => 'l',
        'l' => 'l',
        'l' => 'l',
        '?' => 'l',
        'L' => 'L',
        'L' => 'L',
        'L' => 'L',
        'L' => 'L',
        '?' => 'L',


        'ñ' => 'n',
        'n' => 'n',
        'n' => 'n',
        'n' => 'n',
        '?' => 'n',
        'Ñ' => 'N',
        'N' => 'N',
        'N' => 'N',
        'N' => 'N',

        'ò' => 'o',
        'ó' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'ö' => 'o',
        'ð' => 'o',
        'ø' => 'o',
        'o' => 'o',
        'o' => 'o',
        'o' => 'o',
        'o' => 'o',
        'o' => 'o',
        '?' => 'o',
        'Ò' => 'O',
        'Ó' => 'O',
        'Ô' => 'O',
        'Õ' => 'O',
        'Ö' => 'O',
        'Ø' => 'O',
        'O' => 'O',
        'O' => 'O',
        'O' => 'O',
        'O' => 'O',
        'O' => 'O',
        '?' => 'O',


        'r' => 'r',
        'r' => 'r',
        'r' => 'r',
        'R' => 'R',
        'R' => 'R',
        'R' => 'R',


        's' => 's',
        'š' => 's',
        's' => 's',
        's' => 's',
        'S' => 'S',
        'Š' => 'S',
        'S' => 'S',
        'S' => 'S',

        't' => 't',
        't' => 't',
        't' => 't',
        'T' => 'T',
        'T' => 'T',
        'T' => 'T',


        'ù' => 'u',
        'ú' => 'u',
        'û' => 'u',
        'ü' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'Ù' => 'U',
        'Ú' => 'U',
        'Û' => 'U',
        'Ü' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',


        'w' => 'w',
        'W' => 'W',

        'ý' => 'y',
        'ÿ' => 'y',
        'y' => 'y',
        'Ý' => 'Y',
        'Ÿ' => 'Y',
        'Y' => 'Y',

        'z' => 'z',
        'z' => 'z',
        'ž' => 'z',
        'Z' => 'Z',
        'Z' => 'Z',
        'Ž' => 'Z',


        // accentuated ligatures
        '?' => 'A',
        '?' => 'a',
    ];
    return strtr($str, $map);
}

What’s the best RESTful method to return total number of items in an object?

Interesting discussion regarding Designing REST API for returning count of multiple objects: https://groups.google.com/g/api-craft/c/qbI2QRrpFew/m/h30DYnrqEwAJ?pli=1

As an API consumer, I would expect each count value to be represented either as a subresource to the countable resource (i.e. GET /tasks/count for a count of tasks), or as a field in a bigger aggregation of metadata related to the concerned resource (i.e. GET /tasks/metadata). By scoping related endpoints under the same parent resource (i.e. /tasks), the API becomes intuitive, and the purpose of an endpoint can (usually) be inferred from its path and HTTP method.

Additional thoughts:

  1. If each individual count is only useful in combination with other counts (for a statistics dashboard, for example), you could possibly expose a single endpoint which aggregates and returns all counts at once.
  2. If you have an existing endpoint for listing all resources (i.e. GET /tasks for listing all tasks), the count could be included in the response as metadata, either as HTTP headers or in the response body. Doing this will incur unnecessary load on the API, which might be negligible depending on your use case.

Transitions on the CSS display property

You can concatenate two transitions or more, and visibility is what comes handy this time.

_x000D_
_x000D_
div {_x000D_
  border: 1px solid #eee;_x000D_
}_x000D_
div > ul {_x000D_
  visibility: hidden;_x000D_
  opacity: 0;_x000D_
  transition: visibility 0s, opacity 0.5s linear;_x000D_
}_x000D_
div:hover > ul {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div>_x000D_
  <ul>_x000D_
    <li>Item 1</li>_x000D_
    <li>Item 2</li>_x000D_
    <li>Item 3</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Don't forget the vendor prefixes to the transition property.)

More details are in this article.

re.sub erroring with "Expected string or bytes-like object"

I suppose better would be to use re.match() function. here is an example which may help you.

import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]  
sentences

How to loop and render elements in React-native?

You would usually use map for that kind of thing.

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);

(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)

As a side, I would use an object instead of an array. I find it looks nicer:

initialArr = [
  {
    id: 1,
    color: "blue",
    text: "text1"
  },
  {
    id: 2,
    color: "red",
    text: "text2"
  },
];

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);

How to get the currently logged in user's user id in Django?

I wrote this in an ajax view, but it is a more expansive answer giving the list of currently logged in and logged out users.

The is_authenticated attribute always returns True for my users, which I suppose is expected since it only checks for AnonymousUsers, but that proves useless if you were to say develop a chat app where you need logged in users displayed.

This checks for expired sessions and then figures out which user they belong to based on the decoded _auth_user_id attribute:

def ajax_find_logged_in_users(request, client_url):
    """
    Figure out which users are authenticated in the system or not.
    Is a logical way to check if a user has an expired session (i.e. they are not logged in)
    :param request:
    :param client_url:
    :return:
    """
    # query non-expired sessions
    sessions = Session.objects.filter(expire_date__gte=timezone.now())
    user_id_list = []
    # build list of user ids from query
    for session in sessions:
        data = session.get_decoded()
        # if the user is authenticated
        if data.get('_auth_user_id'):
            user_id_list.append(data.get('_auth_user_id'))

    # gather the logged in people from the list of pks
    logged_in_users = CustomUser.objects.filter(id__in=user_id_list)
    list_of_logged_in_users = [{user.id: user.get_name()} for user in logged_in_users]

    # Query all logged in staff users based on id list
    all_staff_users = CustomUser.objects.filter(is_resident=False, is_active=True, is_superuser=False)
    logged_out_users = list()
    # for some reason exclude() would not work correctly, so I did this the long way.
    for user in all_staff_users:
        if user not in logged_in_users:
            logged_out_users.append(user)
    list_of_logged_out_users = [{user.id: user.get_name()} for user in logged_out_users]

    # return the ajax response
    data = {
        'logged_in_users': list_of_logged_in_users,
        'logged_out_users': list_of_logged_out_users,
    }
    print(data)

    return HttpResponse(json.dumps(data))

What are the correct version numbers for C#?

The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.

The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.

Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.

How to check if a "lateinit" variable has been initialized?

There is a lateinit improvement in Kotlin 1.2 that allows to check the initialization state of lateinit variable directly:

lateinit var file: File    

if (this::file.isInitialized) { ... }

See the annoucement on JetBrains blog or the KEEP proposal.

UPDATE: Kotlin 1.2 has been released. You can find lateinit enhancements here:

In reactJS, how to copy text to clipboard?

You can also use react hooks into function components or stateless components with this piece of code: PS: Make sure you install useClippy through npm/yarn with this command: npm install use-clippy or yarn add use-clippy

import React from 'react';
import useClippy from 'use-clippy';

export default function YourComponent() {

// clipboard is the contents of the user's clipboard.
  // setClipboard('new value') wil set the contents of the user's clipboard.

  const [clipboard, setClipboard] = useClippy();

  return (
    <div>

      {/* Button that demonstrates reading the clipboard. */}
      <button
        onClick={() => {
          alert(`Your clipboard contains: ${clipboard}`);
        }}
      >
        Read my clipboard
      </button>

      {/* Button that demonstrates writing to the clipboard. */}
      <button
        onClick={() => {
          setClipboard(`Random number: ${Math.random()}`);
        }}
      >
        Copy something
      </button>
    </div>
  );
}

Terminating a Java Program

Because System.exit() is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit() method. It is standard for 0 to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.

return on the other hand is a reserved key word that the compiler knows well. return returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void as you have not supplied anything to return.

How to change column datatype from character to numeric in PostgreSQL 8.4

Step 1: Add new column with integer or numeric as per your requirement

Step 2: Populate data from varchar column to numeric column

Step 3: drop varchar column

Step 4: change new numeric column name as per old varchar column

ORDER BY the IN value list

And here's another solution that works and uses a constant table (http://www.postgresql.org/docs/8.3/interactive/sql-values.html):

SELECT * FROM comments AS c,
(VALUES (1,1),(3,2),(2,3),(4,4) ) AS t (ord_id,ord)
WHERE (c.id IN (1,3,2,4)) AND (c.id = t.ord_id)
ORDER BY ord

But again I'm not sure that this is performant.

I've got a bunch of answers now. Can I get some voting and comments so I know which is the winner!

Thanks All :-)

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

If it has happened after upgrading Android Studio, It can be caused by an out of date buildtool, Update Android SDK BuildTools

How can I get the current date and time in UTC or GMT in Java?

this is my implementation:

public static String GetCurrentTimeStamp()
{
    Calendar cal=Calendar.getInstance();
    long offset = cal.getTimeZone().getOffset(System.currentTimeMillis());//if you want in UTC else remove it .
    return new java.sql.Timestamp(System.currentTimeMillis()+offset).toString();    
}

How to Import Excel file into mysql Database from PHP

You are probably having a problem with the sort of CSV file that you have.

Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.

Live Video Streaming with PHP

PHP/AJAX/MySQL will not be enough for creating the live video streaming application There is a similar thread here. It primarily suggests using Flex or Silverlight.

multiprocessing: How do I share a dict among multiple processes?

multiprocessing is not like threading. Each child process will get a copy of the main process's memory. Generally state is shared via communication (pipes/sockets), signals, or shared memory.

Multiprocessing makes some abstractions available for your use case - shared state that's treated as local by use of proxies or shared memory: http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes

Relevant sections:

How do I right align div elements?

I know this is an old post but couldn't you just use <div id=xyz align="right"> for right.

You can just replace right with left, center and justify.

Worked on my site:)