Programs & Examples On #Render html

What is the difference between char array and char pointer in C?

char* and char[] are different types, but it's not immediately apparent in all cases. This is because arrays decay into pointers, meaning that if an expression of type char[] is provided where one of type char* is expected, the compiler automatically converts the array into a pointer to its first element.

Your example function printSomething expects a pointer, so if you try to pass an array to it like this:

char s[10] = "hello";
printSomething(s);

The compiler pretends that you wrote this:

char s[10] = "hello";
printSomething(&s[0]);

How to rename a component in Angular CLI?

In WebStorm, you can right click ? Refactor ? Rename on the name of the component in the TypeScript file and it will change the name everywhere.

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

How do you get/set media volume (not ringtone volume) in Android?

Instead of AudioManager.STREAM_RING you shoul use AudioManager.STREAM_MUSIC This question has already discussed here.

Install an apk file from command prompt?

You can install an apk to a specific device/emulator by entering the device/emulator identifier before the keyword 'install' and then the path to the apk. Note that the -s switch, if any, after the 'install' keyword signifies installing to the sd card. Example:

adb -s emulator-5554 install myapp.apk

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -Uri $url -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Spring sets the default content-type to octet-stream when the response is missing that field. All you need to do is to add a message converter to fix this.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I use jQuery for this:

jQuery('li').wrapInner('<span class="li_content" />');

& with some CSS:

li { color: red; }
li span.li_content { color: black; }

maybe overkill, but handy if you're coding for a CMS and you don't want to ask your editors to put an extra span in every list-items.

How do I create a new class in IntelliJ without using the mouse?

On Mac you can navigate to the location in Project view where you want to create your class and then use ?N followed by Enter.

How can I access an internal class from an external assembly?

I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

 Install-Package Mono.Cecil

And the code like:

static readonly string[] s_toInject = {
  // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
  "MyAssembly"
};

static void Main(string[] args) {
  const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";

   var parameters = new ReaderParameters();
   var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
   foreach (var toInject in s_toInject) {
     var ca = new CustomAttribute(
       asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                      typeof(string)})));
     ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
     asm.Assembly.CustomAttributes.Add(ca);
   }
   asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
   // note if the assembly is strongly-signed you need to resign it like
   // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
   //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
   // });
}

Plot a bar using matplotlib using a dictionary

For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))

plt.show()

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

Can we make unsigned byte in Java

Yes and no. Ive been digging around with this problem. Like i understand this:

The fact is that java has signed interger -128 to 127.. It is possible to present a unsigned in java with:

public static int toUnsignedInt(byte x) {
    return ((int) x) & 0xff;
}

If you for example add -12 signed number to be unsigned you get 244. But you can use that number again in signed, it has to be shifted back to signed and it´ll be again -12.

If you try to add 244 to java byte you'll get outOfIndexException.

Cheers..

Detect Safari using jQuery

My best solution

function getBrowserInfo() {
  const ua = navigator.userAgent; let tem;
  let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  if (/trident/i.test(M[1])) {
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    return { name: 'IE ', version: (tem[1] || '') };
  }
  if (M[1] === 'Chrome') {
    tem = ua.match(/\bOPR\/(\d+)/);
    if (tem != null) {
      return { name: 'Opera', version: tem[1] };
    }
  }
  M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
  tem = ua.match(/version\/(\d+)/i);
  if (tem != null) {
    M.splice(1, 1, tem[1]);
  }
  return {
    name: M[0],
    version: M[1],
  };
}

getBrowserInfo();

How can I make PHP display the error instead of giving me 500 Internal Server Error

Be careful to check if

display_errors

or

error_reporting

is active (not a comment) somewhere else in the ini file.

My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my

display_errors = on;

So remember the last one counts!

C# version of java's synchronized keyword?

Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)] should look like

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]

How do you detect the clearing of a "search" HTML5 input?

Here's one way of achieving this. You need to add incremental attribute to your html or it won't work.

_x000D_
_x000D_
window.onload = function() {_x000D_
  var tf = document.getElementById('textField');_x000D_
  var button = document.getElementById('b');_x000D_
  button.disabled = true;_x000D_
  var onKeyChange = function textChange() {_x000D_
    button.disabled = (tf.value === "") ? true : false;_x000D_
  }_x000D_
  tf.addEventListener('keyup', onKeyChange);_x000D_
  tf.addEventListener('search', onKeyChange);_x000D_
_x000D_
}
_x000D_
<input id="textField" type="search" placeholder="search" incremental="incremental">_x000D_
<button id="b">Go!</button>
_x000D_
_x000D_
_x000D_

How to Generate Unique ID in Java (Integer)?

It's easy if you are somewhat constrained.

If you have one thread, you just use uniqueID++; Be sure to store the current uniqueID when you exit.

If you have multiple threads, a common synchronized generateUniqueID method works (Implemented the same as above).

The problem is when you have many CPUs--either in a cluster or some distributed setup like a peer-to-peer game.

In that case, you can generally combine two parts to form a single number. For instance, each process that generates a unique ID can have it's own 2-byte ID number assigned and then combine it with a uniqueID++. Something like:

return (myID << 16) & uniqueID++

It can be tricky distributing the "myID" portion, but there are some ways. You can just grab one out of a centralized database, request a unique ID from a centralized server, ...

If you had a Long instead of an Int, one of the common tricks is to take the device id (UUID) of ETH0, that's guaranteed to be unique to a server--then just add on a serial number.

AngularJS: Service vs provider vs factory

Using as reference this page and the documentation (which seems to have greatly improved since the last time I looked), I put together the following real(-ish) world demo which uses 4 of the 5 flavours of provider; Value, Constant, Factory and full blown Provider.

HTML:

<div ng-controller="mainCtrl as main">
    <h1>{{main.title}}*</h1>
    <h2>{{main.strapline}}</h2>
    <p>Earn {{main.earn}} per click</p>
    <p>You've earned {{main.earned}} by clicking!</p>
    <button ng-click="main.handleClick()">Click me to earn</button>
    <small>* Not actual money</small>
</div>

app

var app = angular.module('angularProviders', []);

// A CONSTANT is not going to change
app.constant('range', 100);

// A VALUE could change, but probably / typically doesn't
app.value('title', 'Earn money by clicking');
app.value('strapline', 'Adventures in ng Providers');

// A simple FACTORY allows us to compute a value @ runtime.
// Furthermore, it can have other dependencies injected into it such
// as our range constant.
app.factory('random', function randomFactory(range) {
    // Get a random number within the range defined in our CONSTANT
    return Math.random() * range;
});

// A PROVIDER, must return a custom type which implements the functionality 
// provided by our service (see what I did there?).
// Here we define the constructor for the custom type the PROVIDER below will 
// instantiate and return.
var Money = function(locale) {

    // Depending on locale string set during config phase, we'll
    // use different symbols and positioning for any values we 
    // need to display as currency
    this.settings = {
        uk: {
            front: true,
            currency: '£',
            thousand: ',',
            decimal: '.'
        },
        eu: {
            front: false,
            currency: '€',
            thousand: '.',
            decimal: ','
        }
    };

    this.locale = locale;
};

// Return a monetary value with currency symbol and placement, and decimal 
// and thousand delimiters according to the locale set in the config phase.
Money.prototype.convertValue = function(value) {

    var settings = this.settings[this.locale],
        decimalIndex, converted;

    converted = this.addThousandSeparator(value.toFixed(2), settings.thousand);

    decimalIndex = converted.length - 3;

    converted = converted.substr(0, decimalIndex) +
        settings.decimal +
        converted.substr(decimalIndex + 1);    

    converted = settings.front ?
            settings.currency + converted : 
            converted + settings.currency; 

    return converted;   
};

// Add supplied thousand separator to supplied value
Money.prototype.addThousandSeparator = function(value, symbol) {
   return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, symbol);
};

// PROVIDER is the core recipe type - VALUE, CONSTANT, SERVICE & FACTORY
// are all effectively syntactic sugar built on top of the PROVIDER construct
// One of the advantages of the PROVIDER is that we can configure it before the
// application starts (see config below).
app.provider('money', function MoneyProvider() {

    var locale;

    // Function called by the config to set up the provider
    this.setLocale = function(value) {
        locale = value;   
    };

    // All providers need to implement a $get method which returns
    // an instance of the custom class which constitutes the service
    this.$get = function moneyFactory() {
        return new Money(locale);
    };
});

// We can configure a PROVIDER on application initialisation.
app.config(['moneyProvider', function(moneyProvider) {
    moneyProvider.setLocale('uk');
    //moneyProvider.setLocale('eu'); 
}]);

// The ubiquitous controller
app.controller('mainCtrl', function($scope, title, strapline, random, money) {

    // Plain old VALUE(s)
    this.title = title;
    this.strapline = strapline;

    this.count = 0;

    // Compute values using our money provider    
    this.earn = money.convertValue(random); // random is computed @ runtime
    this.earned = money.convertValue(0);

    this.handleClick = function() { 
        this.count ++;
        this.earned = money.convertValue(random * this.count);
    };
});

Working demo.

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

Simply use the "utf-8-sig" codec:

fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")

That gives you a unicode string without the BOM. You can then use

s = u.encode("utf-8")

to get a normal UTF-8 encoded string back in s. If your files are big, then you should avoid reading them all into memory. The BOM is simply three bytes at the beginning of the file, so you can use this code to strip them out of the file:

import os, sys, codecs

BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)

path = sys.argv[1]
with open(path, "r+b") as fp:
    chunk = fp.read(BUFSIZE)
    if chunk.startswith(codecs.BOM_UTF8):
        i = 0
        chunk = chunk[BOMLEN:]
        while chunk:
            fp.seek(i)
            fp.write(chunk)
            i += len(chunk)
            fp.seek(BOMLEN, os.SEEK_CUR)
            chunk = fp.read(BUFSIZE)
        fp.seek(-BOMLEN, os.SEEK_CUR)
        fp.truncate()

It opens the file, reads a chunk, and writes it out to the file 3 bytes earlier than where it read it. The file is rewritten in-place. As easier solution is to write the shorter file to a new file like newtover's answer. That would be simpler, but use twice the disk space for a short period.

As for guessing the encoding, then you can just loop through the encoding from most to least specific:

def decode(s):
    for encoding in "utf-8-sig", "utf-16":
        try:
            return s.decode(encoding)
        except UnicodeDecodeError:
            continue
    return s.decode("latin-1") # will always work

An UTF-16 encoded file wont decode as UTF-8, so we try with UTF-8 first. If that fails, then we try with UTF-16. Finally, we use Latin-1 — this will always work since all 256 bytes are legal values in Latin-1. You may want to return None instead in this case since it's really a fallback and your code might want to handle this more carefully (if it can).

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

ERROR Android emulator gets killed

I have been struggling with the The emulator process for AVD Pixel_2_API_30 was killed for a while now. I was trying to launch a Pixel 2 API 30 running android 11.0, I tried all the possible solutions but nothing seemed to work. I decided t use a different setup e.g. Pixel 2 API 28 running android 9.0, and it worked perfectly. I am not sure what causes the bug in the higher-level API or android version though... So my suggestion is to change the API and android version IF all of the other solutions didn't work.

Python check if list items are integers?

You can use exceptional handling as str.digit will only work for integers and can fail for something like this too:

>>> str.isdigit(' 1')
False

Using a generator function:

def solve(lis):                                        
    for x in lis:
        try:
            yield float(x)
        except ValueError:    
            pass

>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))                                    
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6]   #returns converted values

or may be you wanted this:

def solve(lis):
    for x in lis:
        try:
            float(x)
            return True
        except:
            return False
...         
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']

or using ast.literal_eval, this will work for all types of numbers:

>>> from ast import literal_eval
>>> def solve(lis):
    for x in lis:
        try:
            literal_eval(x)
            return True
        except ValueError:   
             return False
...         
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]                               
['1', '2', '3', '4', '1.5', '2.6', '1+0j']

How to set environment variables in Python?

You may need to consider some further aspects for code robustness;

when you're storing an integer-valued variable as an environment variable, try

os.environ['DEBUSSY'] = str(myintvariable)

then for retrieval, consider that to avoid errors, you should try

os.environ.get('DEBUSSY', 'Not Set')

possibly substitute '-1' for 'Not Set'

so, to put that all together

myintvariable = 1
os.environ['DEBUSSY'] = str(myintvariable)
strauss = int(os.environ.get('STRAUSS', '-1'))
# NB KeyError <=> strauss = os.environ['STRAUSS']
debussy = int(os.environ.get('DEBUSSY', '-1'))

print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)

Cannot push to GitHub - keeps saying need merge

If by any chance git pull prints Already up-to-date then you might want to check the global git push.default param (In ~/.gitconfig). Set it to simple if it was in matching. The below answer explains why:

Git - What is the difference between push.default "matching" and "simple"

Also, it is worth checking if your local branch is out of date using git remote show origin and do a pull if needed

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

How to know if an object has an attribute in Python

Another possible option, but it depends if what you mean by before:

undefined = object()

class Widget:

    def __init__(self):
        self.bar = 1

    def zoom(self):
        print("zoom!")

a = Widget()

bar = getattr(a, "bar", undefined)
if bar is not undefined:
    print("bar:%s" % (bar))

foo = getattr(a, "foo", undefined)
if foo is not undefined:
    print("foo:%s" % (foo))

zoom = getattr(a, "zoom", undefined)
if zoom is not undefined:
    zoom()

output:

bar:1
zoom!

This allows you to even check for None-valued attributes.

But! Be very careful you don't accidentally instantiate and compare undefined multiple places because the is will never work in that case.

Update:

because of what I was warning about in the above paragraph, having multiple undefineds that never match, I have recently slightly modified this pattern:

undefined = NotImplemented

NotImplemented, not to be confused with NotImplementedError, is a built-in: it semi-matches the intent of a JS undefined and you can reuse its definition everywhere and it will always match. The drawbacks is that it is "truthy" in booleans and it can look weird in logs and stack traces (but you quickly get over it when you know it only appears in this context).

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

Countercheck if boostrap/cache/config.php database details are correct. That should give you an hint if they are.

If they are not, then you need to clear the cache using the following steps :

  1. rm -fr bootstrap/cache/*
  2. php artisan optimize

builder for HashMap

Here is a very simple one ...

public class FluentHashMap<K, V> extends java.util.HashMap<K, V> {
  public FluentHashMap<K, V> with(K key, V value) {
    put(key, value);
    return this;
  }

  public static <K, V> FluentHashMap<K, V> map(K key, V value) {
    return new FluentHashMap<K, V>().with(key, value);
  }
}

then

import static FluentHashMap.map;

HashMap<String, Integer> m = map("a", 1).with("b", 2);

See https://gist.github.com/culmat/a3bcc646fa4401641ac6eb01f3719065

How can I write an anonymous function in Java?

Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).

A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.

private static String pretty(Node node) {
    return "Node: " + new Object() {
        String print(Node cur) {
            return cur.isTerminal() ?
                cur.name() :
                ("("+print(cur.left())+":"+print(cur.right())+")");
        }
    }.print(node);
}

(I originally wrote this using node rather than cur in the print method. Say NO to capturing "implicitly final" locals?)

How to delete a file from SD card?

 public static boolean deleteDirectory(File path) {
    // TODO Auto-generated method stub
    if( path.exists() ) {
        File[] files = path.listFiles();
        for(int i=0; i<files.length; i++) {
            if(files[i].isDirectory()) {
                deleteDirectory(files[i]);
            }
            else {
                files[i].delete();
            }
        }
    }
    return(path.delete());
 }

This Code will Help you.. And In Android Manifest You have to get Permission to make modification..

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

proper hibernate annotation for byte[]

What is the portable way to annotate a byte[] property?

It depends on what you want. JPA can persist a non annotated byte[]. From the JPA 2.0 spec:

11.1.6 Basic Annotation

The Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive, types, wrappers of the primitive types, java.lang.String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements Serializable. As described in Section 2.8, the use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

And Hibernate will map a it "by default" to a SQL VARBINARY (or a SQL LONGVARBINARY depending on the Column size?) that PostgreSQL handles with a bytea.

But if you want the byte[] to be stored in a Large Object, you should use a @Lob. From the spec:

11.1.24 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation or with the ElementCollection annotation when the element collection value is of basic type. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property and, except for string and character types, defaults to Blob.

And Hibernate will map it to a SQL BLOB that PostgreSQL handles with a oid .

Is this fixed in some recent version of hibernate?

Well, the problem is that I don't know what the problem is exactly. But I can at least say that nothing has changed since 3.5.0-Beta-2 (which is where a changed has been introduced)in the 3.5.x branch.

But my understanding of issues like HHH-4876, HHH-4617 and of PostgreSQL and BLOBs (mentioned in the javadoc of the PostgreSQLDialect) is that you are supposed to set the following property

hibernate.jdbc.use_streams_for_binary=false

if you want to use oid i.e. byte[] with @Lob (which is my understanding since VARBINARY is not what you want with Oracle). Did you try this?

As an alternative, HHH-4876 suggests using the deprecated PrimitiveByteArrayBlobType to get the old behavior (pre Hibernate 3.5).

References

  • JPA 2.0 Specification
    • Section 2.8 "Mapping Defaults for Non-Relationship Fields or Properties"
    • Section 11.1.6 "Basic Annotation"
    • Section 11.1.24 "Lob Annotation"

Resources

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

It might be due to various issues.I cant say which one is there in your case.

Below given reasons may be there:

  • DCOM is not enabled in host PC or target PC or on both.
  • Your Firewall or even your antivirus is preventing the access.
  • Any WMI related service is disabled.

Some WMI related services are as given:

  • Remote Access Auto Connection Manager
  • Remote Access Connection Manager
  • Remote Procedure Call (RPC)
  • Remote Procedure Call (RPC) Locator
  • Remote Registry

For DCOM setting refer:

  • Key: HKLM\Software\Microsoft\OLE, Value: EnableDCOM

The value should be set to 'Y' .

Getting current directory in VBScript

Your line

Directory = CurrentDirectory\attribute.exe

does not match any feature I have encountered in a vbscript instruction manual. The following works for me, tho not sure what/where you expect "attribute.exe" to reside.

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run curDir & "\testme.bat", 1
set WinScriptHost = nothing

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

CSS Pseudo-classes with inline styles

Not CSS, but inline:

<a href="#" 
   onmouseover = "this.style.textDecoration = 'none'"
   onmouseout  = "this.style.textDecoration = 'underline'">Hello</a>

See example →

How to check if a scope variable is undefined in AngularJS template?

Posting new answer since Angular behavior has changed. Checking equality with undefined now works in angular expressions, at least as of 1.5, as the following code works:

ng-if="foo !== undefined"

When this ng-if evaluates to true, deleting the percentages property off the appropriate scope and calling $digest removes the element from the document, as you would expect.

Bootstrap 3.0 Popovers and tooltips

You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.

<script type="text/javascript">

    $(document).ready(function() {

        $('.btn-danger').tooltip();

    }); //END $(document).ready()

</script>

Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup".

NSString with \n or line break

I found that when I was reading strings in from a .plist file, occurrences of "\n" were parsed as "\\n". The solution for me was to replace occurrences of "\\n" with "\n". For example, given an instance of NSString named myString read in from my .plist file, I had to call...

myString = [myString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

... before assigning it to my UILabel instance...

myLabel.text = myString;

How to delete specific rows and columns from a matrix in a smarter way?

You can use

t1<- t1[-4:-6,-7:-9]  

or

t1 <- t1[-(4:6), -(7:9)]

or

t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]

You can pass vectors to select rows/columns to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns.

> t1 <- array(1:20, dim=c(10,10));

> t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2   12    2   12    2   12
[2,]    3   13    3   13    3   13
[3,]    5   15    5   15    5   15
[4,]    8   18    8   18    8   18
[5,]   10   20   10   20   10   20

Group query results by month and year in postgresql

select to_char(date,'Mon') as mon,
       extract(year from date) as yyyy,
       sum("Sales") as "Sales"
from yourtable
group by 1,2

At the request of Radu, I will explain that query:

to_char(date,'Mon') as mon, : converts the "date" attribute into the defined format of the short form of month.

extract(year from date) as yyyy : Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.

sum("Sales") as "Sales" : The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.

group by 1,2 : The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.

Add new row to dataframe, at specific row-index, not appended?

for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

allEdges <- data.frame(c(edges$V1,edges$V2))

Defining Z order of views of RelativeLayout in Android

Or put the overlapping button or views inside a FrameLayout. Then, the RelativeLayout in the xml file will respect the order of child layouts as they added.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Have you looked under Advanced Security Settings?

something like below image change permissions of folder to IIS_IUSRS

enter image description here

How to download a file from a URL in C#?

Check for a network connection using GetIsNetworkAvailable() to avoid creating empty files when not connected to a network.

if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
    using (System.Net.WebClient client = new System.Net.WebClient())
    {                        
          client.DownloadFileAsync(new Uri("http://www.examplesite.com/test.txt"),
          "D:\\test.txt");
    }                  
}

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

Purpose of "%matplotlib inline"

If you don't know what backend is , you can read this: https://matplotlib.org/tutorials/introductory/usage.html#backends

Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people run Jupyter notebooks and draw inline plots for quick data analysis. Others embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications. Some people use matplotlib in batch scripts to generate postscript images from numerical simulations, and still others run web application servers to dynamically serve up graphs. To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the "frontend" is the user facing code, i.e., the plotting code, whereas the "backend" does all the hard work behind-the-scenes to make the figure.

So when you type %matplotlib inline , it activates the inline backend. As discussed in the previous posts :

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

What is the difference between a JavaBean and a POJO?

POJOS with certain conventions (getter/setter,public no-arg constructor ,private variables) and are in action(ex. being used for reading data by form) are JAVABEANS.

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

How can I use grep to show just filenames on Linux?

From the grep(1) man page:

  -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)

TypeScript: correct way to do string equality?

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

Change bootstrap datepicker date format on select

As of 2016 I used datetimepicker like this:

$(function () {
    $('#date_box').datetimepicker({
        format: 'YYYY-MM-DD hh:mm'
    });
});

How to configure slf4j-simple

This is a sample simplelogger.properties which you can place on the classpath (uncomment the properties you wish to use):

# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.

# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info

# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=

# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false

# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z

# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true

# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true

# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Thanks for all the answers. I tried all of them but none of them worked for me. What did work was to delete the applicationhost.config from the .vs folder (found in the folder of your project/solution) and create a new virtual directory (Project Properties > Web > Create Virtual Directory). Hope this will help somebody else.

How do C++ class members get initialized if I don't do it explicitly?

It depends on how the class is constructed

Answering this question comes understanding a huge switch case statement in the C++ language standard, and one which is hard for mere mortals to get intuition about.

As a simple example of how difficult thing are:

main.cpp

#include <cassert>

int main() {
    struct C { int i; };

    // This syntax is called "default initialization"
    C a;
    // i undefined

    // This syntax is called "value initialization"
    C b{};
    assert(b.i == 0);
}

In default initialization you would start from: https://en.cppreference.com/w/cpp/language/default_initialization we go to the part "The effects of default initialization are" and start the case statement:

  • "if T is a non-POD": no (the definition of POD is in itself a huge switch statement)
  • "if T is an array type": no
  • "otherwise, nothing is done": therefore it is left with an undefined value

Then, if someone decides to value initialize we go to https://en.cppreference.com/w/cpp/language/value_initialization "The effects of value initialization are" and start the case statement:

  • "if T is a class type with no default constructor or with a user-provided or deleted default constructor": not the case. You will now spend 20 minutes Googling those terms:
    • we have an implicitly defined default constructor (in particular because no other constructor was defined)
    • it is not user-provided (implicitly defined)
    • it is not deleted (= delete)
  • "if T is a class type with a default constructor that is neither user-provided nor deleted": yes

This is why I strongly recommend that you just never rely on "implicit" zero initialization. Unless there are strong performance reasons, explicitly initialize everything, either on the constructor if you defined one, or using aggregate initialization. Otherwise you make things very very risky for future developers.

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.

However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.

If you had a row named full_brand_name and you wanted to use the first two letters as a short name in the field small_name you could use:

CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
  SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END

How do you create a dictionary in Java?

There's an Abstract Class Dictionary

http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html

However this requires implementation.

Java gives us a nice implementation called a Hashtable

http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Here is the complete solution for PostgreSQL 9+, updated recently.

CREATE USER readonly  WITH ENCRYPTED PASSWORD 'readonly';
GRANT USAGE ON SCHEMA public to readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

-- repeat code below for each database:

GRANT CONNECT ON DATABASE foo to readonly;
\c foo
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; --- this grants privileges on new tables generated in new database "foo"
GRANT USAGE ON SCHEMA public to readonly; 
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Thanks to https://jamie.curle.io/creating-a-read-only-user-in-postgres/ for several important aspects

If anyone find shorter code, and preferably one that is able to perform this for all existing databases, extra kudos.

how to install python distutils

If the system Python is borked (i.e. the OS packages split distutils in a python-devel package) and you can’t ask a sysadmin to install the missing piece, then you’ll have to install your own Python. It requires some header files and a compiler toolchain. If you can’t have those, try compiling a Python on an identical computer and just copying it.

dynamically set iframe src

Try this...

function urlChange(url) {
    var site = url+'?toolbar=0&amp;navpanes=0&amp;scrollbar=0';
    document.getElementById('iFrameName').src = site;
}

<a href="javascript:void(0);" onClick="urlChange('www.mypdf.com/test.pdf')">TEST </a>

How do I PHP-unserialize a jQuery-serialized form?

Simply do this

$get = explode('&', $_POST['seri']); // explode with and

foreach ($get as $key => $value) {
    $need[substr($value, 0 , strpos($value, '='))] =  substr(
        $value, 
        strpos( $value, '=' ) + 1 
    );
}

// access your query param name=ddd&email=aaaaa&username=wwwww&password=wwww&password=eeee
var_dump($need['name']);

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Make sure you set the Build Platform Target to x86 or x64 so that it is compatible with your DLL - which might be compiled for a 32 bit platform.

Android M Permissions: onRequestPermissionsResult() not being called

Here i want to show my code how i managed this.

public class CheckPermission {

public Context context;

public static final int PERMISSION_REQUEST_CODE =  200;

public CheckPermission(Context context){
    this.context = context;
}

public boolean isPermissionGranted(){
    int read_contact = ContextCompat.checkSelfPermission(context.getApplicationContext() , READ_CONTACTS);
    int phone = ContextCompat.checkSelfPermission(context.getApplicationContext() , CALL_PHONE);

    return read_contact == PackageManager.PERMISSION_GRANTED && phone == PackageManager.PERMISSION_GRANTED;
   }
}

Here in this class i want to check permission granted or not. Is not then i will call permission from my MainActivity like

public void requestForPermission() {
       ActivityCompat.requestPermissions(MainActivity.this, new String[]    {READ_CONTACTS, CALL_PHONE}, PERMISSION_REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
                    showMessageOKCancel("You need to allow access to both the permissions",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE},
                                                PERMISSION_REQUEST_CODE);
                                    }
                                }
                            });
                    return;
                }
            }
    }
}

Now in the onCreate method you need to call requestForPermission() function.

That's it.Also you can request multiple permission at a time.

PHPDoc type hinting for array of objects?

<?php foreach($this->models as /** @var Model_Object_WheelModel */ $model): ?>
    <?php
    // Type hinting now works:
    $model->getImage();
    ?>
<?php endforeach; ?>

"unmappable character for encoding" warning in Java

Most of the time this compile error comes when unicode(UTF-8 encoded) file compiling

javac -encoding UTF-8 HelloWorld.java

and also You can add this compile option to your IDE ex: Intellij idea
(File>settings>Java Compiler) add as additional command line parameter

enter image description here

-encoding : encoding Set the source file encoding name, such as EUC-JP and UTF-8.. If -encoding is not specified, the platform default converter is used. (DOC)

When does Java's Thread.sleep throw InterruptedException?

If an InterruptedException is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt() method. The wait method detects that and throws an InterruptedException so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.

If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:

} catch (InterruptedException e) {
  Thread.currentThread().interrupt();
  // code for stopping current task so thread stops
}

Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.

What might be better is to add this:

} catch (InterruptedException e) {
  throw new RuntimeException("Unexpected interrupt", e);
}

...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.

Cast int to varchar

Should be able to do something like this also:

Select (id :> VARCHAR(10)) as converted__id_int
from t9 

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

jquery .live('click') vs .click()

.live() is used if elements are being added after the initial page load. Say you have a button which gets added by an AJAX call after the page gets loaded. This new button will not be accessible using .click(), so you'll have to use .live('click')

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

How can I print using JQuery

Try like

$('.printMe').click(function(){
     window.print();
});

or if you want to print selected area try like

$('.printMe').click(function(){
     $("#outprint").print();
});

Should we pass a shared_ptr by reference or by value?

Pass by const reference, it's faster. If you need to store it, say in some container, the ref. count will be auto-magically incremented by the copy operation.

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I had the same issue. I checked the version of System.Data.SqlServerCe in C:\Windows\assembly. It was 3.5.1.0. So I installed version 4.0.0 from below link (x86) and works fine.

http://www.microsoft.com/download/en/details.aspx?id=17876

Modify property value of the objects in list using Java 8 streams

You can use peek to do that.

List<Fruit> newList = fruits.stream()
    .peek(f -> f.setName(f.getName() + "s"))
    .collect(Collectors.toList());

Rename all files in directory from $filename_h to $filename_half?

Just use bash, no need to call external commands.

for file in *_h.png
do
  mv "$file" "${file/_h.png/_half.png}"
done

Do not add #!/bin/sh

For those that need that one-liner:

for file in *.png; do mv "$file" "${file/_h.png/_half.png}"; done

In Android EditText, how to force writing uppercase?

To get all capital, use the following in your XML:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAllCaps="true"
    android:inputType="textCapCharacters"
/>

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.

However, there are other considerations at play here too.

Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.

Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).

If you refer to classic VxWorks RTOS kernel, they define three mechanisms:

  • mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner.
  • binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads.
  • counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero.

Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.

Reset select2 value and show placeholder

$("#customers_select").val([]).trigger('change')

this will remove values AND most important for me - it also remove an empty x button

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Changing three.js background to transparent or other color

In 2020 using r115 it works very good with this:

const renderer = new THREE.WebGLRenderer({ alpha: true }); const scene = new THREE.Scene(); scene.background = null;

CRC32 C or C++ implementation

The crc code in zlib (http://zlib.net/) is among the fastest there is, and has a very liberal open source license.

And you should not use adler-32 except for special applications where speed is more important than error detection performance.

How to verify CuDNN installation?

To check installation of CUDA, run below command, if it’s installed properly then below command will not throw any error and will print correct version of library.

function lib_installed() { /sbin/ldconfig -N -v $(sed 's/:/ /' <<< $LD_LIBRARY_PATH) 2>/dev/null | grep $1; }
function check() { lib_installed $1 && echo "$1 is installed" || echo "ERROR: $1 is NOT installed"; }
check libcuda
check libcudart

To check installation of CuDNN, run below command, if CuDNN is installed properly then you will not get any error.

function lib_installed() { /sbin/ldconfig -N -v $(sed 's/:/ /' <<< $LD_LIBRARY_PATH) 2>/dev/null | grep $1; }
function check() { lib_installed $1 && echo "$1 is installed" || echo "ERROR: $1 is NOT installed"; }
check libcudnn 

OR

you can run below command from any directory

nvcc -V

it should give output something like this

 nvcc: NVIDIA (R) Cuda compiler driver
 Copyright (c) 2005-2016 NVIDIA Corporation
 Built on Tue_Jan_10_13:22:03_CST_2017
 Cuda compilation tools, release 8.0, V8.0.61

Change form size at runtime in C#

You cannot change the Width and Height properties of the Form as they are readonly. You can change the form's size like this:

button1_Click(object sender, EventArgs e)
{
    // This will change the Form's Width and Height, respectively.
    this.Size = new Size(420, 200);
}

How do I convert csv file to rdd

How about this?

val Delimeter = ","
val textFile = sc.textFile("data.csv").map(line => line.split(Delimeter))

Generate a random point within a circle (uniformly)

First we generate a cdf[x] which is

The probability that a point is less than distance x from the centre of the circle. Assume the circle has a radius of R.

obviously if x is zero then cdf[0] = 0

obviously if x is R then the cdf[R] = 1

obviously if x = r then the cdf[r] = (Pi r^2)/(Pi R^2)

This is because each "small area" on the circle has the same probability of being picked, So the probability is proportionally to the area in question. And the area given a distance x from the centre of the circle is Pi r^2

so cdf[x] = x^2/R^2 because the Pi cancel each other out

we have cdf[x]=x^2/R^2 where x goes from 0 to R

So we solve for x

R^2 cdf[x] = x^2

x = R Sqrt[ cdf[x] ]

We can now replace cdf with a random number from 0 to 1

x = R Sqrt[ RandomReal[{0,1}] ]

Finally

r = R Sqrt[  RandomReal[{0,1}] ];
theta = 360 deg * RandomReal[{0,1}];
{r,theta}

we get the polar coordinates {0.601168 R, 311.915 deg}

How do I install cygwin components from the command line?

Usually before installing a package one has to know its exact name:

# define a string to search
export to_srch=perl

# get html output of search and pick only the cygwin package names
wget -qO- "https://cygwin.com/cgi-bin2/package-grep.cgi?grep=$to_srch&arch=x86_64" | \
perl -l -ne 'm!(.*?)<\/a>\s+\-(.*?)\:(.*?)<\/li>!;print $2'

# and install 
# install multiple packages at once, note the
setup-x86_64.exe -q -s http://cygwin.mirror.constant.com -P "<<chosen_package_name>>"

How to find if div with specific id exists in jQuery?

You can handle it in different ways,

Objective is to check if the div exist then execute the code. Simple.

Condition:

$('#myDiv').length

Note:

#myDiv -> < div id='myDiv' > <br>
.myDiv -> < div class='myDiv' > 

This will return a number every time it is executed so if there is no div it will give a Zero [0], and as we no 0 can be represented as false in binary so you can use it in if statement. And you can you use it as a comparison with a none number. while any there are three statement given below

// Statement 0
// jQuery/Ajax has replace [ document.getElementById with $ sign ] and etc
// if you don't want to use jQuery/ajax 

   if (document.getElementById(name)) { 
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 1
   if ($('#'+ name).length){ // if 0 then false ; if not 0 then true
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 2
    if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1]
           $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>"); 
    }
// Statement 3
    if ($('#'+ name).length > 0 ) {
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 4
    if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist.
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

Cannot GET / Nodejs Error

If you are getting this error, it could be because you don't have a route defined for your get.

For example:

const express = require('express');

const app = express();

app.get('/people', function (req, res) {
    res.send('hello');
})

app.listen(3000);


http://http://localhost:3000/people --> this works
http://http://localhost:3000 --> this will output Cannot GET / message.

Get human readable version of file size?

I like the fixed precision of senderle's decimal version, so here's a sort of hybrid of that with joctee's answer above (did you know you could take logs with non-integer bases?):

from math import log
def human_readable_bytes(x):
    # hybrid of https://stackoverflow.com/a/10171475/2595465
    #      with https://stackoverflow.com/a/5414105/2595465
    if x == 0: return '0'
    magnitude = int(log(abs(x),10.24))
    if magnitude > 16:
        format_str = '%iP'
        denominator_mag = 15
    else:
        float_fmt = '%2.1f' if magnitude % 3 == 1 else '%1.2f'
        illion = (magnitude + 1) // 3
        format_str = float_fmt + ['', 'K', 'M', 'G', 'T', 'P'][illion]
    return (format_str % (x * 1.0 / (1024 ** illion))).lstrip('0')

Manipulate a url string by adding GET parameters

After searching for many resources/answers on this topic, I decided to code my own. Based on @TaylorOtwell's answer here, this is how I process incoming $_GET request and modify/manipulate each element.

Assuming the url is: http://domain.com/category/page.php?a=b&x=y And I want only one parameter for sorting: either ?desc=column_name or ?asc=column_name. This way, single url parameter is enough to sort and order simultaneously. So the URL will be http://domain.com/category/page.php?a=b&x=y&desc=column_name on first click of the associated table header row.

Then I have table row headings that I want to sort DESC on my first click, and ASC on the second click of the same heading. (Each first click should "ORDER BY column DESC" first) And if there is no sorting, it will sort by "date then id" by default.

You may improve it further, like you may add cleaning/filtering functions to each $_GET component but the below structure lays the foundation.

foreach ($_GET AS $KEY => $VALUE){
    if ($KEY == 'desc'){
        $SORT = $VALUE;
        $ORDER = "ORDER BY $VALUE DESC";
        $URL_ORDER = $URL_ORDER . "&asc=$VALUE";
    } elseif ($KEY == 'asc'){
        $SORT = $VALUE;
        $ORDER = "ORDER BY $VALUE ASC";
        $URL_ORDER = $URL_ORDER . "&desc=$VALUE";
    } else {
        $URL_ORDER .= "&$KEY=$VALUE";
        $URL .= "&$KEY=$VALUE";
    }
}
if (!$ORDER){$ORDER = 'ORDER BY date DESC, id DESC';}
if ($URL_ORDER){$URL_ORDER = $_SERVER[SCRIPT_URL] . '?' . trim($URL_ORDER, '&');}
if ($URL){$URL = $_SERVER[SCRIPT_URL] . '?' . trim($URL, '&');}

(You may use $_SERVER[SCRIPT_URI] for full URL beginning with http://domain.com)

Then I use resulting $ORDER I get above, in the MySQL query:

"SELECT * FROM table WHERE limiter = 'any' $ORDER";

Now the function to look at the URL if there is a previous sorting and add sorting (and ordering) parameter to URL with "?" or "&" according to the sequence:

        function sort_order ($_SORT){
            global $SORT, $URL_ORDER, $URL;
            if ($SORT == $_SORT){
                return $URL_ORDER;
            } else {
                if (strpos($URL, '?') !== false){
                    return "$URL&desc=$_SORT";
                } else {                        
                    return "$URL?desc=$_SORT";
                }
            }
        }

Finally, the table row header to use the function:

        echo "<th><a href='".sort_order('id')."'>ID</a></th>";

Summary: this will read the URL, modify each of the $_GET components and make the final URL with parameters of your choice with the correct form of usage of "?" and "&"

What's the best UI for entering date of birth?

I had tried datePicker with my user but it turn out to be a bad UI to them. What I end up base on their request is to have 3 textbox where they can quickly type [ day ] [ month ] [ year ] :(

mongodb/mongoose findMany - find all documents with IDs listed in array

Ids is the array of object ids:

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];

Using Mongoose with callback:

Model.find().where('_id').in(ids).exec((err, records) => {});

Using Mongoose with async function:

const records = await Model.find().where('_id').in(ids).exec();

Or more concise:

const records = await Model.find({ '_id': { $in: ids } });

Don't forget to change Model with your actual model.

Get PHP class property by string

If you want to access the property without creating an intermediate variable, use the {} notation:

$something = $object->{'something'};

That also allows you to build the property name in a loop for example:

for ($i = 0; $i < 5; $i++) {
    $something = $object->{'something' . $i};
    // ...
}

Laravel orderBy on a relationship

Try this solution.

$mainModelData = mainModel::where('column', $value)
    ->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
    ->orderBy('relation_table.title', 'ASC')
    ->with(['relationModal' => function ($q) {
        $q->where('column', 'value');
    }])->get();

Example:

$user = User::where('city', 'kullu')
    ->join('salaries', 'users.id', '=', 'salaries.user_id')
    ->orderBy('salaries.amount', 'ASC')
    ->with(['salaries' => function ($q) {
        $q->where('amount', '>', '500000');
    }])->get();

You can change the column name in join() as per your database structure.

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"

How do you convert a byte array to a hexadecimal string in C?

Based on Yannuth's answer but simplified.

Here, length of dest[] is implied to be twice of len, and its allocation is managed by the caller.

void create_hex_string_implied(const unsigned char *src, size_t len, unsigned char *dest)
{
    static const unsigned char table[] = "0123456789abcdef";

    for (; len > 0; --len)
    {
        unsigned char c = *src++;
        *dest++ = table[c >> 4];
        *dest++ = table[c & 0x0f];
    }
}

How can I split and parse a string in Python?

Python string parsing walkthrough

Split a string on space, get a list, show its type, print it out:

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

If you have two delimiters next to each other, empty string is assumed:

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

Split a string on underscore and grab the 5th item in the list:

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

Collapse multiple spaces into one

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

When you pass no parameter to Python's split method, the documentation states: "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace".

Hold onto your hats boys, parse on a regular expression:

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

The regular expression "[a-m]+" means the lowercase letters a through m that occur one or more times are matched as a delimiter. re is a library to be imported.

Or if you want to chomp the items one at a time:

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula

Creating a singleton in Python

One liner (I am not proud, but it does the job):

class Myclass:
  def __init__(self):
      # do your stuff
      globals()[type(self).__name__] = lambda: self # singletonify

Error: Cannot find module html

Simple way is to use the EJS template engine for serving .html files. Put this line right next to your view engine setup:

app.engine('html', require('ejs').renderFile);

What is the significance of load factor in HashMap?

The documentation explains it pretty well:

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

As with all performance optimizations, it is a good idea to avoid optimizing things prematurely (i.e. without hard data on where the bottlenecks are).

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

Can I use Objective-C blocks as properties?

Here's an example of how you would accomplish such a task:

#import <Foundation/Foundation.h>
typedef int (^IntBlock)();

@interface myobj : NSObject
{
    IntBlock compare;
}

@property(readwrite, copy) IntBlock compare;

@end

@implementation myobj

@synthesize compare;

- (void)dealloc 
{
   // need to release the block since the property was declared copy. (for heap
   // allocated blocks this prevents a potential leak, for compiler-optimized 
   // stack blocks it is a no-op)
   // Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
   [compare release];
   [super dealloc];
}
@end

int main () {
    @autoreleasepool {
        myobj *ob = [[myobj alloc] init];
        ob.compare = ^
        {
            return rand();
        };
        NSLog(@"%i", ob.compare());
        // if not ARC
        [ob release];
    }

    return 0;
}

Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)(). If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id), and change your block to:

^ (id obj1, id obj2)
{
    return rand();
};

I hope this helps.

EDIT March 12, 2012:

For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.

For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html

Calling a user defined function in jQuery

jQuery.fn.make_me_red = function() {
    alert($(this).attr('id'));
    $(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
    //$(this).siblings(".hello").make_me_red(); 
    $(this).make_me_red(); 
    $(this).addClass("active");
});
?

Function declaration and callback in jQuery.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

Find UNC path of a network drive?

$CurrentFolder = "H:\Documents"
$Query = "Select * from Win32_NetworkConnection where LocalName = '" + $CurrentFolder.Substring( 0, 2 ) + "'"
( Get-WmiObject -Query $Query ).RemoteName

OR

$CurrentFolder = "H:\Documents"
$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query "Select * from Win32_NetworkConnection where LocalName = '$Tst'" ).RemoteName

How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:

$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...

As an alias:

$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...

Please note that I control my Python version via conda environments, because of that I can use python instead of python3 for using Python 3.

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29';

it helps , you can convert the values as DATE before comparing.

How to name variables on the fly?

Another tricky solution is to name elements of list and attach it:

list_name = list(
    head(iris),
    head(swiss),
    head(airquality)
    )

names(list_name) <- paste("orca", seq_along(list_name), sep="")
attach(list_name)

orca1
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Is there an equivalent to background-size: cover and contain for image elements?

For IE you also need to include the second line - width: 100%;

.mydiv img {
    max-width: 100%;
    width: 100%;
}

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

Maintain the aspect ratio of a div with CSS

As @web-tiki already show a way to use vh/vw, I also need a way to center in the screen, here is a snippet code for 9:16 portrait.

.container {
  width: 100vw;
  height: calc(100vw * 16 / 9);
  transform: translateY(calc((100vw * 16 / 9 - 100vh) / -2));
}

translateY will keep this center in the screen. calc(100vw * 16 / 9) is expected height for 9/16.(100vw * 16 / 9 - 100vh) is overflow height, so, pull up overflow height/2 will keep it center on screen.

For landscape, and keep 16:9, you show use

.container {
  width: 100vw;
  height: calc(100vw * 9 / 16);
  transform: translateY(calc((100vw * 9 / 16 - 100vh) / -2));
}

The ratio 9/16 is ease to change, no need to predefined 100:56.25 or 100:75.If you want to ensure height first, you should switch width and height, e.g. height:100vh;width: calc(100vh * 9 / 16) for 9:16 portrait.

If you want to adapted for different screen size, you may also interest

  • background-size cover/contain
    • Above style is similar to contain, depends on width:height ratio.
  • object-fit
    • cover/contain for img/video tag
  • @media (orientation: portrait)/@media (orientation: landscape)
    • Media query for portrait/landscape to change the ratio.

Filtering Table rows using Jquery

I used Beetroot-Betroot's solution, but instead of using contains, I used containsNC, which makes it case insensitive.

$.extend($.expr[":"], {
"containsNC": function(elem, i, match, array) {
return (elem.textContent || elem.innerText ||
"").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});

Find a private field with Reflection?

One thing that you need to be aware of when reflecting on private members is that if your application is running in medium trust (as, for instance, when you are running on a shared hosting environment), it won't find them -- the BindingFlags.NonPublic option will simply be ignored.

How to select date without time in SQL

Its too late but following worked for me well

declare @vCurrentDate date=getutcdate()

select @vCurrentDate

When data type is date, hours would be truncated

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

Yes it's possible, just add inline styles for the element which you adding after or before, Example

 <style>
     .horizontalProgress:after { width: 45%; }
 </style><!-- Change Value from Here -->

 <div class="horizontalProgress"></div>

How do you use colspan and rowspan in HTML tables?

<body>
<table>
<tr><td colspan="2" rowspan="2">1</td><td colspan="4">2</td></tr>
<tr><td>3</td><td>3</td><td>3</td><td>3</td></tr>
<tr><td colspan="2">1</td><td>3</td><td>3</td><td>3</td><td>3</td></tr>
</table>
</body>

How can I create a link to a local file on a locally-run web page?

back to 2017:

use URL.createObjectURL( file ) to create local link to file system that user select;

don't forgot to free memory by using URL.revokeObjectURL()

Convert Java String to sql.Timestamp

If you get time as string in format such as 1441963946053 you simply could do something as following:

//String timestamp;
Long miliseconds = Long.valueOf(timestamp);
Timestamp ti = new Timestamp(miliseconds);

Create a menu Bar in WPF?

Yes, a menu gives you the bar but it doesn't give you any items to put in the bar. You need something like (from one of my own projects):

<!-- Menu. -->
<Menu Width="Auto" Height="20" Background="#FFA9D1F4" DockPanel.Dock="Top">
    <MenuItem Header="_Emulator">
    <MenuItem Header="Load..." Click="MenuItem_Click" />
    <MenuItem Header="Load again" Click="menuEmulLoadLast" />
    <Separator />
    <MenuItem Click="MenuItem_Click">
        <MenuItem.Header>
            <DockPanel>
                <TextBlock>Step</TextBlock>
                <TextBlock Width="10"></TextBlock>
                <TextBlock HorizontalAlignment="Right">F2</TextBlock>
            </DockPanel>
        </MenuItem.Header>
    </MenuItem>
    :

What is the default encoding of the JVM?

It's going to be locale-dependent. Different locale, different default encoding.

Cannot implicitly convert type 'int' to 'short'

The problem is, that adding two Int16 results in an Int32 as others have already pointed out.
Your second question, why this problem doesn't already occur at the declaration of those two variables is explained here: http://msdn.microsoft.com/en-us/library/ybs77ex4%28v=VS.71%29.aspx:

short x = 32767;

In the preceding declaration, the integer literal 32767 is implicitly converted from int to short. If the integer literal does not fit into a short storage location, a compilation error will occur.

So, the reason why it works in your declaration is simply that the literals provided are known to fit into a short.

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

Optimal way to concatenate/aggregate strings

SOLUTION

The definition of optimal can vary, but here's how to concatenate strings from different rows using regular Transact SQL, which should work fine in Azure.

;WITH Partitioned AS
(
    SELECT 
        ID,
        Name,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) AS NameNumber,
        COUNT(*) OVER (PARTITION BY ID) AS NameCount
    FROM dbo.SourceTable
),
Concatenated AS
(
    SELECT 
        ID, 
        CAST(Name AS nvarchar) AS FullName, 
        Name, 
        NameNumber, 
        NameCount 
    FROM Partitioned 
    WHERE NameNumber = 1

    UNION ALL

    SELECT 
        P.ID, 
        CAST(C.FullName + ', ' + P.Name AS nvarchar), 
        P.Name, 
        P.NameNumber, 
        P.NameCount
    FROM Partitioned AS P
        INNER JOIN Concatenated AS C 
                ON P.ID = C.ID 
                AND P.NameNumber = C.NameNumber + 1
)
SELECT 
    ID,
    FullName
FROM Concatenated
WHERE NameNumber = NameCount

EXPLANATION

The approach boils down to three steps:

  1. Number the rows using OVER and PARTITION grouping and ordering them as needed for the concatenation. The result is Partitioned CTE. We keep counts of rows in each partition to filter the results later.

  2. Using recursive CTE (Concatenated) iterate through the row numbers (NameNumber column) adding Name values to FullName column.

  3. Filter out all results but the ones with the highest NameNumber.

Please keep in mind that in order to make this query predictable one has to define both grouping (for example, in your scenario rows with the same ID are concatenated) and sorting (I assumed that you simply sort the string alphabetically before concatenation).

I've quickly tested the solution on SQL Server 2012 with the following data:

INSERT dbo.SourceTable (ID, Name)
VALUES 
(1, 'Matt'),
(1, 'Rocks'),
(2, 'Stylus'),
(3, 'Foo'),
(3, 'Bar'),
(3, 'Baz')

The query result:

ID          FullName
----------- ------------------------------
2           Stylus
3           Bar, Baz, Foo
1           Matt, Rocks

Which is the correct C# infinite loop, for (;;) or while (true)?

Even I also say the below one is better :)

while(true)
{

}

What's the best way to trim std::string?

The accepted answer and even Boost's version did not work for me, so I wrote the following version:

std::string trim(const std::string& input) {
    std::stringstream string_stream;
    for (const auto character : input) {
        if (!isspace(character)) {
            string_stream << character;
        }
    }

    return string_stream.str();
}

This will remove any whitespace character from anywhere in the string and return a new copy of the string.

How to uninstall Jenkins?

These instructions apply if you installed using the official Jenkins Mac installer from http://jenkins-ci.org/

Execute uninstall script from terminal:

'/Library/Application Support/Jenkins/Uninstall.command'

or use Finder to navigate into that folder and double-click on Uninstall.command.

Finally delete last configuration bits which might have been forgotten:

sudo rm -rf /var/root/.jenkins ~/.jenkins

If the uninstallation script cannot be found (older Jenkins version), use following commands:

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins "/Library/Application Support/Jenkins" /Library/Documentation/Jenkins

and if you want to get rid of all the jobs and builds:

sudo rm -rf /Users/Shared/Jenkins

and to delete the jenkins user and group (if you chose to use them):

sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins

These commands are also invoked by the uninstall script in newer Jenkins versions, and should be executed too:

sudo rm -f /etc/newsyslog.d/jenkins.conf
pkgutil --pkgs | grep 'org\.jenkins-ci\.' | xargs -n 1 sudo pkgutil --forget

How do I perform a Perl substitution on a string while keeping the original?

The statement:

(my $newstring = $oldstring) =~ s/foo/bar/g;

Which is equivalent to:

my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

Alternatively, as of Perl 5.13.2 you can use /r to do a non destructive substitution:

use 5.013;
#...
my $newstring = $oldstring =~ s/foo/bar/gr;

Conda environments not showing up in Jupyter Notebook

If your environments are not showing up, make sure you have installed

  • nb_conda_kernels in the environment with Jupyter
  • ipykernel in the Python environment you want to access

Anaconda's documentation states that

nb_conda_kernels should be installed in the environment from which you run Jupyter Notebook or JupyterLab. This might be your base conda environment, but it need not be. For instance, if the environment notebook_env contains the notebook package, then you would run

conda install -n notebook_env nb_conda_kernels

Any other environments you wish to access in your notebooks must have an appropriate kernel package installed. For instance, to access a Python environment, it must have the ipykernel package; e.g.

conda install -n python_env ipykernel

To utilize an R environment, it must have the r-irkernel package; e.g.

conda install -n r_env r-irkernel

For other languages, their corresponding kernels must be installed.

In addition to Python, by installing the appropriatel *kernel package, Jupyter can access kernels from a ton of other languages including R, Julia, Scala/Spark, JavaScript, bash, Octave, and even MATLAB.

Note that at the time originally posting this, there was a possible cause from nb_conda not yet supporting Python 3.6 environments.

If other solutions fail to get Jupyter to recognize other conda environments, you can always install and run jupyter from within a specific environment. You may not be able to see or switch to other environments from within Jupyter though.

$ conda create -n py36_test -y python=3.6 jupyter
$ source activate py36_test
(py36_test) $ which jupyter
/home/schowell/anaconda3/envs/py36_test/bin/jupyter
(py36_test) $ jupyter notebook

Notice that I am running Python 3.6.1 in this notebook: enter image description here

Note that if you do this with many environments, the added storage space from installing Jupyter into every environment may be undesirable (depending on your system).

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

Php artisan make:auth command is not defined

If you using >5 version of laravel then you will use.

composer require laravel/ui --dev **or** composer require laravel/ui

And then

php artisan ui:auth

How much RAM is SQL Server actually using?

  1. Start -> Run -> perfmon
  2. Look at the zillions of counters that SQL Server installs

wkhtmltopdf: cannot connect to X server

  1. Download file from this link
  2. Extract it and move executable file(/wkhtmltox/bin/wkhtmltopdf) to /usr/bin/
  3. Rename it to wkhtmltopdf if current name is not wkhtmltopdf. So that now you have an executable at /usr/bin/wkhtmltopdf
  4. Set permissions: sudo chmod a+x /usr/bin/wkhtmltopdf
  5. Install required support packages. sudo apt-get install openssl build-essential xorg libssl-dev
  6. Now, check with wkhtmltopdf http://www.google.com test.pdf hint: detail information from this link

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.

Automatically capture output of last command into a variable using Bash?

The shell doesn't have perl-like special symbols that store the echo result of the last command.

Learn to use the pipe symbol with awk.

find . | awk '{ print "FILE:" $0 }'

In the example above you could do:

find . -name "foo.txt" | awk '{ print "mv "$0" ~/bar/" | "sh" }'

What's the equivalent of Java's Thread.sleep() in JavaScript?

Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:

async function sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec));
}

You can then use the sleep function in any other async function like this:

async function testSleep() {
    console.log("Waiting for 1 second...");
    await sleep(1000);
    console.log("Waiting done."); // Called 1 second after the first console.log
}

This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.

From MDN:

The await expression causes async function execution to pause until a Promise is fulfilled or rejected, and to resume execution of the async function after fulfillment.

For a full explanation see:

What's the best way to do a backwards loop in C/C#/C++?

NOTE: This post ended up being far more detailed and therefore off topic, I apologize.

That being said my peers read it and believe it is valuable 'somewhere'. This thread is not the place. I would appreciate your feedback on where this should go (I am new to the site).


Anyway this is the C# version in .NET 3.5 which is amazing in that it works on any collection type using the defined semantics. This is a default measure (reuse!) not performance or CPU cycle minimization in most common dev scenario although that never seems to be what happens in the real world (premature optimization).

*** Extension method working over any collection type and taking an action delegate expecting a single value of the type, all executed over each item in reverse **

Requres 3.5:

public static void PerformOverReversed<T>(this IEnumerable<T> sequenceToReverse, Action<T> doForEachReversed)
      {
          foreach (var contextItem in sequenceToReverse.Reverse())
              doForEachReversed(contextItem);
      }

Older .NET versions or do you want to understand Linq internals better? Read on.. Or not..

ASSUMPTION: In the .NET type system the Array type inherits from the IEnumerable interface (not the generic IEnumerable only IEnumerable).

This is all you need to iterate from beginning to end, however you want to move in the opposite direction. As IEnumerable works on Array of type 'object' any type is valid,

CRITICAL MEASURE: We assume if you can process any sequence in reverse order that is 'better' then only being able to do it on integers.

Solution a for .NET CLR 2.0-3.0:

Description: We will accept any IEnumerable implementing instance with the mandate that each instance it contains is of the same type. So if we recieve an array the entire array contains instances of type X. If any other instances are of a type !=X an exception is thrown:

A singleton service:

public class ReverserService { private ReverserService() { }

    /// <summary>
    /// Most importantly uses yield command for efficiency
    /// </summary>
    /// <param name="enumerableInstance"></param>
    /// <returns></returns>
    public static IEnumerable ToReveresed(IEnumerable enumerableInstance)
    {
        if (enumerableInstance == null)
        {
            throw new ArgumentNullException("enumerableInstance");
        }

        // First we need to move forwarad and create a temp
        // copy of a type that allows us to move backwards
        // We can use ArrayList for this as the concrete
        // type

        IList reversedEnumerable = new ArrayList();
        IEnumerator tempEnumerator = enumerableInstance.GetEnumerator();

        while (tempEnumerator.MoveNext())
        {
            reversedEnumerable.Add(tempEnumerator.Current);
        }

        // Now we do the standard reverse over this using yield to return
        // the result
        // NOTE: This is an immutable result by design. That is 
        // a design goal for this simple question as well as most other set related 
        // requirements, which is why Linq results are immutable for example
        // In fact this is foundational code to understand Linq

        for (var i = reversedEnumerable.Count - 1; i >= 0; i--)
        {
            yield return reversedEnumerable[i];
        }
    }
}



public static class ExtensionMethods
{

      public static IEnumerable ToReveresed(this IEnumerable enumerableInstance)
      {
          return ReverserService.ToReveresed(enumerableInstance);
      }
 }

[TestFixture] public class Testing123 {

    /// <summary>
    /// .NET 1.1 CLR
    /// </summary>
    [Test]
    public void Tester_fornet_1_dot_1()
    {
        const int initialSize = 1000;

        // Create the baseline data
        int[] myArray = new int[initialSize];

        for (var i = 0; i < initialSize; i++)
        {
            myArray[i] = i + 1;
        }

        IEnumerable _revered = ReverserService.ToReveresed(myArray);

        Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
    }

    [Test]
    public void tester_why_this_is_good()
    {

        ArrayList names = new ArrayList();
        names.Add("Jim");
        names.Add("Bob");
        names.Add("Eric");
        names.Add("Sam");

        IEnumerable _revered = ReverserService.ToReveresed(names);

        Assert.IsTrue(TestAndGetResult(_revered).Equals("Sam"));


    }

    [Test]
    public void tester_extension_method()
  {

        // Extension Methods No Linq (Linq does this for you as I will show)
        var enumerableOfInt = Enumerable.Range(1, 1000);

        // Use Extension Method - which simply wraps older clr code
        IEnumerable _revered = enumerableOfInt.ToReveresed();

        Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));


    }


    [Test]
    public void tester_linq_3_dot_5_clr()
    {

        // Extension Methods No Linq (Linq does this for you as I will show)
        IEnumerable enumerableOfInt = Enumerable.Range(1, 1000);

        // Reverse is Linq (which is are extension methods off IEnumerable<T>
        // Note you must case IEnumerable (non generic) using OfType or Cast
        IEnumerable _revered = enumerableOfInt.Cast<int>().Reverse();

        Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));


    }



    [Test]
    public void tester_final_and_recommended_colution()
    {

        var enumerableOfInt = Enumerable.Range(1, 1000);
        enumerableOfInt.PerformOverReversed(i => Debug.WriteLine(i));

    }



    private static object TestAndGetResult(IEnumerable enumerableIn)
    {
      //  IEnumerable x = ReverserService.ToReveresed(names);

        Assert.IsTrue(enumerableIn != null);
        IEnumerator _test = enumerableIn.GetEnumerator();

        // Move to first
        Assert.IsTrue(_test.MoveNext());
        return _test.Current;
    }
}

move a virtual machine from one vCenter to another vCenter

Copying the VM files onto an external HDD and then bringing it in to the destination will take a lot longer and requires multiple steps. Using vCenter Converter Standalone Client will do everything for you and is much faster. No external HDD required. Not sure where you got the cloning part from. vCenter Converter Standalone Client is simply copying the VM files by importing and exporting from source to destination, shutdown the source VM, then register the VM at destination and power on. All in one step. Takes about 1 min to set that up vCenter Converter Standalone Client.

Custom format for time command

Not quite sure what you are asking, have you tried:

time yourscript | tail -n1 >log

Edit: ok, so you know how to get the times out and you just want to change the format. It would help if you described what format you want, but here are some things to try:

time -p script

This changes the output to one time per line in seconds with decimals. You only want the real time, not the other two so to get the number of seconds use:

time -p script | tail -n 3 | head -n 1

IndentationError: unexpected unindent WHY?

It's because you have:

def readTTable(fname):
    try:

without a matching except block after the try: block. Every try must have at least one matching except.

See the Errors and Exceptions section of the Python tutorial.

Best way to check for "empty or null value"

If database having large number of records then null check can take more time you can use null check in different ways like : 1) where columnname is null 2) where not exists() 3) WHERE (case when columnname is null then true end)

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

As I know, PDO_MYSQLND replaced PDO_MYSQL in PHP 5.3. Confusing part is that name is still PDO_MYSQL. So now ND is default driver for MySQL+PDO.

Overall, to execute multiple queries at once you need:

  • PHP 5.3+
  • mysqlnd
  • Emulated prepared statements. Make sure PDO::ATTR_EMULATE_PREPARES is set to 1 (default). Alternatively you can avoid using prepared statements and use $pdo->exec directly.

Using exec

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works regardless of statements emulation
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$db->exec($sql);

Using statements

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$stmt = $db->prepare($sql);
$stmt->execute();

A note:

When using emulated prepared statements, make sure you have set proper encoding (that reflects actual data encoding) in DSN (available since 5.3.6). Otherwise there can be a slight possibility for SQL injection if some odd encoding is used.

How to secure phpMyAdmin

Another solution is to use the config file without any settings. The first time you might have to include your mysql root login/password so it can install all its stuff but then remove it.

$cfg['Servers'][$i]['auth_type'] = 'cookie';

$cfg['Servers'][$i]['host'] = 'localhost';

$cfg['Servers'][$i]['connect_type'] = 'tcp';

$cfg['Servers'][$i]['compress'] = false;

$cfg['Servers'][$i]['extension'] = 'mysql';

Leaving it like that without any apache/lighhtpd aliases will just present to you a log in screen. enter image description here

You can log in with root but it is advised to create other users and only allow root for local access. Also remember to use string passwords, even if short but with a capital, and number of special character. for example !34sy2rmbr! aka "easy 2 remember"

-EDIT: A good password now a days is actually something like words that make no grammatical sense but you can remember because they funny. Or use keepass to generate strong randoms an have easy access to them

How to add display:inline-block in a jQuery show() function?

Use css() just after show() or fadeIn() like this:

$('div.className').fadeIn().css('display', 'inline-block');

Setting up a JavaScript variable from Spring model by using Thymeleaf

Thymeleaf 3 now:

  • Display a constant:

    <script th:inline="javascript">
    var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";
    </script>
    
  • Display a variable:

    var message = [[${message}]];
    
  • Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).

    Thymeleaf calls this: JavaScript natural templates

    var message = /*[[${message}]]*/ "";
    

    Thymeleaf will ignore everything we have written after the comment and before the semicolon.

More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining

Overlapping Views in Android

Yes, that is possible. The challenge, however, is to do their layout properly. The easiest way to do it would be to have an AbsoluteLayout and then put the two images where you want them to be. You don't need to do anything special for the transparent png except having it added later to the layout.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

I had the same as well.Making the Id (0) doing "(your Model value).setId(0)" solved my problem.

Parse date without timezone javascript

I have the same issue. I get a date as a String, for example: '2016-08-25T00:00:00', but I need to have Date object with correct time. To convert String into object, I use getTimezoneOffset:

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

getTimezoneOffset() will return ether negative or positive value. This must be subtracted to work in every location in world.

Use Font Awesome Icons in CSS

#content h2:before {
    content: "\f055";
    font-family: FontAwesome;
    left:0;
    position:absolute;
    top:0;
}

Example Link: https://codepen.io/bungeedesign/pen/XqeLQg

Get Icon code from: https://fontawesome.com/cheatsheet?from=io

List<T> OrderBy Alphabetical Order

Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:

var peopleInOrder = people.OrderBy(person => person.LastName);

To sort in place, you'd need an IComparer<Person> or a Comparison<Person>. For that, you may wish to consider ProjectionComparer in MiscUtil.

(I know I keep bringing MiscUtil up - it just keeps being relevant...)

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

Getting reference to the top-most view/window in iOS application

There are two parts of the problem: Top window, top view on top window.

All the existing answers missed the top window part. But [[UIApplication sharedApplication] keyWindow] is not guaranteed to be the top window.

  1. Top window. It is very unlikely that there will be two windows with the same windowLevel coexist for an app, so we can sort all the windows by windowLevel and get the topmost one.

    UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
        return win1.windowLevel - win2.windowLevel;
    }] lastObject];
    
  2. Top view on top window. Just to be complete. As already pointed out in the question:

    UIView *topView = [[topWindow subviews] lastObject];
    

How to change environment's font size?

Press Ctrl and use the mouse wheel to zoom In or Out.

How to get visitor's location (i.e. country) using geolocation?

A free and easy to use service is provided at Webtechriser (click here to read the article) (called wipmania). This one is a JSONP service and requires plain javascript coding with HTML. It can also be used in JQuery. I modified the code a bit to change the output format and this is what I've used and found to be working: (it's the code of my HTML page)

_x000D_
_x000D_
<html>_x000D_
    <body>_x000D_
        <p id="loc"></p>_x000D_
_x000D_
_x000D_
        <script type="text/javascript">_x000D_
            var a = document.getElementById("loc");_x000D_
_x000D_
               function jsonpCallback(data) { _x000D_
             a.innerHTML = "Latitude: " + data.latitude + _x000D_
                              "<br/>Longitude: " + data.longitude + _x000D_
                              "<br/>Country: " + data.address.country; _x000D_
              }_x000D_
        </script>_x000D_
        <script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"_x000D_
                     type="text/javascript"></script>_x000D_
_x000D_
_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

PLEASE NOTE: This service gets the location of the visitor without prompting the visitor to choose whether to share their location, unlike the HTML 5 geolocation API (the code that you've written). Therefore, privacy is compromised. So, you should make judicial use of this service.

BeanFactory not initialized or already closed - call 'refresh' before

I had the same error and I had not made any changes to the application config or the web.xml. Multiple tries to revert back some minor changes to code was not clearing the exceptions. Finally it worked after restarting STS.

How to calculate md5 hash of a file using javascript

There is a couple scripts out there on the internet to create an MD5 Hash.

The one from webtoolkit is good, http://www.webtoolkit.info/javascript-md5.html

Although, I don't believe it will have access to the local filesystem as that access is limited.

How do I convert datetime to ISO 8601 in PHP

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601

Procedural

For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));

Play/pause HTML 5 video using JQuery

Sorry for my other answer. No-one liked it, but I have found another way that you can do it.

You can use Video.js! You can find the documentation and how-to's here.

Calculate MD5 checksum for a file

I know this question was already answered, but this is what I use:

using (FileStream fStream = File.OpenRead(filename)) {
    return GetHash<MD5>(fStream)
}

Where GetHash:

public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
    StringBuilder sb = new StringBuilder();

    MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
    using (T crypt = (T) create.Invoke(null, null)) {
        byte[] hashBytes = crypt.ComputeHash(stream);
        foreach (byte bt in hashBytes) {
            sb.Append(bt.ToString("x2"));
        }
    }
    return sb.ToString();
}

Probably not the best way, but it can be handy.

How to get a div to resize its height to fit container?

Unfortunately, there is no fool-proof way of achieving this. A block will only expand to the height of its container if it is not floated. Floated blocks are considered outside of the document flow.

One way to do the following without using JavaScript is via a technique called Faux-Columns.

It basically involves applying a background-image to the parent elements of the floated elements which makes you believe that the two elements are the same height.

More information available at:

A List Apart: Articles: Faux Columns

Understanding the set() function

As an unordered collection type, set([8, 1, 6]) is equivalent to set([1, 6, 8]).

While it might be nicer to display the set contents in sorted order, that would make the repr() call more expensive.

Internally, the set type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.

To produce the repr() output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.

SQL Not Like Statement not working

mattgcon,

Should work, do you get more rows if you run the same SQL with the "NOT LIKE" line commented out? If not, check the data. I know you mentioned in your question, but check that the actual SQL statement is using that clause. The other answers with NULL are also a good idea.

How to automatically allow blocked content in IE?

You have two options:

  1. Use a Mark of the Web. This will enable a single html page to load. It See here for details. To do this, add the following to your web page below the doctype and above the html tag:

    <!-- saved from url=(0014)about:internet -->

  2. Disable this feature. To do so go to Internet Options->Advanced->Security->Allow Active Content... Then close IE. When you restart IE, it will not give you this error.

method in class cannot be applied to given types

generateNumbers() expects a parameter and you aren't passing one in!

generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.

Running .sh scripts in Git Bash

If you wish to execute a script file from the git bash prompt on Windows, just precede the script file with sh

sh my_awesome_script.sh

How to Remove Array Element and Then Re-Index Array?

You better use array_shift(). That will return the first element of the array, remove it from the array and re-index the array. All in one efficient method.

convert string to specific datetime format?

This another helpful code:

"2011-05-19 10:30:14".to_datetime.strftime('%a %b %d %H:%M:%S %Z %Y')

Check for file exists or not in sql server?

You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:

set nocount on
declare cur cursor local fast_forward for
    (select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;

fetch from cur into @fullpath
while @@FETCH_STATUS = 0
    begin
        exec xp_fileexist @fullpath, @isExists out
        if @isExists = 1            
            print @fullpath + char(9) + char(9) + 'file exists'
        else            
            print @fullpath + char(9) + char(9) + 'file does not exists'
        fetch from cur into @fullpath
    end
close cur
deallocate cur

or you can put it in a tempTable if you want to integrate it in your frontend..

create proc GetFileStatus as
begin
    set nocount on
    create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
    declare cur cursor local fast_forward for
        (select filepath from Directory)
    open cur;
    declare @fullpath varchar(250);
    declare @isExists int;

    fetch from cur into @fullpath
    while @@FETCH_STATUS = 0
        begin
            exec xp_fileexist @fullpath, @isExists out
            if @isExists = 1                
                insert into #tempFileStatus values(@fullpath,'File exist')
            else
                insert into #tempFileStatus values(@fullpath,'File does not exists')
            fetch from cur into @fullpath
        end
    close cur
    deallocate cur
    select * from #tempFileStatus
    drop table #tempFileStatus
end

then call it using:

exec GetFileStatus

Rollback a Git merge

Reverting a merge commit has been exhaustively covered in other questions. When you do a fast-forward merge, the second one you describe, you can use git reset to get back to the previous state:

git reset --hard <commit_before_merge>

You can find the <commit_before_merge> with git reflog, git log, or, if you're feeling the moxy (and haven't done anything else): git reset --hard HEAD@{1}

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

SVN repository backup strategies

Here a GUI Windows tool for make a dump of local and remote subversion repositories:

https://falsinsoft-software.blogspot.com/p/svn-backup-tool.html

The tool description says:

This simply tool allow to make a dump backup of a local and remote subversion repository. The software work in the same way of the "svnadmin" but is not a GUI frontend over it. Instead use directly the subversion libraries for allow to create dump in standalone mode without any other additional tool.

Hope this help...

UIView Infinite 360 degree rotation animation?

Swift :

func runSpinAnimationOnView(view:UIView , duration:Float, rotations:Double, repeatt:Float ) ->()
    {
        let rotationAnimation=CABasicAnimation();

        rotationAnimation.keyPath="transform.rotation.z"

        let toValue = M_PI * 2.0 * rotations ;


        // passing it a float
        let someInterval = CFTimeInterval(duration)

        rotationAnimation.toValue=toValue;
        rotationAnimation.duration=someInterval;
        rotationAnimation.cumulative=true;
        rotationAnimation.repeatCount=repeatt;
        view.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")


    }

How to hide soft keyboard on android after clicking outside EditText?

Adding on to a previous answer by @sumit sonawane , this solution will not hide the keyboard if the user is scrolling.

public long pressTime = 0;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        pressTime = System.currentTimeMillis();
    }
    else if (ev.getAction() == MotionEvent.ACTION_UP) {
        long releaseTime = System.currentTimeMillis();
        if (releaseTime-pressTime < 200) {
            if (getCurrentFocus() != null) {
                GhostTube.print("BottomNavActivity", "Touch event with keyboard detected...");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent(ev);
}

Add code to your activity, will also take care of fragments.

How do I lowercase a string in Python?

Also, you can overwrite some variables:

s = input('UPPER CASE')
lower = s.lower()

If you use like this:

s = "Kilometer"
print(s.lower())     - kilometer
print(s)             - Kilometer

It will work just when called.

Best way to make a shell script daemon?

try executing using & if you save this file as program.sh

you can use

$. program.sh &

How to use subList()

To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:

dataList.subList(30, 35);

A guaranteed safe way to do this is:

dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );

Remove grid, background color, and top and right borders from ggplot2

Simplification from the above Andrew's answer leads to this key theme to generate the half border.

theme (panel.border = element_blank(),
       axis.line    = element_line(color='black'))

Can two Java methods have same name with different return types?

According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {
    public static void main(String... args) {
        Main.<Integer>print();
        Main.<Short>print();
        Main.<Byte>print();
        Main.<Void>print();
    }

    public static <T extends Integer> int print() {
        System.out.println("here - Integer");
        return 0;
    }
    public static <T extends Short> short print() {
        System.out.println("here - Short");
        return 0;
    }
    public static <T extends Byte> byte print() {
        System.out.println("here - Byte");
        return 0;
    }
    public static <T extends Void> void print() {
        System.out.println("here - Void");
    }
}

Prints

here - Integer
here - Short
here - Byte
here - Void

For more details, read my article here

Use underscore inside Angular controllers

I use this:

var myapp = angular.module('myApp', [])
  // allow DI for use in controllers, unit tests
  .constant('_', window._)
  // use in views, ng-repeat="x in _.range(3)"
  .run(function ($rootScope) {
     $rootScope._ = window._;
  });

See https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection about halfway for some more info on run.

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

Android. WebView and loadData

the answers above doesn't work in my case. You need to specify utf-8 in meta tag

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <!-- you content goes here -->
    </body>
</html>

git pull aborted with error filename too long

On windows run "cmd " as administrator and execute command.

"C:\Program Files\Git\mingw64\etc>"
"git config --system core.longpaths true"

or you have to chmod for the folder whereever git is installed.

or manullay update your file manually by going to path "Git\mingw64\etc"

[http]
    sslBackend = schannel
[diff "astextplain"]
    textconv = astextplain
[filter "lfs"]
    clean = git-lfs clean -- %f
    smudge = git-lfs smudge -- %f
    process = git-lfs filter-process
    required = true
[credential]
    helper = manager
**[core]
    longpaths = true**

IIS Express Windows Authentication

This answer may help if: 1) your site used to work with Windows authentication before upgrading to Visual Studio 2015 and 2) and your site is attempting to load /login.aspx (even though there is no such file on your site).

Add the following two lines to the appSettingssection of your site's Web.config.

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>

Java decimal formatting using String.format?

java.text.NumberFormat is probably what you want.

How to Initialize char array from a string

That's one of the cases a script to generate the appropriate code might help.

Show space, tab, CRLF characters in editor of Visual Studio

Edit -> Advanced -> View White Space or Ctrl+E,S

deleting folder from java

Try this:

public static boolean deleteDir(File dir) 
{ 
  if (dir.isDirectory()) 
  { 
    String[] children = dir.list(); 
    for (int i=0; i<children.length; i++)
      return deleteDir(new File(dir, children[i])); 
  }  
  // The directory is now empty or this is a file so delete it 
  return dir.delete(); 
} 

How to call a C# function from JavaScript?

Server-side functions are on the server-side, client-side functions reside on the client. What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.

More info can be found here and here

How to make an inline element appear on new line, or block element not occupy the whole line?

Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose

.feature_desc {
    display: block;
}
.feature_desc:before {
    content: "";
    display: block;
}

might give you want you want to achieve without the <br/> element. Though it would help to see your CSS applied to these elements.

NOTE. The example above doesn't work in IE7 though.

Fundamental difference between Hashing and Encryption algorithms

A Hash function turns a variable-sized amount of text into a fixed-sized text.

Hash

Source: https://en.wikipedia.org/wiki/Hash_function


Hash functions in PHP

A hash turns a string to a hashed string. See below.

HASH:

$str = 'My age is 29';
$hash = hash('sha1', $str);
echo $hash; // OUTPUT: 4d675d9fbefc74a38c89e005f9d776c75d92623e

Passwords are usually stored in their hashed representation instead as readable text. When an end-user wants gain access to an application protected with a password then a password must be given during authentication. When the user submits his password, then the valid authentication system receives the password and hashes this given password. This password hash is compared to the hash known by the system. Access is granted in case of equality.

DEHASH:

SHA1 is a one-way hash. Which means that you can't dehash the hash.

However, you can brute-force the hash. Please see: https://hashkiller.co.uk/sha1-decrypter.aspx.

MD5, is another hash. A MD5 dehasher can be found on this website: https://www.md5online.org/.

To hamper brute-force attacks on hashes a salt can be given. In php you can use password_hash() for creating a password hash. The function password_hash() automatically creates a salt. To verify a password on a password hash (with a salt) use password_verify().

// Invoke this little script 3 times, and it will give you everytime a new hash
$password = '1234';  
$hash = password_hash($password, PASSWORD_DEFAULT);  

echo $hash; 
// OUTPUT 

$2y$10$ADxKiJW/Jn2DZNwpigWZ1ePwQ4il7V0ZB4iPeKj11n.iaDtLrC8bu 

$2y$10$H8jRnHDOMsHFMEZdT4Mk4uI4DCW7/YRKjfdcmV3MiA/WdzEvou71u 

$2y$10$qhyfIT25jpR63vCGvRbEoewACQZXQJ5glttlb01DmR4ota4L25jaW

One password can be represented by more then one hash. When you verify the password with different password hashes by using password_verify(), then the password will be accepted as a valid password.

$password = '1234';  

$hash = '$2y$10$ADxKiJW/Jn2DZNwpigWZ1ePwQ4il7V0ZB4iPeKj11n.iaDtLrC8bu';  
var_dump( password_verify($password, $hash) );  

$hash = '$2y$10$H8jRnHDOMsHFMEZdT4Mk4uI4DCW7/YRKjfdcmV3MiA/WdzEvou71u';  
var_dump( password_verify($password, $hash) );  

$hash = '$2y$10$qhyfIT25jpR63vCGvRbEoewACQZXQJ5glttlb01DmR4ota4L25jaW';  
var_dump( password_verify($password, $hash) );

// OUTPUT 

boolean true 

boolean true 

boolean true




An Encryption function transforms a text into a nonsensical ciphertext by using an encryption key, and vice versa. enter image description here

Source: https://en.wikipedia.org/wiki/Encryption


Encryption in PHP

Let's dive into some PHP code that handles encryption.

--- The Mcrypt extention ---

ENCRYPT:

$cipher = MCRYPT_RIJNDAEL_128;
$key = 'A_KEY';
$data = 'My age is 29';
$mode = MCRYPT_MODE_ECB;

$encryptedData = mcrypt_encrypt($cipher, $key , $data , $mode);
var_dump($encryptedData);

//OUTPUT:
string '„Ùòyªq³¿ì¼üÀpå' (length=16)

DECRYPT:

$decryptedData = mcrypt_decrypt($cipher, $key , $encryptedData, $mode);
$decryptedData = rtrim($decryptedData, "\0\4"); // Remove the nulls and EOTs at the END
var_dump($decryptedData);

//OUTPUT:
string 'My age is 29' (length=12)

--- The OpenSSL extention ---

The Mcrypt extention was deprecated in 7.1. and removed in php 7.2. The OpenSSL extention should be used in php 7. See the code snippets below:

$key = 'A_KEY';
$data = 'My age is 29';

// ENCRYPT
$encryptedData = openssl_encrypt($data , 'AES-128-CBC', $key, 0, 'IV_init_vector01');
var_dump($encryptedData);

// DECRYPT    
$decryptedData = openssl_decrypt($encryptedData, 'AES-128-CBC', $key, 0, 'IV_init_vector01');
var_dump($decryptedData);

//OUTPUT
string '4RJ8+18YkEd7Xk+tAMLz5Q==' (length=24)
string 'My age is 29' (length=12)

Convert JSON String to JSON Object c#

string result = await resp.Content.ReadAsStringAsync(); List _Resp = JsonConvert.DeserializeObject<List>(result); //List _objList = new List((IEnumerable)_Resp);

            IList usll = _Resp.Select(a => a.lttsdata).ToList();
            // List<ListViewClass> _objList = new List<ListViewClass>((IEnumerable<ListViewClass>)_Resp);
            //IList usll = _objList.OrderBy(a=> a.ReqID).ToList();
            Lv.ItemsSource = usll;

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

PHP code to convert a MySQL query to CSV

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;

(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)

or:

$select = "SELECT * FROM table_name";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                            
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

moment.js, how to get day of week number

Define "doesn't work".

_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const dow = date.day();_x000D_
console.log(dow);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

This prints "4", as expected.

How to get a table cell value using jQuery?

Try this,

$(document).ready(function(){
$(".items").delegate("tr.classname", "click", function(data){
            alert(data.target.innerHTML);//this will show the inner html
    alert($(this).find('td:eq(0)').html());//this will alert the value in the 1st column.
    });
});