Programs & Examples On #Application bar

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

Returning a promise in an async function in TypeScript

When you do new Promise((resolve)... the type inferred was Promise<{}> because you should have used new Promise<number>((resolve).

It is interesting that this issue was only highlighted when the async keyword was added. I would recommend reporting this issue to the TS team on GitHub.

There are many ways you can get around this issue. All the following functions have the same behavior:

const whatever1 = () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever2 = async () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever3 = async () => {
    return await new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever4 = async () => {
    return Promise.resolve(4);
};

const whatever5 = async () => {
    return await Promise.resolve(4);
};

const whatever6 = async () => Promise.resolve(4);

const whatever7 = async () => await Promise.resolve(4);

In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>.

How to enable cURL in PHP / XAMPP

Basic tip: After enabling the CURL in php.ini file, you need to restart the web server to make it work (my experience says).

'typeid' versus 'typeof' in C++

You can use Boost demangle to accomplish a nice looking name:

#include <boost/units/detail/utility.hpp>

and something like

To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

Efficient way to do batch INSERTS with JDBC

In my code I have no direct access to the 'preparedStatement' so I cannot use batch, I just pass it the query and a list of parameters. The trick however is to create a variable length insert statement, and a LinkedList of parameters. The effect is the same as the top example, with variable parameter input length.See below (error checking omitted). Assuming 'myTable' has 3 updatable fields: f1, f2 and f3

String []args={"A","B","C", "X","Y","Z" }; // etc, input list of triplets
final String QUERY="INSERT INTO [myTable] (f1,f2,f3) values ";
LinkedList params=new LinkedList();
String comma="";
StringBuilder q=QUERY;
for(int nl=0; nl< args.length; nl+=3 ) { // args is a list of triplets values
    params.add(args[nl]);
    params.add(args[nl+1]);
    params.add(args[nl+2]);
    q.append(comma+"(?,?,?)");
    comma=",";
}      
int nr=insertIntoDB(q, params);

in my DBInterface class I have:

int insertIntoDB(String query, LinkedList <String>params) {
    preparedUPDStmt = connectionSQL.prepareStatement(query);
    int n=1;
    for(String x:params) {
        preparedUPDStmt.setString(n++, x);
    }
    int updates=preparedUPDStmt.executeUpdate();
    return updates;
}

How to list only files and not directories of a directory Bash?

Listing content of some directory, without subdirectories

I like using ls options, for sample:

  • -l use a long listing format
  • -t sort by modification time, newest first
  • -r reverse order while sorting
  • -F, --classify append indicator (one of */=>@|) to entries
  • -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc...

Sometime --color and all others. (See ls --help)

Listing everything but folders

This will show files, symlinks, devices, pipe, sockets etc.

so

find /some/path -maxdepth 1 ! -type d

could be sorted by date easily:

find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +

Listing files only:

or

find /some/path -maxdepth 1 -type f

sorted by size:

find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +

Prevent listing of hidden entries:

To not show hidden entries, where name begin by a dot, you could add ! -name '.*':

find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +

Then

You could replace /some/path by . to list for current directory or .. for parent directory.

The difference between sys.stdout.write and print?

In Python 2, if you need to pass around a function, then you can assign os.sys.stdout.write to a variable. You cannot do this (in the REPL) with print.

>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>>

That works as expected.

>>> cmd=print
  File "<stdin>", line 1
    cmd=print
            ^
SyntaxError: invalid syntax

That does not work. print is a magical function.

Why and how to fix? IIS Express "The specified port is in use"

  1. Close the VS
    1. Start again - right click and run as admin
    2. Run your project again.

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

How to remove the border highlight on an input text element

Use this code:

input:focus {
    outline: 0;
}

UITapGestureRecognizer - single tap and double tap

Some view have there own double tap recognizers built in (MKMapView being an example). To get around this you will need to implement UIGestureRecognizerDelegate method shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES:

First implement your double and single recognizers:

// setup gesture recognizers
UITapGestureRecognizer* singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(mapViewTapped:)];
singleTapRecognizer.delegate = self;
singleTapRecognizer.numberOfTapsRequired = 1;


UITapGestureRecognizer* doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                      action:@selector(mapViewDoubleTapped:)];
doubleTapRecognizer.delegate = self;    // this allows
doubleTapRecognizer.numberOfTapsRequired = 2;
[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

And then implement:

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer {  return YES; }

How to output an Excel *.xls file from classic ASP

There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.

Create a tar.xz in one command

Try this: tar -cf file.tar file-to-compress ; xz -z file.tar

Note:

  1. tar.gz and tar.xz are not the same; xz provides better compression.
  2. Don't use pipe | because this runs commands simultaneously. Using ; or & executes commands one after another.

Open multiple Eclipse workspaces on the Mac

I found this solution a while back, can't remember where but it still seems to work well for me.

Create a copy of Eclipse.app for each workspace you want to work in (for this example ProjectB.app), then open ProjectB.app/Contents/MacOS/eclipse.ini and add these two lines at the beginning of the file:

-data
/Users/eric/Workspaces/projectb

... substituting where your workspace is located. When you launch ProjectB.app it will automatically start with that workspace instead of prompting for a location, and you should be able to run it at the same time as other Eclipse instances with no problem.

mysql select from n last rows

because it is autoincrement, here's my take:

Select * from tbl 
where certainconditionshere 
and autoincfield >= (select max(autoincfield) from tbl) - $n

Join between tables in two different databases?

Yes, assuming the account has appropriate permissions you can use:

SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;

You just need to prefix the table reference with the name of the database it resides in.

Sort Array of object by object field in Angular 6

You can simply use Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

Working Example :

_x000D_
_x000D_
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
 _x000D_
 console.log(array);
_x000D_
_x000D_
_x000D_

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

It seems the new version of msbuild does not ship with Microsoft.WebApplication.targets. To fix you need to update your csproj file as so:

1) Edit the web app csproj (right click). Find the section in the csproj towards the bottom concerning build tools. It should look like so.

<PropertyGroup>  
  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
</PropertyGroup>  
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />  
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />  
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />  

2) You need to add one VSToolsPath line below the VisualStudioVersion tag so it looks like so

<PropertyGroup>  
  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
  <!--Add the below line to fix the project loading in VS 2017 -->
  <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  <!--End -->
</PropertyGroup>  
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />  
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />  
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />  

Reference link: https://alastaircrabtree.com/cannot-open-vs-2015-web-project-in-vs-2017/

Why is __init__() always called after __new__()?

I realize that this question is quite old but I had a similar issue. The following did what I wanted:

class Agent(object):
    _agents = dict()

    def __new__(cls, *p):
        number = p[0]
        if not number in cls._agents:
            cls._agents[number] = object.__new__(cls)
        return cls._agents[number]

    def __init__(self, number):
        self.number = number

    def __eq__(self, rhs):
        return self.number == rhs.number

Agent("a") is Agent("a") == True

I used this page as a resource http://infohost.nmt.edu/tcc/help/pubs/python/web/new-new-method.html

How does facebook, gmail send the real time notification?

The way Facebook does this is pretty interesting.

A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.

The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.

Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.

In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.

Implementing:

Server Side:

There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:

while(!has_event_happened()) {
   sleep(5);
}

echo json_encode(get_events());
  • The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.

  • Don't forget to change your PHP max execution time, otherwise it will timeout early!

Client Side:

Take a look at the jQuery plugin for doing Comet interaction:

That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:

function doPoll() {
   $.get("events.php", {}, function(result) {
      $.each(result.events, function(event) { //iterate over the events
          //do something with your event
      });
      doPoll(); 
      //this effectively causes the poll to run again as
      //soon as the response comes back
   }, 'json'); 
}

$(document).ready(function() {
    $.ajaxSetup({
       timeout: 1000*60//set a global AJAX timeout of a minute
    });
    doPoll(); // do the first poll
});

The whole thing depends a lot on how your existing architecture is put together.

@font-face not working

I'm also facing this type of problem. After trying all solutions I got final solution on this problem. Reasons for this type of problem is per-defined global fonts. Use !important keyword for each line in @font-face is the solution for this problem.

Full description and example for Solution of this problem is here :- http://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html

IN Clause with NULL or IS NULL

An in statement will be parsed identically to field=val1 or field=val2 or field=val3. Putting a null in there will boil down to field=null which won't work.

(Comment by Marc B)

I would do this for clairity

SELECT *
FROM tbl_name
WHERE 
(id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)

Removing the textarea border in HTML

textarea {
border: 0;
overflow: auto; }

less CSS ^ you can't align the text to the bottom unfortunately.

DateTime.TryParseExact() rejecting valid formats

Here you can check for couple of things.

  1. Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
  2. CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo provider = new CultureInfo("en-US"), you may write it like. .

    if (!DateTime.TryParseExact(txtStartDate.Text, formats, 
                    System.Globalization.CultureInfo.InvariantCulture,
                    System.Globalization.DateTimeStyles.None, out startDate))
    {
        //your condition fail code goes here
        return false;
    }
    else
    {
        //success code
    }
    

Android: How to overlay a bitmap and draw over a bitmap?

I can't believe no one has answered this yet! A rare occurrence on SO!

1

The question doesn't quite make sense to me. But I'll give it a stab. If you're asking about direct drawing to a canvas (polygons, shading, text etc...) vs. loading a bitmap and blitting it onto the canvas that would depend on the complexity of your drawing. As the drawing gets more complex the CPU time required will increase accordingly. However, blitting a bitmap onto a canvas will always be a constant time which is proportional to the size of the bitmap.

2

Without knowing what "something" is how can I show you how to do it? You should be able to figure out #2 from the answer for #3.

3

Assumptions:

  • bmp1 is larger than bmp2.
  • You want them both overlaid from the top left corner.

        private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
            Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmp1, new Matrix(), null);
            canvas.drawBitmap(bmp2, new Matrix(), null);
            return bmOverlay;
        }
    

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

SQL order string as number

Another and simple way

ORDER BY ABS(column_name)

How do I get my page title to have an icon?

The accepted answer works perfectly fine. I just want to mention a minor problem with the answer devXen has given.

If you set the icon like this:

<link rel="shortcut icon" type="image/x-icon" href="icon.ico">

The icon will work as expected:

enter image description here

However, if you set it like devXen has suggested:

<title> Amir A. Shabani</title>

The title of the page moves upon refresh:

enter image description here

So I would advise using <link> instead.

Get latest from Git branch

If you have forked a repository fro Delete your forked copy and fork it again from master.

Difference between string and char[] types in C++

A char array is just that - an array of characters:

  • If allocated on the stack (like in your example), it will always occupy eg. 256 bytes no matter how long the text it contains is
  • If allocated on the heap (using malloc() or new char[]) you're responsible for releasing the memory afterwards and you will always have the overhead of a heap allocation.
  • If you copy a text of more than 256 chars into the array, it might crash, produce ugly assertion messages or cause unexplainable (mis-)behavior somewhere else in your program.
  • To determine the text's length, the array has to be scanned, character by character, for a \0 character.

A string is a class that contains a char array, but automatically manages it for you. Most string implementations have a built-in array of 16 characters (so short strings don't fragment the heap) and use the heap for longer strings.

You can access a string's char array like this:

std::string myString = "Hello World";
const char *myStringChars = myString.c_str();

C++ strings can contain embedded \0 characters, know their length without counting, are faster than heap-allocated char arrays for short texts and protect you from buffer overruns. Plus they're more readable and easier to use.


However, C++ strings are not (very) suitable for usage across DLL boundaries, because this would require any user of such a DLL function to make sure he's using the exact same compiler and C++ runtime implementation, lest he risk his string class behaving differently.

Normally, a string class would also release its heap memory on the calling heap, so it will only be able to free memory again if you're using a shared (.dll or .so) version of the runtime.

In short: use C++ strings in all your internal functions and methods. If you ever write a .dll or .so, use C strings in your public (dll/so-exposed) functions.

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

I've got this exact error, but in my case I was binding values for the LIMIT clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset; resulted in LIMIT '10' OFFSET '1'; instead of LIMIT 10 OFFSET 1;. What helps to correct that is the following:

$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);

Truncate/round whole number in JavaScript?

I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:

function truncateToInt(x)
{
    if(x > 0)
    {
         return Math.floor(x);
    }
    else
    {
         return Math.ceil(x);
    }
 }

Then:

y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3

Notice: This answer was written when Math.trunc(x) was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x).

jQuery - Increase the value of a counter when a button is clicked

I'm going to try this the following way. I've placed the count variable inside the "onfocus" function so as to keep it from becoming a global variable. The idea is to create a counter for each image in a tumblr blog.

$(document).ready(function() {

  $("#image1").onfocus(function() {

  var count;

    if (count == undefined || count == "" || count == 0) {
    var count = 0;
    }

    count++;
    $("#counter1").html("Image Views: " + count);
  }
});

Then, outside the script tags and in the desired place in the body I'll add:

<div id="counter1"></div>

What is a Python egg?

"Egg" is a single-file importable distribution format for Python-related projects.

"The Quick Guide to Python Eggs" notes that "Eggs are to Pythons as Jars are to Java..."

Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

Show row number in row header of a DataGridView

You can also draw the string dynamically inside the RowPostPaint event:

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

How to compare strings

You could use strcmp():

/* strcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szKey[] = "apple";
  char szInput[80];
  do {
     printf ("Guess my favourite fruit? ");
     gets (szInput);
  } while (strcmp (szKey,szInput) != 0);
  puts ("Correct answer!");
  return 0;
}

How to show matplotlib plots in python

You have to use show() methode when you done all initialisations in your code in order to see the complet version of plot:

import matplotlib.pyplot as plt

plt.plot(x, y)
................
................
plot.show()

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

offsetting an html anchor to adjust for fixed header

Pure css solution inspired by Alexander Savin:

a[name] {
  padding-top: 40px;
  margin-top: -40px;
  display: inline-block; /* required for webkit browsers */
}

Optionally you may want to add the following if the target is still off the screen:

  vertical-align: top;

Return Boolean Value on SQL Select Statement

Possibly something along these lines:

SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT)
FROM dummy WHERE id = 1;

http://sqlfiddle.com/#!3/5e555/1

remove inner shadow of text input

None of the solution are working currently. Here is my solution. You can add prefixes.

box-shadow: inset 0px 0px 0px 0px red;

Execution failed for task :':app:mergeDebugResources'. Android Studio

For me. I changed the color of .xml image (vector image) like this.

ic_action_add.xml

  <vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="#FFFFFF"
    android:alpha="0.8">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

to:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="#FFFFFF"
    android:alpha="0.8">
  <path
      android:fillColor="#FF000000"
      android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

i just changed android:fillColor="@android:color/white" to android:fillColor="#FF000000"

and it's worked for me :)

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

An expression of non-boolean type specified in a context where a condition is expected

I also got this error when I forgot to add ON condition when specifying my join clause.

How to duplicate sys.stdout to a log file?

Here is another solution, which is more general than the others -- it supports splitting output (written to sys.stdout) to any number of file-like objects. There's no requirement that __stdout__ itself is included.

import sys

class multifile(object):
    def __init__(self, files):
        self._files = files
    def __getattr__(self, attr, *args):
        return self._wrap(attr, *args)
    def _wrap(self, attr, *args):
        def g(*a, **kw):
            for f in self._files:
                res = getattr(f, attr, *args)(*a, **kw)
            return res
        return g

# for a tee-like behavior, use like this:
sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])

# all these forms work:
print 'abc'
print >>sys.stdout, 'line2'
sys.stdout.write('line3\n')

NOTE: This is a proof-of-concept. The implementation here is not complete, as it only wraps methods of the file-like objects (e.g. write), leaving out members/properties/setattr, etc. However, it is probably good enough for most people as it currently stands.

What I like about it, other than its generality, is that it is clean in the sense it doesn't make any direct calls to write, flush, os.dup2, etc.

Are string.Equals() and == operator really same?

The Header property of the TreeViewItem is statically typed to be of type object.

Therefore the == yields false. You can reproduce this with the following simple snippet:

object s1 = "Hallo";

// don't use a string literal to avoid interning
string s2 = new string(new char[] { 'H', 'a', 'l', 'l', 'o' });

bool equals = s1 == s2;         // equals is false
equals = string.Equals(s1, s2); // equals is true

Jquery Date picker Default Date

interesting, datepicker default date is current date as I found,

but you can set date by

$("#yourinput").datepicker( "setDate" , "7/11/2011" );

don't forget to check you system date :)

Insert HTML from CSS

No. The only you can do is to add content (and not an element) using :before or :after pseudo-element.

More information: http://www.w3.org/TR/CSS2/generate.html#before-after-content

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar):

17.6.3.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also:

17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

Ajax Success and Error function failure

I was having the same issue and fixed it by simply adding a dataType = "text" line to my ajax call. Make the dataType match the response you expect to get back from the server (your "insert successful" or "something went wrong" error message).

How to access the elements of a 2D array?

If you have this :

a = [[1, 1], [2, 1],[3, 1]]

You can easily access this by using :

print(a[0][2])
a[0][1] = 7
print(a)

Using sed and grep/egrep to search and replace

Another way to do this

find . -name *.xml -exec sed -i "s/4.6.0-SNAPSHOT/5.0.0-SNAPSHOT/" {} \;

Some help regarding the above command

The find will do the find for you on the current directory indicated by .

-name the name of the file in my case its pom.xml can give wild cards.

-exec execute

sed stream editor

-i ignore case

s is for substitute

/4.6.0.../ String to be searched

/5.0.0.../ String to be replaced

How to create relationships in MySQL

Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.

If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.

For example, in a query you link two tables in a select statement with a join:

SELECT a, b from table1 LEFT JOIN table2 USING (common_field);

How to find a user's home directory on linux or unix?

If you want to find a specific user's home directory, I don't believe you can do it directly.

When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX() family of calls.

Modify request parameter with servlet filter

This is what i ended up doing

//import ../../Constants;

public class RequestFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        try {
            CustomHttpServletRequest customHttpServletRequest = new CustomHttpServletRequest((HttpServletRequest) servletRequest);
            filterChain.doFilter(customHttpServletRequest, servletResponse);
        } finally {
            //do something here
        }
    }



    @Override
    public void destroy() {

    }

     public static Map<String, String[]> ADMIN_QUERY_PARAMS = new HashMap<String, String[]>() {
        {
            put("diagnostics", new String[]{"false"});
            put("skipCache", new String[]{"false"});
        }
    };

    /*
        This is a custom wrapper over the `HttpServletRequestWrapper` which 
        overrides the various header getter methods and query param getter methods.
        Changes to the request pojo are
        => A custom header is added whose value is a unique id
        => Admin query params are set to default values in the url
    */
    private class CustomHttpServletRequest extends HttpServletRequestWrapper {
        public CustomHttpServletRequest(HttpServletRequest request) {
            super(request);
            //create custom id (to be returned) when the value for a
            //particular header is asked for
            internalRequestId = RandomStringUtils.random(10, true, true) + "-local";
        }

        public String getHeader(String name) {
            String value = super.getHeader(name);
            if(Strings.isNullOrEmpty(value) && isRequestIdHeaderName(name)) {
                value = internalRequestId;
            }
            return value;
        }

        private boolean isRequestIdHeaderName(String name) {
            return Constants.RID_HEADER.equalsIgnoreCase(name) || Constants.X_REQUEST_ID_HEADER.equalsIgnoreCase(name);
        }

        public Enumeration<String> getHeaders(String name) {
            List<String> values = Collections.list(super.getHeaders(name));
            if(values.size()==0 && isRequestIdHeaderName(name)) {
                values.add(internalRequestId);
            }
            return Collections.enumeration(values);
        }

        public Enumeration<String> getHeaderNames() {
            List<String> names = Collections.list(super.getHeaderNames());
            names.add(Constants.RID_HEADER);
            names.add(Constants.X_REQUEST_ID_HEADER);
            return Collections.enumeration(names);
        }

        public String getParameter(String name) {
            if (ADMIN_QUERY_PARAMS.get(name) != null) {
                return ADMIN_QUERY_PARAMS.get(name)[0];
            }
            return super.getParameter(name);
        }

        public Map<String, String[]> getParameterMap() {
            Map<String, String[]> paramsMap = new HashMap<>(super.getParameterMap());
            for (String paramName : ADMIN_QUERY_PARAMS.keySet()) {
                if (paramsMap.get(paramName) != null) {
                    paramsMap.put(paramName, ADMIN_QUERY_PARAMS.get(paramName));
                }
            }
            return paramsMap;
        }

        public String[] getParameterValues(String name) {
            if (ADMIN_QUERY_PARAMS.get(name) != null) {
                return ADMIN_QUERY_PARAMS.get(name);
            }
            return super.getParameterValues(name);
        }

        public String getQueryString() {
            Map<String, String[]> map = getParameterMap();
            StringBuilder builder = new StringBuilder();
            for (String param: map.keySet()) {
                for (String value: map.get(param)) {
                    builder.append(param).append("=").append(value).append("&");
                }
            }
            builder.deleteCharAt(builder.length() - 1);
            return builder.toString();
        }
    }
}

Programmatically center TextView text

if your text size is small, you should make the width of your text view to be "fill_parent". After that, you can set your TextView Gravity to center :

TextView textView = new TextView(this);
textView.setText(message);
textView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);

What is the syntax meaning of RAISERROR()

The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).

The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.

How to concatenate multiple lines of output to one line?

Here is the method using ex editor (part of Vim):

  • Join all lines and print to the standard output:

    $ ex +%j +%p -scq! file
    
  • Join all lines in-place (in the file):

    $ ex +%j -scwq file
    

    Note: This will concatenate all lines inside the file it-self!

Creating a select box with a search option

This will done by using jquery. Here is the code

<select class="chosen" style="width:500px;">
<option>Html</option>
<option>Css</option>
<option>Css3</option>
<option>Php</option>
<option>MySql</option>
<option>Javascript</option>
<option>Jquery</option>
<option>Html5</option>
<option>Wordpress</option>
<option>Joomla</option>
<option>Druple</option>
<option>Json</option>
<option>Angular Js</option>
</select>
</div>
<script type="text/javascript">
$(".chosen").chosen();
</script>

Working Example Here...

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

In addition to @Bruno's answer, you need to supply the -name for alias, otherwise Tomcat will throw Alias name tomcat does not identify a key entry error

Sample Command: openssl pkcs12 -export -in localhost.crt -inkey localhost.key -out localhost.p12 -name localhost

The transaction log for the database is full

To fix this problem, change Recovery Model to Simple then Shrink Files Log

1. Database Properties > Options > Recovery Model > Simple

2. Database Tasks > Shrink > Files > Log

Done.

Then check your db log file size at Database Properties > Files > Database Files > Path

To check full sql server log: open Log File Viewer at SSMS > Database > Management > SQL Server Logs > Current

tar: Error is not recoverable: exiting now

If you got "Error is not recoverable: exiting now" You might have specified incorrect path references.

[me@host ~]$ tar -xvf nameOfMyTar.tar -C /someSubDirectory/
tar: /someSubDirectory: Cannot open: No such file or directory
tar: Error is not recoverable: exiting now
[me@host ~]$

Make sure you provide correct relative or absolute directory references e.g.:

[me@host ~]$ tar -xvf ./nameOfMyTar.tar -C ./someSubDirectory/
./foo/
./bar/
[me@host ~]$ 

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In my specific case I seemed to have been missing the dependency

 <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.3.RELEASE</version>
 </dependency>

multiple axis in matplotlib with different scales

If I understand the question, you may interested in this example in the Matplotlib gallery.

enter image description here

Yann's comment above provides a similar example.


Edit - Link above fixed. Corresponding code copied from the Matplotlib gallery:

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right", axes=par2,
                                        offset=(offset, 0))

par2.axis["right"].toggle(all=True)

host.set_xlim(0, 2)
host.set_ylim(0, 2)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.legend()

host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())

plt.draw()
plt.show()

#plt.savefig("Test")

Select rows of a matrix that meet a condition

I will choose a simple approach using the dplyr package.

If the dataframe is data.

library(dplyr)
result <- filter(data, three == 11)

Convert Unicode to ASCII without errors in Python

As an extension to Ignacio Vazquez-Abrams' answer

>>> u'a?ä'.encode('ascii', 'ignore')
'a'

It is sometimes desirable to remove accents from characters and print the base form. This can be accomplished with

>>> import unicodedata
>>> unicodedata.normalize('NFKD', u'a?ä').encode('ascii', 'ignore')
'aa'

You may also want to translate other characters (such as punctuation) to their nearest equivalents, for instance the RIGHT SINGLE QUOTATION MARK unicode character does not get converted to an ascii APOSTROPHE when encoding.

>>> print u'\u2019'
’
>>> unicodedata.name(u'\u2019')
'RIGHT SINGLE QUOTATION MARK'
>>> u'\u2019'.encode('ascii', 'ignore')
''
# Note we get an empty string back
>>> u'\u2019'.replace(u'\u2019', u'\'').encode('ascii', 'ignore')
"'"

Although there are more efficient ways to accomplish this. See this question for more details Where is Python's "best ASCII for this Unicode" database?

SQL query for extracting year from a date

SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020

Using logging in multiple modules

Actually every logger is a child of the parent's package logger (i.e. package.subpackage.module inherits configuration from package.subpackage), so all you need to do is just to configure the root logger. This can be achieved by logging.config.fileConfig (your own config for loggers) or logging.basicConfig (sets the root logger). Setup logging in your entry module (__main__.py or whatever you want to run, for example main_script.py. __init__.py works as well)

using basicConfig:

# package/__main__.py
import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

using fileConfig:

# package/__main__.py
import logging
import logging.config

logging.config.fileConfig('logging.conf')

and then create every logger using:

# package/submodule.py
# or
# package/subpackage/submodule.py
import logging
log = logging.getLogger(__name__)

log.info("Hello logging!")

For more information see Advanced Logging Tutorial.

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Making a list of evenly spaced numbers in a certain range in python

Similar to unutbu's answer, you can use numpy's arange function, which is analog to Python's intrinsic function range. Notice that the end point is not included, as in range:

>>> import numpy as np
>>> a = np.arange(0,5, 0.5)
>>> a
array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5])
>>> a = np.arange(0,5, 0.5) # returns a numpy array
>>> a
array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5])
>>> a.tolist() # if you prefer it as a list
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]

Which version of CodeIgniter am I currently using?

From a controller or view - use the following to display the version:

<?php
   echo CI_VERSION;
?>

How can I detect when the mouse leaves the window?

Maybe if you're constantly listening to OnMouseOver in the body tag, then callback when the event is not ocurring, but, as Zack states, this could be very ugly, because not all the browsers handle events the same way, there is even some possibility that you lose the MouseOver even by being over a div in the same page.

How to cut an entire line in vim and paste it?

Yep, use dd in command line. Also I recommend to print useful image with ViM hotkeys available at http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html

Is it possible to write to the console in colour in .NET?

Yes, it is possible as follows. These colours can be used in a console application to view some errors in red, etc.

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour

How to open an existing project in Eclipse?

from Eclipse main gui: select "Window->Show View->Other->General->Project Explorer" Double-clicking on "Project Explorer" brings up the "Project Explorer" window which shows every project in your workspace. That worked for me.

Good luck.

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

Firebug-like debugger for Google Chrome

Firebug Lite supports to inspect HTML elements, computed CSS style, and a lot more. Since it's pure JavaScript, it works in many different browsers. Just include the script in your source, or add the bookmarklet to your bookmark bar to include it on any page with a single click.

http://getfirebug.com/lite.html

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case I had tried to make code more readable by putting:

"LONGTEXTSTRING " +
"LONGTEXTSTRING" +
"LONGTEXTSTRING"

Once I changed it to

LONGTEXTSTRING LONGTEXTSTRING LONGTEXTSTRING 

Then it worked

How to check whether the user uploaded a file in PHP?

<!DOCTYPE html>
<html>
<body>

<form action="#" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input name="my_files[]" type="file" multiple="multiple" />
    <input type="submit" value="Upload Image" name="submit">
</form>


<?php

 if (isset($_FILES['my_files']))
  {
    $myFile = $_FILES['my_files'];
    $fileCount = count($myFile["name"]);


        for ($i = 0; $i <$fileCount; $i++)
         {
           $error = $myFile["error"][$i]; 

            if ($error == '4')  // error 4 is for "no file selected"
             {
               echo "no file selected";
             }
            else
             {

               $name =  $myFile["name"][$i];
               echo $name; 
               echo "<br>"; 
               $temporary_file = $myFile["tmp_name"][$i];
               echo $temporary_file;
               echo "<br>";
               $type = $myFile["type"][$i];
               echo $type;
               echo "<br>";
               $size = $myFile["size"][$i];
               echo $size;
               echo "<br>";



               $target_path = "uploads/$name";   //first make a folder named "uploads" where you will upload files


                 if(move_uploaded_file($temporary_file,$target_path))
                  {
                   echo " uploaded";
                   echo "<br>";
                   echo "<br>";
                  }
                   else
                  {
                   echo "no upload ";
                  }




              }
        }  
}
        ?>


</body>
</html>

But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.

What is lexical scope?

This topic is strongly related with the built-in bind function and introduced in ECMAScript 6 Arrow Functions. It was really annoying, because for every new "class" (function actually) method we wanted to use, we had to bind this in order to have access to the scope.

JavaScript by default doesn't set its scope of this on functions (it doesn't set the context on this). By default you have to explicitly say which context you want to have.

The arrow functions automatically gets so-called lexical scope (have access to variable's definition in its containing block). When using arrow functions it automatically binds this to the place where the arrow function was defined in the first place, and the context of this arrow functions is its containing block.

See how it works in practice on the simplest examples below.

Before Arrow Functions (no lexical scope by default):

const programming = {
  language: "JavaScript",
  getLanguage: function() {
    return this.language;
  }
}

const globalScope = programming.getLanguage;
console.log(globalScope()); // Output: undefined

const localScope = programming.getLanguage.bind(programming);
console.log(localScope()); // Output: "JavaScript"

With arrow functions (lexical scope by default):

const programming = {
  language: "JavaScript",
  getLanguage: function() {
    return this.language;
  }
}

const arrowFunction = () => {
    console.log(programming.getLanguage());
}

arrowFunction(); // Output: "JavaScript"

How to stretch in width a WPF user control to its window?

This worked for me. don't assign any width or height to the UserControl and define row and column definition in the parent window.

<UserControl x:Class="MySampleApp.myUC"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d"  
        >
   <Grid>

    </Grid>
</UserControl>


 <Window xmlns:MySampleApp="clr-namespace:MySampleApp"  x:Class="MySampleApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="auto" Width="auto" MinWidth="1000" >
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />           
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />            
    </Grid.ColumnDefinitions>
    <MySampleApp:myUC Grid.Column="0" Grid.Row="0" />       
</Grid>

What is the simplest SQL Query to find the second largest value?


select * from (select ROW_NUMBER() over (Order by Col_x desc) as Row, Col_1
    from table_1)as table_new tn inner join table_1 t1
    on tn.col_1 = t1.col_1
where row = 2

Hope this help to get the value for any row.....

Java : Cannot format given Object as a Date

This worked for me:

String dat="02/08/2017";
long date=new SimpleDateFormat("dd/MM/yyyy").parse(dat,newParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(date);
System.out.println(dbDate);

C# DataRow Empty-check

AFAIK, there is no method that does this in the framework. Even if there was support for something like this in the framework, it would essentially be doing the same thing. And that would be looking at each cell in the DataRow to see if it is empty.

Checking letter case (Upper/Lower) within a string in Java

package passwordValidator;

import java.util.Scanner;

public class Main {
    /**
     * @author felipe mello.
     */

    private static Scanner scanner = new Scanner(System.in);

     /*
     * Create a password validator(from an input string) via TDD
     * The validator should return true if
     *  The Password is at least 8 characters long
     *  The Password contains uppercase Letters(atLeastOne)
     *  The Password contains digits(at least one)
     *  The Password contains symbols(at least one)
     */


    public static void main(String[] args) {
        System.out.println("Please enter a password");
        String password = scanner.nextLine();   

        checkPassword(password);
    }
    /**
     * 
     * @param checkPassword the method check password is validating the input from the the user and check if it matches the password requirements
     * @return
     */
    public static boolean checkPassword(String password){
        boolean upperCase = !password.equals(password.toLowerCase()); //check if the input has a lower case letter
        boolean lowerCase = !password.equals(password.toUpperCase()); //check if the input has a CAPITAL case letter
        boolean isAtLeast8 = password.length()>=8;                    //check if the input is greater than 8 characters
        boolean hasSpecial = !password.matches("[A-Za-z0-9]*");       // check if the input has a special characters
        boolean hasNumber = !password.matches(".*\\d+.*");            //check if the input contains a digit
        if(!isAtLeast8){
            System.out.println("Your Password is not big enough\n please enter a password with minimun of 8 characters");
            return true;
        }else if(!upperCase){
            System.out.println("Password must contain at least one UPPERCASE letter");
            return true;
        }else if(!lowerCase){
            System.out.println("Password must contain at least one lower case letter");
            return true;
        }else if(!hasSpecial){
            System.out.println("Password must contain a special character");
            return true;
        }else if(hasNumber){
            System.out.println("Password must contain at least one number");
            return true;
        }else{
            System.out.println("Your password: "+password+", sucessfully match the requirements");
            return true;
        }

    }
}

Set inputType for an EditText Programmatically?

According to the TextView docs, the programmatic version of android:password is setTransformationMethod(), not setInputType(). So something like:

mEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());

should do the trick.

C# Debug - cannot start debugging because the debug target is missing

I also get this error quite often.

I solve this by modifying the code (doing a very small change), saving it, then building the solution again.

Get JSONArray without array name?

You don't need to call json.getJSONArray() at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject; use a JSONArray. This should suffice:

// ...
JSONArray json = new JSONArray(result);
// ...

for(int i=0;i<json.length();i++){                        
    HashMap<String, String> map = new HashMap<String, String>();    
    JSONObject e = json.getJSONObject(i);

    map.put("id",  String.valueOf(i));
    map.put("name", "Earthquake name:" + e.getString("eqid"));
    map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
    mylist.add(map);            
}

You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray at the root, not a JSONObject.

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

You should done my guideline:
1. Add bellow source into Gemfile

source 'https://rails-assets.org' do
  gem 'rails-assets-tether', '>= 1.1.0'
end
  1. Run command:

    bundle install

  2. Add this line after jQuery in application.js.

    //= require jquery
    //= require tether

  3. Restart rails server.

SQL Server - stop or break execution of a SQL script

you could wrap your SQL statement in a WHILE loop and use BREAK if needed

WHILE 1 = 1
BEGIN
   -- Do work here
   -- If you need to stop execution then use a BREAK


    BREAK; --Make sure to have this break at the end to prevent infinite loop
END

jQuery.css() - marginLeft vs. margin-left?

when is marginLeft being used:

$("div").css({
    marginLeft:'12px',
    backgroundPosition:'10px -10px',
    minHeight: '40px'
});

As you can see, attributes that has a hyphen on it are converted to camelcased format. Using the margin-left from the previous code block above would make JavaScript bonkers because it will treat the hyphen as an operation for subtraction.

when is margin-left used:

$("div").css("margin-left","12px").css("background-position","10px -10px").css("min-height","40px");

Theoretically, both code blocks will do the same thing. We can allow hyphens on the second block because it is a string value while compared to the first block, it is somewhat an object.
Now that should make sense.

how to get current location in google map android

Your current location might not be available immediately, after the map fragment is initialized.

After set

googleMap.setMyLocationEnabled(true);

you have to wait until you see the blue dot shown on your MapView. Then

Location myLocation = googleMap.getMyLocation();

myLocation won't be null.

I think you better use the LocationClient instead, and implement your own LocationListener.onLocationChanged(Location l)

Receiving Location Updates will show you how to get current location from LocationClient

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

Please check if the python version you are using is also 64 bit. If not then that could be the issue. You would be using a 32 bit python version and would have installed a 64 bit binaries for the OPENCV library.

iFrame onload JavaScript event

Update

As of jQuery 3.0, the new syntax is just .on:

see this answer here and the code:

$('iframe').on('load', function() {
    // do stuff 
});

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

Using R to download zipped data file, extract, and import data

Try this code. It works for me:

unzip(zipfile="<directory and filename>",
      exdir="<directory where the content will be extracted>")

Example:

unzip(zipfile="./data/Data.zip",exdir="./data")

C++: constructor initializer for arrays

There is no array-construction syntax that ca be used in this context, at least not directly. You can accomplish what you're trying to accomplish by something along the lines of:

Bar::Bar()
{
    static const int inits [] = {4,5,6};
    static const size_t numInits = sizeof(inits)/sizeof(inits[0]);
    std::copy(&inits[0],&inits[numInits],foo);  // be careful that there are enough slots in foo
}

...but you'll need to give Foo a default constructor.

Emulator in Android Studio doesn't start

If you're getting

Failed on eglChooseConfig
Could not initialize emulated framebuffer

See this answer. You may not be in 32-bit color mode, which will cause android GPU emulation to fail.

https://stackoverflow.com/a/48529994/290072

Guzzlehttp - How get the body of a response from Guzzle 6?

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:

$contents = (string) $response->getBody();

You can also do it with

$contents = $response->getBody()->getContents();

The difference between the two approaches is that getContents returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind or seek .

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents

Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

What is the meaning of "POSIX"?

Some facts about POSIX that are not so bright.

POSIX is also the system call interface or API, and it is nearly 30 years old.

It was designed for serialized data access to local storage, using single computers with single CPUs.

Security was not a major concern in POSIX by design, leading to numerous race condition attacks over the years and forcing programmers to work around these limitations.

Serious bugs are still being discovered, bugs that could have been averted with a more secure POSIX API design.

POSIX expects users to issue one synchronous call at a time and wait for its results before issuing the next. Today's programmers expect to issue many asynchronous requests at a time to improve overall throughput.

This synchronous API is particularly bad for accessing remote and cloud objects, where high latency matters.

How to make UIButton's text alignment center? Using IB

You can do this from storyboard. Select your button. Set Line Break 'Word Wrap', Set your title 'Plain' to 'Attributed'. Select 'Center alignment'. This part is important => Click ...(More) Button. And select line breaking mode to 'Character Wrap'.

Capturing URL parameters in request.GET

To clarify camflan's explanation, let's suppose you have

  • the rule url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page')
  • a in incoming request for http://domain/user/thaiyoshi/?message=Hi

The URL dispatcher rule will catch parts of the URL path (here "user/thaiyoshi/") and pass them to the view function along with the request object.

The query string (here message=Hi) is parsed and parameters are stored as a QueryDict in request.GET. No further matching or processing for HTTP GET parameters is done.

This view function would use both parts extracted from the URL path and a query parameter:

def profile_page(request, username=None):
    user = User.objects.get(username=username)
    message = request.GET.get('message')

As a side note, you'll find the request method (in this case "GET", and for submitted forms usually "POST") in request.method. In some cases it's useful to check that it matches what you're expecting.

Update: When deciding whether to use the URL path or the query parameters for passing information, the following may help:

  • use the URL path for uniquely identifying resources, e.g. /blog/post/15/ (not /blog/posts/?id=15)
  • use query parameters for changing the way the resource is displayed, e.g. /blog/post/15/?show_comments=1 or /blog/posts/2008/?sort_by=date&direction=desc
  • to make human friendly URLs, avoid using ID numbers and use e.g. dates, categories and/or slugs: /blog/post/2008/09/30/django-urls/

Passing on command line arguments to runnable JAR

Why not ?

Just modify your Main-Class to receive arguments and act upon the argument.

public class wiki2txt {

    public static void main(String[] args) {

          String fileName = args[0];

          // Use FileInputStream, BufferedReader etc here.

    }
}

Specify the full path in the commandline.

java -jar wiki2txt /home/bla/enwiki-....xml

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

These days you can just use the file extension

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

Use Toast inside Fragment

        public void onClick(View v) {
            Context context = v.getContext();
            CharSequence text = "Message";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

TSQL How do you output PRINT in a user defined function?

I got around this by temporarily rewriting my function to something like this:

IF OBJECT_ID ('[dbo].[fx_dosomething]', 'TF') IS NOT NULL
  drop function [dbo].[fx_dosomething];
GO

create FUNCTION dbo.fx_dosomething ( @x numeric )
returns @t table (debug varchar(100), x2 numeric)
as
begin
 declare @debug varchar(100)
 set @debug = 'printme';

 declare @x2 numeric
 set @x2 = 0.123456;

 insert into @t values (@debug, @x2)
 return 
end
go

select * from fx_dosomething(0.1)

How to find a value in an array of objects in JavaScript?

There's already a lot of good answers here so why not one more, use a library like lodash or underscore :)

obj = {
   1 : { name : 'bob' , dinner : 'pizza' },
   2 : { name : 'john' , dinner : 'sushi' },
   3 : { name : 'larry', dinner : 'hummus' }
}

_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

How do I put my website's logo to be the icon image in browser tabs?

  1. ADD THIS
**<HEAD>**

  < link rel="icon" href="directory/image.png">

Then run and enjoy it

Getting A File's Mime Type In Java

If you're an Android developer, you can use a utility class android.webkit.MimeTypeMap which maps MIME-types to file extensions and vice versa.

Following code snippet may help you.

private static String getMimeType(String fileUrl) {
    String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

How to check what version of jQuery is loaded?

// My original 'goto' means to get the version
$.fn.jquery

// Another *similar* option
$().jQuery

// If there is concern that there may be multiple implementations of `$` then:
jQuery.fn.jquery

Recently I have had issues using $.fn.jquery/$().jQuery on a few sites so I wanted to note a third simple command to pull the jQuery version.

If you get back a version number -- usually as a string -- then jQuery is loaded and that is what version you're working with. If not loaded then you should get back undefined or maybe even an error.

Pretty old question and I've seen a few people that have already mentioned my answer in comments. However, I find that sometimes great answers that are left as comments can go unnoticed; especially when there are a lot of comments to an answer you may find yourself digging through piles of them looking for a gem. Hopefully this helps someone out!

Angular window resize event

Assuming that < 600px means mobile to you, you can use this observable and subscribe to it:

First we need the current window size. So we create an observable which only emits a single value: the current window size.

initial$ = Observable.of(window.innerWidth > 599 ? false : true);

Then we need to create another observable, so that we know when the window size was changed. For this we can use the "fromEvent" operator. To learn more about rxjs`s operators please visit: rxjs

resize$ = Observable.fromEvent(window, 'resize').map((event: any) => {
  return event.target.innerWidth > 599 ? false : true;
 });

Merg these two streams to receive our observable:

mobile$ = Observable.merge(this.resize$, this.initial$).distinctUntilChanged();

Now you can subscribe to it like this:

mobile$.subscribe((event) => { console.log(event); });

Remember to unsubscribe :)

How to catch an Exception from a thread

Did you play around with setDefaultUncaughtExceptionHandler() and the alike methods of the Thread class? From the API: "By setting the default uncaught exception handler, an application can change the way in which uncaught exceptions are handled (such as logging to a specific device, or file) for those threads that would already accept whatever "default" behavior the system provided."

You might find the answer to your problem there... good luck! :-)

Spacing between elements

If you want vertical spacing between elements, use a margin.

Don't add extra elements if you don't need to.

Remove all occurrences of char from string

If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.

StringUtils.remove("TextX Xto modifyX", 'X');

How do I pass a variable to the layout using Laravel' Blade templating?

Simplest way to solve:

view()->share('title', 'My Title Here');

Or using view Facade:

use View;

...

View::share('title', 'My Title Here');

Is there a command line command for verifying what version of .NET is installed

you can check installed c# compilers and the printed version of the .net:

@echo off

for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do (
    set "l="
    for /f "skip=1 tokens=2 delims=k" %%$ in ('"%%# #"') do (
        if not defined l (
            echo Installed: %%$
            set l=%%$
        )
    )
)

echo latest installed .NET %l%

the csc.exe does not have a -version switch but it prints the .net version in its logo. You can also try with msbuild.exe but .net framework 1.* does not have msbuild.

Creating an Array from a Range in VBA

Using Value2 gives a performance benefit. As per Charles Williams blog

Range.Value2 works the same way as Range.Value, except that it does not check the cell format and convert to Date or Currency. And thats probably why its faster than .Value when retrieving numbers.

So

DirArray = [a1:a5].Value2

Bonus Reading

  • Range.Value: Returns or sets a Variant value that represents the value of the specified range.
  • Range.Value2: The only difference between this property and the Value property is that the Value2 property doesn't use the Currency and Date data types.

ImageView in circular through xml

The above methods don't seem to work if you're using the src attribute. What I did is to put two image views inside a frame layout one above another like this:

<FrameLayout android:id="@+id/frame"
             android:layout_width="40dp"
             android:layout_height="40dp">

    <ImageView android:id="@+id/pic"
               android:layout_width="40dp"
               android:layout_height="40dp"
               android:src="@drawable/my_picture" />

    <ImageView android:id="@+id/circle_crop"
               android:layout_width="40dp"
               android:layout_height="40dp"
               android:src="@drawable/circle_crop" />

</FrameLayout>

Simply put a circular_crop.png in your drawable folder which is in the shape of your image dimensions (a square in my case) with a white background and a transparent circle in the center. You can use this image if you have want a square imageview.

Round image

Just download the picture above.

Git: Installing Git in PATH with GitHub client for Windows

Git’s executable is actually located in: C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin\git.exe

Now that we have located the executable all we have to do is add it to our PATH:

  • Right-Click on My Computer
  • Click Advanced System Settings
  • Click Environment Variables
  • Then under System Variables look for the path variable and click edit
  • Add the path to git’s bin and cmd at the end of the string like this:

;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\bin;C:\Users\<user>\AppData\Local\GitHub\PortableGit_<guid>\cmd

What is class="mb-0" in Bootstrap 4?

Bootstrap has a wide range of responsive margin and padding utility classes. They work for all breakpoints:

xs (<=576px), sm (>=576px), md (>=768px), lg (>=992px) or xl (>=1200px))

The classes are used in the format:

{property}{sides}-{size} for xs & {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

m - sets margin

p - sets padding


t - sets margin-top or padding-top

b - sets margin-bottom or padding-bottom

l - sets margin-left or padding-left

r - sets margin-right or padding-right

x - sets both padding-left and padding-right or margin-left and margin-right

y - sets both padding-top and padding-bottom or margin-top and margin-bottom

blank - sets a margin or padding on all 4 sides of the element


0 - sets margin or padding to 0

1 - sets margin or padding to .25rem (4px if font-size is 16px)

2 - sets margin or padding to .5rem (8px if font-size is 16px)

3 - sets margin or padding to 1rem (16px if font-size is 16px)

4 - sets margin or padding to 1.5rem (24px if font-size is 16px)

5 - sets margin or padding to 3rem (48px if font-size is 16px)

auto - sets margin to auto

See more at Bootstrap 4.5 - Spacing

Read more in w3schools

PHP Function with Optional Parameters

You can just set the default value to null.

<?php
function functionName($value, $value2 = null) {
// do stuff
}

How to increase the timeout period of web service in asp.net?

1 - You can set a timeout in your application :

var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite

It is in milliseconds.

2 - Also you can increase timeout value in httpruntime tag in web/app.config :

<configuration>
     <system.web>
          <httpRuntime executionTimeout="<<**seconds**>>" />
          ...
     </system.web>
</configuration>

For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source

Programmatically Check an Item in Checkboxlist where text is equal to what I want

All Credit to @Jim Scott -- just added one touch. (ASP.NET 4.5 & C#)

Refractoring this a little more... if you pass the CheckBoxList as an object to the method, you can reuse it for any CheckBoxList. Also you can use either the Text or the Value.

private void SelectCheckBoxList(string valueToSelect, CheckBoxList lst)
{
    ListItem listItem = lst.Items.FindByValue(valueToSelect);
    //ListItem listItem = lst.Items.FindByText(valueToSelect);
    if (listItem != null) listItem.Selected = true;
}

//How to call it -- in this case from a SQLDataReader and "chkRP" is my CheckBoxList`

SelectCheckBoxList(dr["kRPId"].ToString(), chkRP);`

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

Exec sp_configure 'show advanced options', 1;
RECONFIGURE;
GO

Exec sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1; 
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1;
GO

Insert into OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0','Data Source=C:\upload_test.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]
SELECT ColumnNames FROM Your_table -- Sheet Should be already Present along with headers

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 0;
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 0;
GO

Exec sp_configure 'Ad Hoc Distributed Queries', 0;
RECONFIGURE;
GO

Exec sp_configure 'show advanced options', 0
RECONFIGURE;
GO

Search and replace a line in a file in Python

A more pythonic way would be to use context managers like the code below:

from tempfile import mkstemp
from shutil import move
from os import remove

def replace(source_file_path, pattern, substring):
    fh, target_file_path = mkstemp()
    with open(target_file_path, 'w') as target_file:
        with open(source_file_path, 'r') as source_file:
            for line in source_file:
                target_file.write(line.replace(pattern, substring))
    remove(source_file_path)
    move(target_file_path, source_file_path)

You can find the full snippet here.

Is not an enclosing class Java

As stated in the docs:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Automated testing for REST Api

API test automation, up to once per minute, is a service available through theRightAPI. You create your test scenarios, and execute them. Once those tests do what you expect them to, you can then schedule them. Tests can be 'chained' together for scenarios that require authentication. For example, you can have a test that make an OAuth request to Twitter, and creates a shared token that can then be used by any other test. Tests can also have validation criteria attached to ensure http status codes, or even detailed inspection of the responses using javascript or schema validation. Once tests are scheduled, you can then have alerts notify you as soon as a particular test fails validation, or is behaving out of established ranges for response time or response size.

Avoiding "resource is out of sync with the filesystem"

If this occurs trying to delete a folder (on *nix) and Refresh does not help, open a terminal and look for a symlink below the folder you are trying to delete and remove this manually. This solved my issues.

Split an NSString to access one particular piece

NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];

Update 7/3/2018:

Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:

let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]

Although note that it gives you an array of Substring. If you need to convert these back to ordinary strings, use map

let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]

or

let firstBit = String(substrings[0])

Uninstall Eclipse under OSX?

Under Lion I deleted the following files and folders:

  • eclipse in /Applications (obviously)

  • .eclipse in ~

  • .eclipse_keyring in ~

  • org.eclipse.eclipse in ~/Library/Caches

  • org.eclipse.eclipse.savedState in ~/Library/Saved Application State/

Some of them are hidden so you should delete them via Terminal.

Are list-comprehensions and functional functions faster than "for loops"?

You ask specifically about map(), filter() and reduce(), but I assume you want to know about functional programming in general. Having tested this myself on the problem of computing distances between all points within a set of points, functional programming (using the starmap function from the built-in itertools module) turned out to be slightly slower than for-loops (taking 1.25 times as long, in fact). Here is the sample code I used:

import itertools, time, math, random

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

point_set = (Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3))
n_points = 100
pick_val = lambda : 10 * random.random() - 5
large_set = [Point(pick_val(), pick_val()) for _ in range(n_points)]
    # the distance function
f_dist = lambda x0, x1, y0, y1: math.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2)
    # go through each point, get its distance from all remaining points 
f_pos = lambda p1, p2: (p1.x, p2.x, p1.y, p2.y)

extract_dists = lambda x: itertools.starmap(f_dist, 
                          itertools.starmap(f_pos, 
                          itertools.combinations(x, 2)))

print('Distances:', list(extract_dists(point_set)))

t0_f = time.time()
list(extract_dists(large_set))
dt_f = time.time() - t0_f

Is the functional version faster than the procedural version?

def extract_dists_procedural(pts):
    n_pts = len(pts)
    l = []    
    for k_p1 in range(n_pts - 1):
        for k_p2 in range(k_p1, n_pts):
            l.append((pts[k_p1].x - pts[k_p2].x) ** 2 +
                     (pts[k_p1].y - pts[k_p2].y) ** 2)
    return l

t0_p = time.time()
list(extract_dists_procedural(large_set)) 
    # using list() on the assumption that
    # it eats up as much time as in the functional version

dt_p = time.time() - t0_p

f_vs_p = dt_p / dt_f
if f_vs_p >= 1.0:
    print('Time benefit of functional progamming:', f_vs_p, 
          'times as fast for', n_points, 'points')
else:
    print('Time penalty of functional programming:', 1 / f_vs_p, 
          'times as slow for', n_points, 'points')

How can I fill out a Python string with spaces?

Use Python 2.7's mini formatting for strings:

'{0: <8}'.format('123')

This left aligns, and pads to 8 characters with the ' ' character.

How to draw border around a UILabel?

Using an NSAttributedString string for your labels attributedText is probably your best bet. Check out this example.

Proper way to restrict text input values (e.g. only numbers)

<input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57" ondragstart="return false;" ondrop="return false;"> 

Input filed only accept numbers, But it's temporary fix only.

Escape dot in a regex range

Because the dot is inside character class (square brackets []).

Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):

Any character except ^-]\ add that character to the possible matches for the character class.

Remove part of a string

You can use a built-in for this, strsplit:

> s = "TGAS_1121"
> s1 = unlist(strsplit(s, split='_', fixed=TRUE))[2]
> s1    
 [1] "1121"

strsplit returns both pieces of the string parsed on the split parameter as a list. That's probably not what you want, so wrap the call in unlist, then index that array so that only the second of the two elements in the vector are returned.

Finally, the fixed parameter should be set to TRUE to indicate that the split parameter is not a regular expression, but a literal matching character.

How can I get onclick event on webview in android?

Thats because its tied to the web view not the button. I had the same problem after implementing. The button had no affect but the page in the web view did.

How to sort an array of ints using a custom comparator?

You don't need external library:

Integer[] input = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(input, (a, b) -> b - a); // reverse order
return Arrays.stream(input).mapToInt(Integer::intValue).toArray();

error::make_unique is not a member of ‘std’

1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

How to remove a branch locally?

As far I can understand the original problem, you added commits to local master by mistake and did not push that changes yet. Now you want to cancel your changes and hope to delete your local changes and to create a new master branch from the remote one.

You can just reset your changes and reload master from remote server:

git reset --hard origin/master

Count records for every month in a year

select count(*) 
from table_emp 
 where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'

How to list the tables in a SQLite database file that was opened with ATTACH?

The easiest way to do this is to open the database directly and use the .dump command, rather than attaching it after invoking the SQLite 3 shell tool.

So... (assume your OS command line prompt is $) instead of $sqlite3:

sqlite3> ATTACH database.sqlite as "attached"

From your OS command line, open the database directly:

$sqlite3 database.sqlite
sqlite3> .dump

How to create a new figure in MATLAB?

The other thing to be careful about, is to use the clf (clear figure) command when you are starting a fresh plot. Otherwise you may be plotting on a pre-existing figure (not possible with the figure command by itself, but if you do figure(2) there may already be a figure #2), with more than one axis, or an axis that is placed kinda funny. Use clf to ensure that you're starting from scratch:

figure(N);
clf;
plot(something);
...

Regex to match only uppercase "words" with some exceptions

Maybe you can run this regex first to see if the line is all caps:

^[A-Z \d\W]+$

That will match only if it's a line like THING P1 MUST CONNECT TO X2.

Otherwise, you should be able to pull out the individual uppercase phrases with this:

[A-Z][A-Z\d]+

That should match "P1" and "J236" in The thing P1 must connect to the J236 thing in the Foo position.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I suggest you run:

$ brew update && brew upgrade

Until couple of minutes ago I had this problem, too. Because I have an up to date PHP version, I solved it with:

$ brew reinstall php55

Hope that helps.

shift a std_logic_vector of n bit to right or left

Personally, I think the concatenation is the better solution. The generic implementation would be

entity shifter is
    generic (
        REGSIZE  : integer := 8);
    port(
        clk      : in  str_logic;
        Data_in  : in  std_logic;
        Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;

architecture bhv of shifter is
    signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
    process (clk) begin
        if rising_edge(clk) then
            shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
        end if;
    end process;
end bhv;
Data_out <= shift_reg;

Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.

Strange "java.lang.NoClassDefFoundError" in Eclipse

I had a similar problem and it had to do with the libraries referenced by the java build path; I was referencing libraries that didn't exist anymore when I did an update. When I removed these references, by project started running again.

The libraries are listed under the Java Build Path in the project properties window.

Hope this helps.

How can I see an the output of my C programs using Dev-C++?

i think you should link your project in console mode

just press Ctrl+h and in General tab select console.

how to zip a folder itself using java

I found this solution worked perfectly fine for me. Doesn't require any third party apis

'test' is actually a folder will lots of file inside.

String folderPath= "C:\Users\Desktop\test";
String zipPath = "C:\Users\Desktop\test1.zip";

private boolean zipDirectory(String folderPath, String zipPath) throws IOException{

        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        ZipOutputStream zos = null;

        try{
            zos = new ZipOutputStream(new FileOutputStream(zipPath));
            updateSourceFolder(new File(folderPath));

            if (sourceFolder == null) {
                zos.close();
                return false;
            }
            generateFileAndFolderList(new File(folderPath));

            for (String unzippedFile: fileList) {
                System.out.println(sourceFolder + unzippedFile);

                ZipEntry entry = new ZipEntry(unzippedFile);
                zos.putNextEntry(entry);

                if ((unzippedFile.substring(unzippedFile.length()-1)).equals(File.separator))
                    continue;
                try{
                    fis = new FileInputStream(sourceFolder + unzippedFile);
                    int len=0;
                    while ((len = fis.read(buffer))>0) {
                        zos.write(buffer,0,len);
                    }
                } catch(IOException e) {
                    return false;
                } finally {
                    if (fis != null)
                        fis.close();
                }
            }
            zos.closeEntry();
        } catch(IOException e) {
            return false;
        } finally {
            zos.close();
            fileList = null;
            sourceFolder = null;
        }
        return true;
    }

    private void generateFileAndFolderList(File node) {
        if (node.isFile()) {
            fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
        }
        if (node.isDirectory()) {
            String dir = node.getAbsoluteFile().toString();
            fileList.add(dir.substring(sourceFolder.length(), dir.length()) + File.separator);

            String[] subNode = node.list();
            for (String fileOrFolderName : subNode) {
                generateFileAndFolderList(new File(node, fileOrFolderName));
            }
        }
    }

    private void updateSourceFolder(File node) {
        if (node.isFile() || node.isDirectory()) {
            String sf = node.getAbsoluteFile().toString();
            sourceFolder = sf.substring(0, (sf.lastIndexOf("/") > 0 ? sf.lastIndexOf("/") : sf.lastIndexOf("\\")));
            sourceFolder += File.separator;
        } else
            sourceFolder = null;
    }

    private String generateZipEntry(String file) {
        return file.substring(sourceFolder.length(), file.length());
    }

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

Convert IEnumerable to DataTable

I've written a library to handle this for me. It's called DataTableProxy and is available as a NuGet package. Code and documentation is on Github

What is the problem with shadowing names defined in outer scopes?

There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data argument as yadda, but miss one of the places it is used in the function's body... Now data refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError if you didn't have a global name data.

Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo.

Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.

None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.

Loading an image to a <img> from <input file>

_x000D_
_x000D_
$('document').ready(function () {
    $("#imgload").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#imgshow').attr('src', e.target.result);
            }
            reader.readAsDataURL(this.files[0]);
        }
    });
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imgload" >
<img src="#" id="imgshow" align="left">
_x000D_
_x000D_
_x000D_

That works for me in jQuery.

How to match "anything up until this sequence of characters" in a regular expression?

As @Jared Ng and @Issun pointed out, the key to solve this kind of RegEx like "matching everything up to a certain word or substring" or "matching everything after a certain word or substring" is called "lookaround" zero-length assertions. Read more about them here.

In your particular case, it can be solved by a positive look ahead: .+?(?=abc)

A picture is worth a thousand words. See the detail explanation in the screenshot.

Regex101 Screenshot

Changing password with Oracle SQL Developer

The built-in reset password option may not work for user. In this case the password can be reset using following SQL statement:

ALTER user "user" identified by "NewPassword" replace "OldPassword";

Returning JSON object as response in Spring Boot

More correct create DTO for API queries, for example entityDTO:

  1. Default response OK with list of entities:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public List<EntityDto> getAll() {
    return entityService.getAllEntities();
}

But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:

@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getOneParameterMap() {
    return ResponseEntity.status(HttpStatus.CREATED).body(
            Collections.singletonMap("key", "value"));
}
  1. And if you need return map of some parameters(since Java 9):
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getSomeParameters() {
    return ResponseEntity.status(HttpStatus.OK).body(Map.of(
            "key-1", "value-1",
            "key-2", "value-2",
            "key-3", "value-3"));
}

Simple http post example in Objective-C?

Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.

//POST DATA
NSString *theBody = [NSString stringWithFormat:@"parameter=%@",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = @"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:@"%@/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:@"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(@"Trying to call ws %@",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"Download Error:%@",error.description);
    }
    if (data) {

        //
        // THIS CODE IS FOR PRINTING THE RESPONSE
        //
        NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
        NSLog(@"Response:%@",returnString);

        //PARSE JSON RESPONSE
        NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:NULL];

        if ( json_response ) {
            if ( [json_response isKindOfClass:[NSDictionary class]] ) {
                // do dictionary things
                for ( NSString *key in [json_response allKeys] ) {
                    NSLog(@"%@: %@", key, json_response[key]);
                }
            }
            else if ( [json_response isKindOfClass:[NSArray class]] ) {
                NSLog(@"%@",json_response);
            }
        }
        else {
            NSLog(@"Error serializing JSON: %@", error);
            NSLog(@"RAW RESPONSE: %@",data);
            NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
            NSLog(@"Response:%@",returnString2);
        }
    }
}];

Hope this helps!

How is Java platform-independent when it needs a JVM to run?

Doesn't independent means that Java code should be able to run on any machine and would need no special software to be installed (JVM in this case has to be present in the machine)?

With Java, you can compile source code on Windows and the compiled code (bytecode to be precise) can be executed (interpreted) on any platform running a JVM. So yes you need a JVM but the JVM can run any compiled code, the compiled code is platform independent.

In other words, you have both portability of source code and portability of compiled code.

Like, for example, we need to have Turbo C Compiler in order to compile C/C++ source code and then execute it.. The machine has to have the C compiler.

The machine doesn't have to have a C compiler, the machine has to use a platform specific binary. With C or C++, the compiled code is specific to each architecture, it is platform independent.

In other words, with C / C++ you have portability of source code (with some discipline) but not portability of compiled code: you need to recompile for each architecture into platform specific binaries.

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

Java: How to convert List to Map

With , you'll be able to do this in one line using streams, and the Collectors class.

Map<String, Item> map = 
    list.stream().collect(Collectors.toMap(Item::getKey, item -> item));

Short demo:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test{
    public static void main (String [] args){
        List<Item> list = IntStream.rangeClosed(1, 4)
                                   .mapToObj(Item::new)
                                   .collect(Collectors.toList()); //[Item [i=1], Item [i=2], Item [i=3], Item [i=4]]

        Map<String, Item> map = 
            list.stream().collect(Collectors.toMap(Item::getKey, item -> item));

        map.forEach((k, v) -> System.out.println(k + " => " + v));
    }
}
class Item {

    private final int i;

    public Item(int i){
        this.i = i;
    }

    public String getKey(){
        return "Key-"+i;
    }

    @Override
    public String toString() {
        return "Item [i=" + i + "]";
    }
}

Output:

Key-1 => Item [i=1]
Key-2 => Item [i=2]
Key-3 => Item [i=3]
Key-4 => Item [i=4]

As noted in comments, you can use Function.identity() instead of item -> item, although I find i -> i rather explicit.

And to be complete note that you can use a binary operator if your function is not bijective. For example let's consider this List and the mapping function that for an int value, compute the result of it modulo 3:

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<String, Integer> map = 
    intList.stream().collect(toMap(i -> String.valueOf(i % 3), i -> i));

When running this code, you'll get an error saying java.lang.IllegalStateException: Duplicate key 1. This is because 1 % 3 is the same as 4 % 3 and hence have the same key value given the key mapping function. In this case you can provide a merge operator.

Here's one that sum the values; (i1, i2) -> i1 + i2; that can be replaced with the method reference Integer::sum.

Map<String, Integer> map = 
    intList.stream().collect(toMap(i -> String.valueOf(i % 3), 
                                   i -> i, 
                                   Integer::sum));

which now outputs:

0 => 9 (i.e 3 + 6)
1 => 5 (i.e 1 + 4)
2 => 7 (i.e 2 + 5)

Hope it helps! :)

How to use regex in file find

Start with:

find . -name '*.log.*.zip' -a -mtime +1

You may not need a regex, try:

 find . -name '*.log.*-*-*.zip' -a -mtime +1

You will want the +1 in order to match 1, 2, 3 ...

python BeautifulSoup parsing table

Here you go:

data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
table_body = table.find('tbody')

rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele]) # Get rid of empty values

This gives you:

[ [u'1359711259', u'SRF', u'08/05/2013', u'5310 4 AVE', u'K', u'19', u'125.00', u'$'], 
  [u'7086775850', u'PAS', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'125.00', u'$'], 
  [u'7355010165', u'OMT', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'145.00', u'$'], 
  [u'4002488755', u'OMT', u'02/12/2014', u'NB 1ST AVE @ E 23RD ST', u'5', u'115.00', u'$'], 
  [u'7913806837', u'OMT', u'03/03/2014', u'5015 4th Ave', u'K', u'46', u'115.00', u'$'], 
  [u'5080015366', u'OMT', u'03/10/2014', u'EB 65TH ST @ 16TH AV E', u'7', u'50.00', u'$'], 
  [u'7208770670', u'OMT', u'04/08/2014', u'333 15th St', u'K', u'70', u'65.00', u'$'], 
  [u'$0.00\n\n\nPayment Amount:']
]

Couple of things to note:

  • The last row in the output above, the Payment Amount is not a part of the table but that is how the table is laid out. You can filter it out by checking if the length of the list is less than 7.
  • The last column of every row will have to be handled separately since it is an input text box.

Ansible - Use default if a variable is not defined

You can use Jinja's default:

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"

How to set the allowed url length for a nginx request (error code: 414, uri too large)

From: http://nginx.org/r/large_client_header_buffers

Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

Console logging for react?

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

_x000D_
_x000D_
const Console = prop => (
  console[Object.keys(prop)[0]](...Object.values(prop))
  ,null // ? React components must return something 
)

// Some component with JSX and a logger inside
const App = () => 
  <div>
    <p>imagine this is some component</p>
    <Console log='foo' />
    <p>imagine another component</p>
    <Console warn='bar' />
  </div>

// Render 
ReactDOM.render(
  <App />,
  document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
_x000D_
_x000D_

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

"Could not get any response" response when using postman with subdomain

Unchecking proxy and SSL Certificate Verification didn't work for me.

Unsetting PROXY environment variables did the trick.

export http_proxy=
export ftp_proxy=
export https_proxy=

Change to the directory where Postman is installed and then:

./Postman

Creating an R dataframe row-by-row

Depending on the format of your new row, you might use tibble::add_row if your new row is simple and can specified in "value-pairs". Or you could use dplyr::bind_rows, "an efficient implementation of the common pattern of do.call(rbind, dfs)".

Access index of the parent ng-repeat from child ng-repeat

Take a look at my answer to a similar question.
By aliasing $index we do not have to write crazy stuff like $parent.$parent.$index.


Way more elegant solution whan $parent.$index is using ng-init:

<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
    <li  class="section_title {{section.active}}" >
        {{section.name}}
    </li>
    <ul>
        <li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
            {{tutorial.name}}
        </li>
    </ul>
</ul>

Plunker: http://plnkr.co/edit/knwGEnOsAWLhLieKVItS?p=info

UIView Hide/Show with animation

You can do it VERY easily using Animatics library:

//To hide button:
AlphaAnimator(0) ~> button

//to show button
AlphaAnimator(1) ~> button

Accurate way to measure execution times of php scripts

You can use the microtime function for this. From the documentation:

microtime — Return current Unix timestamp with microseconds


If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {

}
$time_elapsed_secs = microtime(true) - $start;

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I found that useful, stabbing service function as sinon.stub().returns($q.when({})):

this.myService = {
   myFunction: sinon.stub().returns( $q.when( {} ) )
};

this.scope = $rootScope.$new();
this.angularStubs = {
    myService: this.myService,
    $scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );

controller:

this.someMethod = function(someObj) {
   myService.myFunction( someObj ).then( function() {
        someObj.loaded = 'bla-bla';
   }, function() {
        // failure
   } );   
};

and test

const obj = {
    field: 'value'
};
this.ctrl.someMethod( obj );

this.scope.$digest();

expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );

Conditional Count on a field

I would need to display the jobid, jobname and 5 fields called Priority1, Priority2, Priority3, Priority4. Priority5.

Something's wrong with your query design. You're showing a specific job in each row as well, and so you'll either have a situation where ever row has four priority columns with a '0' and one priority column with a '1' (the priority for that job) or you'll end up repeating the count for all priorities on every row.

What do you really want to show here?

What is the instanceof operator in JavaScript?

I think it's worth noting that instanceof is defined by the use of the "new" keyword when declaring the object. In the example from JonH;

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

What he didn't mention is this;

var color1 = String("green");
color1 instanceof String; // returns false

Specifying "new" actually copied the end state of the String constructor function into the color1 var, rather than just setting it to the return value. I think this better shows what the new keyword does;

function Test(name){
    this.test = function(){
        return 'This will only work through the "new" keyword.';
    }
    return name;
}

var test = new Test('test');
test.test(); // returns 'This will only work through the "new" keyword.'
test // returns the instance object of the Test() function.

var test = Test('test');
test.test(); // throws TypeError: Object #<Test> has no method 'test'
test // returns 'test'

Using "new" assigns the value of "this" inside the function to the declared var, while not using it assigns the return value instead.

Redirect Windows cmd stdout and stderr to a single file

There is, however, no guarantee that the output of SDTOUT and STDERR are interweaved line-by-line in timely order, using the POSIX redirect merge syntax.

If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.

A dedicated console output logger (I.e. the "StdOut/StdErr Logger" by 'LoRd MuldeR') may be more reliable for such a task.

See: MuldeR's OpenSource Projects

Storing Python dictionaries

Minimal example, writing directly to a file:

import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))

or safely opening / closing:

import json
with open(filename, 'wb') as outfile:
    json.dump(data, outfile)
with open(filename) as infile:
    data = json.load(infile)

If you want to save it in a string instead of a file:

import json
json_str = json.dumps(data)
data = json.loads(json_str)

Using NSPredicate to filter an NSArray based on NSDictionary keys

It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT

NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];    
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];

Filtered in this case contains the dictionary.

(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)

Spring: How to get parameters from POST body?

You can get entire post body into a POJO. Following is something similar

@RequestMapping(
    value = { "/api/pojo/edit" }, 
    method = RequestMethod.POST, 
    produces = "application/json", 
    consumes = ["application/json"])
@ResponseBody
public Boolean editWinner( @RequestBody Pojo pojo) { 

Where each field in Pojo (Including getter/setters) should match the Json request object that the controller receives..

Firebase onMessageReceived not called when app in background

By default the Launcher Activity in you app will be launched when your app is in background and you click the notification, if you have any data part with your notifcation you can handle it in the same activity as follows,

if(getIntent().getExtras()! = null){
  //do your stuff
}else{
  //do that you normally do
}

Styling Password Fields in CSS

The problem is that (as of 2016), for the password field, Firefox and Internet Explorer use the character "Black Circle" (?), which uses the Unicode code point 25CF, but Chrome uses the character "Bullet" (•), which uses the Unicode code point 2022.

As you can see, even in the StackOverflow font the two characters have different sizes.

The font you're using, "Lucida Sans Unicode", has an even greater disparity between the sizes of these two characters, leading to you noticing the difference.

The simple solution is to use a font in which both characters have similar sizes.

The fix could thus be to use a default font of the browser, which should render the characters in the password field just fine:

input[type="password"] {
    font-family: caption;
}

addID in jQuery?

do you mean a method?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

android on Text Change Listener

var filenameText = findViewById(R.id.filename) as EditText
filenameText.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        filename = filenameText.text.toString()
        Log.i("FileName: ", filename)
    }
    
    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})

Creating a file name as a timestamp in a batch job

CP source.log %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.log

But it's locale dependent. I'm not sure if %DATE% is localized, or depends on the format specified for the short date in Windows.

Here is a locale-independent way to extract the current date from this answer, but it depends on WMIC and FOR /F:

FOR /F %%A IN ('WMIC OS GET LocalDateTime ^| FINDSTR \.') DO @SET B=%%A
CP source.log %B:~0,4%-%B:~4,2%-%B:~6,2%.log

Change visibility of ASP.NET label with JavaScript

If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:

<asp:Label runat="server" id="Label1" style="display: none;" />

Then, you could make it visible on the client side with:

document.getElementById('Label1').style.display = 'inherit';

You could make it hidden again with:

document.getElementById('Label1').style.display = 'none';

Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.

Can pm2 run an 'npm start' script

To use npm run

pm2 start npm --name "{app_name}" -- run {script_name}

Center form submit buttons HTML / CSS

I'm assuming that the buttons are supposed to be next to each other on the same line, they should not each be centered using the 'auto' margin, but placed inside a div with a defined width that has a margin '0 auto':

CSS:

#centerbuttons{
   width:250px; 
   margin:0 auto;
}       

HTML (after removing the margin properties from your buttons' CSS):

<div id="centerbuttons">
     <input value="Search" title="Search" type="submit"> 
     <input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit">
</div>

Android Studio how to run gradle sync manually?

WARNING: --recompile-scripts command has been deprecated since gradle's version 5.0. To check your gradle version, run gradle -v.

./gradlew --recompile-scripts

it will do a sync without building anything.


Alternatively, with command line in your root project

./gradlew build

It will sync and build your app, and take longer than just a Gradle sync

To see all available gradle task, use ./gradlew tasks

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

Arrow functions => best ES6 feature so far. They are a tremendously powerful addition to ES6, that I use constantly.

Wait, you can't use arrow function everywhere in your code, its not going to work in all cases like this where arrow functions are not usable. Without a doubt, the arrow function is a great addition it brings code simplicity.

But you can’t use an arrow function when a dynamic context is required: defining methods, create objects with constructors, get the target from this when handling events.

Arrow functions should NOT be used because:

  1. They do not have this

    It uses “lexical scoping” to figure out what the value of “this” should be. In simple word lexical scoping it uses “this” from the inside the function’s body.

  2. They do not have arguments

    Arrow functions don’t have an arguments object. But the same functionality can be achieved using rest parameters.

    let sum = (...args) => args.reduce((x, y) => x + y, 0) sum(3, 3, 1) // output - 7 `

  3. They cannot be used with new

    Arrow functions can't be construtors because they do not have a prototype property.

When to use arrow function and when not:

  1. Don't use to add function as a property in object literal because we can not access this.
  2. Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map, reduce, or forEach.
  3. Use function declarations for functions you’d call by name (because they’re hoisted).
  4. Use arrow functions for callbacks (because they tend to be terser).

Windows Scheduled task succeeds but returns result 0x1

This answer was originally edited into the question by the asker.


The problem was that the batch file WAS throwing a silent error. The final POPD was doing no work and was incorrectly called with no opening PUSHD.

Broken code:

CD /D "C:\Program Files (x86)\Olim, LLC\Collybus DR Upload" CALL CollybusUpload.exe POPD

Correct code:

PUSHD "C:\Program Files (x86)\Olim, LLC\Collybus DR Upload" CALL CollybusUpload.exe POPD

asp.net Button OnClick event not firing

Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button even properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button. this should work

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

Hide all warnings in ipython

I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
HTML('''<script>
code_show_err=false; 
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
} 
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);