Programs & Examples On #Qtreewidget

QTreeWidget is a class in Qt that provides a tree-like view of data.

How do I read the source code of shell commands?

    cd ~ && apt-get source coreutils && ls -d coreutils*     

You should be able to use a command like this on ubuntu to gather the source for a package, you can omit sudo assuming your downloading to a location you own.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

The octothorpe/number-sign/hashmark has a special significance in an URL, it normally identifies the name of a section of a document. The precise term is that the text following the hash is the anchor portion of an URL. If you use Wikipedia, you will see that most pages have a table of contents and you can jump to sections within the document with an anchor, such as:

https://en.wikipedia.org/wiki/Alan_Turing#Early_computers_and_the_Turing_test

https://en.wikipedia.org/wiki/Alan_Turing identifies the page and Early_computers_and_the_Turing_test is the anchor. The reason that Facebook and other Javascript-driven applications (like my own Wood & Stones) use anchors is that they want to make pages bookmarkable (as suggested by a comment on that answer) or support the back button without reloading the entire page from the server.

In order to support bookmarking and the back button, you need to change the URL. However, if you change the page portion (with something like window.location = 'http://raganwald.com';) to a different URL or without specifying an anchor, the browser will load the entire page from the URL. Try this in Firebug or Safari's Javascript console. Load http://minimal-github.gilesb.com/raganwald. Now in the Javascript console, type:

window.location = 'http://minimal-github.gilesb.com/raganwald';

You will see the page refresh from the server. Now type:

window.location = 'http://minimal-github.gilesb.com/raganwald#try_this';

Aha! No page refresh! Type:

window.location = 'http://minimal-github.gilesb.com/raganwald#and_this';

Still no refresh. Use the back button to see that these URLs are in the browser history. The browser notices that we are on the same page but just changing the anchor, so it doesn't reload. Thanks to this behaviour, we can have a single Javascript application that appears to the browser to be on one 'page' but to have many bookmarkable sections that respect the back button. The application must change the anchor when a user enters different 'states', and likewise if a user uses the back button or a bookmark or a link to load the application with an anchor included, the application must restore the appropriate state.

So there you have it: Anchors provide Javascript programmers with a mechanism for making bookmarkable, indexable, and back-button-friendly applications. This technique has a name: It is a Single Page Interface.

p.s. There is a fourth benefit to this technique: Loading page content through AJAX and then injecting it into the current DOM can be much faster than loading a new page. In addition to the speed increase, further tricks like loading certain portions in the background can be performed under the programmer's control.

p.p.s. Given all of that, the 'bang' or exclamation mark is a further hint to Google's web crawler that the exact same page can be loaded from the server at a slightly different URL. See Ajax Crawling. Another technique is to make each link point to a server-accessible URL and then use unobtrusive Javascript to change it into an SPI with an anchor.

Here's the key link again: The Single Page Interface Manifesto

When would you use the Builder Pattern?

Building on the previous answers (pun intended), an excellent real-world example is Groovy's built in support for Builders.

See Builders in the Groovy Documentation

Amazon S3 direct file upload from client browser - private key disclosure

Here is how you generate a policy document using node and serverless

"use strict";

const uniqid = require('uniqid');
const crypto = require('crypto');

class Token {

    /**
     * @param {Object} config SSM Parameter store JSON config
     */
    constructor(config) {

        // Ensure some required properties are set in the SSM configuration object
        this.constructor._validateConfig(config);

        this.region = config.region; // AWS region e.g. us-west-2
        this.bucket = config.bucket; // Bucket name only
        this.bucketAcl = config.bucketAcl; // Bucket access policy [private, public-read]
        this.accessKey = config.accessKey; // Access key
        this.secretKey = config.secretKey; // Access key secret

        // Create a really unique videoKey, with folder prefix
        this.key = uniqid() + uniqid.process();

        // The policy requires the date to be this format e.g. 20181109
        const date = new Date().toISOString();
        this.dateString = date.substr(0, 4) + date.substr(5, 2) + date.substr(8, 2);

        // The number of minutes the policy will need to be used by before it expires
        this.policyExpireMinutes = 15;

        // HMAC encryption algorithm used to encrypt everything in the request
        this.encryptionAlgorithm = 'sha256';

        // Client uses encryption algorithm key while making request to S3
        this.clientEncryptionAlgorithm = 'AWS4-HMAC-SHA256';
    }

    /**
     * Returns the parameters that FE will use to directly upload to s3
     *
     * @returns {Object}
     */
    getS3FormParameters() {
        const credentialPath = this._amazonCredentialPath();
        const policy = this._s3UploadPolicy(credentialPath);
        const policyBase64 = new Buffer(JSON.stringify(policy)).toString('base64');
        const signature = this._s3UploadSignature(policyBase64);

        return {
            'key': this.key,
            'acl': this.bucketAcl,
            'success_action_status': '201',
            'policy': policyBase64,
            'endpoint': "https://" + this.bucket + ".s3-accelerate.amazonaws.com",
            'x-amz-algorithm': this.clientEncryptionAlgorithm,
            'x-amz-credential': credentialPath,
            'x-amz-date': this.dateString + 'T000000Z',
            'x-amz-signature': signature
        }
    }

    /**
     * Ensure all required properties are set in SSM Parameter Store Config
     *
     * @param {Object} config
     * @private
     */
    static _validateConfig(config) {
        if (!config.hasOwnProperty('bucket')) {
            throw "'bucket' is required in SSM Parameter Store Config";
        }
        if (!config.hasOwnProperty('region')) {
            throw "'region' is required in SSM Parameter Store Config";
        }
        if (!config.hasOwnProperty('accessKey')) {
            throw "'accessKey' is required in SSM Parameter Store Config";
        }
        if (!config.hasOwnProperty('secretKey')) {
            throw "'secretKey' is required in SSM Parameter Store Config";
        }
    }

    /**
     * Create a special string called a credentials path used in constructing an upload policy
     *
     * @returns {String}
     * @private
     */
    _amazonCredentialPath() {
        return this.accessKey + '/' + this.dateString + '/' + this.region + '/s3/aws4_request';
    }

    /**
     * Create an upload policy
     *
     * @param {String} credentialPath
     *
     * @returns {{expiration: string, conditions: *[]}}
     * @private
     */
    _s3UploadPolicy(credentialPath) {
        return {
            expiration: this._getPolicyExpirationISODate(),
            conditions: [
                {bucket: this.bucket},
                {key: this.key},
                {acl: this.bucketAcl},
                {success_action_status: "201"},
                {'x-amz-algorithm': 'AWS4-HMAC-SHA256'},
                {'x-amz-credential': credentialPath},
                {'x-amz-date': this.dateString + 'T000000Z'}
            ],
        }
    }

    /**
     * ISO formatted date string of when the policy will expire
     *
     * @returns {String}
     * @private
     */
    _getPolicyExpirationISODate() {
        return new Date((new Date).getTime() + (this.policyExpireMinutes * 60 * 1000)).toISOString();
    }

    /**
     * HMAC encode a string by a given key
     *
     * @param {String} key
     * @param {String} string
     *
     * @returns {String}
     * @private
     */
    _encryptHmac(key, string) {
        const hmac = crypto.createHmac(
            this.encryptionAlgorithm, key
        );
        hmac.end(string);

        return hmac.read();
    }

    /**
     * Create an upload signature from provided params
     * https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html#signing-request-intro
     *
     * @param policyBase64
     *
     * @returns {String}
     * @private
     */
    _s3UploadSignature(policyBase64) {
        const dateKey = this._encryptHmac('AWS4' + this.secretKey, this.dateString);
        const dateRegionKey = this._encryptHmac(dateKey, this.region);
        const dateRegionServiceKey = this._encryptHmac(dateRegionKey, 's3');
        const signingKey = this._encryptHmac(dateRegionServiceKey, 'aws4_request');

        return this._encryptHmac(signingKey, policyBase64).toString('hex');
    }
}

module.exports = Token;

The configuration object used is stored in SSM Parameter Store and looks like this

{
    "bucket": "my-bucket-name",
    "region": "us-west-2",
    "bucketAcl": "private",
    "accessKey": "MY_ACCESS_KEY",
    "secretKey": "MY_SECRET_ACCESS_KEY",
}

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I have the same issue(in my 3-Tire level project) and I fixed it by adding/installing the EF to my main Project.

C# - Winforms - Global Variables

Or you could put your globals in the app.config

How do I check if a given Python string is a substring of another one?

string.find("substring") will help you. This function returns -1 when there is no substring.

How to use a link to call JavaScript?

just use javascript:---- exemplale

javascript:var JFL_81371678974472 = new JotformFeedback({ formId: '81371678974472', base: 'https://form.jotform.me/', windowTitle: 'Photobook Series', background: '#e44c2a', fontColor: '#FFFFFF', type: 'false', height: 700, width: 500, openOnLoad: true })

How to put a component inside another component in Angular2?

You don't put a component in directives

You register it in @NgModule declarations:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyChildComponent ],
  bootstrap: [ App ]
})

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

Cannot find control with name: formControlName in angular reactive form

I also had this error, and you helped me solve it. If formGroup or formGroupName are not written with the good case, then the name of the control is not found. Correct the case of formGroup or formGroupName and it is OK.

Linq select object from list depending on objects attribute

Your expression is never going to evaluate.

You are comparing a with a property of a.

a is of type Answer. a.Correct, I'm guessing is a boolean.

Long form:-

Answer = answer.SingleOrDefault(a => a.Correct == true);

Short form:-

Answer = answer.SingleOrDefault(a => a.Correct);

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

highlight the navigation menu for the current page

I would normally handle this on the server-side of things (meaning PHP, ASP.NET, etc). The idea is that when the page is loaded, the server-side controls the mechanism (perhaps by setting a CSS value) that is reflected in the resulting HTML the client sees.

How can I tell gcc not to inline a function?

Use the noinline attribute:

int func(int arg) __attribute__((noinline))
{
}

You should probably use it both when you declare the function for external use and when you write the function.

Closing JFrame with button click

You cat use setVisible () method of JFrame (and set visibility to false) or dispose () method which is more similar to close operation.

.htaccess file to allow access to images folder to view pictures?

Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:

Options -Indexes

Or try:

Options All -Indexes

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

I found this question because having trouble with configparser.ConfigParser().read(fp) when opening files with UTF8 BOM header.

For those who are looking for a solution to remove the header so that ConfigPhaser could open the config file instead of reporting an error of: File contains no section headers, please open the file like the following:

configparser.ConfigParser().read(config_file_path, encoding="utf-8-sig")

This could save you tons of effort by making the remove of the BOM header of the file unnecessary.

(I know this sounds unrelated, but hopefully this could help people struggling like me.)

How to round the double value to 2 decimal points?

public static double addDoubles(double a, double b) {
        BigDecimal A = new BigDecimal(a + "");
        BigDecimal B = new BigDecimal(b + "");
        return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

How to find sitemap.xml path on websites?

I don't think there's a standard as to the location of the sitemap. That's the reason why you should specify an arbitrary URL to your sitemap when you're adding one using Google's Webmaster Tools.

How can I make a JUnit test wait?

Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.

If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.

To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.

It has a nice fluent api as well

await().until(() -> 
{
    return yourConditionIsMet();
});  

https://github.com/jayway/awaitility

AJAX cross domain call

You will need to dynamically insert a script tag into the page that references the data. Using JSONP, you can execute some callback function when the script has loaded.

The wikipedia page on JSONP has a concise example; the script tag:

<script type="text/javascript" src="http://domain1.com/getjson?jsonp=parseResponse">
</script>

would return the JSON data wrapped in a call to parseResponse:

parseResponse({"Name": "Cheeso", "Rank": 7})

(depending on the configuration of the getjson script on domain1.com)

The code to insert the tag dynamically would be something like:

var s = document.createElement("script");
s.src = "http://domain1.com/getjson?jsonp=parseResponse";
s.type = "text/javascript";
document.appendChild(s);

Should have subtitle controller already set Mediaplayer error Android

To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)

XOR operation with two strings in java

Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).

You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.

Is String.Contains() faster than String.IndexOf()?

Contains calls IndexOf:

public bool Contains(string value)
{
    return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

Which calls CompareInfo.IndexOf, which ultimately uses a CLR implementation.

If you want to see how strings are compared in the CLR this will show you (look for CaseInsensitiveCompHelper).

IndexOf(string) has no options and Contains()uses an Ordinal compare (a byte-by-byte comparison rather than trying to perform a smart compare, for example, e with é).

So IndexOf will be marginally faster (in theory) as IndexOf goes straight to a string search using FindNLSString from kernel32.dll (the power of reflector!).

Updated for .NET 4.0 - IndexOf no longer uses Ordinal Comparison and so Contains can be faster. See comment below.

How do I repair an InnoDB table?

Step 1.

Stop MySQL server

Step 2.

add this line to my.cnf ( In windows it is called my.ini )

set-variable=innodb_force_recovery=6

Step 3.

delete ib_logfile0 and ib_logfile1

Step 4.

Start MySQL server

Step 5.

Run this command:

mysqlcheck --database db_name table_name -uroot -p

After you have successfully fixed the crashed innodb table, don't forget to remove #set-variable=innodb_force_recovery=6 from my.cnf and then restart MySQL server again.

How to pass anonymous types as parameters?

You can do it like this:

public void LogEmployees<T>(List<T> list) // Or IEnumerable<T> list
{
    foreach (T item in list)
    {

    }
}

... but you won't get to do much with each item. You could call ToString, but you won't be able to use (say) Name and Id directly.

UICollectionView spacing margins

Just to correct some wrong information in this page:

1- minimumInteritemSpacing: The minimum spacing to use between items in the same row.

The default value: 10.0.

(For a vertically scrolling grid, this value represents the minimum spacing between items in the same row.)

2- minimumLineSpacing : The minimum spacing to use between lines of items in the grid.

Ref: http://developer.apple.com/library/ios/#documentation/uikit/reference/UICollectionViewFlowLayout_class/Reference/Reference.html

What is the best way to know if all the variables in a Class are null?

This can be done fairly easily using a Lombok generated equals and a static EMPTY object:

import lombok.Data;

public class EmptyCheck {
    public static void main(String[] args) {
        User user1 = new User();

        User user2 = new User();
        user2.setName("name");

        System.out.println(user1.isEmpty()); // prints true
        System.out.println(user2.isEmpty()); // prints false
    }

    @Data
    public static class User {
        private static final User EMPTY = new User();

        private String id;
        private String name;
        private int age;

        public boolean isEmpty() {
            return this.equals(EMPTY);
        }
    }
}

Prerequisites:

  • Default constructor should not be implemented with custom behavior as that is used to create the EMPTY object
  • All fields of the class should have an implemented equals (built-in Java types are usually not a problem, in case of custom types you can use Lombok)

Advantages:

  • No reflection involved
  • As new fields added to the class, this does not require any maintenance as due to Lombok they will be automatically checked in the equals implementation
  • Unlike some other answers this works not just for null checks but also for primitive types which have a non-null default value (e.g. if field is int it checks for 0, in case of boolean for false, etc.)

SSL cert "err_cert_authority_invalid" on mobile chrome only

I just spent the morning dealing with this. The problem wasn't that I had a certificate missing. It was that I had an extra.

I started out with my ssl.conf containing my server key and three files provided by my SSL certificate authority:

#   Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer

#   Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key

#   Server Certificate Chain:
SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem

#   Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem

It worked fine on desktops, but Chrome on Android gave me err_cert_authority_invalid

A lot of headaches, searching and poor documentation later, I figured out that it was the Server Certificate Chain:

SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem

That was creating a second certificate chain which was incomplete. I commented out that line, leaving me with

#   Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer

#   Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key

#   Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem

and now it's working on Android again. This was on Linux running Apache 2.2.

cursor.fetchall() vs list(cursor) in Python

cursor.fetchall() and list(cursor) are essentially the same. The different option is to not retrieve a list, and instead just loop over the bare cursor object:

for result in cursor:

This can be more efficient if the result set is large, as it doesn't have to fetch the entire result set and keep it all in memory; it can just incrementally get each item (or batch them in smaller batches).

Current date without time

String test = DateTime.Now.ToString("dd.MM.yyy");

Wildcard string comparison in Javascript

Instead Animals == "bird*" Animals = "bird*" should work.

Python convert tuple to string

Easiest way would be to use join like this:

>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'

This works because your delimiter is essentially nothing, not even a blank space: ''.

Row count on the Filtered data

I know this an old thread, but I found out using the Subtotal method in VBA also accurately renders a count of the rows. The formula I found is in this article, and looks like this:

Application.WorksheetFunction.Subtotal(2, .Range("A2:A" & .Rows(.Rows.Count).End(xlUp).Row))

I tested it and it came out accurately every time, rendering the correct number of visible rows in column A.

Hopefully this will help some other wayfarer of the 'Net like me.

Unit testing private methods in C#

Another thought here is to extend testing to "internal" classes/methods, giving more of a white-box sense of this testing. You can use InternalsVisibleToAttribute on the assembly to expose these to separate unit testing modules.

In combination with sealed class you can approach such encapsulation that test method are visible only from unittest assembly your methods. Consider that protected method in sealed class is de facto private.

[assembly: InternalsVisibleTo("MyCode.UnitTests")]
namespace MyCode.MyWatch
{
    #pragma warning disable CS0628 //invalid because of InternalsVisibleTo
    public sealed class MyWatch
    {
        Func<DateTime> _getNow = delegate () { return DateTime.Now; };


       //construktor for testing purposes where you "can change DateTime.Now"
       internal protected MyWatch(Func<DateTime> getNow)
       {
           _getNow = getNow;
       }

       public MyWatch()
       {            
       }
   }
}

And unit test:

namespace MyCode.UnitTests
{

[TestMethod]
public void TestminuteChanged()
{
    //watch for traviling in time
    DateTime baseTime = DateTime.Now;
    DateTime nowforTesting = baseTime;
    Func<DateTime> _getNowForTesting = delegate () { return nowforTesting; };

    MyWatch myWatch= new MyWatch(_getNowForTesting );
    nowforTesting = baseTime.AddMinute(1); //skip minute
    //TODO check myWatch
}

[TestMethod]
public void TestStabilityOnFebruary29()
{
    Func<DateTime> _getNowForTesting = delegate () { return new DateTime(2024, 2, 29); };
    MyWatch myWatch= new MyWatch(_getNowForTesting );
    //component does not crash in overlap year
}
}

Show/hide 'div' using JavaScript

And the Purescript answer, for people using Halogen:

import CSS (display, displayNone)
import Halogen.HTML as HH
import Halogen.HTML.CSS as CSS

render state = 
  HH.div [ CSS.style $ display displayNone ] [ HH.text "Hi there!" ]

If you "inspect element", you'll see something like:

<div style="display: none">Hi there!</div>

but nothing will actually display on your screen, as expected.

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

Using Jasmine to spy on a function without an object

A very simple way:

import * as myFunctionContainer from 'whatever-lib';

const fooSpy = spyOn(myFunctionContainer, 'myFunc');

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

How to convert an NSTimeInterval (seconds) into minutes

Brian Ramsay’s code, de-pseudofied:

- (NSString*)formattedStringForDuration:(NSTimeInterval)duration
{
    NSInteger minutes = floor(duration/60);
    NSInteger seconds = round(duration - minutes * 60);
    return [NSString stringWithFormat:@"%d:%02d", minutes, seconds];
}

How to monitor the memory usage of Node.js?

The built-in process module has a method memoryUsage that offers insight in the memory usage of the current Node.js process. Here is an example from in Node v0.12.2 on a 64-bit system:

$ node --expose-gc
> process.memoryUsage();  // Initial usage
{ rss: 19853312, heapTotal: 9751808, heapUsed: 4535648 }
> gc();                   // Force a GC for the baseline.
undefined
> process.memoryUsage();  // Baseline memory usage.
{ rss: 22269952, heapTotal: 11803648, heapUsed: 4530208 }
> var a = new Array(1e7); // Allocate memory for 10m items in an array
undefined
> process.memoryUsage();  // Memory after allocating so many items
{ rss: 102535168, heapTotal: 91823104, heapUsed: 85246576 }
> a = null;               // Allow the array to be garbage-collected
null
> gc();                   // Force GC (requires node --expose-gc)
undefined
> process.memoryUsage();  // Memory usage after GC
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4528072 }
> process.memoryUsage();  // Memory usage after idling
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4753376 }

In this simple example, you can see that allocating an array of 10M elements consumers approximately 80MB (take a look at heapUsed).
If you look at V8's source code (Array::New, Heap::AllocateRawFixedArray, FixedArray::SizeFor), then you'll see that the memory used by an array is a fixed value plus the length multiplied by the size of a pointer. The latter is 8 bytes on a 64-bit system, which confirms that observed memory difference of 8 x 10 = 80MB makes sense.

How to use the onClick event for Hyperlink using C# code?

Wow, you have a huge misunderstanding how asp.net works.

This line of code

System.Diagnostics.Process.Start("help/AdminTutorial.html");

Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.

A very easy solution would be to change the href attribute of the link in you page_load method.

Your aspx code:

<a href="#" runat="server" id="myLink">Tutorial</a>

Your codebehind / cs code of page_load:

...
if (userinfo.user == "Admin")
{
  myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else 
{
  myLink.Attributes["href"] = "help/otherSite.html";
}
...

Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.

Writing an input integer into a cell

I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.

So

Range("RefNo") = InputBox("....") 

is safer than

Range("H1") = InputBox("....") 

You can set the value of several cells, too.

Range("Results").Resize(10,3) = arrResults()

where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this

Option Base 1

at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).

How to monitor network calls made from iOS Simulator

Recently i found a git repo that makes it easy.

You can try it.

This is an app's screenshot: enter image description here

Best regards.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

npm install Error: rollbackFailedOptional

    # first this
    > npm config rm proxy
    > npm config rm https-proxy

    # then this
    > npm config set registry https://registry.npmjs.org/

solved my problem.

Again: Be sure to check whether you have internet connected properly.

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

A similar error appears while pulling the changes from the origin. If you are trying in Intellij from the menu options, the pull might not work directly.

Go to terminal and type this command and this should work out: git pull origin master

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

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

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

Lua - Current time in milliseconds

I use LuaSocket to get more precision.

require "socket"
print("Milliseconds: " .. socket.gettime()*1000)

This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).

angularjs getting previous route path

modification for the code above:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('prev path: ' + absOldUrl.$$route.originalPath);
});

Why does "return list.sort()" return None, not the list?

Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

 x.compress().chop(y).sort(z)

which would be the same as

  x.compress()
  x.chop(y)
  x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

 y = x.rstrip("\n").split(":").lower()

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

You can go here to download the Java JRE.

You can go here to download the Java JDK.

After that you need to set up your environmental variables in Windows:

  1. Right-click My Computer
  2. Click Properties
  3. Go to Advanced System Settings
  4. Click on the Advanced tab
  5. Click on Environment Variables

EDIT: See screenshot for environmental variables

enter image description here

android:drawableLeft margin and/or padding

define a shape for your edittext and give it a padding For Example

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <padding
        android:left="5dp"
        android:right="5dp"
    />
    <solid android:color="#F6F6F6" />
    <stroke
        android:width="1px"
        android:color="#C3C3C3" />

    <corners
        android:bottomLeftRadius="1dp"
        android:bottomRightRadius="1dp"
        android:topLeftRadius="1dp"
        android:topRightRadius="1dp" />
</shape>

The padding defined in this shape will help in give padding to drawableleft or right ---------------------- Apply this shape on EditView

 <EditText
            android:id="@+id/example"
            android:layout_width="fill_parent"
            android:layout_height="36dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@drawable/shape2"
            android:drawableLeft="@drawable/icon1"
            android:drawablePadding="@dimen/txtDrwblPadding"
            android:ems="10"
         />

using that defined shape as background will give your EditText some style plus margin to drawableLeft.

GLYPHICONS - bootstrap icon font hex value

If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file

 @font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How to deal with certificates using Selenium?

And in C# (.net core) using Selenium.Webdriver and Selenium.Chrome.Webdriver like this:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--ignore-certificate-errors");
using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),options))
{ 
  ...
}

How can I see if a Perl hash already has a certain key?

I would counsel against using if ($hash{$key}) since it will not do what you expect if the key exists but its value is zero or empty.

Convert date to YYYYMM format

SELECT CONVERT(nvarchar(6), GETDATE(), 112)

SQL variable to hold list of integers

You can't do it like this, but you can execute the entire query storing it in a variable.

For example:

DECLARE @listOfIDs NVARCHAR(MAX) = 
    '1,2,3'

DECLARE @query NVARCHAR(MAX) = 
    'Select *
     From TabA
     Where TabA.ID in (' + @listOfIDs + ')'

Exec (@query)

rake assets:precompile RAILS_ENV=production not working as required

I had this problem today. I fixed it being being explict about my require

gem 'uglifier', '>= 1.0.3', require: 'uglifier'

I had mine still in the assets group.

What is the difference between localStorage, sessionStorage, session and cookies?

These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.

Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.

Local Storage does the same thing, but persists even when the browser is closed and reopened.

You can set and retrieve stored data as follows:

sessionStorage.setItem('key', 'value');

var data = sessionStorage.getItem('key');

Similarly for localStorage.

installing vmware tools: location of GCC binary?

First execute this

sudo apt-get install gcc binutils make linux-source

Then run again

/usr/bin/vmware-config-tools.pl

This is all you need to do. Now your system has the gcc make and the linux kernel sources.

Do I need to close() both FileReader and BufferedReader?

I'm late, but:

BufferReader.java:

public BufferedReader(Reader in) {
  this(in, defaultCharBufferSize);
}

(...)

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}

Bring element to front using CSS

Another Note: z-index must be considered when looking at children objects relative to other objects.

For example

<div class="container">
    <div class="branch_1">
        <div class="branch_1__child"></div>
    </div>
    <div class="branch_2">
        <div class="branch_2__child"></div>
    </div>
</div>

If you gave branch_1__child a z-index of 99 and you gave branch_2__child a z-index of 1, but you also gave your branch_2 a z-index of 10 and your branch_1 a z-index of 1, your branch_1__child still will not show up in front of your branch_2__child

Anyways, what I'm trying to say is; if a parent of an element you'd like to be placed in front has a lower z-index than its relative, that element will not be placed higher.

The z-index is relative to its containers. A z-index placed on a container farther up in the hierarchy basically starts a new "layer"

Incep[inception]tion

Here's a fiddle to play around:

https://jsfiddle.net/orkLx6o8/

How to work with string fields in a C struct?

On strings and memory allocation:

A string in C is just a sequence of chars, so you can use char * or a char array wherever you want to use a string data type:

typedef struct     {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} patient;

Then you need to allocate memory for the structure itself, and for each of the strings:

patient *createPatient(int number, char *name, 
  char *addr, char *bd, char sex) {

  // Allocate memory for the pointers themselves and other elements
  // in the struct.
  patient *p = malloc(sizeof(struct patient));

  p->number = number; // Scalars (int, char, etc) can simply be copied

  // Must allocate memory for contents of pointers.  Here, strdup()
  // creates a new copy of name.  Another option:
  // p->name = malloc(strlen(name)+1);
  // strcpy(p->name, name);
  p->name = strdup(name);
  p->address = strdup(addr);
  p->birthdate = strdup(bd);
  p->gender = sex;
  return p;
}

If you'll only need a few patients, you can avoid the memory management at the expense of allocating more memory than you really need:

typedef struct     {
  int number;
  char name[50];       // Declaring an array will allocate the specified
  char address[200];   // amount of memory when the struct is created,
  char birthdate[50];  // but pre-determines the max length and may
  char gender;         // allocate more than you need.
} patient;

On linked lists:

In general, the purpose of a linked list is to prove quick access to an ordered collection of elements. If your llist contains an element called num (which presumably contains the patient number), you need an additional data structure to hold the actual patients themselves, and you'll need to look up the patient number every time.

Instead, if you declare

typedef struct llist
{
  patient *p;
  struct llist *next;
} list;

then each element contains a direct pointer to a patient structure, and you can access the data like this:

patient *getPatient(list *patients, int num) {
  list *l = patients;
  while (l != NULL) {
    if (l->p->num == num) {
      return l->p;
    }
    l = l->next;
  }
  return NULL;
}

AutoComplete TextBox in WPF

If you have a small number of values to auto complete, you can simply add them in xaml. Typing will invoke auto-complete, plus you have dropdowns too.

<ComboBox Text="{Binding CheckSeconds, UpdateSourceTrigger=PropertyChanged}"
          IsEditable="True">
    <ComboBoxItem Content="60"/>
    <ComboBoxItem Content="120"/>
    <ComboBoxItem Content="180"/>
    <ComboBoxItem Content="300"/>
    <ComboBoxItem Content="900"/>
</ComboBox>

What are .NumberFormat Options In Excel VBA?

dovers gives us his great answer and based on it you can try use it like

public static class CellDataFormat
{
        public static string General { get { return "General"; } }
        public static string Number { get { return "0"; } }

        // Your custom format 
        public static string NumberDotTwoDigits { get { return "0.00"; } }

        public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
        public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
        public static string Date { get { return "m/d/yy"; } }
        public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
        public static string Percentage { get { return "0.00%"; } }
        public static string Fraction { get { return "# ?/?"; } }
        public static string Scientific { get { return "0.00E+00"; } }
        public static string Text { get { return "@"; } }
        public static string Special { get { return ";;"; } }
        public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}

How to disable an input type=text?

You can also by jquery:

$('#foo')[0].disabled = true;

Working example:

_x000D_
_x000D_
$('#foo')[0].disabled = true;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input id="foo" placeholder="placeholder" value="value" />
_x000D_
_x000D_
_x000D_

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

clientHeight/clientWidth returning different values on different browsers

This has to do with the browser's box model. Use something like jQuery or another JavaScript abstraction library to normalize the DOM model.

Console.log(); How to & Debugging javascript

I like to add these functions in the head.

window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};

Now log won't break IE I can enable it or disable it in one place I can log inline

$(".classname").log(); //show an array of all elements with classname class

History or log of commands executed in Git

I found out that in my version of git bash "2.24.0.windows.2" in my "home" folder under windows users, there will be a file called ".bash-history" with no file extension in that folder. It's only created after you exit from bash.

Here's my workflow:

  1. before exiting bash type "history >> history.txt" [ENTER]
  2. exit the bash prompt
  3. hold Win+R to open the Run command box
  4. enter shell:profile
  5. open "history.txt" to confirm that my text was added
  6. On a new line press [F5] to enter a timestamp
  7. save and close the history textfile
  8. Delete the ".bash-history" file so the next session will create a new history

If you really want points I guess you could make a batch file to do all this but this is good enough for me. Hope it helps someone.

This certificate has an invalid issuer Apple Push Services

Here is how we fixed this.

Step 1: Open Keychain access, delete "Apple world wide Developer relations certification authority" (which expires on 14th Feb 2016) from both "Login" and "System" sections. If you can't find it, use “Show Expired Certificates” in the View menu.

Step 2: Download this and add it to Keychain access -> Certificates (which expires on 8th Feb 2023).

Step 3: Everything should be back to normal and working now.

Reference: Apple Worldwide Developer Relations Intermediate Certificate Expiration

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I think it occurs due to the missing of environment variable named HTTPPORT. Just create that environment variable as 8080 will resolve the issue. or replace HTTPPORT as 8080 in the URL.

try this, http://127.0.0.1:8080/apex/f?p=4950

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

Query to display all tablespaces in a database and datafiles

SELECT a.file_name,
       substr(A.tablespace_name,1,14) tablespace_name,
       trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
       trunc(a.bytes/1024/1024) allocated_mb,
       trunc(A.MAXSIZE/1024/1024) capacity,
       a.autoextensible ae
FROM (
     SELECT file_id, file_name,
            tablespace_name,
            autoextensible,
            bytes,
            decode(autoextensible,'YES',maxbytes,bytes) maxsize
     FROM   dba_data_files
     GROUP BY file_id, file_name,
              tablespace_name,
              autoextensible,
              bytes,
              decode(autoextensible,'YES',maxbytes,bytes)
     ) a,
     (SELECT file_id,
             tablespace_name,
             sum(bytes) free
      FROM   dba_free_space
      GROUP BY file_id,
               tablespace_name
      ) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC; 

Generate an integer that is not among four billion given ones

  • The simplest approach is to find the minimum number in the file, and return 1 less than that. This uses O(1) storage, and O(n) time for a file of n numbers. However, it will fail if number range is limited, which could make min-1 not-a-number.

  • The simple and straightforward method of using a bitmap has already been mentioned. That method uses O(n) time and storage.

  • A 2-pass method with 2^16 counting-buckets has also been mentioned. It reads 2*n integers, so uses O(n) time and O(1) storage, but it cannot handle datasets with more than 2^16 numbers. However, it's easily extended to (eg) 2^60 64-bit integers by running 4 passes instead of 2, and easily adapted to using tiny memory by using only as many bins as fit in memory and increasing the number of passes correspondingly, in which case run time is no longer O(n) but instead is O(n*log n).

  • The method of XOR'ing all the numbers together, mentioned so far by rfrankel and at length by ircmaxell answers the question asked in stackoverflow#35185, as ltn100 pointed out. It uses O(1) storage and O(n) run time. If for the moment we assume 32-bit integers, XOR has a 7% probability of producing a distinct number. Rationale: given ~ 4G distinct numbers XOR'd together, and ca. 300M not in file, the number of set bits in each bit position has equal chance of being odd or even. Thus, 2^32 numbers have equal likelihood of arising as the XOR result, of which 93% are already in file. Note that if the numbers in file aren't all distinct, the XOR method's probability of success rises.

Can't connect to MySQL server on 'localhost' (10061) after Installation

I had the same issue and basically resolved it by pointing to a specific port number that my MySQL server was running on. Below is the command. Please edit the code to fit your case i.e your port number,your mysql server username,your password.

    mysql -u root -pYourMysqlRootPassword -P3307 

AngularJS - convert dates in controller

create a filter.js and you can make this as reusable

angular.module('yourmodule').filter('date', function($filter)
{
    return function(input)
    {
        if(input == null){ return ""; }
        var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
        return _date.toUpperCase();
    };
});

view

<span>{{ d.time | date }}</span>

or in controller

var filterdatetime = $filter('date')( yourdate );

Date filtering and formatting in Angular js.

Bootstrap 4 - Responsive cards in card-columns

Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
}

SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX

Or, CSS only like this...

@media (min-width: 576px) {
    .card-columns {
        column-count: 2;
    }
}

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;
    }
}

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;
    }
}

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;
    }
}

CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ

Simple proof that GUID is not unique

You can show that in O(1) time with a variant of the quantum bogosort algorithm.

Guid g1 = Guid.NewGuid();
Guid g2 = Guid.NewGuid();
if(g1 != g2) Universe.Current.Destroy();

Python element-wise tuple operations like sum

Yes. But you can't redefine built-in types. You have to subclass them:

class MyTuple(tuple):
    def __add__(self, other):
         if len(self) != len(other):
             raise ValueError("tuple lengths don't match")
         return MyTuple(x + y for (x, y) in zip(self, other))

How to read a text file in project's root directory?

private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

The method above will bring you something like this:

"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"

From here you can navigate backwards using System.IO.Directory.GetParent:

_filePath = Directory.GetParent(_filePath).FullName;

1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:

_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;

Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:

_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);

Hope it helps.

How to output git log with the first line only?

Better and easier git log by making an alias. Paste the code below to terminal just once for one session. Paste the code to zshrc or bash profile to make it persistant.

git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Output

git lg

Output changed lines

git lg -p

Alternatively (recommended)
Paste this code to global .gitconfig file

[alias]
  lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

Further Reading.
https://coderwall.com/p/euwpig/a-better-git-log
Advanced Reading.
http://durdn.com/blog/2012/11/22/must-have-git-aliases-advanced-examples/

AngularJS does not send hidden field value

Directly assign the value to model in data-ng-value attribute. Since Angular interpreter doesn't recognize hidden fields as part of ngModel.

<input type="hidden" name="pfuserid" data-ng-value="newPortfolio.UserId = data.Id"/>

Highlight a word with jQuery

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

error: command 'gcc' failed with exit status 1 on CentOS

yum install gcc-c++

on aws ec2 (aws linux),it works

??

ImportError: No module named model_selection

In Late September 2016, SciKit Learn 0.18 was released and there was a slight change to the code. With SciKit Learn 0.18 the train_test_split function is now imported from model_selection instead of cross_validation.

from sklearn.cross_validation import train_test_split

has been changed to :

from sklearn.model_selection import train_test_split

The same has also happened for GridSearchCV.

passing argument to DialogFragment

as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle.

the built-in method for that in the Fragment class is setArguments(Bundle) and getArguments().

basically, what you do is set up a bundle with all your Parcelable items and send them on.
in turn, your Fragment will get those items in it's onCreate and do it's magic to them.

the way shown in the DialogFragment link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually.

Android video streaming example

I had the same problem but finally I found the way.

Here is the walk through:

1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)

2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.

3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:

:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}

NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...

NOTE: You can see, the video codec is MP4V which is supported by android.

4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:

mVideoView = (VideoView) findViewById(R.id.surface_view);

mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));

5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...

Question: Anybody know how to reduce buffering time and play video almost live ?

How to load image to WPF in runtime?

In WPF an image is typically loaded from a Stream or an Uri.

BitmapImage supports both and an Uri can even be passed as constructor argument:

var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);

If the image file is located in a local folder, you would have to use a file:// Uri. You could create such a Uri from a path like this:

var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);

If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:

var uri = new Uri("pack://application:,,,/Bilder/sas.png");

In this case the Visual Studio Build Action for sas.png would have to be Resource.

Once you have created a BitmapImage and also have an Image control like in this XAML

<Image Name="image1" />

you would simply assign the BitmapImage to the Source property of that Image control:

image1.Source = bitmap;

What is the difference between UNION and UNION ALL?

The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.

from http://zengin.wordpress.com/2007/07/31/union-vs-union-all/

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

I got this same issue when working with Bolts.framework. It turns out that when Bolts gets corrupted, no amount of re-importing will fix the issue. I had to go back to the original download file and reimport it completely from scratch. This fixed it right away. It was such a weird issue that it took me forever to figure it out... hopefully this tip will spare some of you from the same frustrations :)

Print a div using javascript in angularJS single page application

I done this way:

$scope.printDiv = function (div) {
  var docHead = document.head.outerHTML;
  var printContents = document.getElementById(div).outerHTML;
  var winAttr = "location=yes, statusbar=no, menubar=no, titlebar=no, toolbar=no,dependent=no, width=865, height=600, resizable=yes, screenX=200, screenY=200, personalbar=no, scrollbars=yes";

  var newWin = window.open("", "_blank", winAttr);
  var writeDoc = newWin.document;
  writeDoc.open();
  writeDoc.write('<!doctype html><html>' + docHead + '<body onLoad="window.print()">' + printContents + '</body></html>');
  writeDoc.close();
  newWin.focus();
}

How to align LinearLayout at the center of its parent?

@jksschneider explation is almost right. Make sure that you haven't set any gravity to parent layout, and then set layout_gravity="center" to your view or layout.

ORA-00932: inconsistent datatypes: expected - got CLOB

You can't put a CLOB in the WHERE clause. From the documentation:

Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data.

If your values are always less than 4k, you can use:

UPDATE IMS_TEST 
   SET TEST_Category           = 'just testing'  
 WHERE to_char(TEST_SCRIPT)    = 'something'
   AND ID                      = '10000239';

It is strange to search by a CLOB anyways.. could you not just search by the ID column?

Setting selected option in laravel form

            @foreach ($categories as $category)
             <option value="{{$category->id}}" 
               @foreach ($posts->postRelateToCategory as $Postcategory)
                 @if ($Postcategory->id == $category->id)
                 {{'selected="selected"'}}
                 @endif 
               @endforeach >
              {{ $category->category_name }} </option>               
            @endforeach    

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Searching if value exists in a list of objects using Linq

Try this, I hope it helps you.

 if (lstCustumers.Any(cus => cus.Firstname == "John"))
 {
     //TODO CODE
 }

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.

I had no luck with any of the above methods.

I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.

This is working very well for me.

(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf

How to truncate milliseconds off of a .NET DateTime

var date = DateTime.Now;

date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);

Omitting all xsi and xsd namespaces when serializing an object in .NET?

...
XmlSerializer s = new XmlSerializer(objectToSerialize.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
s.Serialize(xmlWriter, objectToSerialize, ns);

OS X Framework Library not loaded: 'Image not found'

It was quite simple for me, i just added my framework to my embedded binaries under app targets

Difference between map and collect in Ruby?

The collect and collect! methods are aliases to map and map!, so they can be used interchangeably. Here is an easy way to confirm that:

Array.instance_method(:map) == Array.instance_method(:collect)
 => true

mysql query result into php array

What about this:

while ($row = mysql_fetch_array($result)) 
{
    $new_array[$row['id']]['id'] = $row['id'];
    $new_array[$row['id']]['link'] = $row['link'];
}

To retrieve link and id:

foreach($new_array as $array)
{       
   echo $array['id'].'<br />';
   echo $array['link'].'<br />';
}

SQL Inner join 2 tables with multiple column conditions and update

You need to do

Update table_xpto
set column_xpto = x.xpto_New
    ,column2 = x.column2New
from table_xpto xpto
   inner join table_xptoNew xptoNew ON xpto.bla = xptoNew.Bla
where <clause where>

If you need a better answer, you can give us more information :)

Check if event exists on element

You may use:

$("#foo").unbind('click');

to make sure all click events are unbinded, then attach your event

What is the most effective way for float and double comparison?

My class based on previously posted answers. Very similar to Google's code but I use a bias which pushes all NaN values above 0xFF000000. That allows a faster check for NaN.

This code is meant to demonstrate the concept, not be a general solution. Google's code already shows how to compute all the platform specific values and I didn't want to duplicate all that. I've done limited testing on this code.

typedef unsigned int   U32;
//  Float           Memory          Bias (unsigned)
//  -----           ------          ---------------
//   NaN            0xFFFFFFFF      0xFF800001
//   NaN            0xFF800001      0xFFFFFFFF
//  -Infinity       0xFF800000      0x00000000 ---
//  -3.40282e+038   0xFF7FFFFF      0x00000001    |
//  -1.40130e-045   0x80000001      0x7F7FFFFF    |
//  -0.0            0x80000000      0x7F800000    |--- Valid <= 0xFF000000.
//   0.0            0x00000000      0x7F800000    |    NaN > 0xFF000000
//   1.40130e-045   0x00000001      0x7F800001    |
//   3.40282e+038   0x7F7FFFFF      0xFEFFFFFF    |
//   Infinity       0x7F800000      0xFF000000 ---
//   NaN            0x7F800001      0xFF000001
//   NaN            0x7FFFFFFF      0xFF7FFFFF
//
//   Either value of NaN returns false.
//   -Infinity and +Infinity are not "close".
//   -0 and +0 are equal.
//
class CompareFloat{
public:
    union{
        float     m_f32;
        U32       m_u32;
    };
    static bool   CompareFloat::IsClose( float A, float B, U32 unitsDelta = 4 )
                  {
                      U32    a = CompareFloat::GetBiased( A );
                      U32    b = CompareFloat::GetBiased( B );

                      if ( (a > 0xFF000000) || (b > 0xFF000000) )
                      {
                          return( false );
                      }
                      return( (static_cast<U32>(abs( a - b ))) < unitsDelta );
                  }
    protected:
    static U32    CompareFloat::GetBiased( float f )
                  {
                      U32    r = ((CompareFloat*)&f)->m_u32;

                      if ( r & 0x80000000 )
                      {
                          return( ~r - 0x007FFFFF );
                      }
                      return( r + 0x7F800000 );
                  }
};

How to fix error Base table or view not found: 1146 Table laravel relationship table?

It seems Laravel is trying to use category_posts table (because of many-to-many relationship). But you don't have this table, because you've created category_post table. Change name of the table to category_posts.

Python: count repeated elements in the list

This works for Python 2.6.6

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result

prints

{'a': 2, 'b': 1}

How do I create executable Java program?

If you are using Eclipse , you can try the below 7 steps to get a .exe file for Windows.

step1step2step3

Now you have a JAR file. Use java -jar path/jarname.jar to execute.

enter image description here


If you want to convert this to .exe, you can try http://sourceforge.net/projects/launch4j/files/launch4j-3/

STEP5STEP6

STEP7: Give the .xml file an appropriate name and click "Save". The .xml file is standard, don't worry about it. Your executable file will now be created!

Open PDF in new browser full window

var pdf = MyPdf.pdf;
window.open(pdf);

This will open the pdf document in a full window from JavaScript

A function to open windows would look like this:

function openPDF(pdf){
  window.open(pdf);
  return false;
}

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

Serializing enums with Jackson

Use @JsonCreator annotation, create method getType(), is serialize with toString or object working

{"ATIVO"}

or

{"type": "ATIVO", "descricao": "Ativo"}

...

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SituacaoUsuario {

    ATIVO("Ativo"),
    PENDENTE_VALIDACAO("Pendente de Validação"),
    INATIVO("Inativo"),
    BLOQUEADO("Bloqueado"),
    /**
     * Usuarios cadastrados pelos clientes que não possuem acesso a aplicacao,
     * caso venham a se cadastrar este status deve ser alterado
     */
    NAO_REGISTRADO("Não Registrado");

    private SituacaoUsuario(String descricao) {
        this.descricao = descricao;
    }

    private String descricao;

    public String getDescricao() {
        return descricao;
    }

    // TODO - Adicionar metodos dinamicamente
    public String getType() {
        return this.toString();
    }

    public String getPropertieKey() {
        StringBuilder sb = new StringBuilder("enum.");
        sb.append(this.getClass().getName()).append(".");
        sb.append(toString());
        return sb.toString().toLowerCase();
    }

    @JsonCreator
    public static SituacaoUsuario fromObject(JsonNode node) {
        String type = null;
        if (node.getNodeType().equals(JsonNodeType.STRING)) {
            type = node.asText();
        } else {
            if (!node.has("type")) {
                throw new IllegalArgumentException();
            }
            type = node.get("type").asText();
        }
        return valueOf(type);
    }

}

How can I move a tag on a git branch to a different commit?

Delete it with git tag -d <tagname> and then recreate it on the correct commit.

Java read file and store text in an array

I have found this way of reading strings from files to work best for me

String st, full;
full="";
BufferedReader br = new BufferedReader(new FileReader(URL));
while ((st=br.readLine())!=null) {
    full+=st;
}

"full" will be the completed combination of all of the lines. If you want to add a line break between the lines of text you would do full+=st+"\n";

How to run regasm.exe from command line other than Visual Studio command prompt?

Execute only 1 of the below
Once a command works, skip the rest/ below to it:

Normal:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll /tlb:myTest.tlb
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll /tlb:myTest.tlb /codebase

Only if you face issues, use old version 'v2.0.50727':

%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll /tlb:myTest.tlb
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll /tlb:myTest.tlb 

Only if you built myTest.dll for 64bit Only, use 'Framework64' path:

%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework64\v2.0.50727\RegAsm.exe myTest.dll

Note: 64-bit built dlls will not work on 32-bit platform.

All options:

See https://docs.microsoft.com/en-us/dotnet/framework/tools/regasm-exe-assembly-registration-tool

Wait some seconds without blocking UI execution

This is a good case for using another thread:

// Call some method
this.Method();

Task.Factory.StartNew(() =>
{
    Thread.Sleep(20000);

    // Do things here.
    // NOTE: You may need to invoke this to your main thread depending on what you're doing
});

The above code expects .NET 4.0 or above, otherwise try:

ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
    Thread.Sleep(20000);

    // Do things here
}));

PHP Error: Cannot use object of type stdClass as array (array and object issues)

If you're iterating over an object instead of an array, you'll need to access the properties using:

$id = $blog->id;
$title = $blog->title;
$content = $blog->content;

That, or change your object to an array.

Removing empty lines in Notepad++

You can follow the technique as shown in the following screenshot:

  • Find what: ^\r\n
  • Replace with: keep this empty
  • Search Mode: Regular expression
  • Wrap around: selected

enter image description here

NOTE: for *nix files just find by \n

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

How do I do pagination in ASP.NET MVC?

I think the easiest way to create pagination in ASP.NET MVC application is using PagedList library.

There is a complete example in following github repository. Hope it would help.

public class ProductController : Controller
{
    public object Index(int? page)
    {
        var list = ItemDB.GetListOfItems();

        var pageNumber = page ?? 1; 
        var onePageOfItem = list.ToPagedList(pageNumber, 25); // will only contain 25 items max because of the pageSize

        ViewBag.onePageOfItem = onePageOfProducts;
        return View();
    }
}

Demo Link: http://ajaxpagination.azurewebsites.net/

Source Code: https://github.com/ungleng/SimpleAjaxPagedListAndSearchMVC5

How to get Top 5 records in SqLite?

select * from [Table_Name] limit 5

Pandas - replacing column values

Can try this too!
Create a dictionary of replacement values.

import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

enter image description here

replace_dict= {0:'Female',1:'Male'}
print(replace_dict)

enter image description here

Use the map function for replacing values

data['sex']=data['sex'].map(replace_dict)

Output after replacing
enter image description here

Git: "please tell me who you are" error

i use heroku cli 1. must use all user name and user email

$git config --global user.email .login email.

$git config --global user.name .heroku name.

  1. git pull [git url]
  2. git init
  3. git add *

    5 git commit -m "after config user.name ,user email"

  4. git push heroku master

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

How stable is the git plugin for eclipse?

You can integrate Git-GUI with Eclipse as an alternative to EGit.

See this two part YouTube tutorial specific to Windows:
http://www.youtube.com/watch?v=DcM1xOiaidk
http://www.youtube.com/watch?v=1OrPJClD92s

Setting a timeout for socket operations

Use the Socket() constructor, and connect(SocketAddress endpoint, int timeout) method instead.

In your case it would look something like:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

Quoting from the documentation

connect

public void connect(SocketAddress endpoint, int timeout) throws IOException

Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

Parameters:

endpoint - the SocketAddress
timeout - the timeout value to be used in milliseconds.

Throws:

IOException - if an error occurs during the connection
SocketTimeoutException - if timeout expires before connecting
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket

Since: 1.4

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

My problem was solved after turning Off Windows Firewall Defender in public network as I was connected with that network.

Java Switch Statement - Is "or"/"and" possible?

Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.

For OR, just have 2 cases without the break on the 1st. Eg:

case 'a':
case 'A':
  // do stuff
  break;

How to select a node of treeview programmatically in c#?

TreeViewItem tempItem = new TreeViewItem();
TreeViewItem tempItem1 = new TreeViewItem(); 
tempItem =  (TreeViewItem) treeView1.Items.GetItemAt(0);    // Selecting the first of the top level nodes
tempItem1 = (TreeViewItem)tempItem.Items.GetItemAt(0);      // Selecting the first child of the first first level node
SelectedCategoryHeaderString = tempItem.Header.ToString();  // gets the header for the first top level node
SelectedCategoryHeaderString = tempItem1.Header.ToString(); // gets the header for the first child node of the first top level node
tempItem.IsExpanded = true;         //  will expand the first node

Passing parameter to controller action from a Html.ActionLink

You are using the incorrect overload of ActionLink. Try this

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

Simple and readable version:

const NOW = new Date()
const times = [["second", 1], ["minute", 60], ["hour", 3600], ["day", 86400], ["week", 604800], ["month", 2592000], ["year", 31536000]]

function timeAgo(date) {
    var diff = Math.round((NOW - date) / 1000)
    for (var t = 0; t < times.length; t++) {
        if (diff < times[t][1]) {
            if (t == 0) {
                return "Just now"
            } else {
                diff = Math.round(diff / times[t - 1][1])
                return diff + " " + times[t - 1][0] + (diff == 1?" ago":"s ago")
            }
        }
    }
}

"The system cannot find the file specified"

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. text

Generally issues like this are related to any of the following need to be looked at:

  • firewall settings from the web server to the database server
  • connection string errors
  • enable the appropriate protocol pipes/ tcp-ip

Try connecting to sql server with sql management server on the system that sql server is installed on and work from there. Pay attention to information in the errorlogs.

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I solved this issue by running the following command in an elevated command prompt as specified in this post.

net start mssqlserver

Proper way to renew distribution certificate for iOS

Very simple was to renew your certificate. Go to your developer member centre and go to your Provisioning profile and see what are the certificate Active and InActive and select Inactive certificate and hit Edit button then hit generate button. Now your certificate successful renewal for another 1 year. Thanks

MVC controller : get JSON object from HTTP body?

It seems that if

  • Content-Type: application/json and
  • if POST body isn't tightly bound to controller's input object class

Then MVC doesn't really bind the POST body to any particular class. Nor can you just fetch the POST body as a param of the ActionResult (suggested in another answer). Fair enough. You need to fetch it from the request stream yourself and process it.

[HttpPost]
public ActionResult Index(int? id)
{
    Stream req = Request.InputStream;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();

    InputClass input = null;
    try
    {
        // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
        input = JsonConvert.DeserializeObject<InputClass>(json)
    }

    catch (Exception ex)
    {
        // Try and handle malformed POST body
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    //do stuff

}

Update:

for Asp.Net Core, you have to add [FromBody] attrib beside your param name in your controller action for complex JSON data types:

[HttpPost]
public ActionResult JsonAction([FromBody]Customer c)

Also, if you want to access the request body as string to parse it yourself, you shall use Request.Body instead of Request.InputStream:

Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Here you go: No synchronous tasks.

No synchronous tasks

Synchronous tasks are no longer supported. They often led to subtle mistakes that were hard to debug, like forgetting to return your streams from a task.

When you see the Did you forget to signal async completion? warning, none of the techniques mentioned above were used. You'll need to use the error-first callback or return a stream, promise, event emitter, child process, or observable to resolve the issue.

Using async/await

When not using any of the previous options, you can define your task as an async function, which wraps your task in a promise. This allows you to work with promises synchronously using await and use other synchronous code.

const fs = require('fs');

async function asyncAwaitTask() {
  const { version } = fs.readFileSync('package.json');
  console.log(version);
  await Promise.resolve('some result');
}

exports.default = asyncAwaitTask;

Undefined index error PHP

this error occurred sometime method attribute ( valid passing method ) Error option : method="get" but called by $Fname = $_POST["name"]; or

       method="post" but  called by  $Fname = $_GET["name"];

More info visit http://www.doordie.co.in/index.php

Easy way to build Android UI?

The easiest way is with REBOL 3:

http://rebolforum.com/index.cgi?f=printtopic&permalink=Nick25-Aug-2013/10:08:38-7:00&archiveflag=new

Here are 10 fully functional demo programs, with GUIs. These run on Android and desktop OSs, using the exact same code:

REBOL []
load-gui
view [text "Hello World!"]


REBOL [title: "Tiny Note Editor"]
do %r3-gui.r3  ; download this file manually or just use load-gui as above
view [
    a1: area
    button "Save" on-action [write %notes.txt get-face a1]
    button "Load" on-action [set-face a1 to-string read %notes.txt]
]


REBOL [title: "Data Entry to CSV File"]
do %r3-gui.r3
view [
    text "First Name:"
    f1: field
    text "Last Name:"
    f2: field
    button "Submit" on-action [
        write/append %cntcts.txt rejoin [
            mold get-face f1 " " mold get-face f2 newline
        ]
        request "" "Saved"
    ]
    a1: area
    button "Load" on-action [set-face a1 to-string read %cntcts.txt]
]


REBOL [title: "Text File Reader (How to use a text list file selector)"]
do %r3-gui.r3
view [
    a1: area
    button "Load" on-action [
        files: read %./
        view/modal [
            text "File Name:"
            t2: text-list files on-action [
                set-face a1 to-string read(to-file pick files get-face t2)
                unview
            ]
        ]
    ]
]


REBOL [title: "List-View (Grid) Example"]
do %r3-gui.r3
view [
    text-table ["1" 200 "2" 100 "3"][
        ["asdf" "a" "4"]
        ["sdfg" "b" "3"]
        ["dfgh" "c" "2"]
        ["fghj" "d" "1"]
    ] 
]


REBOL [title: "Calculator"]
do %r3-gui.r3
stylize [
    btn: button [
        facets: [init-size: 50x50]
        actors: [on-action:[set-face f join get-face f get-face face]]
    ]
]
view [
    hgroup [
        f: field return
        btn "1"  btn "2"  btn "3"  btn " + "  return
        btn "4"  btn "5"  btn "6"  btn " - "  return
        btn "7"  btn "8"  btn "9"  btn " * "  return
        btn "0"  btn "."  btn " / "   btn "=" on-action [
            attempt [set-face f form do get-face f]
        ]
    ]
]


REBOL [title: "Sliding Tile Puzzle"]
do %r3-gui.r3
stylize [
    p: button [
        facets: [init-size: 60x60  max-size: 60x60]
        actors: [
            on-action: [
                t: face/gob/offset
                face/gob/offset: x/gob/offset
                x/gob/offset: t
            ]
        ]
    ]
]
view/options [
    hgroup [ 
        p "8"   p "7"   p "6"   return
        p "5"   p "4"   p "3"   return
        p "2"   p "1"   x: box 60x60 white
    ]
] [bg-color: white]


REBOL [title: "Math Test"]
do %r3-gui.r3
random/seed now
x: does [rejoin [random 10 " + " random 20]]
view [
    f1: field (x)
    text "Answer:"
    f2: field on-action [
        either (get-face f2) = (form do get-face f1) [
            request "Yes!" "Yes!"][request "No!" "No!"
        ]
        set-face f1 x
        set-face f2 ""
        focus f2
    ]
]


REBOL [title: "Minimal Cash Register"]
do %r3-gui.r3
stylize [fld: field [init-size: 80]]   
view [
    hgroup [
        text "Cashier:"   cashier: fld 
        text "Item:"      item: fld 
        text "Price:"     price: fld on-action [
            if error? try [to-money get-face price] [
                request "Error" "Price error" 
                return none
            ]
            set-face a rejoin [
                get-face a mold get-face item tab get-face price newline
            ]
            set-face item copy "" set-face price copy ""
            sum: 0
            foreach [item price] load get-face a [
                sum: sum + to-money price
            ]
            set-face subtotal form sum
            set-face tax form sum * .06
            set-face total form sum * 1.06 
            focus item
        ]
        return
        a: area 600x300
        return
        text "Subtotal:"   subtotal: fld 
        text "Tax:"        tax: fld 
        text "Total:"      total: fld
        button "Save" on-action [
            items: replace/all (mold load get-face a) newline " "
            write/append %sales.txt rejoin [
                items newline get-face cashier newline now/date newline
            ]
            set-face item copy "" set-face price copy "" 
            set-face a copy ""    set-face subtotal copy ""
            set-face tax copy "" set-face total copy ""
        ]
    ]
]


REBOL [title: "Requestors"]
do %r3-gui.r3
x: request/ask "Question" "Do you like this?."
either x = false [print "No!"] [print "Yes!"]
x: request/custom "" "Do you like this?" ["Yay" "Boo"]
either x = false [print "Boo!"] [print "Yay!"]
view [button "Click me" on-action[request "Ok" "You clicked the button."]]

String field value length in mongoDB

Here is one of the way in mongodb you can achieve this.

db.usercollection.find({ $where: 'this.name.length < 4' })

Map a network drive to be used by a service

A better way would be to use a symbolic link using mklink.exe. You can just create a link in the file system that any app can use. See http://en.wikipedia.org/wiki/NTFS_symbolic_link.

In PHP, how do you change the key of an array element?

Hmm, I'm not test before, but I think this code working

function replace_array_key($data) {
    $mapping = [
        'old_key_1' => 'new_key_1',
        'old_key_2' => 'new_key_2',
    ];

    $data = json_encode($data);
    foreach ($mapping as $needed => $replace) {
        $data = str_replace('"'.$needed.'":', '"'.$replace.'":', $data);
    }

    return json_decode($data, true);
}

Xcode 10, Command CodeSign failed with a nonzero exit code

In my experience, the reason that caused this problem was I wrongly reset the Keychain Access to default, so I lost my development certificate.

How did I solve this?

  1. I cleaned my Apple Development Certificate from Keychain Access
  2. I cleaned my Apple Development private key from Keychain Access
  3. Then I got the new error : Revoke certificate Your account already has an Apple Development signing certificate for this machine, but its private key is not installed in your keychain. Xcode can create a new one after revoking your existing certificate.
  4. Go to Xcode Preference -> Accounts Tab -> Fine the team name under the Apple ID -> Double Click it -> Click the + button at the bottom left of box -> Select App Development
  5. In the team drop-down of the target, select "None"
  6. Re-select the correct development team
  7. Clean the project by shift+cmd+k
  8. Rebuild the project cmd+b

SQL Server remove milliseconds from datetime

If you are using SQL Server (starting with 2008), choose one of this:

  • CONVERT(DATETIME2(0), YourDateField)
  • LEFT(RTRIM(CONVERT(DATETIMEOFFSET, YourDateField)), 19)
  • CONVERT(DATETIMEOFFSET(0), YourDateField) -- with the addition of a time zone offset

iterating over and removing from a map

Set s=map.entrySet();
Iterator iter = s.iterator();

while (iter.hasNext()) {
    Map.Entry entry =(Map.Entry)iter.next();

    if("value you need to remove".equals(entry.getKey())) {
         map.remove();
    }
}

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

I noticed creation of 'appcompat' library while creating new android project with ADT 22.6.2 version, even when the minSDK was set to 11 and targetSDK was set 19

This was happening because, in the new project template android is using some attributes that are from the support library. For instance if a new project was created with actionbar then in the menu's main.xml one could find app:showAsAction="never" which is from support library.

  • If the app is targeted at android version 11 and above then one can change this attribute to android:showAsAction in menu's main.xml
  • Also the default theme set could be "Theme.AppCompat.Light.DarkActionBar" as shown below (styles.xml)

    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
           <!-- API 14 theme customizations can go here. -->
       </style> 
    

    In this case the parent theme in style.xml has to be changed to "android:style/Theme.Holo.Light.DarkActionBar"

  • In addition to this if reference to Fragment,Fragments Manager from support library was made in the code of MainActivity.java, these have to appropriately changed to Fragment, FragmentManager of the SDK.

Angular2, what is the correct way to disable an anchor element?

You can try this

<a [attr.disabled]="someCondition ? true: null"></a>

SQL query question: SELECT ... NOT IN

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
  and idCustomer is not null

Make sure your list parameter does not contain null values.

Here's an explanation:

WHERE field1 NOT IN (1, 2, 3, null)

is the same as:

WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
  • That last comparision evaluates to null.
  • That null is OR'd with the rest of the boolean expression, yielding null. (*)
  • null is negated, yielding null.
  • null is not true - the where clause only keeps true rows, so all rows are filtered.

(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.

Using CSS :before and :after pseudo-elements with inline CSS?

You can't create pseudo elements in inline css.

However, if you can create a pseudo element in a stylesheet, then there's a way to style it inline by setting an inline style to its parent element, and then using inherit keyword to style the pseudo element, like this:

<parent style="background-image:url(path/to/file); background-size:0px;"></p>

<style> 
   parent:before{
      content:'';
      background-image:inherit;
      (other)
   }
</style>

sometimes this can be handy.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

Your example data does not have any duplicates, but your solution handle them automatically. This means that potentially some of the answers won't match to results of your function in case of duplicates.
Here is my solution which address duplicates the same way as yours. It also scales great!

a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])
rows.in.a1.that.are.not.in.a2  <- function(a1,a2)
{
    a1.vec <- apply(a1, 1, paste, collapse = "")
    a2.vec <- apply(a2, 1, paste, collapse = "")
    a1.without.a2.rows <- a1[!a1.vec %in% a2.vec,]
    return(a1.without.a2.rows)
}

library(data.table)
setDT(a1)
setDT(a2)

# no duplicates - as in example code
r <- fsetdiff(a1, a2)
all.equal(r, rows.in.a1.that.are.not.in.a2(a1,a2))
#[1] TRUE

# handling duplicates - make some duplicates
a1 <- rbind(a1, a1, a1)
a2 <- rbind(a2, a2, a2)
r <- fsetdiff(a1, a2, all = TRUE)
all.equal(r, rows.in.a1.that.are.not.in.a2(a1,a2))
#[1] TRUE

It needs data.table 1.9.8+

Install tkinter for Python

tk-devel also needs to be installed in my case

yum install -y tkinter tk-devel

install these and rebuild python

Watch multiple $scope attributes

Angular introduced $watchGroup in version 1.3 using which we can watch multiple variables, with a single $watchGroup block $watchGroup takes array as first parameter in which we can include all of our variables to watch.

$scope.$watchGroup(['var1','var2'],function(newVals,oldVals){
   console.log("new value of var1 = " newVals[0]);
   console.log("new value of var2 = " newVals[1]);
   console.log("old value of var1 = " oldVals[0]);
   console.log("old value of var2 = " oldVals[1]);
});

Verify External Script Is Loaded

Another way to check an external script is loaded or not, you can use data function of jquery and store a validation flag. Example as :

if(!$("body").data("google-map"))
    {
        console.log("no js");

        $.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initilize",function(){
            $("body").data("google-map",true);

            },function(){
                alert("error while loading script");
            });
        }
    }
    else
    {
        console.log("js already loaded");
    }

Receive result from DialogFragment

Just to have it as one of the options (since no one mentioned it yet) - you could use an event bus like Otto. So in the dialog you do:

bus.post(new AnswerAvailableEvent(42));

And have your caller (Activity or Fragment) subscribe to it:

@Subscribe public void answerAvailable(AnswerAvailableEvent event) {
   // TODO: React to the event somehow!
}

Change collations of all columns of all tables in SQL Server

As I did not find a proper way I wrote a script to do it and I'm sharing it here for those who need it. The script runs through all user tables and collects the columns. If the column type is any char type then it tries to convert it to the given collation.

Columns has to be index and constraint free for this to work.

If someone still has a better solution to this please post it!

DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'Latin1_General_CI_AS';

DECLARE local_table_cursor CURSOR FOR

SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1

OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE local_change_cursor CURSOR FOR

    SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
        , c.name column_name
        , t.Name data_type
        , c.max_length
        , c.column_id
    FROM sys.columns c
    JOIN sys.types t ON c.system_type_id = t.system_type_id
    LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id = OBJECT_ID(@table)
    ORDER BY c.column_id

    OPEN local_change_cursor
    FETCH NEXT FROM local_change_cursor
    INTO @row_id, @column_name, @data_type, @max_length, @column_id

    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF (@max_length = -1) OR (@max_length > 4000) SET @max_length = 4000;

        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' + @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
            PRINT @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR: Some index or constraint rely on the column' + @column_name + '. No conversion possible.'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM local_change_cursor
        INTO @row_id, @column_name, @data_type, @max_length, @column_id

    END

    CLOSE local_change_cursor
    DEALLOCATE local_change_cursor

    FETCH NEXT FROM local_table_cursor
    INTO @table

END

CLOSE local_table_cursor
DEALLOCATE local_table_cursor

GO

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Connecting to local SQL Server database using C#

In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

How can I run a PHP script inside a HTML file?

I'm not sure if this is what you wanted, but this is a very hackish way to include php. What you do is you put the php you want to run in another file, and then you include that file in an image. For example:

RunFromHTML.php

<?php
  $file = fopen("file.txt", "w");
  //This will create a file called file.txt,
  //provided that it has write access to your filesystem
  fwrite($file, "Hello World!");
  //This will write "Hello World!" into file.txt
  fclose($file);
  //Always remember to close your files!
?>

RunPhp.html

<html>
  <!--head should be here, but isn't for demonstration's sake-->
  <body>
    <img style="display: none;" src="RunFromHTML.php">
    <!--This will run RunFromHTML.php-->
  </body>
</html>

Now, after visiting RunPhp.html, you should find a file called file.txt in the same directory that you created the above two files, and the file should contain "Hello World!" inside of it.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

In my case, upgraded from spring-securiy-web 3.1.3 to 4.2.12, the defaultHttpFirewall was changed from DefaultHttpFirewall to StrictHttpFirewall by default. So just define it in XML configuration like below:

<bean id="defaultHttpFirewall" class="org.springframework.security.web.firewall.DefaultHttpFirewall"/>
<sec:http-firewall ref="defaultHttpFirewall"/>

set HTTPFirewall as DefaultHttpFirewall

How can I check the extension of a file?

Use pathlib From Python3.4 onwards.

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

ORDER BY using Criteria API

You need to create an alias for the mother.kind. You do this like so.

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

How do you loop in a Windows batch file?

If you want to do something x times, you can do this:

Example (x = 200):

FOR /L %%A IN (1,1,200) DO (
  ECHO %%A
)

1,1,200 means:

  • Start = 1
  • Increment per step = 1
  • End = 200

Checkbox angular material checked by default

Make sure you have this code on you component:

export class Component {
  checked = true;
}

What are the minimum margins most printers can handle?

For every PostScript printer, one part of its driver is an ASCII file called PostScript Printer Description (PPD). PPDs are used in the CUPS printing system on Linux and Mac OS X as well even for non-PostScript printers.

Every PPD MUST, according to the PPD specification written by Adobe, contain definitions of a *ImageableArea (that's a PPD keyword) for each and every media sizes it can handle. That value is given for example as *ImageableArea Folio/8,25x13: "12 12 583 923" for one printer in this office here, and *ImageableArea Folio/8,25x13: "0 0 595 935" for the one sitting in the next room.

These figures mean "Lower left corner is at (12|12), upper right corner is at (583|923)" (where these figures are measured in points; 72pt == 1inch). Can you see that the first printer does print with a margin of 1/6 inch? -- Can you also see that the next one can even print borderless?

What you need to know is this: Even if the printer can do very small margins physically, if the PPD *ImageableArea is set to a wider margin, the print data generated by the driver and sent to the printer will be clipped according to the PPD setting -- not by the printer itself.

These days more and more models appear on the market which can indeed print edge-to-edge. This is especially true for office laser printers. (Don't know about devices for the home use market.) Sometimes you have to enable that borderless mode with a separate switch in the driver settings, sometimes also on the device itself (front panel, or web interface).

Older models, for example HP's, define in their PPDs their margines quite generously, just to be on the supposedly "safe side". Very often HP used 1/3, 1/2 inch or more (like "24 24 588 768" for Letter format). I remember having hacked HP PPDs and tuned them down to "6 6 606 786" (1/12 inch) before the physical boundaries of the device kicked in and enforced a real clipping of the page image.

Now, PCL and other language printers are not that much different in their margin capabilities from PostScript models.

But of course, when it comes to printing of PDF docs, here you can nearly always choose "print to fit" or similarly named options. Even for a file that itself does not use any margins. That "fit" is what the PDF viewer reads from the driver, and the viewer then scales down the page to the *ImageableArea.

Python conversion between coordinates

If you can't find it in numpy or scipy, here are a couple of quick functions and a point class:

import math

def rect(r, theta):
    """theta in degrees

    returns tuple; (float, float); (x,y)
    """
    x = r * math.cos(math.radians(theta))
    y = r * math.sin(math.radians(theta))
    return x,y

def polar(x, y):
    """returns r, theta(degrees)
    """
    r = (x ** 2 + y ** 2) ** .5
    theta = math.degrees(math.atan2(y,x))
    return r, theta

class Point(object):
    def __init__(self, x=None, y=None, r=None, theta=None):
        """x and y or r and theta(degrees)
        """
        if x and y:
            self.c_polar(x, y)
        elif r and theta:
            self.c_rect(r, theta)
        else:
            raise ValueError('Must specify x and y or r and theta')
    def c_polar(self, x, y, f = polar):
        self._x = x
        self._y = y
        self._r, self._theta = f(self._x, self._y)
        self._theta_radians = math.radians(self._theta)
    def c_rect(self, r, theta, f = rect):
        """theta in degrees
        """
        self._r = r
        self._theta = theta
        self._theta_radians = math.radians(theta)
        self._x, self._y = f(self._r, self._theta)
    def setx(self, x):
        self.c_polar(x, self._y)
    def getx(self):
        return self._x
    x = property(fget = getx, fset = setx)
    def sety(self, y):
        self.c_polar(self._x, y)
    def gety(self):
        return self._y
    y = property(fget = gety, fset = sety)
    def setxy(self, x, y):
        self.c_polar(x, y)
    def getxy(self):
        return self._x, self._y
    xy = property(fget = getxy, fset = setxy)
    def setr(self, r):
        self.c_rect(r, self._theta)
    def getr(self):
        return self._r
    r = property(fget = getr, fset = setr)
    def settheta(self, theta):
        """theta in degrees
        """
        self.c_rect(self._r, theta)
    def gettheta(self):
        return self._theta
    theta = property(fget = gettheta, fset = settheta)
    def set_r_theta(self, r, theta):
        """theta in degrees
        """
        self.c_rect(r, theta)
    def get_r_theta(self):
        return self._r, self._theta
    r_theta = property(fget = get_r_theta, fset = set_r_theta)
    def __str__(self):
        return '({},{})'.format(self._x, self._y)

Excel VBA Macro: User Defined Type Not Defined

I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"

virtualenvwrapper and Python 3

If you already have python3 installed as well virtualenvwrapper the only thing you would need to do to use python3 with the virtual environment is creating an environment using:

which python3 #Output: /usr/bin/python3
mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment

Or, (at least on OSX using brew):

mkvirtualenv --python=`which python3` nameOfEnvironment

Start using the environment and you'll see that as soon as you type python you'll start using python3

Blue and Purple Default links, how to remove?

You need to override the color:

a { color:red } /* Globally */

/* Each state */

a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }

Python Script to convert Image into Byte array

i don't know about converting into a byte array, but it's easy to convert it into a string:

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

Source

How can I convert an image into a Base64 string?

Here is the encoding and decoding code in Kotlin:

 fun encode(imageUri: Uri): String {
    val input = activity.getContentResolver().openInputStream(imageUri)
    val image = BitmapFactory.decodeStream(input , null, null)

    // Encode image to base64 string
    val baos = ByteArrayOutputStream()
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
    var imageBytes = baos.toByteArray()
    val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
    return imageString
}

fun decode(imageString: String) {

    // Decode base64 string to image
    val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
    val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

    imageview.setImageBitmap(decodedImage)
}

Vector erase iterator

res.erase(it) always returns the next valid iterator, if you erase the last element it will point to .end()

At the end of the loop ++it is always called, so you increment .end() which is not allowed.

Simply checking for .end() still leaves a bug though, as you always skip an element on every iteration (it gets 'incremented' by the return from .erase(), and then again by the loop)

You probably want something like:

 while (it != res.end()) {
        it = res.erase(it);    
 }

to erase each element

(for completeness: I assume this is a simplified example, if you simply want every element gone without having to perform an operation on it (e.g. delete) you should simply call res.clear())

When you only conditionally erase elements, you probably want something like

for ( ; it != res.end(); ) {
  if (condition) {
    it = res.erase(it);
  } else {
    ++it;
  }
}

Is it possible to Turn page programmatically in UIPageViewController?

Here's another code example for a single paged view. Implementation for viewControllerAtIndex is omitted here, it should return the correct view controller for the given index.

- (void)changePage:(UIPageViewControllerNavigationDirection)direction {
    NSUInteger pageIndex = ((FooViewController *) [_pageViewController.viewControllers objectAtIndex:0]).pageIndex;

    if (direction == UIPageViewControllerNavigationDirectionForward) {
        pageIndex++;
    }
    else {
        pageIndex--;
    }

    FooViewController *viewController = [self viewControllerAtIndex:pageIndex];

    if (viewController == nil) {
        return;
    }

    [_pageViewController setViewControllers:@[viewController]
                                  direction:direction
                                   animated:YES
                                 completion:nil];
}

Pages can be changed by calling

[self changePage:UIPageViewControllerNavigationDirectionReverse];
[self changePage:UIPageViewControllerNavigationDirectionForward];

Equivalent of typedef in C#

For non-sealed classes simply inherit from them:

public class Vector : List<int> { }

But for sealed classes it's possible to simulate typedef behavior with such base class:

public abstract class Typedef<T, TDerived> where TDerived : Typedef<T, TDerived>, new()
{
    private T _value;

    public static implicit operator T(Typedef<T, TDerived> t)
    {
        return t == null ? default : t._value;
    }

    public static implicit operator Typedef<T, TDerived>(T t)
    {
        return t == null ? default : new TDerived { _value = t };
    }
}

// Usage examples

class CountryCode : Typedef<string, CountryCode> { }
class CurrencyCode : Typedef<string, CurrencyCode> { }
class Quantity : Typedef<int, Quantity> { }

void Main()
{
    var canadaCode = (CountryCode)"CA";
    var canadaCurrency = (CurrencyCode)"CAD";
    CountryCode cc = canadaCurrency;        // Compilation error
    Concole.WriteLine(canadaCode == "CA");  // true
    Concole.WriteLine(canadaCurrency);      // CAD

    var qty = (Quantity)123;
    Concole.WriteLine(qty);                 // 123
}

How to search if dictionary value contains certain string with Python

import re
for i in range(len(myDict.values())):
     for j in range(len(myDict.values()[i])):
             match=re.search(r'Mary', myDict.values()[i][j])
             if match:
                     print match.group() #Mary
                     print myDict.keys()[i] #firstName
                     print myDict.values()[i][j] #Mary-Ann

Working with time DURATION, not time of day

Use format d "days" h:mm:ss or [h]:mm:ss, depending on your needs.

Say you have a duration of 30h 12m 54s:

  • h:mm:ss -> 6:12:54 (not correct for a duration)
  • [h]:mm:ss -> 30:12:54
  • d "days" h:mm:ss -> 1 days 6:12:54

Variations are possible: I like something like d"d" h"h" mm"m" ss"s" which formats as 1d 6h 12m 54s.

How to disable submit button once it has been clicked?

Using JQuery, you can do this..

$("#submitbutton").click(
   function() {
      alert("Sending...");
      window.location.replace("path to url");
   }
);

Laravel 5 How to switch from Production mode

Do not forget to run the command php artisan config:clear after you have made the changes to the .env file. Done this again php artisan env, which will return the correct version.

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

How to add property to a class dynamically?

This seems to work(but see below):

class data(dict,object):
    def __init__(self,*args,**argd):
        dict.__init__(self,*args,**argd)
        self.__dict__.update(self)
    def __setattr__(self,name,value):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be set"%(name,self.__class__.__name__)
    def __delattr__(self,name):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be deleted"%(name,self.__class__.__name__)

If you need more complex behavior, feel free to edit your answer.

edit

The following would probably be more memory-efficient for large datasets:

class data(dict,object):
    def __init__(self,*args,**argd):
        dict.__init__(self,*args,**argd)
    def __getattr__(self,name):
        return self[name]
    def __setattr__(self,name,value):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be set"%(name,self.__class__.__name__)
    def __delattr__(self,name):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be deleted"%(name,self.__class__.__name__)

Copy/duplicate database without using mysqldump

an SQL that shows SQL commands, need to run to duplicate a database from one database to another. for each table there is create a table statement and an insert statement. it assumes both databases are on the same server:

select @fromdb:="crm";
select @todb:="crmen";

SET group_concat_max_len=100000000;


SELECT  GROUP_CONCAT( concat("CREATE TABLE `",@todb,"`.`",table_name,"` LIKE `",@fromdb,"`.`",table_name,"`;\n",
"INSERT INTO `",@todb,"`.`",table_name,"` SELECT * FROM `",@fromdb,"`.`",table_name,"`;") 

SEPARATOR '\n\n')

as sqlstatement
 FROM information_schema.tables where table_schema=@fromdb and TABLE_TYPE='BASE TABLE';

Link a .css on another folder

I dont get it clearly, do you want to link an external css as the structure of files you defined above? If yes then just use the link tag :

    <link rel="stylesheet" type="text/css" href="file.css">

so basically for files that are under your website folder (folder containing your index) you directly call it. For each successive folder use the "/" for example in your case :

    <link rel="stylesheet" type="text/css" href="Fonts/Font1/file name">
    <link rel="stylesheet" type="text/css" href="Fonts/Font2/file name">

Conditional replacement of values in a data.frame

Since you are conditionally indexing df$est, you also need to conditionally index the replacement vector df$a:

index <- df$b == 0
df$est[index] <- (df$a[index] - 5)/2.533 

Of course, the variable index is just temporary, and I use it to make the code a bit more readible. You can write it in one step:

df$est[df$b == 0] <- (df$a[df$b == 0] - 5)/2.533 

For even better readibility, you can use within:

df <- within(df, est[b==0] <- (a[b==0]-5)/2.533)

The results, regardless of which method you choose:

df
          a b      est
1  11.77000 2 0.000000
2  10.90000 3 0.000000
3  10.32000 2 0.000000
4  10.96000 0 2.352941
5   9.90600 0 1.936834
6  10.70000 0 2.250296
7  11.43000 1 0.000000
8  11.41000 2 0.000000
9  10.48512 4 0.000000
10 11.19000 0 2.443743

As others have pointed out, an alternative solution in your example is to use ifelse.

How to check for Is not Null And Is not Empty string in SQL server?

Just check: where value > '' -- not null and not empty

-- COLUMN CONTAINS A VALUE (ie string not null and not empty) :
-- (note: "<>" gives a different result than ">")
select iif(null    > '', 'true', 'false'); -- false (null)
select iif(''      > '', 'true', 'false'); -- false (empty string)
select iif(' '     > '', 'true', 'false'); -- false (space)
select iif('    '  > '', 'true', 'false'); -- false (tab)
select iif('
'                  > '', 'true', 'false'); -- false (newline)
select iif('xxx'   > '', 'true', 'false'); -- true
--
--
-- NOTE - test that tab and newline is processed as expected:
select 'x   x' -- tab
select 'x

x' -- newline

String replace a Backslash

 sSource = StringUtils.replace(sSource, "\\/", "/")

How To Raise Property Changed events on a Dependency Property?

I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example. In the code below, MyControl has two dependency properties - ActiveTabInt and ActiveTabString. When the user clicks the button on the host (MainWindow), ActiveTabString is modified. The PropertyChanged CALLBACK on the dependency property sets the value of ActiveTabInt. The PropertyChanged EVENT is not manually raised by MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

MainWindow.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Get filename and path from URI from mediastore

Try This

Still, if you are getting the problem to get the real path, you can try my answers. Above answers didn't help me.

Explanation:- This method gets the URI and then check the API level of your Android device after that according to API level it will generate the Real path. Code for generating real path method is different according to API levels.

  1. method to get the Real path from URI

    @SuppressLint("ObsoleteSdkInt")
    public String getPathFromURI(Uri uri){
        String realPath="";
    // SDK < API11
        if (Build.VERSION.SDK_INT < 11) {
            String[] proj = { MediaStore.Images.Media.DATA };
            @SuppressLint("Recycle") Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
            int column_index = 0;
            String result="";
            if (cursor != null) {
                column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                realPath=cursor.getString(column_index);
            }
        }
        // SDK >= 11 && SDK < 19
        else if (Build.VERSION.SDK_INT < 19){
            String[] proj = { MediaStore.Images.Media.DATA };
            CursorLoader cursorLoader = new CursorLoader(this, uri, proj, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            if(cursor != null){
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                realPath = cursor.getString(column_index);
            }
        }
        // SDK > 19 (Android 4.4)
        else{
            String wholeID = DocumentsContract.getDocumentId(uri);
            // Split at colon, use second item in the array
            String id = wholeID.split(":")[1];
            String[] column = { MediaStore.Images.Media.DATA };
            // where id is equal to
            String sel = MediaStore.Images.Media._ID + "=?";
            Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null);
            int columnIndex = 0;
            if (cursor != null) {
                columnIndex = cursor.getColumnIndex(column[0]);
                if (cursor.moveToFirst()) {
                    realPath = cursor.getString(columnIndex);
                }
                cursor.close();
            }
        }
        return realPath;
     }
    
  2. Use this method like this

    Log.e(TAG, "getRealPathFromURI: "+getPathFromURI(your_selected_uri) );
    

Output:-

04-06 12:39:46.993 6138-6138/com.app.qtm E/tag: getRealPathFromURI: /storage/emulated/0/Video/avengers_infinity_war_4k_8k-7680x4320.jpg

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

Is it possible to use Visual Studio on macOS?

While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.

What is a good way to handle exceptions when trying to read a file in python?

Adding to @Josh's example;

fName = [FILE TO OPEN]
if os.path.exists(fName):
    with open(fName, 'rb') as f:
        #add you code to handle the file contents here.
elif IOError:
    print "Unable to open file: "+str(fName)

This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!

How to determine one year from now in Javascript

In very simple way. use this code.

// define function 
function nextYearDate(date1) {
    var date2 = new Date(date1);
    var date3 = date2.setDate(date2.getDate() - 1);
    var date = new Date(date3);
    var day = date.getDate();
    var month = date.getMonth()+1;
    var year = date.getFullYear()+1;
    var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
    $("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />

<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />