Programs & Examples On #Http head

Checking if a website is up via Python

Hi this class can do speed and up test for your web page with this class:

 from urllib.request import urlopen
 from socket import socket
 import time


 def tcp_test(server_info):
     cpos = server_info.find(':')
     try:
         sock = socket()
         sock.connect((server_info[:cpos], int(server_info[cpos+1:])))
         sock.close
         return True
     except Exception as e:
         return False


 def http_test(server_info):
     try:
         # TODO : we can use this data after to find sub urls up or down    results
         startTime = time.time()
         data = urlopen(server_info).read()
         endTime = time.time()
         speed = endTime - startTime
         return {'status' : 'up', 'speed' : str(speed)}
     except Exception as e:
         return {'status' : 'down', 'speed' : str(-1)}


 def server_test(test_type, server_info):
     if test_type.lower() == 'tcp':
         return tcp_test(server_info)
     elif test_type.lower() == 'http':
         return http_test(server_info)

"The Controls collection cannot be modified because the control contains code blocks"

you can do the same functionality if you are using script manager in your page. you have to just register the script like this

<asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"   EnablePageMethods="true">  
<Scripts>
      <asp:ScriptReference Path="~/Styles/javascript/jquery.min.js" />
</Scripts>
</asp:ScriptManager>

Using grep to search for hex strings in a file

We tried several things before arriving at an acceptable solution:

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....


root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....

Then found we could get usable results with

xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd

Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.

xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003  @.........S.....
--------------------^^

So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).

The final result seems to be

xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex

0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF  ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03  .$.q............
--------------------------------------------^^

What is SYSNAME data type in SQL Server?

sysname is a built in datatype limited to 128 Unicode characters that, IIRC, is used primarily to store object names when creating scripts. Its value cannot be NULL

It is basically the same as using nvarchar(128) NOT NULL

EDIT

As mentioned by @Jim in the comments, I don't think there is really a business case where you would use sysname to be honest. It is mainly used by Microsoft when building the internal sys tables and stored procedures etc within SQL Server.

For example, by executing Exec sp_help 'sys.tables' you will see that the column name is defined as sysname this is because the value of this is actually an object in itself (a table)

I would worry too much about it.

It's also worth noting that for those people still using SQL Server 6.5 and lower (are there still people using it?) the built in type of sysname is the equivalent of varchar(30)

Documentation

sysname is defined with the documentation for nchar and nvarchar, in the remarks section:

sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128), except that it is not nullable. sysname is used to reference database object names.

To clarify the above remarks, by default sysname is defined as NOT NULL it is certainly possible to define it as nullable. It is also important to note that the exact definition can vary between instances of SQL Server.

Using Special Data Types

The sysname data type is used for table columns, variables, and stored procedure parameters that store object names. The exact definition of sysname is related to the rules for identifiers. Therefore, it can vary between instances of SQL Server. sysname is functionally the same as nvarchar(128) except that, by default, sysname is NOT NULL. In earlier versions of SQL Server, sysname is defined as varchar(30).

Some further information about sysname allowing or disallowing NULL values can be found here https://stackoverflow.com/a/52290792/300863

Just because it is the default (to be NOT NULL) does not guarantee that it will be!

insert multiple rows into DB2 database

other method

INSERT INTO tableName (col1, col2, col3, col4, col5)
select * from table(                        
                    values                                      
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5)    
                    ) tmp

PowerShell Connect to FTP server and get files

For retrieving files /folder from FTP via powerShell I wrote some functions, you can get even hidden stuff from FTP.

Example for getting all files which are not hidden in a specific folder:

Get-FtpChildItem -ftpFolderPath "ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -hidden $false -File

Example for getting all folders(also hidden) in a specific folder:

Get-FtpChildItem -ftpFolderPath"ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -Directory

You can just copy the functions from the following module without needing and 3rd library installing: https://github.com/AstralisSomnium/PowerShell-No-Library-Just-Functions/blob/master/FTPModule.ps1

WCF error: The caller was not authenticated by the service

if needed to specify domain(which authecticates username and password that client uses) in webconfig you can put this in system.serviceModel services service section:

<identity>          
<servicePrincipalName value="example.com" />
</identity>

and in client specify domain and username and password:

 client.ClientCredentials.Windows.ClientCredential.Domain = "example.com";
 client.ClientCredentials.Windows.ClientCredential.UserName = "UserName ";
 client.ClientCredentials.Windows.ClientCredential.Password = "Password";

How to find column names for all tables in all databases in SQL Server

I just realized that the following query would give you all column names from the table in your database (SQL SERVER 2017)

SELECT DISTINCT NAME FROM SYSCOLUMNS 
ORDER BY Name 

OR SIMPLY

SELECT Name FROM SYSCOLUMNS

If you do not care about duplicated names.

Another option is SELECT Column names from INFORMATION_SCHEMA

SELECT DISTINCT column_name  FROM INFORMATION_SCHEMA.COLUMNS
ORDER BY column_name

It is usually more interesting to have the TableName as well as the ColumnName ant the query below does just that.

SELECT 
   Object_Name(Id) As TableName,
   Name As ColumnName
FROM SysColumns

And the results would look like

  TableName    ColumnName
0    Table1    column11
1    Table1    Column12
2    Table2    Column21
3    Table2    Column22
4    Table3    Column23

Passing an array by reference

It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

E.g. int &myArray[100] // array of references

So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

E.g int (&myArray)[100] // reference of an array of 100 ints

Merge some list items in a Python List

my telepathic abilities are not particularly great, but here is what I think you want:

def merge(list_of_strings, indices):
    list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
    list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
    return list_of_strings

I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.

How can I get href links from HTML using Python?

My answer probably sucks compared to the real gurus out there, but using some simple math, string slicing, find and urllib, this little script will create a list containing link elements. I test google and my output seems right. Hope it helps!

import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
  curpos = test.find("href")
  if curpos >= 0:
    testlen = len(test)
    test = test[curpos:testlen]
    curpos = test.find('"')
    testlen = len(test)
    test = test[curpos+1:testlen]
    curpos = test.find('"')
    needle = test[0:curpos]
    if needle.startswith("http" or "www"):
        needlestack.append(needle)
  else:
    sane = 1
for item in needlestack:
  print item

Extracting text from a PDF file using PDFMiner in python?

Full disclosure, I am one of the maintainers of pdfminer.six.

Nowadays, there are multiple api's to extract text from a PDF, depending on your needs. Behind the scenes, all of these api's use the same logic for parsing and analyzing the layout.

(All the examples assume your PDF file is called example.pdf)

Commandline

If you want to extract text just once you can use the commandline tool pdf2txt.py:

$ pdf2txt.py example.pdf

High-level api

If you want to extract text with Python, you can use the high-level api. This approach is the go-to solution if you want to extract text programmatically from many PDF's.

from pdfminer.high_level import extract_text

text = extract_text('example.pdf')

Composable api

There is also a composable api that gives a lot of flexibility in handling the resulting objects. For example, you can implement your own layout algorithm using that. This method is suggested in the other answers, but I would only recommend this when you need to customize the way pdfminer.six behaves.

from io import StringIO

from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser

output_string = StringIO()
with open('example.pdf', 'rb') as in_file:
    parser = PDFParser(in_file)
    doc = PDFDocument(parser)
    rsrcmgr = PDFResourceManager()
    device = TextConverter(rsrcmgr, output_string, laparams=LAParams())
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.create_pages(doc):
        interpreter.process_page(page)

print(output_string.getvalue())

How to dynamically add a class to manual class names?

getBadgeClasses() {
    let classes = "badge m-2 ";
    classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
    return classes;
}

<span className={this.getBadgeClasses()}>Total Count</span>

Cannot start MongoDB as a service

I ran this command:

C:\MongoDB\Server\3.4\bin>net start MongoDB

And got this message:

The service is not responding to the control function. More help is available by typing NET HELPMSG 2186.

After some trials and errors, I noticed when following the tutorial it asked me to name my file mongod.conf but the command was trying to refer to mongod.cfg.

As soon as I corrected that name and re-run the commands,

C:\MongoDB\Server\3.4\bin>sc.exe delete MongoDB
[SC] DeleteService SUCCESS

C:\MongoDB\Server\3.4\bin>sc.exe create MongoDB binPath= "\"C:\MongoDB\Server\3.4\bin\mongod.exe\" --service --config=\"C:\MongoDB\Server\3.4\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"
[SC] CreateService SUCCESS

C:\MongoDB\Server\3.4\bin>net start MongoDB
The MongoDB service is starting....
The MongoDB service was started successfully.

The service started running fine.

Why is my Button text forced to ALL CAPS on Lollipop?

I don't have idea why it is happening but there 3 trivial attempts to make:

  1. Use android:textAllCaps="false" in your layout-v21

  2. Programmatically change the transformation method of the button. mButton.setTransformationMethod(null);

  3. Check your style for Allcaps

Note: public void setAllCaps(boolean allCaps), android:textAllCaps are available from API version 14.

How to show progress dialog in Android?

        final ProgressDialog progDailog = ProgressDialog.show(Inishlog.this, contentTitle, "even geduld aub....", true);//please wait....

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Barcode_edit.setText("");
                showAlert("Product detail saved.");


            }

        };

        new Thread() {
            public void run() {
                try {
         } catch (Exception e) {

                }
                handler.sendEmptyMessage(0);
                progDailog.dismiss();
            }
        }.start();

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

What is the purpose of a plus symbol before a variable?

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.

Example (using the addMonths function in the question):

addMonths(34,1,true);
addMonths("34",1,true);

then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

How to set a ripple effect on textview or imageview on Android?

If you want the ripple to be bounded to the size of the TextView/ImageView use:

<TextView
android:background="?attr/selectableItemBackground"
android:clickable="true"/>

(I think it looks better)

JavaScript OR (||) variable assignment explanation

According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

He also suggests another use for it (quoted): "lightweight normalization of cross-browser differences"

// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;

Composer install error - requires ext_curl when it's actually enabled

For anyone who encounters this issue on Windows i couldn't find my answer on google at all. I just tried running composer require ext-curl and this worked. Alternatively add the following in your composer.json file:

"require": {
"ext-curl": "^7.3"
}

Return values from the row above to the current row

I followed BEN and Thanks and Lot for the Answer,So I used his idea to get my solution, I am posting the same hence if some one else has similar requirement, then you also can use my solution as well, My requirement was something like I want to get the sum of entire data from the first row to the last row, and I was generating the spreadsheet programmatically so don't and can't hard code the row names in sum as the data is always dynamic and number of rows are never constant. My formula was something like as follows.

=SUM(B1:INDIRECT("B"&ROW()-4))

Maven Could not resolve dependencies, artifacts could not be resolved

Looks like you are missing some Maven repos. Ask for your friend's .m2/settings.xml, and you'll probably want to update the POM to include the repositories there.

--edit: after some quick googling, try adding this to your POM:

<repository>
    <id>com.springsource.repository.bundles.release</id>
    <name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
    <url>http://repository.springsource.com/maven/bundles/release</url>
</repository>
<repository>
    <id>com.springsource.repository.bundles.external</id>
    <name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
    <url>http://repository.springsource.com/maven/bundles/external</url>
</repository>

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

Open fancybox from function

If you'd like to simply open a fancybox when a javascript function is called. Perhaps in your code flow and not as a result of a click. Here's how you do it:

function openFancybox() {
  $.fancybox({
     'autoScale': true,
     'transitionIn': 'elastic',
     'transitionOut': 'elastic',
     'speedIn': 500,
     'speedOut': 300,
     'autoDimensions': true,
     'centerOnScroll': true,
     'href' : '#contentdiv'
  });
}

This creates the box using "contentdiv" and opens it.

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

'node' is not recognized as an internal or external command

Node is missing from the SYSTEM PATH, try this in your command line

SET PATH=C:\Program Files\Nodejs;%PATH%

and then try running node

To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm

To be very clean, create a new system variable NODEJS

NODEJS="C:\Program Files\Nodejs"

Then edit the PATH in system variables and add %NODEJS%

PATH=%NODEJS%;...

How can I use "e" (Euler's number) and power operation in python 2.7

Just saying: numpy has this too. So no need to import math if you already did import numpy as np:

>>> np.exp(1)
2.718281828459045

JavaScript operator similar to SQL "like"

No there isn't, but you can check out indexOf as a starting point to developing your own, and/or look into regular expressions. It would be a good idea to familiarise yourself with the JavaScript string functions.

EDIT: This has been answered before:

Emulating SQL LIKE in JavaScript

How to clear the text of all textBoxes in the form?

private void CleanForm(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }

        if( c.Controls.Count > 0)
        {
           CleanForm(c);
        }
    }
}

When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).

Vertical Text Direction

.vertical-text {
    transform: rotate(90deg);
    transform-origin: left top 0;
    float: left;
}

Passing a String by Reference in Java?

String is immutable in java. you cannot modify/change, an existing string literal/object.

String s="Hello"; s=s+"hi";

Here the previous reference s is replaced by the new refernce s pointing to value "HelloHi".

However, for bringing mutability we have StringBuilder and StringBuffer.

StringBuilder s=new StringBuilder(); s.append("Hi");

this appends the new value "Hi" to the same refernce s. //

sql query to find the duplicate records

select distinct title, (
               select count(title) 
               from kmovies as sub 
               where sub.title=kmovies.title) as cnt 
from kmovies 
group by title 
order by cnt desc

Sort a single String in Java

Convert to array of chars ? Sort ? Convert back to String:

String s = "edcba";
char[] c = s.toCharArray();        // convert to array of chars 
java.util.Arrays.sort(c);          // sort
String newString = new String(c);  // convert back to String
System.out.println(newString);     // "abcde"

How to save a plot as image on the disk?

If you use R Studio http://rstudio.org/ there is a special menu to save you plot as any format you like and at any resolution you choose

AngularJS: How can I pass variables between controllers?

There are two ways to do this

1) Use get/set service

2) $scope.$emit('key', {data: value}); //to set the value

 $rootScope.$on('key', function (event, data) {}); // to get the value

DOUBLE vs DECIMAL in MySQL

Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2 it gives you something like 0.30000000000000004. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.

How to export SQL Server 2005 query to CSV

Yeah, there is a very simple utility in Management Studio, if you're just looking to save query results to a CSV.

Right click on the result set, the select "Save Results As". The default file type is CSV.

What is N-Tier architecture?

Martin Fowler demonstrating clearly:

Layering is one of the most common techniques that software designers use to break apart a complicated software system. You see it in machine architectures, where layers descend from a programming language with operating system calls into device drivers and CPU instruction sets, and into logic gates inside chips. Networking has FTP layered on top of TCP, which is on top of IP, which is on top of ethernet.

When thinking of a system in terms of layers, you imagine the principal subsystems in the software arranged in some form of layer cake, where each layer rests on a lower layer. In this scheme the higher layer uses various services defined by the lower layer, but the lower layer is unaware of the higher layer. Furthermore, each layer usually hides its lower layers from the layers above, so layer 4 uses the services of layer 3, which uses the services of layer 2, but layer 4 is unaware of layer 2. (Not all layering architectures are opaque like this, but most are—or rather most are mostly opaque.)

Breaking down a system into layers has a number of important benefits.

• You can understand a single layer as a coherent whole without knowing much about the other layers. You can understand how to build an FTP service on top of TCP without knowing the details of how ethernet works.

• You can substitute layers with alternative implementations of the same basic services. An FTP service can run without change over ethernet, PPP, or whatever a cable company uses.

• You minimize dependencies between layers. If the cable company changes its physical transmission system, providing they make IP work, we don’t have to alter our FTP service.

• Layers make good places for standardization. TCP and IP are standards because they define how their layers should operate.

• Once you have a layer built, you can use it for many higher-level services. Thus, TCP/IP is used by FTP, telnet, SSH, and HTTP. Otherwise, all of these higher-level protocols would have to write their own lower-level protocols. From the Library of Kyle Geoffrey Passarelli

Layering is an important technique, but there are downsides.

• Layers encapsulate some, but not all, things well. As a result you sometimes get cascading changes. The classic example of this in a layered enterprise application is adding a field that needs to display on the UI, must be in the database, and thus must be added to every layer in between.

• Extra layers can harm performance. At every layer things typically need to be transformed from one representation to another. However, the encapsulation of an underlying function often gives you efficiency gains that more than compensate. A layer that controls transactions can be optimized and will then make everything faster. But the hardest part of a layered architecture is deciding what layers to have and what the responsibility of each layer should be.

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Scroll event listener javascript

Wont the below basic approach doesn't suffice your requirements?

HTML Code having a div

<div id="mydiv" onscroll='myMethod();'>


JS will have below code

function myMethod(){ alert(1); }

Disable LESS-CSS Overwriting calc()

Here's a cross-browser less mixin for using CSS's calc with any property:

.calc(@prop; @val) {
  @{prop}: calc(~'@{val}');
  @{prop}: -moz-calc(~'@{val}');
  @{prop}: -webkit-calc(~'@{val}');
  @{prop}: -o-calc(~'@{val}');
}

Example usage:

.calc(width; "100% - 200px");

And the CSS that's output:

width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);

A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp

Detect if an element is visible with jQuery

There's no need, just use fadeToggle() on the element:

$('#testElement').fadeToggle('fast');

Here's a demo.

How do I get the object if it exists, or None if it does not exist?

You can create a generic function for this.

def get_or_none(classmodel, **kwargs):
    try:
        return classmodel.objects.get(**kwargs)
    except classmodel.DoesNotExist:
        return None

Use this like below:

go = get_or_none(Content,name="baby")

go will be None if no entry matches else will return the Content entry.

Note:It will raises exception MultipleObjectsReturned if more than one entry returned for name="baby".

You should handle it on the data model to avoid this kind of error but you may prefer to log it at run time like this:

def get_or_none(classmodel, **kwargs):
    try:
        return classmodel.objects.get(**kwargs)
    except classmodel.MultipleObjectsReturned as e:
        print('ERR====>', e)

    except classmodel.DoesNotExist:
        return None

wp-admin shows blank page, how to fix it?

Try turning on WP Debug. If this is happening due to a PHP error (which I bet that it is), you will be able to see what's going on and fix the error.

CodeIgniter - File upload required validation

I found a solution that works exactly how I want.

I changed

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

To

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

How to check if a MySQL query using the legacy API was successful?

You can use mysql_errno() for this too.

$result = mysql_query($query);

if(mysql_errno()){
    echo "MySQL error ".mysql_errno().": "
         .mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}

How to set a default entity property value with Hibernate

<property name="age" type="integer">
<column name="age" not-null="false" default="null" />
</property>

Simplest way to detect keypresses in javascript

Use event.key and modern JS!

No number codes anymore. You can use "Enter", "ArrowLeft", "r", or any key name directly, making your code far more readable.

NOTE: The old alternatives (.keyCode and .which) are Deprecated.

document.addEventListener("keypress", function onEvent(event) {
    if (event.key === "ArrowLeft") {
        // Move Left
    }
    else if (event.key === "Enter") {
        // Open Menu...
    }
});

Mozilla Docs

Supported Browsers

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

How to make MySQL table primary key auto increment with some prefix

If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.

Tables

CREATE TABLE table1_seq
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
  id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);

Now the trigger

DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
  INSERT INTO table1_seq VALUES (NULL);
  SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;

Then you just insert rows to table1

INSERT INTO Table1 (name) 
VALUES ('Jhon'), ('Mark');

And you'll have

|      ID | NAME |
------------------
| LHPL001 | Jhon |
| LHPL002 | Mark |

Here is SQLFiddle demo

mingw-w64 threads: posix vs win32

Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads

From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

I could find this solution and is working fine:

cd /Applications/Python\ 3.7/
./Install\ Certificates.command

Install python 2.6 in CentOS

Try epel

wget http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
sudo rpm -ivh epel-release-5-4.noarch.rpm
sudo yum install python26

The python executable will be available at /usr/bin/python26

mkdir -p ~/bin
ln -s /usr/bin/python26 ~/bin/python
export PATH=~/bin:$PATH # Append this to your ~/.bash_profile for persistence

Now, python command will execute python 2.6

How to compile a 64-bit application using Visual C++ 2010 Express?

Here are step by step instructions:

  1. Download and install the Windows Software Development Kit version 7.1. Visual C++ 2010 Express does not include a 64 bit compiler, but the SDK does. A link to the SDK: http://msdn.microsoft.com/en-us/windowsserver/bb980924.aspx
  2. Change your project configuration. Go to Properties of your project. On the top of the dialog box there will be a "Configuration" drop-down menu. Make sure that selects "All Configurations." There will also be a "Platform" drop-down that will read "Win32." Finally on the right there is a "Configuration Manager" button - press it. In the dialog that comes up, find your project, hit the Platform drop-down, select New, then select x64. Now change the "Active solution platform" drop-down menu to "x64." When you return to the Properties dialog box, the "Platform" drop-down should now read "x64."
  3. Finally, change your toolset. In the Properties menu of your project, under Configuration Properties | General, change Platform Toolset from "v100" to "Windows7.1SDK".

These steps have worked for me, anyway. Some more details on step 2 can be found in a reference from Microsoft that a previous poster mentioned: http://msdn.microsoft.com/en-us/library/9yb4317s.aspx.

Function to calculate distance between two coordinates

Calculate the Distance between Two Points in javascript

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

For more details refer this: Reference Link

Disable Buttons in jQuery Mobile

For link button,

Calling .button('enable') method only gives effect, but functionally don't.

But I have a trick. We could use HTML5 data- attribute to save/swap value of href and onclick.

see:

http://jsbin.com/ukewu3/74/

source code mode:

http://jsbin.com/ukewu3/74/edit

Array String Declaration

As Tr?n Si Long suggested, use

String[] mStrings = new String[title.length];

And replace string concatation with proper parenthesis.

mStrings[i] = (urlbase + (title[i].replaceAll("[^a-zA-Z]", ""))).toLowerCase() + imgSel;

Try this. If it's problem due to concatation, it will be resolved with proper brackets. Hope it helps.

Wi-Fi Direct and iOS Support

According to this thread:

The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.

How do I access the $scope variable in browser's console using AngularJS?

This requires jQuery to be installed as well, but works perfectly for a dev environment. It looks through each element to get the instances of the scopes then returns them labelled with there controller names. Its also removing any property start with a $ which is what angularjs generally uses for its configuration.

let controllers = (extensive = false) => {
            let result = {};
            $('*').each((i, e) => {
                let scope = angular.element(e).scope();
                if(Object.prototype.toString.call(scope) === '[object Object]' && e.hasAttribute('ng-controller')) {
                    let slimScope = {};
                    for(let key in scope) {
                        if(key.indexOf('$') !== 0 && key !== 'constructor' || extensive) {
                            slimScope[key] = scope[key];
                        }
                    }
                    result[$(e).attr('ng-controller')] = slimScope;
                }
            });

            return result;
        }

C# Listbox Item Double Click Event

It depends whether you ListBox object of the System.Windows.Forms.ListBox class, which does have the ListBox.IndexFromPoint() method. But if the ListBox object is from the System.Windows.Control.Listbox class, the answer from @dark-knight (marked as correct answer) does not work.

Im running Win 10 (1903) and current versions of the .NET framework (4.8). This issue should not be version dependant though, only whether your Application is using WPF or Windows Form for the UI. See also: WPF vs Windows Form

Enable 'xp_cmdshell' SQL Server

Even if this question has resolved, I want to add my advice about that.... since as developer I ignored.

Is important to know that we're talking about MSSQL xp_cmdshell enabled is critical to security, as indicated in the message warning:

Blockquote SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. [...]

Leaving the service enabled is a kind of weakness, that for example in a web-app could reflect and execute commands SQL from an attacker. The popular CWE-89: SQL Injection it could be weakness in the our software, and therefore these type of scenarios could pave the way to possible attacks, such as CAPEC-108: Command Line Execution through SQL Injection

I hope to have done something pleasant, we Developers and Engineer do things with awareness and we will be safer!

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I wasn't completely happy by the --allow-file-access-from-files solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.

Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !

Getting rid of all the rounded corners in Twitter Bootstrap

There is a very easy way to customize Bootstrap:

  1. Just go to http://getbootstrap.com/customize/
  2. Find all "radius" and modify them as you wish.
  3. Click "Compile and Download" and enjoy your own version of Bootstrap.

Fix columns in horizontal scrolling

SOLVED

http://jsfiddle.net/DJqPf/7/

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}
td, th {
    padding: 5px 20px;
    width: 100px;
}
th:first-child {
    position: fixed;
    left: 5px
}

UPDATE

_x000D_
_x000D_
$(function () {  _x000D_
  $('.table-wrapper tr').each(function () {_x000D_
    var tr = $(this),_x000D_
        h = 0;_x000D_
    tr.children().each(function () {_x000D_
      var td = $(this),_x000D_
          tdh = td.height();_x000D_
      if (tdh > h) h = tdh;_x000D_
    });_x000D_
    tr.css({height: h + 'px'});_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
    overflow-x:scroll;_x000D_
    overflow-y:visible;_x000D_
    width:200px;_x000D_
    margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
    padding: 5px 20px;_x000D_
    width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
  _x000D_
}_x000D_
th:first-child {_x000D_
    position: absolute;_x000D_
    left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
    <h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
    <table id="consumption-data" class="data">_x000D_
        <thead class="header">_x000D_
            <tr>_x000D_
                <th>Month</th>_x000D_
                <th>Item 1</th>_x000D_
                <th>Item 2</th>_x000D_
                <th>Item 3</th>_x000D_
                <th>Item 4</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody class="results">_x000D_
            <tr>_x000D_
                <th>Jan is an awesome month</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Feb</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Mar</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Apr</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>  _x000D_
            </tr>_x000D_
            <tr>    _x000D_
                <th>May</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Jun</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
_x000D_
            <tr>_x000D_
                <th>...</th>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to add empty spaces into MD markdown readme on GitHub?

Markdown really changes everything to html and html collapses spaces so you really can't do anything about it. You have to use the &nbsp; for it. A funny example here that I'm writing in markdown and I'll use couple of         here.

Above there are some &nbsp; without backticks

How to check if an element is visible with WebDriver

Verifying ele is visible.

public static boolean isElementVisible(final By by)
    throws InterruptedException {
        boolean value = false;

        if (driver.findElements(by).size() > 0) {
            value = true;
        }
        return value;
    }

IOS: verify if a point is inside a rect

UIView's pointInside:withEvent: could be a good solution. Will return a boolean value indicating wether or not the given CGPoint is in the UIView instance you are using. Example:

UIView *aView = [UIView alloc]initWithFrame:CGRectMake(0,0,100,100);
CGPoint aPoint = CGPointMake(5,5);
BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil];

How to get name of calling function/method in PHP?

The debug_backtrace() function is the only way to know this, if you're lazy it's one more reason you should code the GetCallingMethodName() yourself. Fight the laziness! :D

How to check type of files without extensions in python?

The Python Magic library provides the functionality you need.

You can install the library with pip install python-magic and use it as follows:

>>> import magic

>>> magic.from_file('iceland.jpg')
'JPEG image data, JFIF standard 1.01'

>>> magic.from_file('iceland.jpg', mime=True)
'image/jpeg'

>>> magic.from_file('greenland.png')
'PNG image data, 600 x 1000, 8-bit colormap, non-interlaced'

>>> magic.from_file('greenland.png', mime=True)
'image/png'

The Python code in this case is calling to libmagic beneath the hood, which is the same library used by the *NIX file command. Thus, this does the same thing as the subprocess/shell-based answers, but without that overhead.

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

"Android library projects cannot be launched"?

It says “Android library projects cannot be launched” because Android library projects cannot be launched. That simple. You cannot run a library. If you want to test a library, create an Android project that uses the library, and execute it.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

It's funny how other answers ignore the fact that you can't write to that file...

There are a few workarounds that come to my mind which could help use an arbitrary C:\redirected\settings.xml and use the mvn command as usual happily ever after.

mvn alias

In a Unix shell (or on Cygwin) you can create

alias mvn='mvn --global-settings "C:\redirected\settings.xml"'

so when you're calling mvn blah blah from anywhere the config is "automatically" picked up.
See How to create alias in cmd? if you want this, but don't have a Unix shell.

mvn wrapper

Configure your environment so that mvn is resolved to a wrapper script when typed in the command line:

  • Remove your MVN_HOME/bin or M2_HOME/bin from your PATH so mvn is not resolved any more.
  • Add a folder to PATH (or use an existing one)
  • In that folder create an mvn.bat file with contents:

    call C:\your\path\to\maven\bin\mvn.bat --global-settings "C:\redirected\settings.xml" %*
    

Note: if you want some projects to behave differently you can just create mvn.bat in the same folder as pom.xml so when you run plain mvn it resolves to the local one.

Use where mvn at any time to check how it is resolved, the first one will be run when you type mvn.

mvn.bat hack

If you have write access to C:\your\path\to\maven\bin\mvn.bat, edit the file and add set MAVEN_CMD_LINE_ARG to the :runm2 part:

@REM Start MAVEN2
:runm2
set MAVEN_CMD_LINE_ARGS=--global-settings "C:\redirected\settings.xml" %MAVEN_CMD_LINE_ARGS%
set CLASSWORLDS_LAUNCHER=...

mvn.sh hack

For completeness, you can change the C:\your\path\to\maven\bin\mvn shell script too by changing the exec "$JAVACMD" command's

${CLASSWORLDS_LAUNCHER} "$@"

part to

${CLASSWORLDS_LAUNCHER} --global-settings "C:\redirected\settings.xml" "$@"

Suggestion/Rant

As a person in IT it's funny that you don't have access to your own home folder, for me this constitutes as incompetence from the company you're working for: this is equivalent of hiring someone to do software development, but not providing even the possibility to use anything other than notepad.exe or Microsoft Word to edit the source files. I'd suggest to contact your help desk or administrator and request write access at least to that particular file so that you can change the path of the local repository.

Disclaimer: None of these are tested for this particular use case, but I successfully used all of them previously for various other software.

How to build jars from IntelliJ properly?

When i use these solution this error coming:

java -jar xxxxx.jar

no main manifest attribute, in xxxxx.jar

and solution is:

You have to change manifest directory:

<project folder>\src\main\java 

change java to resources

<project folder>\src\main\resources

How can I analyze a heap dump in IntelliJ? (memory leak)

I would like to update the answers above to 2018 and say to use both VisualVM and Eclipse MAT.

How to use:

VisualVM is used for live monitoring and dump heap. You can also analyze the heap dumps there with great power, however MAT have more capabilities (such as automatic analysis to find leaks) and therefore, I read the VisualVM dump output (.hprof file) into MAT.



Get VisualVM:

Download VisualVM here: https://visualvm.github.io/

You also need to download the plugin for Intellij: enter image description here

Then you'll see in intellij another 2 new orange icons: enter image description here

Once you run your app with an orange one, in VisualVM you'll see your process on the left, and data on the right. Sit some time and learn this tool, it is very powerful: enter image description here



Get Eclipse's Memory Analysis Tool (MAT) as a standalone:

Download here: https://www.eclipse.org/mat/downloads.php

And this is how it looks: enter image description here enter image description here

Hope it helps!

Is there a way to do repetitive tasks at intervals?

A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.

This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.

So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.

This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.

Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.

Countdown timer in React

You have to setState every second with the seconds remaining (every time the interval is called). Here's an example:

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { time: {}, seconds: 5 };_x000D_
    this.timer = 0;_x000D_
    this.startTimer = this.startTimer.bind(this);_x000D_
    this.countDown = this.countDown.bind(this);_x000D_
  }_x000D_
_x000D_
  secondsToTime(secs){_x000D_
    let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
    let divisor_for_minutes = secs % (60 * 60);_x000D_
    let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
    let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
    let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
    let obj = {_x000D_
      "h": hours,_x000D_
      "m": minutes,_x000D_
      "s": seconds_x000D_
    };_x000D_
    return obj;_x000D_
  }_x000D_
_x000D_
  componentDidMount() {_x000D_
    let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
    this.setState({ time: timeLeftVar });_x000D_
  }_x000D_
_x000D_
  startTimer() {_x000D_
    if (this.timer == 0 && this.state.seconds > 0) {_x000D_
      this.timer = setInterval(this.countDown, 1000);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  countDown() {_x000D_
    // Remove one second, set state so a re-render happens._x000D_
    let seconds = this.state.seconds - 1;_x000D_
    this.setState({_x000D_
      time: this.secondsToTime(seconds),_x000D_
      seconds: seconds,_x000D_
    });_x000D_
    _x000D_
    // Check if we're at zero._x000D_
    if (seconds == 0) { _x000D_
      clearInterval(this.timer);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
      <div>_x000D_
        <button onClick={this.startTimer}>Start</button>_x000D_
        m: {this.state.time.m} s: {this.state.time.s}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
_x000D_
_x000D_

Inline elements shifting when made bold on hover

I had a problem similar to yours. I wanted my links to get bold when you hover over them but not only in the menu but also in the text. As you cen guess it would be a real chore figuring out all the different widths. The solution is pretty simple:

Create a box that contains the link text in bold but coloured like your background and but your real link above it. Here's an example from my page:

CSS:

.hypo { font-weight: bold; color: #FFFFE0; position: static; z-index: 0; }
.hyper { position: absolute; z-index: 1; }

Of course you need to replace #FFFFE0 by the background colour of your page. The z-indices don't seem to be necessary but I put them anyway (as the "hypo" element will occur after the "hyper" element in the HTML-Code). Now, to put a link on your page, include the following:

HTML:

You can find foo <a href="http://bar.com" class="hyper">here</a><span class="hypo">here</span>

The second "here" will be invisible and hidden below your link. As this is a static box with your link text in bold, the rest of your text won't shift any longer as it is already shifted before you hover over the link.

Hope I was able to help :).

So long

Check if a variable is null in plsql

Use:

IF Var IS NULL THEN
  var := 5;
END IF;

Oracle 9i+:

var = COALESCE(Var, 5)

Other alternatives:

var = NVL(var, 5)

Reference:

Using parameters in batch files at Windows command line

Using parameters in batch files: %0 and %9

Batch files can refer to the words passed in as parameters with the tokens: %0 to %9.

%0 is the program name as it was called.
%1 is the first command line parameter
%2 is the second command line parameter
and so on till %9.

parameters passed in on the commandline must be alphanumeric characters and delimited by spaces. Since %0 is the program name as it was called, in DOS %0 will be empty for AUTOEXEC.BAT if started at boot time.

Example:

Put the following command in a batch file called mybatch.bat:

@echo off
@echo hello %1 %2
pause

Invoking the batch file like this: mybatch john billy would output:

hello john billy

Get more than 9 parameters for a batch file, use: %*

The Percent Star token %* means "the rest of the parameters". You can use a for loop to grab them, as defined here:

http://www.robvanderwoude.com/parameters.php

Notes about delimiters for batch parameters

Some characters in the command line parameters are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line:

commas (",") are replaced by spaces, unless they are part of a string in 
double quotes

semicolons (";") are replaced by spaces, unless they are part of a string in 
double quotes

"=" characters are sometimes replaced by spaces, not if they are part of a 
string in double quotes

the first forward slash ("/") is replaced by a space only if it immediately 
follows the command, without a leading space

multiple spaces are replaced by a single space, unless they are part of a 
string in double quotes

tabs are replaced by a single space

leading spaces before the first command line argument are ignored

Conversion from List<T> to array T[]

List<int> list = new List<int>();
int[] intList = list.ToArray();

is it your solution?

Docker container will automatically stop after "docker run -d"

Running docker with interactive mode might solve the issue.

Here is the example for running image with and without interactive mode

chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0 b6b9a942a79b1243bada59db19c7999cfff52d0a8744542fa843c95354966a18

chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker ps

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker run -d -t -i test_again1.0 bash c3d6a9529fd70c5b2dc2d7e90fe662d19c6dad8549e9c812fb2b7ce2105d7ff5

chaitra@RSK-IND-BLR-L06:~/dockers$ sudo docker ps

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c3d6a9529fd7 test_again1.0 "bash" 2 seconds ago Up 1 second awesome_haibt

How do you access a website running on localhost from iPhone browser

Find your system's IP address and on what port you are running the website.

Say your IP address is 121.300.00.250 and your port is 8080.

[Port number: see your web browser while running the page eg: localhost:8080/... then the port number is 8080]

Now in your mobile go to 121.300.00.250:8080/.. and you'll find your website.

IMPORTANT: You have to make sure that your server (e.g Apache Tomcat) is in started condition

How to copy and edit files in Android shell?

Since the permission policy on my device is a bit paranoid (cannot adb pull application data), I wrote a script to copy files recursively.

Note: this recursive file/folder copy script is intended for Android!

copy-r:

#! /system/bin/sh

src="$1"
dst="$2"
dir0=`pwd`

myfind() {
    local fpath=$1

    if [ -e "$fpath" ]
    then
    echo $fpath
    if [ -d "$fpath" ]
    then
        for fn in $fpath/*
        do
            myfind $fn
        done
    fi
    else
    : echo "$fpath not found"
    fi
}


if [ ! -z "$dst" ]
then
    if [ -d "$src" ]
    then
    echo 'the source is a directory'

    mkdir -p $dst

    if [[ "$dst" = /* ]]
    then
        : # Absolute path
    else
        # Relative path
        dst=`pwd`/$dst
    fi

    cd $src
    echo "COPYING files and directories from `pwd`"
    for fn in $(myfind .)
    do
        if [ -d $fn ]
        then
            echo "DIR  $dst/$fn"
            mkdir -p $dst/$fn
        else
            echo "FILE $dst/$fn"
            cat $fn >$dst/$fn
        fi
    done
    echo "DONE"
    cd $dir0

    elif [ -f "$src" ]
    then
    echo 'the source is a file'
    srcn="${src##*/}"
    if [ -z "$srcn" ]
    then
        srcn="$src"
    fi

    if [[ "$dst" = */ ]]
    then
        mkdir -p $dst
        echo "copying $src" '->' "$dst/$srcn"
        cat $src >$dst/$srcn
    elif [ -d "$dst" ]
    then
        echo "copying $src" '->' "$dst/$srcn"
        cat $src >$dst/$srcn
    else
        dstdir=${dst%/*}
        if [ ! -z "$dstdir" ]
        then
            mkdir -p $dstdir
        fi
        echo "copying $src" '->' "$dst"
        cat $src >$dst
    fi
    else
    echo "$src is neither a file nor a directory"
    fi
else
    echo "Use: copy-r src-dir dst-dir"
    echo "Use: copy-r src-file existing-dst-dir"
    echo "Use: copy-r src-file dst-dir/"
    echo "Use: copy-r src-file dst-file"
fi

Here I provide the source of a lightweight find for Android because on some devices this utility is missing. Instead of myfind one can use find, if it is defined on the device.

Installation:

$ adb push copy-r /sdcard/

Running within adb shell (rooted):

# . /sdcard/copy-r files/ /sdcard/files3 

or

# source /sdcard/copy-r files/ /sdcard/files3 

(The hash # above is the su prompt, while . is the command that causes the shell to run the specified file, almost the same as source).

After copying, I can adb pull the files from the sd-card.

Writing files to the app directory was trickier, I tried to set r/w permissions on files and its subdirectories, it did not work (well, it allowed me to read, but not write, which is strange), so I had to do:

        String[] cmdline = { "sh", "-c", "source /sdcard/copy-r /sdcard/files4 /data/data/com.example.myapp/files" }; 
        try {
            Runtime.getRuntime().exec(cmdline);
        } catch (IOException e) {
            e.printStackTrace();
        }

in the application's onCreate().

PS just in case someone needs the code to unprotect application's directories to enable adb shell access on a non-rooted phone,

        setRW(appContext.getFilesDir().getParentFile());

    public static void setRW(File... files) {
        for (File file : files) {
            if (file.isDirectory()) {
                setRW(file.listFiles()); // Calls same method again.
            } else {
            }
            file.setReadable(true, false);
            file.setWritable(true, false);
        }
    }

although for some unknown reason I could read but not write.

How to get list of all installed packages along with version in composer?

Is there a way to get it via $event->getComposer()->getRepositoryManager()->getAllPackages()

Hibernate: How to fix "identifier of an instance altered from X to Y"?

It is a problem in your update method. Just instance new User before you save changes and you will be fine. If you use mapping between DTO and Entity class, than do this before mapping.

I had this error also. I had User Object, trying to change his Location, Location was FK in User table. I solved this problem with

@Transactional
public void update(User input) throws Exception {

    User userDB = userRepository.findById(input.getUserId()).orElse(null);
    userDB.setLocation(new Location());
    userMapper.updateEntityFromDto(input, userDB);

    User user= userRepository.save(userDB);
}  

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Either remove the DEFINER=.. statement from your sqldump file, or replace the user values with CURRENT_USER.

The MySQL server provided by RDS does not allow a DEFINER syntax for another user (in my experience).

You can use a sed script to remove them from the file:

sed 's/\sDEFINER=`[^`]*`@`[^`]*`//g' -i oldfile.sql

How can I check whether Google Maps is fully loaded?

I'm creating html5 mobile apps and I noticed that the idle, bounds_changed and tilesloaded events fire when the map object is created and rendered (even if it is not visible).

To make my map run code when it is shown for the first time I did the following:

google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
    //this part runs when the mapobject is created and rendered
    google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
        //this part runs when the mapobject shown for the first time
    });
});

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

What, exactly, is needed for "margin: 0 auto;" to work?

It will also work with display:table - a useful display property in this case because it doesn't require a width to be set. (I know this post is 5 years old, but it's still relevant to passers-by ;)

css divide width 100% to 3 column

I do not think you can do it in CSS, but you can calculate a pixel perfect width with javascript. Let's say you use jQuery:

HTML code:

<div id="container">
   <div id="col1"></div>
   <div id="col2"></div>
   <div id="col3"></div>
</div>

JS Code:

$(function(){
   var total = $("#container").width();
   $("#col1").css({width: Math.round(total/3)+"px"});
   $("#col2").css({width: Math.round(total/3)+"px"});
   $("#col3").css({width: Math.round(total/3)+"px"});
});

Pandas: Subtracting two date columns and the result being an integer

You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:

import datetime as dt
import numpy as np
import pandas as pd

#Assume we have df_test:
In [222]: df_test
Out[222]: 
   first_date second_date
0  2016-01-31  2015-11-19
1  2016-02-29  2015-11-20
2  2016-03-31  2015-11-21
3  2016-04-30  2015-11-22
4  2016-05-31  2015-11-23
5  2016-06-30  2015-11-24
6         NaT  2015-11-25
7         NaT  2015-11-26
8  2016-01-31  2015-11-27
9         NaT  2015-11-28
10        NaT  2015-11-29
11        NaT  2015-11-30
12 2016-04-30  2015-12-01
13        NaT  2015-12-02
14        NaT  2015-12-03
15 2016-04-30  2015-12-04
16        NaT  2015-12-05
17        NaT  2015-12-06

In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date'] 

In [224]: df_test
Out[224]: 
   first_date second_date  Difference
0  2016-01-31  2015-11-19     73 days
1  2016-02-29  2015-11-20    101 days
2  2016-03-31  2015-11-21    131 days
3  2016-04-30  2015-11-22    160 days
4  2016-05-31  2015-11-23    190 days
5  2016-06-30  2015-11-24    219 days
6         NaT  2015-11-25         NaT
7         NaT  2015-11-26         NaT
8  2016-01-31  2015-11-27     65 days
9         NaT  2015-11-28         NaT
10        NaT  2015-11-29         NaT
11        NaT  2015-11-30         NaT
12 2016-04-30  2015-12-01    151 days
13        NaT  2015-12-02         NaT
14        NaT  2015-12-03         NaT
15 2016-04-30  2015-12-04    148 days
16        NaT  2015-12-05         NaT
17        NaT  2015-12-06         NaT

Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.

In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)

In [227]: df_test
Out[227]: 
   first_date second_date  Difference  Diffference
0  2016-01-31  2015-11-19     73 days           73
1  2016-02-29  2015-11-20    101 days          101
2  2016-03-31  2015-11-21    131 days          131
3  2016-04-30  2015-11-22    160 days          160
4  2016-05-31  2015-11-23    190 days          190
5  2016-06-30  2015-11-24    219 days          219
6         NaT  2015-11-25         NaT          NaN
7         NaT  2015-11-26         NaT          NaN
8  2016-01-31  2015-11-27     65 days           65
9         NaT  2015-11-28         NaT          NaN
10        NaT  2015-11-29         NaT          NaN
11        NaT  2015-11-30         NaT          NaN
12 2016-04-30  2015-12-01    151 days          151
13        NaT  2015-12-02         NaT          NaN
14        NaT  2015-12-03         NaT          NaN
15 2016-04-30  2015-12-04    148 days          148
16        NaT  2015-12-05         NaT          NaN
17        NaT  2015-12-06         NaT          NaN

Hope that helps.

Android: How can I get the current foreground activity (from a service)?

I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks to keep track of current activity and then expose it through a service:

public interface ContextProvider {
    Context getActivityContext();
}

public class MyApplication extends Application implements ContextProvider {
    private Activity currentActivity;

    @Override
    public Context getActivityContext() {
         return currentActivity;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityStarted(Activity activity) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityPaused(Activity activity) {
                MyApplication.this.currentActivity = null;
            }

            @Override
            public void onActivityStopped(Activity activity) {
                // don't clear current activity because activity may get stopped after
                // the new activity is resumed
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                // don't clear current activity because activity may get destroyed after
                // the new activity is resumed
            }
        });
    }
}

Then configure your DI container to return instance of MyApplication for ContextProvider, e.g.

public class ApplicationModule extends AbstractModule {    
    @Provides
    ContextProvider provideMainActivity() {
        return MyApplication.getCurrent();
    }
}

(Note that implementation of getCurrent() is omitted from the code above. It's just a static variable that's set from the application constructor)

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

How to deselect a selected UITableView cell?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}

ng-mouseover and leave to toggle item using mouse in angularjs

Angular solution

You can fix it like this:

$scope.hoverIn = function(){
    this.hoverEdit = true;
};

$scope.hoverOut = function(){
    this.hoverEdit = false;
};

Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.

Also you need to put ngRepeat on li:

<ul>
    <li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
        {{task.name}}
        <span ng-show="hoverEdit">
            <a>Edit</a>
        </span>
    </li>
</ul>

Demo

CSS solution

However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:

ul li span {display: none;}
ul li:hover span {display: inline;}

Asp.net Validation of viewstate MAC failed

This solution worked for me in ASP.NET 4.5 using a Web Forms site.

  1. Use the following site to generate a Machine Key: http://www.blackbeltcoder.com/Resources/MachineKey.aspx
  2. Copy Full Machine Key Code.
  3. Go To your Web.Config File.
  4. Paste the Machine Key in the following code section:
    <configuration>
      <system.web>
        <machineKey ... />
      </system.web>
    </configuration> 

You should not see the viewstate Mac failed error anymore. Each website in the same app pool should have a separate machine key otherwise this error will continue.

jQuery get the id/value of <li> element after click function

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});?

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

space between divs - display table-cell

<div style="display:table;width:100%"  >
<div style="display:table-cell;width:49%" id="div1">
content
</div>

<!-- space between divs - display table-cell -->
<div style="display:table-cell;width:1%" id="separated"></div>
<!-- //space between divs - display table-cell -->

<div style="display:table-cell;width:50%" id="div2">
content
</div>
</div>

CSS z-index not working (position absolute)

I solved my z-index problem by making the body wrapper z-index:-1 and the body z-index:-2, and the other divs z-index:1.

And then the later divs didn't work unless I had z-index 200+. Even though I had position:relative on each element, with the body at default z-index it wouldn't work.

Hope this helps somebody.

Loading PictureBox Image from resource file with path (Part 3)

Setting "Copy to Output Directory" to "Copy always" or "Copy if newer" may help for you.

Your PicPath is a relative path that is converted into an absolute path at some time while loading the image. Most probably you will see that there are no images on the specified location if you use Path.GetFullPath(PicPath) in Debug.

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

How to hide first section header in UITableView (grouped style)

easiest by far is to return nil, or "" in func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? for a section where you do not wish to display header.

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Xml serialization - Hide null values

You can define some default values and it prevents the fields from being serialized.

    [XmlElement, DefaultValue("")]
    string data;

    [XmlArray, DefaultValue(null)]
    List<string> data;

FileProvider - IllegalArgumentException: Failed to find configured root

None of this worked for me. The only approach that works is not to declare an explicit path in xml. So do this and be happy:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="." />
</paths>

Here too has a excelent tutorial about this question: https://www.youtube.com/watch?v=9ZxRTKvtfnY&t=613s

Using Mysql in the command line in osx - command not found?

modify your bash profile as follows <>$vim ~/.bash_profile export PATH=/usr/local/mysql/bin:$PATH Once its saved you can type in mysql to bring mysql prompt in your terminal.

C# List<string> to string with delimiter

You can also do this with linq if you'd like

var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);

Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate might perform slower (probably more string concatenation operations).

How to compare 2 dataTables

How about merging 2 data tables and then comparing the changes? Not sure if that will fill 100% of your needs but for the quick compare it will do a job.

public DataTable GetTwoDataTablesChanges(DataTable firstDataTable, DataTable secondDataTable)
{ 
     firstDataTable.Merge(secondDataTable);
     return secondDataTable.GetChanges();
}

You can read more about DataTable.Merge()

here

What is the best way to call a script from another script?

This is possible in Python 2 using

execfile("test2.py")

See the documentation for the handling of namespaces, if important in your case.

In Python 3, this is possible using (thanks to @fantastory)

exec(open("test2.py").read())

However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.

Understanding dict.copy() - shallow or deep?

In your second part, you should use new = original.copy()

.copy and = are different things.

substring index range

See the javadoc. It's an inclusive index for the first argument and exclusive for the second.

Comparing boxed Long values 127 and 128

num1 and num2 are Long objects. You should be using equals() to compare them. == comparison might work sometimes because of the way JVM boxes primitives, but don't depend on it.

if (num1.equals(num1))
{
 //code
}

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

htaccess - How to force the client's browser to clear the cache?

Now the following wont help you with files that are already cached, but moving forward, you can use the following to easily force a request to get something new, without changing the actual filename.

# Rewrite all requests for JS and CSS files to files of the same name, without
# any numbers in them. This lets the JS and CSS be force out of cache easily
# by putting a number at the end of the filename
# e.g. a request for static/js/site-52.js will get the file static/js/site.js instead.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^static/(js|css)/([a-z]+)-([0-9]+)\.(js|css)$ /site/$1/$2.$4 [R=302,NC,L]
</IfModule>

Of course, the higher up in your folder structure you do this type of approach, the more you kick things out of cache with a simple change.

So for example, if you store the entire css and javascript of your site in one main folder

/assets/js
/assets/css
/assets/...

Then you can could start referencing it as "assets-XXX" in your html, and use a rule like so to kick all assets content out of cache.

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^assets-([a-z0-9]+)/(.*) /$2 [R=302,NC,L]
</IfModule> 

Note that if you do go with this, after you have it working, change the 302 to a 301, and then caching will kick in. When it's a 302 it wont cache at the browser level because it's a temporary redirect. If you do it this way, then you could bump up the expiry default time to 30 days for all assets, since you can easily kick things out of cache by simply changing the folder name in the login page.

<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresDefault A2592000
</IfModule>

How to see the CREATE VIEW code for a view in PostgreSQL?

These is a little thing to point out.
Using the function pg_get_viewdef or pg_views or information_schema.views you will always get a rewrited version of your original DDL.
The rewited version may or not be the same as your originl DDL script.

If the Rule Manager rewrite your view definition your original DLL will be lost and you will able to read the only the rewrited version of your view definition.
Not all views are rewrited but if you use sub-select or joins probably your views will be rewrited.

In Java, how do I parse XML as a String instead of a file?

I'm using this method

public Document parseXmlFromString(String xmlString){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
    org.w3c.dom.Document document = builder.parse(inputStream);
    return document;
}

Python threading.timer - repeat function every 'n' seconds

From Equivalent of setInterval in python:

import threading

def setInterval(interval):
    def decorator(function):
        def wrapper(*args, **kwargs):
            stopped = threading.Event()

            def loop(): # executed in another thread
                while not stopped.wait(interval): # until stopped
                    function(*args, **kwargs)

            t = threading.Thread(target=loop)
            t.daemon = True # stop if the program exits
            t.start()
            return stopped
        return wrapper
    return decorator

Usage:

@setInterval(.5)
def function():
    "..."

stop = function() # start timer, the first call is in .5 seconds
stop.set() # stop the loop
stop = function() # start new timer
# ...
stop.set() 

Or here's the same functionality but as a standalone function instead of a decorator:

cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls() 

Here's how to do it without using threads.

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

  1. Download jar file containing the JavaDocs.
  2. Open the Build Path page of the project (right click, properties, Java build path).
  3. Open the Libraries tab.
  4. Expand the node of the library in question (JavaFX).
  5. Select JavaDoc location and click edit.
  6. Enter the location to the file which contains the Javadoc (the one you just downloaded).

Convert Map<String,Object> to Map<String,String>

Now that we have Java 8/streams, we can add one more possible answer to the list:

Assuming that each of the values actually are String objects, the cast to String should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.

Map<String,Object> map = new HashMap<>();
Map<String,String> newMap = map.entrySet().stream()
     .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

automating telnet session using bash scripts

You can use expect scripts instaed of bash. Below example show how to telnex into an embedded board having no password

#!/usr/bin/expect

set ip "<ip>"

spawn "/bin/bash"
send "telnet $ip\r"
expect "'^]'."
send "\r"
expect "#"
sleep 2

send "ls\r"
expect "#"

sleep 2
send -- "^]\r"
expect "telnet>"
send  "quit\r"
expect eof

Best practice for partial updates in a RESTful service

Regarding your Update.

The concept of CRUD I believe has caused some confusion regarding API design. CRUD is a general low level concept for basic operations to perform on data, and HTTP verbs are just request methods (created 21 years ago) that may or may not map to a CRUD operation. In fact, try to find the presence of the CRUD acronym in the HTTP 1.0/1.1 specification.

A very well explained guide that applies a pragmatic convention can be found in the Google cloud platform API documentation. It describes the concepts behind the creation of a resource based API, one that emphasizes a big amount of resources over operations, and includes the use cases that you are describing. Although is a just a convention design for their product, I think it makes a lot of sense.

The base concept here (and one that produces a lot of confusion) is the mapping between "methods" and HTTP verbs. One thing is to define what "operations" (methods) your API will do over which types of resources (for example, get a list of customers, or send an email), and another are the HTTP verbs. There must be a definition of both, the methods and the verbs that you plan to use and a mapping between them.

It also says that, when an operation does not map exactly with a standard method (List, Get, Create, Update, Delete in this case), one may use "Custom methods", like BatchGet, which retrieves several objects based on several object id input, or SendEmail.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

Forward host port to docker container

A simple but relatively insecure way would be to use the --net=host option to docker run.

This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.

This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.

For example, you can test it out by running the following command, which assumes your image is called my_image, your image includes the telnet utility, and the service you want to connect to is on port 25:

docker run --rm -i -t --net=host my_image telnet localhost 25

If you consider doing it this way, please see the caution about security on this page:

https://docs.docker.com/articles/networking/

It says:

--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.

How to do fade-in and fade-out with JavaScript and CSS

Here's my attempt with Javascript and CSS3 animation So the HTML:

 <div id="handle">Fade</div> 
 <div id="slideSource">Whatever you want images or  text here</div>

The CSS3 with transitions:

div#slideSource {
opacity:1;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;     
transition: opacity 3s; 
}

div#slideSource.fade {
opacity:0;
}

The Javascript part. Check if the className exists, if it does then add the class and transitions.

document.getElementById('handle').onclick = function(){
    if(slideSource.className){
        document.getElementById('slideSource').className = '';
    } else {
        document.getElementById('slideSource').className = 'fade';
    }
}

Just click and it will fade in and out. I would recommend using JQuery as Itai Sagi mentioned. I left out Opera and MS, so I would recommend using prefixr to add that in the css. This is my first time posting on stackoverflow but it should work fine.

Using jquery to get all checked checkboxes with a certain class name

HTML

 <p> <input type="checkbox" name="fruits" id="fruits"  value="1" /> Apple </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="2" /> Banana </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="3" /> Mango </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="4" /> Grape </p>

Jquery

for storing the selected fruit values define array.

 fruitArray = [];

$.each will iterate the checked check boxes and pushed into array.

 $.each($("input[name='fruits']:checked"), function (K, V) {    
    fruitArray.push(V.value);        
});

                                       

Easiest way to detect Internet connection on iOS?

Sorry for replying too late but I hope this answer can help somebody in future.

Following is a small native C code snippet that can check internet connectivity without any extra class.

Add the following headers:

#include<unistd.h>
#include<netdb.h>

Code:

-(BOOL)isNetworkAvailable
{
    char *hostname;
    struct hostent *hostinfo;
    hostname = "google.com";
    hostinfo = gethostbyname (hostname);
    if (hostinfo == NULL){
        NSLog(@"-> no connection!\n");
        return NO;
    }
    else{
        NSLog(@"-> connection established!\n");
        return YES;
    }
}

Swift 3

func isConnectedToInternet() -> Bool {
    let hostname = "google.com"
    //let hostinfo = gethostbyname(hostname)
    let hostinfo = gethostbyname2(hostname, AF_INET6)//AF_INET6
    if hostinfo != nil {
        return true // internet available
      }
     return false // no internet
    }

Check if a path represents a file or a folder

Clean solution while staying with the nio API:

Files.isDirectory(path)
Files.isRegularFile(path)

How do you log content of a JSON object in Node.js?

console.log(obj);

Run: node app.js > output.txt

How to make a <div> always full screen?

I don't have IE Josh, could you please test this for me. Thanks.

<html>
<head>
    <title>Hellomoto</title>
    <style text="text/javascript">
        .hellomoto
        {
            background-color:#ccc;
            position:absolute;
            top:0px;
            left:0px;
            width:100%;
            height:100%;
            overflow:auto;
        }
        body
        {
            background-color:#ff00ff;
            padding:0px;
            margin:0px;
            width:100%;
            height:100%;
            overflow:hidden;
        }
        .text
        {
            background-color:#cc00cc;
            height:800px;
            width:500px;
        }
    </style>
</head>
<body>
<div class="hellomoto">
    <div class="text">hellomoto</div>
</div>
</body>
</html>

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

jQuery: how to change title of document during .ready()?

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.

The correct way to do this is on the server side.

In your layout, there at some point will be some code which puts the text in the div. Make this code also set some instance variable such as @page_title, and then in your outer layout have it do <%= @page_title || 'Default Title' %>

Passing ArrayList through Intent

I have done this one by Passing ArrayList in form of String.

  1. Add compile 'com.google.code.gson:gson:2.2.4' in dependencies block build.gradle.

  2. Click on Sync Project with Gradle Files

Cars.java:

public class Cars {
    public String id, name;
}

FirstActivity.java

When you want to pass ArrayList:

List<Cars> cars= new ArrayList<Cars>();
cars.add(getCarModel("1", "A"));
cars.add(getCarModel("2", "B"));
cars.add(getCarModel("3", "C"));
cars.add(getCarModel("4", "D"));

Gson gson = new Gson();

String jsonCars = gson.toJson(cars);

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("list_as_string", jsonCars);
startActivity(intent);

Get CarsModel by Function:

private Cars getCarModel(String id, String name){
       Cars cars = new Cars();
       cars.id = id;
       cars.name = name;
    return cars;
 }

SecondActivity.java

You have to import java.lang.reflect.Type ;

on onCreate() to retrieve ArrayList:

String carListAsString = getIntent().getStringExtra("list_as_string");

Gson gson = new Gson();
Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(carListAsString, type);
for (Cars cars : carsList){
   Log.i("Car Data", cars.id+"-"+cars.name);
}

Hope this will save time, I saved it.

Done

How to use confirm using sweet alert?

You need To use then() function, like this

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!"
 }).then(
       function () { /*Your Code Here*/ },
       function () { return false; });

How do I disable a href link in JavaScript?

Instead of void you can also use:

<a href="javascript:;">this link is disabled</a> 

Function for C++ struct

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};

jQuery $.cookie is not a function

I had this problem as well. I found out that having a $(document).ready function that included a $.cookie in a script tag inside body while having cookie js load in the head BELOW jquery as intended resulted in $(document).ready beeing processed before the cookie plugin could finish loading.

I moved the cookie plugin load script in the body before the $(document).ready script and the error disappeared :D

Add (insert) a column between two columns in a data.frame

Easy solution. In a data frame with 5 columns, If you want insert another column between 3 and 4...

tmp <- data[, 1:3]
tmp$example <- NA # or any value.
data <- cbind(tmp, data[, 4:5]

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Create an ArrayList with multiple object types?

User Defined Class Array List Example

import java.util.*;  

public class UserDefinedClassInArrayList {

    public static void main(String[] args) {

        //Creating user defined class objects  
        Student s1=new Student(1,"AAA",13);  
        Student s2=new Student(2,"BBB",14);  
        Student s3=new Student(3,"CCC",15); 

        ArrayList<Student> al=new ArrayList<Student>();
        al.add(s1);
        al.add(s2);  
        al.add(s3);  

        Iterator itr=al.iterator();  

        //traverse elements of ArrayList object  
        while(itr.hasNext()){  
            Student st=(Student)itr.next();  
            System.out.println(st.rollno+" "+st.name+" "+st.age);  
        }  
    }
}

class Student{  
    int rollno;  
    String name;  
    int age;  
    Student(int rollno,String name,int age){  
        this.rollno=rollno;  
        this.name=name;  
        this.age=age;  
    }  
} 

Program Output:

1 AAA 13

2 BBB 14

3 CCC 15

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

Solved the issue by going to File >> Project Structure >> Facets and then adding all the configuration files to Spring Facet. After that it started detecting files in which the beans reside and was able to sort the issue. IntelliJ giving this check is quite valuable and IMHO shouldn't be disabled.

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

There is another issue you have to take care of it when you try mapping column which is string length, for example TK_NO nvarchar(50) you will have to map to the same length as the destination field.

How to find sum of multiple columns in a table in SQL Server 2005?

Just as a regular SELECT?

SELECT 
   Val1, Val2, Val3,
   Total = Val1 + Val2 + Val3
FROM dbo.Emp

Or do you want to determine that total and update the table with those values?

UPDATE dbo.Emp
SET Total = Val1 + Val2 + Val3

If you want to have this total be current at all times - you should have a computed column in your table:

ALTER TABLE dbo.Emp
ADD CurrentTotal AS Val1 + Val2 + Val3 PERSISTED

Then you will always get the current total - even if the values change:

SELECT 
   Val1, Val2, Val3, CurrentTotal
FROM dbo.Emp

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

To view the content in alert use:

alert( $(response).find("#result").html() );

How do I print the content of a .txt file in Python?

print ''.join(file('example.txt'))

How to clear Facebook Sharer cache?

Facebook treats each url as unique and caches the page based on that url, so if you want to share the latest url the simplest solution is to add a query string with the url being shared. In simple words just add ?v=1 at the end of the url. Any number can be used in place of 1.

Hat tip: Umair Jabbar

What is the use of the square brackets [] in sql statements?

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space)--but then you'd need to use brackets every time you referred to that column.

The newer tools add them everywhere just in case or for consistency.

How to remove item from a python list in a loop?

hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:

x[:] = [value for value in x if len(value)==2]

However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).

glglgl's answer suffers from O(n²) complexity, because list.remove is O(n).

Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del keywork to remove by index:

to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
    del x[index]

Now del x[i] is also O(n) because you need to copy all elements after index i (a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.

[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress which was introduced in python 2.7:

from itertools import compress

selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
    x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:]  # trim the end of the list

MySQL user DB does not have password columns - Installing MySQL on OSX

Root Cause: root has no password, and your python connect statement should reflect that.

To solve error 1698, change your python connect password to ''.

note: manually updating the user's password will not solve the problem, you will still get error 1698

Sending email from Command-line via outlook without having to click send

Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:

$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")

You could then launch the script from the command line as per this example:

powershell.exe -noexit c:\scripts\test.ps1

Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage command, making things easier.

Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.

Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:

Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg  = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
        objOutlookRecip.Type = olTo
        ' Set the Subject, Body, and Importance of the message.
        .Subject = "This is an Automation test with Microsoft Outlook"
        .Body = "This is the body of the message." &vbCrLf & vbCrLf
        .Importance = olImportanceHigh  'High importance

        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
        End If

        For Each ObjOutlookRecip In .Recipients
            objOutlookRecip.Resolve
        Next

        .Save
        .Send
    End With
    Set objOutlook = Nothing
End Sub

Then, launch Outlook from the command line with the /autorun parameter, as per this answer (alter path/macroname as necessary):

C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname

Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.

What is a Y-combinator?

Other answers provide pretty concise answer to this, without one important fact: You don't need to implement fixed point combinator in any practical language in this convoluted way and doing so serves no practical purpose (except "look, I know what Y-combinator is"). It's important theoretical concept, but of little practical value.

ImportError: No module named dateutil.parser

If you're using a virtualenv, make sure that you are running pip from within the virtualenv.

$ which pip
/Library/Frameworks/Python.framework/Versions/Current/bin/pip
$ find . -name pip -print
./flask/bin/pip
./flask/lib/python2.7/site-packages/pip
$ ./flask/bin/pip install python-dateutil

PHP to search within txt file and echo the whole line

And a PHP example, multiple matching lines will be displayed:

<?php
$file = 'somefile.txt';
$searchfor = 'name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

How to stop event bubbling on checkbox click

replace

event.preventDefault();
return false;

with

event.stopPropagation();

event.stopPropagation()

Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

event.preventDefault()

Prevents the browser from executing the default action. Use the method isDefaultPrevented to know whether this method was ever called (on that event object).

Conversion of System.Array to List

Just use the existing method.. .ToList();

   List<int> listArray = array.ToList();

KISS(KEEP IT SIMPLE SIR)

git status shows fatal: bad object HEAD

Your repository is broken. But you can probably fix it AND keep your edits:

  1. Back up first: cp your_repository your_repositry_bak
  2. Clone the broken repository (still works): git clone your_repository your_repository_clone
  3. Replace the broken .git folder with the one from the clone: rm -rf your_repository/.git && cp your_repository_clone/.git your_repository/ -r
  4. Delete clone & backup (if everything is fine): rm -r your_repository_*

int *array = new int[n]; what is this function actually doing?

int *array = new int[n];

It declares a pointer to a dynamic array of type int and size n.

A little more detailed answer: new allocates memory of size equal to sizeof(int) * n bytes and return the memory which is stored by the variable array. Also, since the memory is dynamically allocated using new, you've to deallocate it manually by writing (when you don't need anymore, of course):

delete []array;

Otherwise, your program will leak memory of at least sizeof(int) * n bytes (possibly more, depending on the allocation strategy used by the implementation).

How to redirect page after click on Ok button on sweet alert?

I did it by using this code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
        <script>

        $(".confirm").on('click',function(){
            window.location.href = "index.php";
        });

        </script>

Thanks.

How do I turn off the mysql password validation?

For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html

Then you should edit your mysqld.cnf file, for instance :

vim /etc/mysql/mysql.conf.d/mysqld.cnf

Then, add in the [mysqld] part, the following :

plugin-load-add=validate_password.so
validate_password_policy=LOW

Basically, if you edit your default, it will looks like :

[mysqld]
#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW

Then, you can restart:

systemctl restart mysql

If you forget the plugin-load-add=validate_password.so part, you will it an error at restart.

Enjoy !

if-else statement inside jsx: ReactJS

What about switch case instead of if-else

  render() {
    switch (this.state.route) {
      case 'loginRoute':
        return (
            <Login changeRoute={this.changeRoute}
              changeName={this.changeName}
              changeRole={this.changeRole} />
        );
      case 'adminRoute':
        return (
            <DashboardAdmin
              role={this.state.role}
              name={this.state.name}
              changeRoute={this.changeRoute}
            />
        );
      default: 
        return <></>;
    }

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

json_decode to array

json_decode($data, true); // Returns data in array format 

json_decode($data); // Returns collections 

So, If want an array than you can pass the second argument as 'true' in json_decode function.

image.onload event and browser cache

I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).

How can I get the max (or min) value in a vector?

Let,

 #include <vector>

 vector<int> v {1, 2, 3, -1, -2, -3};

If the vector is sorted in ascending or descending order then you can find it with complexity O(1).

For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].

If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].

If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.

int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++)  //start iterating from the second element
{
    if(v[i] < smallest_element)
    {
       smallest_element = v[i];
    }
    if(v[i] > largest_element)
    {
       largest_element = v[i];
    }
}

You can use iterator,

for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
    if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
    {
      smallest_element = *it;
    }
    if(*it > largest_element)
    {
      largest_element = *it;
    }
}

You can calculate it in input section (when you have to find smallest or largest element from a given vector)

int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
    cin>>value;
    if(i==0)
    {
        smallest_element= value; //smallest_element=v[0];
        largest_element= value; //also, largest_element = v[0]
    }

    if(value<smallest_element and i>0)
    {
        smallest_element = value;
    }

    if(value>largest_element and i>0)
    {
        largest_element = value;
    }
    v.push_back(value);
}

Also you can get smallest/largest element by built in functions

#include<algorithm>

int smallest_element = *min_element(v.begin(),v.end());

int largest_element  = *max_element(v.begin(),v.end());

You can get smallest/largest element of any range by using this functions. such as,

vector<int> v {1,2,3,-1,-2,-3};

cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements

cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements

cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)

cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)

I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Lazy Set

VARIABLE = value

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

VARIABLE := value

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

VARIABLE ?= value

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

ifeq ($(origin FOO), undefined)
  FOO = bar
endif

See the documentation for more details.

Append

VARIABLE += value

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

Comparing Java enum members: == or equals()?

I prefer to use == instead of equals:

Other reason, in addition to the others already discussed here, is you could introduce a bug without realizing it. Suppose you have this enums which is exactly the same but in separated pacakges (it's not common, but it could happen):

First enum:

package first.pckg

public enum Category {
    JAZZ,
    ROCK,
    POP,
    POP_ROCK
}

Second enum:

package second.pckg

public enum Category {
    JAZZ,
    ROCK,
    POP,
    POP_ROCK
}

Then suppose you use the equals like next in item.category which is first.pckg.Category but you import the second enum (second.pckg.Category) instead the first without realizing it:

import second.pckg.Category;
...

Category.JAZZ.equals(item.getCategory())

So you will get allways false due is a different enum although you expect true because item.getCategory() is JAZZ. And it could be be a bit difficult to see.

So, if you instead use the operator == you will have a compilation error:

operator == cannot be applied to "second.pckg.Category", "first.pckg.Category"

import second.pckg.Category; 
...

Category.JAZZ == item.getCategory() 

mysql update multiple columns with same now()

You can put the following code on the default value of the timestamp column: CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, so on update the two columns take the same value.

How does the @property decorator work in Python?

The property() function returns a special descriptor object:

>>> property()
<property object at 0x10ff07940>

It is this object that has extra methods:

>>> property().getter
<built-in method getter of property object at 0x10ff07998>
>>> property().setter
<built-in method setter of property object at 0x10ff07940>
>>> property().deleter
<built-in method deleter of property object at 0x10ff07998>

These act as decorators too. They return a new property object:

>>> property().getter(None)
<property object at 0x10ff079f0>

that is a copy of the old object, but with one of the functions replaced.

Remember, that the @decorator syntax is just syntactic sugar; the syntax:

@property
def foo(self): return self._foo

really means the same thing as

def foo(self): return self._foo
foo = property(foo)

so foo the function is replaced by property(foo), which we saw above is a special object. Then when you use @foo.setter(), what you are doing is call that property().setter method I showed you above, which returns a new copy of the property, but this time with the setter function replaced with the decorated method.

The following sequence also creates a full-on property, by using those decorator methods.

First we create some functions and a property object with just a getter:

>>> def getter(self): print('Get!')
... 
>>> def setter(self, value): print('Set to {!r}!'.format(value))
... 
>>> def deleter(self): print('Delete!')
... 
>>> prop = property(getter)
>>> prop.fget is getter
True
>>> prop.fset is None
True
>>> prop.fdel is None
True

Next we use the .setter() method to add a setter:

>>> prop = prop.setter(setter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is None
True

Last we add a deleter with the .deleter() method:

>>> prop = prop.deleter(deleter)
>>> prop.fget is getter
True
>>> prop.fset is setter
True
>>> prop.fdel is deleter
True

Last but not least, the property object acts as a descriptor object, so it has .__get__(), .__set__() and .__delete__() methods to hook into instance attribute getting, setting and deleting:

>>> class Foo: pass
... 
>>> prop.__get__(Foo(), Foo)
Get!
>>> prop.__set__(Foo(), 'bar')
Set to 'bar'!
>>> prop.__delete__(Foo())
Delete!

The Descriptor Howto includes a pure Python sample implementation of the property() type:

class Property:
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

C: socket connection timeout

The answers about using select()/poll() are right and code should be written this way to be portable.

However, since you're on Linux, you can do this:

int synRetries = 2; // Send a total of 3 SYN packets => Timeout ~7s
setsockopt(fd, IPPROTO_TCP, TCP_SYNCNT, &synRetries, sizeof(synRetries));

See man 7 tcp and man setsockopt.

I used this to speed up the connect-timeout in a program I needed to patch quickly. Hacking it to timeout via select()/poll() was not an option.

Is it possible to append Series to rows of DataFrame without making a list first?

Maybe an easier way would be to add the pandas.Series into the pandas.DataFrame with ignore_index=True argument to DataFrame.append(). Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value)
    DF = DF.append(SR_row,ignore_index=True)

Demo -

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])

In [3]: df
Out[3]:
   A  B
0  1  2
1  3  4

In [5]: s = pd.Series([5,6],index=['A','B'])

In [6]: s
Out[6]:
A    5
B    6
dtype: int64

In [36]: df.append(s,ignore_index=True)
Out[36]:
   A  B
0  1  2
1  3  4
2  5  6

Another issue in your code is that DataFrame.append() is not in-place, it returns the appended dataframe, you would need to assign it back to your original dataframe for it to work. Example -

DF = DF.append(SR_row,ignore_index=True)

To preserve the labels, you can use your solution to include name for the series along with assigning the appended DataFrame back to DF. Example -

DF = DataFrame()
for sample,data in D_sample_data.items():
    SR_row = pd.Series(data.D_key_value,name=sample)
    DF = DF.append(SR_row)
DF.head()

Write to UTF-8 file in Python

I use the file *nix command to convert a unknown charset file in a utf-8 file

# -*- encoding: utf-8 -*-

# converting a unknown formatting file in utf-8

import codecs
import commands

file_location = "jumper.sub"
file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location)

file_stream = codecs.open(file_location, 'r', file_encoding)
file_output = codecs.open(file_location+"b", 'w', 'utf-8')

for l in file_stream:
    file_output.write(l)

file_stream.close()
file_output.close()

How to Add Incremental Numbers to a New Column Using Pandas

Here:

df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880

How to determine the current iPhone/device model?

You can use BDLocalizedDevicesModels framework to parse device info and get the name.

Then just call UIDevice.currentDevice.productName in your code.

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

Match whitespace but not newlines

m/ /g just give space in / /, and it will work. Or use \S — it will replace all the special characters like tab, newlines, spaces, and so on.

How can I get stock quotes using Google Finance API?

Building upon the shoulders of giants...here's a one-liner I wrote to zap all of Google's current stock data into local Bash shell variables:

stock=$1 

# Fetch from Google Finance API, put into local variables
eval $(curl -s "http://www.google.com/ig/api?stock=$stock"|sed 's/</\n</g' |sed '/data=/!d; s/ data=/=/g; s/\/>/; /g; s/</GF_/g' |tee /tmp/stockprice.tmp.log)

echo "$stock,$(date +%Y-%m-%d),$GF_open,$GF_high,$GF_low,$GF_last,$GF_volume"

Then you will have variables like $GF_last $GF_open $GF_volume etc. readily available. Run env or see inside /tmp/stockprice.tmp.log

http://www.google.com/ig/api?stock=TVIX&output=csv by itself returns:

<?xml version="1.0"?>
<xml_api_reply version="1">
<finance module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<symbol data="TVIX"/>
<pretty_symbol data="TVIX"/>
<symbol_lookup_url data="/finance?client=ig&amp;q=TVIX"/>
<company data="VelocityShares Daily 2x VIX Short Term ETN"/>
<exchange data="AMEX"/>
<exchange_timezone data="ET"/>
<exchange_utc_offset data="+05:00"/>
<exchange_closing data="960"/>
<divisor data="2"/>
<currency data="USD"/>
<last data="57.45"/>
<high data="59.70"/>
<low data="56.85"/>

etc.

So for stock="FBM" /tmp/stockprice.tmp.log (and your environment) will contain:

GF_symbol="FBM"; 
GF_pretty_symbol="FBM"; 
GF_symbol_lookup_url="/finance?client=ig&amp;q=FBM"; 
GF_company="Focus Morningstar Basic Materials Index ETF"; 
GF_exchange="NYSEARCA"; 
GF_exchange_timezone=""; 
GF_exchange_utc_offset=""; 
GF_exchange_closing=""; 
GF_divisor="2"; 
GF_currency="USD"; 
GF_last="22.82"; 
GF_high="22.82"; 
GF_low="22.82"; 
GF_volume="100"; 
GF_avg_volume=""; 
GF_market_cap="4.56"; 
GF_open="22.82"; 
GF_y_close="22.80"; 
GF_change="+0.02"; 
GF_perc_change="0.09"; 
GF_delay="0"; 
GF_trade_timestamp="8 hours ago"; 
GF_trade_date_utc="20120228"; 
GF_trade_time_utc="184541"; 
GF_current_date_utc="20120229"; 
GF_current_time_utc="033534"; 
GF_symbol_url="/finance?client=ig&amp;q=FBM"; 
GF_chart_url="/finance/chart?q=NYSEARCA:FBM&amp;tlf=12"; 
GF_disclaimer_url="/help/stock_disclaimer.html"; 
GF_ecn_url=""; 
GF_isld_last=""; 
GF_isld_trade_date_utc=""; 
GF_isld_trade_time_utc=""; 
GF_brut_last=""; 
GF_brut_trade_date_utc=""; 
GF_brut_trade_time_utc=""; 
GF_daylight_savings="false"; 

Get pixel color from canvas, on mousemove

Here's a complete, self-contained example. First, use the following HTML:

<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>

Then put some squares on the canvas with random background colors:

var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);

And print each color on mouseover:

$('#example').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "<br>" + hex);
});

The code above assumes the presence of jQuery and the following utility functions:

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function randomInt(max) {
  return Math.floor(Math.random() * max);
}

function randomColor() {
    return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}

See it in action here:

_x000D_
_x000D_
// set up some sample squares with random colors
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);

$('#example').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "<br>" + hex);
});

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function randomInt(max) {
  return Math.floor(Math.random() * max);
}

function randomColor() {
    return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>

    
_x000D_
_x000D_
_x000D_

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Saving and Reading Bitmaps/Images from Internal memory in Android

    public static String saveImage(String folderName, String imageName, RelativeLayout layoutCollage) {
        String selectedOutputPath = "";
        if (isSDCARDMounted()) {
            File mediaStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
            // Create a storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("PhotoEditorSDK", "Failed to create directory");
                }
            }
            // Create a media file name
            selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
            Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
            File file = new File(selectedOutputPath);
            try {
                FileOutputStream out = new FileOutputStream(file);
                if (layoutCollage != null) {
                    layoutCollage.setDrawingCacheEnabled(true);
                    layoutCollage.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
                }
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return selectedOutputPath;
    }



private static boolean isSDCARDMounted() {
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

Is this how you define a function in jQuery?

First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.

Here's an example:

$(document).ready( function () {

    var MyBlah = function($blah) { alert($blah);  };

    MyBlah("Hello this works") // Inside the anonymous function we are cool.

 });

MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)

This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.

Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.

Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).

Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:

$('div#message').myBlah("hello")

See also: http://www.re-cycledair.com/creating-jquery-plugins

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Just Add:

android:screenOrientation="portrait"

in "AndroidManifest.xml" :

<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
android:label="@string/app_name">
</activity>

How to put two divs side by side

Regarding the width of your website, you'll want to consider using a wrapper class to surround your content (this should help to constrain your element widths and prevent them from expanding too far beyond the content):

<style>
.wrapper {
  width: 980px;
}
</style>

<body>
  <div class="wrapper">
    //everything else
  </div>
</body>

As far as the content boxes go, I would suggest trying to use

<style>
.boxes {
  display: inline-block;
  width: 360px;
  height: 360px;
}
#leftBox {
  float: left;
}
#rightBox {
  float: right;
}
</style>

I would spend some time researching the box-object model and all of the "display" properties. They will be forever helpful. Pay particularly close attention to "inline-block", I use it practically every day.

Get properties and values from unknown object

I haven't found this to work on, say Application objects. I have however had success with

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

string rval = serializer.Serialize(myAppObj);

Parse JSON String into List<string>

Since you are using JSON.NET, personally I would go with serialization so that you can have Intellisense support for your object. You'll need a class that represents your JSON structure. You can build this by hand, or you can use something like json2csharp to generate it for you:

e.g.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class RootObject
{
    public List<Person> People { get; set; }
}

Then, you can simply call JsonConvert's methods to deserialize the JSON into an object:

RootObject instance = JsonConvert.Deserialize<RootObject>(json);

Then you have Intellisense:

var firstName = instance.People[0].FirstName;
var lastName = instance.People[0].LastName;

Trust Anchor not found for Android SSL Connection

**Set proper alias name**
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
            String alias = cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);

iPhone App Icons - Exact Radius?

The iphone rounds corners for you, all you need is a square 57x57 png icon and u should be good

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If you are having this problem with a homebrew installation of maven 3 on the OSX 10.9.4 then check out this blog post.

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

span with onclick event inside a tag

<a href="http://the.url.com/page.html">
    <span onclick="hide(); return false">Hide me</span>
</a>

This is the easiest solution.

Trusting all certificates with okHttp

This is sonxurxo's solution in Kotlin, if anyone needs it.

private fun getUnsafeOkHttpClient(): OkHttpClient {
    // Create a trust manager that does not validate certificate chains
    val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        }

        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        }

        override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
    })

    // Install the all-trusting trust manager
    val sslContext = SSLContext.getInstance("SSL")
    sslContext.init(null, trustAllCerts, java.security.SecureRandom())
    // Create an ssl socket factory with our all-trusting manager
    val sslSocketFactory = sslContext.socketFactory

    return OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
        .hostnameVerifier { _, _ -> true }.build()
}

Generating an MD5 checksum of a file

There is a way that's pretty memory inefficient.

single file:

import hashlib
def file_as_bytes(file):
    with file:
        return file.read()

print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()

list of files:

[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:

[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]

If you only want 128 bits worth of digest you can do .digest()[:16].

This will give you a list of tuples, each tuple containing the name of its file and its hash.

Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.

Here is a way that is more complex, but memory efficient:

import hashlib

def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
    for block in bytesiter:
        hasher.update(block)
    return hasher.hexdigest() if ashexstr else hasher.digest()

def file_as_blockiter(afile, blocksize=65536):
    with afile:
        block = afile.read(blocksize)
        while len(block) > 0:
            yield block
            block = afile.read(blocksize)


[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
    for fname in fnamelst]

And, again, since MD5 is broken and should not really ever be used anymore:

[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
    for fname in fnamelst]

Again, you can put [:16] after the call to hash_bytestr_iter(...) if you only want 128 bits worth of digest.