Programs & Examples On #Itemrenderer

Questions pertaining to creating and using a custom ItemRenderer to display bound data in Flash constrols such as List and DataGrid.

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

SSIS Integration with Visual Studio 2017 available from Aug 2017.

SSIS designer is now available for Visual Studio 2017! ARCHIVE

I installed in July 2018 and appears working fine. See Download link

checked = "checked" vs checked = true

document.getElementById('myRadio') returns you the DOM element, i'll reference it as elem in this answer.

elem.checked accesses the property named checked of the DOM element. This property is always a boolean.

When writing HTML you use checked="checked" in XHTML; in HTML you can simply use checked. When setting the attribute (this is done via .setAttribute('checked', 'checked')) you need to provide a value since some browsers consider an empty value being non-existent.

However, since you have the DOM element you have no reason to set the attribute since you can simply use the - much more comfortable - boolean property for it. Since non-empty strings are considered true in a boolean context, setting elem.checked to 'checked' or anything else that is not a falsy value (even 'false' or '0') will check the checkbox. There is not reason not to use true and false though so you should stick with the proper values.

pass JSON to HTTP POST Request

I feel

var x = request.post({
       uri: config.uri,
       json: reqData
    });

Defining like this will be the effective way of writing your code. And application/json should be automatically added. There is no need to specifically declare it.

Chosen Jquery Plugin - getting selected values

if you want to get text of a selected option (chosen get display selected value)

 $("#select-id").chosen().find("option:selected" ).text();

How to resolve the "ADB server didn't ACK" error?

i have solve this problem several times using the same steps :

1- Close Eclipse.

2- Restart your phone.

3- End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.

4- Issue kill and start command in \platform-tools\

C:\sdk\platform-tools>adb kill-server

C:\sdk\platform-tools>adb start-server

5- If it says something like 'started successfully', you are good.

but now it's doesn't work cause i have an anti-virus called "Baidu", this program have run "Baidu ADB server", finally i turn this process off and retry above steps it's work properly.

Can HTML be embedded inside PHP "if" statement?

Yes.

<?  if($my_name == 'someguy') { ?>
        HTML_GOES_HERE
<?  } ?>

PHP AES encrypt / decrypt

Here's an improved version based on code written by blade

  • add comments
  • overwrite arguments before throwing to avoid leaking secrets with the exception
  • check return values from openssl and hmac functions

The code:

class Crypto
{
    /**
     * Encrypt data using OpenSSL (AES-256-CBC)
     * @param string $plaindata Data to be encrypted
     * @param string $cryptokey key for encryption (with 256 bit of entropy)
     * @param string $hashkey key for hashing (with 256 bit of entropy)
     * @return string IV+Hash+Encrypted as raw binary string. The first 16
     *     bytes is IV, next 32 bytes is HMAC-SHA256 and the rest is
     *     $plaindata as encrypted.
     * @throws Exception on internal error
     *
     * Based on code from: https://stackoverflow.com/a/46872528
     */
    public static function encrypt($plaindata, $cryptokey, $hashkey)
    {
        $method = "AES-256-CBC";
        $key = hash('sha256', $cryptokey, true);
        $iv = openssl_random_pseudo_bytes(16);

        $cipherdata = openssl_encrypt($plaindata, $method, $key, OPENSSL_RAW_DATA, $iv);

        if ($cipherdata === false)
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: openssl_encrypt() failed:".openssl_error_string());
        }

        $hash = hash_hmac('sha256', $cipherdata.$iv, $hashkey, true);

        if ($hash === false)
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: hash_hmac() failed");
        }

        return $iv.$hash.$cipherdata;
    }

    /**
    * Decrypt data using OpenSSL (AES-256-CBC)
     * @param string $encrypteddata IV+Hash+Encrypted as raw binary string
     *     where the first 16 bytes is IV, next 32 bytes is HMAC-SHA256 and
     *     the rest is encrypted payload.
     * @param string $cryptokey key for decryption (with 256 bit of entropy)
     * @param string $hashkey key for hashing (with 256 bit of entropy)
     * @return string Decrypted data
     * @throws Exception on internal error
     *
     * Based on code from: https://stackoverflow.com/a/46872528
     */
    public static function decrypt($encrypteddata, $cryptokey, $hashkey)
    {
        $method = "AES-256-CBC";
        $key = hash('sha256', $cryptokey, true);
        $iv = substr($encrypteddata, 0, 16);
        $hash = substr($encrypteddata, 16, 32);
        $cipherdata = substr($encrypteddata, 48);

        if (!hash_equals(hash_hmac('sha256', $cipherdata.$iv, $hashkey, true), $hash))
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: Hash verification failed");
        }

        $plaindata = openssl_decrypt($cipherdata, $method, $key, OPENSSL_RAW_DATA, $iv);

        if ($plaindata === false)
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: openssl_decrypt() failed:".openssl_error_string());
        }

        return $plaindata;
    }
}

If you truly cannot have proper encryption and hash keys but have to use an user entered password as the only secret, you can do something like this:

/**
 * @param string $password user entered password as the only source of
 *   entropy to generate encryption key and hash key.
 * @return array($encryption_key, $hash_key) - note that PBKDF2 algorithm
 *   has been configured to take around 1-2 seconds per conversion
 *   from password to keys on a normal CPU to prevent brute force attacks.
 */
public static function generate_encryptionkey_hashkey_from_password($password)
{
    $hash = hash_pbkdf2("sha512", "$password", "salt$password", 1500000);
    return str_split($hash, 64);
}

Multiple file upload in php

Just came across the following solution:

http://www.mydailyhacks.org/2014/11/05/php-multifile-uploader-for-php-5-4-5-5/

it is a ready PHP Multi File Upload Script with an form where you can add multiple inputs and an AJAX progress bar. It should work directly after unpacking on the server...

What is the difference between Python and IPython?

Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

You can install Ipython using pip - pip install ipython

You can run Ipython by typing ipython in your terminal window.

Django template how to look up a dictionary value with a variable

You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup. Example: foo["bar"]
  • Attribute lookup. Example: foo.bar
  • List-index lookup. Example: foo[bar]

But you can make a filter which lets you pass in an argument:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

@register.filter(name='lookup')
def lookup(value, arg):
    return value[arg]

{{ mydict|lookup:item.name }}

How to get the containing form of an input?

I use a bit of jQuery and old style javascript - less code

$($(this)[0].form) 

This is a complete reference to the form containing the element

Swift - iOS - Dates and times in different format

func convertDateFormater(date: String) -> String {   
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    dateFormatter.timeZone = NSTimeZone(name: "UTC")

    guard let date = dateFormatter.dateFromString(date) else {
        assert(false, "no date from string")
        return ""
    }

    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date)

    return timeStamp
}

Edit for Swift 4

func convertDateFormatter(date: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    dateFormatter.locale = Locale(identifier: "your_loc_id")
    let convertedDate = dateFormatter.date(from: date)

    guard dateFormatter.date(from: date) != nil else {
        assert(false, "no date from string")
        return ""
    } 

    dateFormatter.dateFormat = "yyyy MMM HH:mm EEEE"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: convertedDate!)

    return timeStamp
}

Angular checkbox and ng-click

The order of execution of ng-click and ng-model is ambiguous since they do not define clear priorities. Instead you should use ng-change or a $watch on the $scope to ensure that you obtain the correct values of the model variable.

In your case, this should work:

<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">

How can I get the selected VALUE out of a QCombobox?

It seems you need to do combobox->itemData(combobox->currentIndex()) if you want to get the current data of the QComboBox.

If you are using your own class derived from QComboBox, you can add a currentData() function.

How do I clone a Django model instance object and save it to the database?

This does an in-memory copy that you can mutate independently.

original = CheckoutItem(title="test", ...)
copy = CheckoutItem()

for f in CheckoutItem._meta.fields:
   setattr(copy, f.attname, getattr(original, f.attname))

Or, as a method:


    def clone(self):
        """Returns a clone of this instance."""

        clone = self.__class__()
        for f in self.__class__._meta.fields:
            setattr(clone, f.attname, getattr(self, f.attname))

        return clone

PHP - get base64 img string decode and save as jpg (resulting empty image )

A minor simplification on the example by @naresh. Should deal with permission issues and offer some clarification.

$data = '<base64_encoded_string>';

$data = base64_decode($data);

$img = imagecreatefromstring($data);

header('Content-Type: image/png');

$file = '<path_to_home_or_user_directory>/decoded_images/test.png';

imagepng($img, $file);

imagedestroy($img);

Eclipse Optimize Imports to Include Static Imports

If you highlight the method Assert.assertEquals(val1, val2) and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

Import text file as single character string

Too bad that Sharon's solution cannot be used anymore. I've added Josh O'Brien's solution with asieira's modification to my .Rprofile file:

read.text = function(pathname)
{
    return (paste(readLines(pathname), collapse="\n"))
}

and use it like this: txt = read.text('path/to/my/file.txt'). I couldn't replicate bumpkin's (28 oct. 14) finding, and writeLines(txt) showed the contents of file.txt. Also, after write(txt, '/tmp/out') the command diff /tmp/out path/to/my/file.txt reported no differences.

Failed to find target with hash string 'android-25'

the default gradle version 3.3 may have some bugs, I switched to gradle 3.5 and everything got ok

how to call a method in another Activity from Activity

public class ActivityB extends AppCompatActivity {

static Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    try {

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String texto = bundle.getString("message");
            if (texto != null) {
              //code....
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void launch(String message) {
        Intent intent = new Intent(mContext, ActivityB.class);
        intent.putExtra("message", message);
        mContext.startActivity(intent);
    }
}

In ActivityA or Service.

public class Service extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {    

        String text = "Value to send";
        ActivityB.launch(text);
        Log.d(TAG, text);
    }
}

rake assets:precompile RAILS_ENV=production not working as required

To explain the problem, your error is as follows:

LoadError: cannot load such file -- uglifier
      (in /home/cool_tech/cool_tech/app/assets/javascripts/application.js)

This means somewhere in application.js, your app is referencing uglifier (probably in the manifest area at the top of the file). To fix the issue, you either need to remove the reference to uglifier, or make sure the uglifier file is present in your app, hence the answers you've been provided


Fix

If you've had no luck with adding the gem to your GemFile, a quick fix would be to remove any reference to uglifier in your application.js manifest. This, of course, will be temporary, but will at least allow you to precompile your assets

How do I find all of the symlinks in a directory tree?

What I do is create a script in my bin directory that is like an alias. For example I have a script named lsd ls -l | grep ^d

you could make one lsl ls -lR | grep ^l

Just chmod them +x and you are good to go.

How can I sort a std::map first by value, then by key?

As explained in Nawaz's answer, you cannot sort your map by itself as you need it, because std::map sorts its elements based on the keys only. So, you need a different container, but if you have to stick to your map, then you can still copy its content (temporarily) into another data structure.

I think, the best solution is to use a std::set storing flipped key-value pairs as presented in ks1322's answer. The std::set is sorted by default and the order of the pairs is exactly as you need it:

3) If lhs.first<rhs.first, returns true. Otherwise, if rhs.first<lhs.first, returns false. Otherwise, if lhs.second<rhs.second, returns true. Otherwise, returns false.

This way you don't need an additional sorting step and the resulting code is quite short:

std::map<std::string, int> m;  // Your original map.
m["realistically"] = 1;
m["really"]        = 8;
m["reason"]        = 4;
m["reasonable"]    = 3;
m["reasonably"]    = 1;
m["reassemble"]    = 1;
m["reassembled"]   = 1;
m["recognize"]     = 2;
m["record"]        = 92;
m["records"]       = 48;
m["recs"]          = 7;

std::set<std::pair<int, std::string>> s;  // The new (temporary) container.

for (auto const &kv : m)
    s.emplace(kv.second, kv.first);  // Flip the pairs.

for (auto const &vk : s)
    std::cout << std::setw(3) << vk.first << std::setw(15) << vk.second << std::endl;

Output:

  1  realistically
  1     reasonably
  1     reassemble
  1    reassembled
  2      recognize
  3     reasonable
  4         reason
  7           recs
  8         really
 48        records
 92         record

Code on Ideone

Note: Since C++17 you can use range-based for loops together with structured bindings for iterating over a map. As a result, the code for copying your map becomes even shorter and more readable:

for (auto const &[k, v] : m)
    s.emplace(v, k);  // Flip the pairs.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

You can avoid compiler warning with workarounds like this one:

List<?> resultRaw = query.list();
List<MyObj> result = new ArrayList<MyObj>(resultRaw.size());
for (Object o : resultRaw) {
    result.add((MyObj) o);
}

But there are some issues with this code:

  • created superfluous ArrayList
  • unnecessary loop over all elements returned from the query
  • longer code.

And the difference is only cosmetic, so using such workarounds is - in my opinion - pointless.

You have to live with these warnings or suppress them.

Laravel migration table field's type change

all other answers are Correct But Before you run

php artisan migrate

make sure you run this code first

composer require doctrine/dbal

to avoid this error

RuntimeException : Changing columns for table "items" requires Doctrine DBAL; install "doctrine/dbal".

How to fade changing background image

This was the only reasonable thing I found to fade a background image.

<div id="foo">
  <!-- some content here -->
</div>

Your CSS; now enhanced with CSS3 transition.

#foo {
  background-image: url(a.jpg);
  transition: background 1s linear;
}

Now swap out the background

document.getElementById("foo").style.backgroundImage = "url(b.jpg)";

Voilà, it fades!


Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work. In which case, the image will change without a transition. Given <1% of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.

How do I get countifs to select all non-blank cells in Excel?

Use a criteria of "<>". It will count anything which isn't an empty cell, including #NAME? or #DIV/0!. As to why it works, damned if I know, but Excel seems to understand it.

Note: works nicely in Google Spreadsheet too

Simplest way to detect a pinch

Unfortunately, detecting pinch gestures across browsers is a not as simple as one would hope, but HammerJS makes it a lot easier!

Check out the Pinch Zoom and Pan with HammerJS demo. This example has been tested on Android, iOS and Windows Phone.

You can find the source code at Pinch Zoom and Pan with HammerJS.

For your convenience, here is the source code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport"_x000D_
        content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">_x000D_
  <title>Pinch Zoom</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div>_x000D_
_x000D_
    <div style="height:150px;background-color:#eeeeee">_x000D_
      Ignore this area. Space is needed to test on the iPhone simulator as pinch simulation on the_x000D_
      iPhone simulator requires the target to be near the middle of the screen and we only respect_x000D_
      touch events in the image area. This space is not needed in production._x000D_
    </div>_x000D_
_x000D_
    <style>_x000D_
_x000D_
      .pinch-zoom-container {_x000D_
        overflow: hidden;_x000D_
        height: 300px;_x000D_
      }_x000D_
_x000D_
      .pinch-zoom-image {_x000D_
        width: 100%;_x000D_
      }_x000D_
_x000D_
    </style>_x000D_
_x000D_
    <script src="https://hammerjs.github.io/dist/hammer.js"></script>_x000D_
_x000D_
    <script>_x000D_
_x000D_
      var MIN_SCALE = 1; // 1=scaling when first loaded_x000D_
      var MAX_SCALE = 64;_x000D_
_x000D_
      // HammerJS fires "pinch" and "pan" events that are cumulative in nature and not_x000D_
      // deltas. Therefore, we need to store the "last" values of scale, x and y so that we can_x000D_
      // adjust the UI accordingly. It isn't until the "pinchend" and "panend" events are received_x000D_
      // that we can set the "last" values._x000D_
_x000D_
      // Our "raw" coordinates are not scaled. This allows us to only have to modify our stored_x000D_
      // coordinates when the UI is updated. It also simplifies our calculations as these_x000D_
      // coordinates are without respect to the current scale._x000D_
_x000D_
      var imgWidth = null;_x000D_
      var imgHeight = null;_x000D_
      var viewportWidth = null;_x000D_
      var viewportHeight = null;_x000D_
      var scale = null;_x000D_
      var lastScale = null;_x000D_
      var container = null;_x000D_
      var img = null;_x000D_
      var x = 0;_x000D_
      var lastX = 0;_x000D_
      var y = 0;_x000D_
      var lastY = 0;_x000D_
      var pinchCenter = null;_x000D_
_x000D_
      // We need to disable the following event handlers so that the browser doesn't try to_x000D_
      // automatically handle our image drag gestures._x000D_
      var disableImgEventHandlers = function () {_x000D_
        var events = ['onclick', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',_x000D_
                      'onmouseup', 'ondblclick', 'onfocus', 'onblur'];_x000D_
_x000D_
        events.forEach(function (event) {_x000D_
          img[event] = function () {_x000D_
            return false;_x000D_
          };_x000D_
        });_x000D_
      };_x000D_
_x000D_
      // Traverse the DOM to calculate the absolute position of an element_x000D_
      var absolutePosition = function (el) {_x000D_
        var x = 0,_x000D_
          y = 0;_x000D_
_x000D_
        while (el !== null) {_x000D_
          x += el.offsetLeft;_x000D_
          y += el.offsetTop;_x000D_
          el = el.offsetParent;_x000D_
        }_x000D_
_x000D_
        return { x: x, y: y };_x000D_
      };_x000D_
_x000D_
      var restrictScale = function (scale) {_x000D_
        if (scale < MIN_SCALE) {_x000D_
          scale = MIN_SCALE;_x000D_
        } else if (scale > MAX_SCALE) {_x000D_
          scale = MAX_SCALE;_x000D_
        }_x000D_
        return scale;_x000D_
      };_x000D_
_x000D_
      var restrictRawPos = function (pos, viewportDim, imgDim) {_x000D_
        if (pos < viewportDim/scale - imgDim) { // too far left/up?_x000D_
          pos = viewportDim/scale - imgDim;_x000D_
        } else if (pos > 0) { // too far right/down?_x000D_
          pos = 0;_x000D_
        }_x000D_
        return pos;_x000D_
      };_x000D_
_x000D_
      var updateLastPos = function (deltaX, deltaY) {_x000D_
        lastX = x;_x000D_
        lastY = y;_x000D_
      };_x000D_
_x000D_
      var translate = function (deltaX, deltaY) {_x000D_
        // We restrict to the min of the viewport width/height or current width/height as the_x000D_
        // current width/height may be smaller than the viewport width/height_x000D_
_x000D_
        var newX = restrictRawPos(lastX + deltaX/scale,_x000D_
                                  Math.min(viewportWidth, curWidth), imgWidth);_x000D_
        x = newX;_x000D_
        img.style.marginLeft = Math.ceil(newX*scale) + 'px';_x000D_
_x000D_
        var newY = restrictRawPos(lastY + deltaY/scale,_x000D_
                                  Math.min(viewportHeight, curHeight), imgHeight);_x000D_
        y = newY;_x000D_
        img.style.marginTop = Math.ceil(newY*scale) + 'px';_x000D_
      };_x000D_
_x000D_
      var zoom = function (scaleBy) {_x000D_
        scale = restrictScale(lastScale*scaleBy);_x000D_
_x000D_
        curWidth = imgWidth*scale;_x000D_
        curHeight = imgHeight*scale;_x000D_
_x000D_
        img.style.width = Math.ceil(curWidth) + 'px';_x000D_
        img.style.height = Math.ceil(curHeight) + 'px';_x000D_
_x000D_
        // Adjust margins to make sure that we aren't out of bounds_x000D_
        translate(0, 0);_x000D_
      };_x000D_
_x000D_
      var rawCenter = function (e) {_x000D_
        var pos = absolutePosition(container);_x000D_
_x000D_
        // We need to account for the scroll position_x000D_
        var scrollLeft = window.pageXOffset ? window.pageXOffset : document.body.scrollLeft;_x000D_
        var scrollTop = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;_x000D_
_x000D_
        var zoomX = -x + (e.center.x - pos.x + scrollLeft)/scale;_x000D_
        var zoomY = -y + (e.center.y - pos.y + scrollTop)/scale;_x000D_
_x000D_
        return { x: zoomX, y: zoomY };_x000D_
      };_x000D_
_x000D_
      var updateLastScale = function () {_x000D_
        lastScale = scale;_x000D_
      };_x000D_
_x000D_
      var zoomAround = function (scaleBy, rawZoomX, rawZoomY, doNotUpdateLast) {_x000D_
        // Zoom_x000D_
        zoom(scaleBy);_x000D_
_x000D_
        // New raw center of viewport_x000D_
        var rawCenterX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
        var rawCenterY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
        // Delta_x000D_
        var deltaX = (rawCenterX - rawZoomX)*scale;_x000D_
        var deltaY = (rawCenterY - rawZoomY)*scale;_x000D_
_x000D_
        // Translate back to zoom center_x000D_
        translate(deltaX, deltaY);_x000D_
_x000D_
        if (!doNotUpdateLast) {_x000D_
          updateLastScale();_x000D_
          updateLastPos();_x000D_
        }_x000D_
      };_x000D_
_x000D_
      var zoomCenter = function (scaleBy) {_x000D_
        // Center of viewport_x000D_
        var zoomX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
        var zoomY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
        zoomAround(scaleBy, zoomX, zoomY);_x000D_
      };_x000D_
_x000D_
      var zoomIn = function () {_x000D_
        zoomCenter(2);_x000D_
      };_x000D_
_x000D_
      var zoomOut = function () {_x000D_
        zoomCenter(1/2);_x000D_
      };_x000D_
_x000D_
      var onLoad = function () {_x000D_
_x000D_
        img = document.getElementById('pinch-zoom-image-id');_x000D_
        container = img.parentElement;_x000D_
_x000D_
        disableImgEventHandlers();_x000D_
_x000D_
        imgWidth = img.width;_x000D_
        imgHeight = img.height;_x000D_
        viewportWidth = img.offsetWidth;_x000D_
        scale = viewportWidth/imgWidth;_x000D_
        lastScale = scale;_x000D_
        viewportHeight = img.parentElement.offsetHeight;_x000D_
        curWidth = imgWidth*scale;_x000D_
        curHeight = imgHeight*scale;_x000D_
_x000D_
        var hammer = new Hammer(container, {_x000D_
          domEvents: true_x000D_
        });_x000D_
_x000D_
        hammer.get('pinch').set({_x000D_
          enable: true_x000D_
        });_x000D_
_x000D_
        hammer.on('pan', function (e) {_x000D_
          translate(e.deltaX, e.deltaY);_x000D_
        });_x000D_
_x000D_
        hammer.on('panend', function (e) {_x000D_
          updateLastPos();_x000D_
        });_x000D_
_x000D_
        hammer.on('pinch', function (e) {_x000D_
_x000D_
          // We only calculate the pinch center on the first pinch event as we want the center to_x000D_
          // stay consistent during the entire pinch_x000D_
          if (pinchCenter === null) {_x000D_
            pinchCenter = rawCenter(e);_x000D_
            var offsetX = pinchCenter.x*scale - (-x*scale + Math.min(viewportWidth, curWidth)/2);_x000D_
            var offsetY = pinchCenter.y*scale - (-y*scale + Math.min(viewportHeight, curHeight)/2);_x000D_
            pinchCenterOffset = { x: offsetX, y: offsetY };_x000D_
          }_x000D_
_x000D_
          // When the user pinch zooms, she/he expects the pinch center to remain in the same_x000D_
          // relative location of the screen. To achieve this, the raw zoom center is calculated by_x000D_
          // first storing the pinch center and the scaled offset to the current center of the_x000D_
          // image. The new scale is then used to calculate the zoom center. This has the effect of_x000D_
          // actually translating the zoom center on each pinch zoom event._x000D_
          var newScale = restrictScale(scale*e.scale);_x000D_
          var zoomX = pinchCenter.x*newScale - pinchCenterOffset.x;_x000D_
          var zoomY = pinchCenter.y*newScale - pinchCenterOffset.y;_x000D_
          var zoomCenter = { x: zoomX/newScale, y: zoomY/newScale };_x000D_
_x000D_
          zoomAround(e.scale, zoomCenter.x, zoomCenter.y, true);_x000D_
        });_x000D_
_x000D_
        hammer.on('pinchend', function (e) {_x000D_
          updateLastScale();_x000D_
          updateLastPos();_x000D_
          pinchCenter = null;_x000D_
        });_x000D_
_x000D_
        hammer.on('doubletap', function (e) {_x000D_
          var c = rawCenter(e);_x000D_
          zoomAround(2, c.x, c.y);_x000D_
        });_x000D_
_x000D_
      };_x000D_
_x000D_
    </script>_x000D_
_x000D_
    <button onclick="zoomIn()">Zoom In</button>_x000D_
    <button onclick="zoomOut()">Zoom Out</button>_x000D_
_x000D_
    <div class="pinch-zoom-container">_x000D_
      <img id="pinch-zoom-image-id" class="pinch-zoom-image" onload="onLoad()"_x000D_
           src="https://hammerjs.github.io/assets/img/pano-1.jpg">_x000D_
    </div>_x000D_
_x000D_
_x000D_
  </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

How to get the parent dir location

I tried:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))

C# Reflection: How to get class reference from string?

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

How to redirect to action from JavaScript method?

Youcan either send a Ajax request to server or use window.location to that url.

Difference between char* and const char*?

In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char * or const char *.

However, the difference is that if the pointer is const char * then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char * then it does not.

maven compilation failure

Add <sourceDirectory>src</sourceDirectory> in your pom.xml with proper reference. Adding this solved my problem

Resource files not found from JUnit test cases

You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.

All that stuff represents the default in Maven. So best practice is don't define it it's already done.

    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

How can I reverse the order of lines in a file?

Just Bash :) (4.0+)

function print_reversed {
    local lines i
    readarray -t lines

    for (( i = ${#lines[@]}; i--; )); do
        printf '%s\n' "${lines[i]}"
    done
}

print_reversed < file

Detecting a redirect in ajax request?

The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648

Android Studio Run/Debug configuration error: Module not specified

Try to delete the app.iml in your project directory and restart android studio

UTF-8 encoded html pages show ? (questions marks) instead of characters

Looks like nobody mentioned

SET NAMES utf8;

I found this solution here and it helped me. How to apply it:

To be all UTF-8, issue the following statement just after you’ve made the connection to the database server: SET NAMES utf8;

Maybe this will help someone.

How to detect duplicate values in PHP array?

Stuff them into a map (pseudocode)

map[string -> int] $m
foreach($word in $array)
{
    if(!$m.contains($word))
        $m[$word] = 0;

    $m[$word] += 1;
}

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Omitting one Setter/Getter in Lombok

If you have setter and getter as private it will come up in PMD checks.

Python: List vs Dict for look up table

A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part.


EDIT: for your new question, YES, a set would be better. Just create 2 sets, one for sequences ended in 1 and other for the sequences ended in 89. I have sucessfully solved this problem using sets.

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

Rails create or update magic?

You can do it in one statement like this:

CachedObject.where(key: "the given key").first_or_create! do |cached|
   cached.attribute1 = 'attribute value'
   cached.attribute2 = 'attribute value'
end

getElementById in React

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

See this answer for more info on How to access the dom element in React

Make an HTTP request with android

For me, the easiest way is using library called Retrofit2

We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :

    public interface MyService {

      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);

      @GET("user")
      Call<UserDetails> getUserDetails(@Header("Authorization") String   credentials);

      @POST("users/new")
      Call<User> createUser(@Body User user);

      @FormUrlEncoded
      @POST("user/edit")
      Call<User> updateUser(@Field("first_name") String first, 
                            @Field("last_name") String last);

      @Multipart
      @PUT("user/photo")
      Call<User> updateUser(@Part("photo") RequestBody photo, 
                            @Part("description") RequestBody description);

      @Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
      })
      @GET("users/{username}")
      Call<User> getUser(@Path("username") String username);    

    }

And the best is, we can do it asynchronously easily using enqueue method

how can I enable PHP Extension intl?

i had this prob but solved ! enable the extension=php_intl.dll now if you restart XAMPP this error will popup "msvcp110.dll is missing form your computer"

for solving this error: download this file from : https://www.dll-files.com/msvcp110.dll.html then put this file to C:windows and then restart xampp it will works.

C# 30 Days From Todays Date

A possible solution would be on first run, create a file containing the current date and put it in IsolatedStorage. For subsequent runs, check the contents of the file and compare with the current date; if the date difference is greater than 30 days, inform the user and close the application.

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

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

What is setBounds and how do I use it?

The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components. Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.

For the NullLayoutManager (in case you used new JPanel(null)) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.

So with public void Component.setBounds(int x, int y, int width, int height) you specify where your component is placed and how many pixel it is wide and high.

Here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      JPanel panel = new JPanel(null);

      JLabel helloLabel = new JLabel("Hello world!");
      helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
      panel.add(helloLabel);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}

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

Solution

Function btox converts arbitrary data *bb to an unterminated string *xp of n hexadecimal digits:

void btox(char *xp, const char *bb, int n) 
{
    const char xx[]= "0123456789ABCDEF";
    while (--n >= 0) xp[n] = xx[(bb[n>>1] >> ((1 - (n&1)) << 2)) & 0xF];
}

Example

#include <stdio.h>

typedef unsigned char uint8;

void main(void) 
{
    uint8 buf[] = {0, 1, 10, 11};
    int n = sizeof buf << 1;
    char hexstr[n + 1];

    btox(hexstr, buf, n);
    hexstr[n] = 0; /* Terminate! */
    printf("%s\n", hexstr);
}

Result: 00010A0B.

Live: Tio.run.

String to LocalDate

java.time

Since Java 1.8, you can achieve this without an extra library by using the java.time classes. See Tutorial.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
formatter = formatter.withLocale( putAppropriateLocaleHere );  // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("2005-nov-12", formatter);

The syntax is nearly the same though.

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

Difference between java.lang.RuntimeException and java.lang.Exception

There are two types of exception, You can recover from checked exception if you get such kind of exception. Runtime exception are irrecoverable, runtime exceptions are programming errors, and programmer should take care of it while writing the code, and continue execution of this might give you incorrect result. Runtime exceptions are about violating precondition ex. you have an array of size 10, and you are trying to access 11 th element, it will throw ArrayIndexOutOfBoundException

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

NTFS performance and large volumes of files and directories

100,000 should be fine.

I have (anecdotally) seen people having problems with many millions of files and I have had problems myself with Explorer just not having a clue how to count past 60-something thousand files, but NTFS should be good for the volumes you're talking.

In case you're wondering, the technical (and I hope theoretical) maximum number of files is: 4,294,967,295

How can I see normal print output created during pytest run?

When running the test use the -s option. All print statements in exampletest.py would get printed on the console when test is run.

py.test exampletest.py -s

How to create a DB for MongoDB container on start up?

The official mongo image has merged a PR to include the functionality to databases and admin users at startup.

The database initialisation will run scripts in /docker-entrypoint-initdb.d/ when there is nothing populated in the /data/db directory.

Database Initialisation

The mongo container image provides the /docker-entrypoint-initdb.d/ path to deploy custom .js or .sh setup scripts that will be run once on database initialisation. .js scripts will be run against test by default or MONGO_INITDB_DATABASE if defined in the environment.

COPY mysetup.sh /docker-entrypoint-initdb.d/

or

COPY mysetup.js /docker-entrypoint-initdb.d/

A simple initialisation mongo shell javascript file that demonstrates setting up the container collection with data, logging and how to exit with an error (for result checking).

let error = true

let res = [
  db.container.drop(),
  db.container.createIndex({ myfield: 1 }, { unique: true }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.insert({ myfield: 'hello', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello2', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' })
]

printjson(res)

if (error) {
  print('Error, exiting')
  quit(1)
}

Admin User Setup

The environment variables to control "root" user setup are

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

Example

docker run -d \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password \
  mongod

or Dockerfile

FROM docker.io/mongo
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD password

You don't need to use --auth on the command line as the docker entrypoint.sh script adds this in when it detects the environment variables exist.

intelliJ IDEA 13 error: please select Android SDK

  1. Go to Project structure (Ctrl + Alt + shift + S) -> Platforn settings -> SDKs -> press "Plus" icon
  2. Select "Android SDK" and input the SDKs path (for exanple: C:\Program Files (x86)\Android\android-sdk)
  3. Apply or OK button
  4. Be happy

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

Instead of relying on the default virtual host mechanism in apache, you can define one last catchall virtualhost that uses an arbitrary ServerName and a wildcard ServerAlias, e.g.

ServerName catchall.mydomain.com
ServerAlias *.mydomain.com

In that way you can use SNI and apache will not send back the SSL warning.

Of course, this only works if you can describe all of your domains easily using a wildcard syntax.

How can I find the product GUID of an installed MSI setup?

There is also a very helpful GUI tool called Product Browser which appears to be made by Microsoft or at least an employee of Microsoft.

It can be found on Github here Product Browser

I personally had a very easy time locating the GUID I needed with this.

What is Ad Hoc Query?

An Ad-Hoc Query is a query that cannot be determined prior to the moment the query is issued. It is created in order to get information when need arises and it consists of dynamically constructed SQL which is usually constructed by desktop-resident query tools. An ad hoc query does not reside in the computer or the database manager but is dynamically created depending on the needs of the data user.

In SQL, an ad hoc query is a loosely typed command/query whose value depends upon some variable. Each time the command is executed, the result is different, depending on the value of the variable. It cannot be predetermined and usually comes under dynamic programming SQL query. An ad hoc query is short lived and is created at runtime.

Jquery to open Bootstrap v3 modal of remote url

So basically, in jquery what we can do is to load href attribute using the load function. This way we can use the url in <a> tag and load that in modal-body.

<a  href='/site/login' class='ls-modal'>Login</a>

//JS script
$('.ls-modal').on('click', function(e){
  e.preventDefault();
  $('#myModal').modal('show').find('.modal-body').load($(this).attr('href'));
});

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

How to use absolute path in twig functions

Additional info to generate absolute URL using a command (to send an email for instance)

In a command, {{ absolute_url(path('index')) }} is not working out of the box.

You will need to add the additional configuration shown in antongorodezkiy's answer.

But in case you don't want to change the configuration because you are not sure how it could impact the whole app, you can configure the router in the command.

Here is the doc :

https://symfony.com/doc/3.4/console/request_context.html

Here is the code :

use Symfony\Component\Routing\RouterInterface;
// ...

class DemoCommand extends Command
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        parent::__construct();

        $this->router = $router;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $context = $this->router->getContext();
        $context->setHost('example.com');
        $context->setScheme('https');
        $context->setBaseUrl('my/path');

        $url = $this->router->generate('route-name', ['param-name' => 'param-value']);
        // ...
    }
}

To generate the URL in the Twig template

<a href="{{ absolute_url(path(...)) }}"></a>

You can fetch the HOST and SCHEME from your env file

$context = $this->router->getContext();
$context->setHost($_ENV['NL_HOST']);
$context->setScheme($_ENV['NL_SCHEME']);

Just define the variable in .env and .env.local files

NL_HOST=mydomain.com
NL_SCHEME=https

Copy from one workbook and paste into another

You copied using Cells.
If so, no need to PasteSpecial since you are copying data at exactly the same format.
Here's your code with some fixes.

Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet

Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")

Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")

ws1.Cells.Copy ws2.cells
y.Close True
x.Close False

If however you really want to paste special, use a dynamic Range("Address") to copy from.
Like this:

ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
y.Close True
x.Close False

Take note of the : colon after the .Copy which is a Statement Separating character.
Using Object.PasteSpecial requires to be executed in a new line.
Hope this gets you going.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I solved this problem by deleting the empty users creating by MySQL. I only have root user and my own user. I deleted the rest.

What does "subject" mean in certificate?

The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.

If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.

The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.

If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK

To look at your certificates on a microsoft machine:-

Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.

In the other areas of the store you will see the other trusted certificates used to validate signatures etc.

How to enable Bootstrap tooltip on disabled button?

These workarounds are ugly. I've debugged the problem is that bootstrap automatically set CSS property pointer-events: none on disabled elements.

This magic property causes that JS is not able to handle any event on elements that matches CSS selector.

If you overwrite this property to default one, everything works like a charm, including tooltips!

.disabled {
  pointer-events: all !important;
}

However you shouldn't use so general selector, because you will probably have to manually stop JavaScript event propagation way you know (e.preventDefault()).

How to get the top position of an element?

If you want the position relative to the document then:

$("#myTable").offset().top;

but often you will want the position relative to the closest positioned parent:

$("#myTable").position().top;

How to change Angular CLI favicon

What really works for me was putting my favicon into assets folder and apear automatically in the browser.

  1. change location to assets folder inside src folder.
  2. change index.html like this <link rel="icon" type="image/x-icon" href="assets/favicon.png">

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

multiple axis in matplotlib with different scales

Since Steve Tjoa's answer always pops up first and mostly lonely when I search for multiple y-axes at Google, I decided to add a slightly modified version of his answer. This is the approach from this matplotlib example.

Reasons:

  • His modules sometimes fail for me in unknown circumstances and cryptic intern errors.
  • I don't like to load exotic modules I don't know (mpl_toolkits.axisartist, mpl_toolkits.axes_grid1).
  • The code below contains more explicit commands of problems people often stumble over (like single legend for multiple axes, using viridis, ...) rather than implicit behavior.

Plot

import matplotlib.pyplot as plt 

# Create figure and subplot manually
# fig = plt.figure()
# host = fig.add_subplot(111)

# More versatile wrapper
fig, host = plt.subplots(figsize=(8,5)) # (width, height) in inches
# (see https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html)
    
par1 = host.twinx()
par2 = host.twinx()
    
host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
    
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

color1 = plt.cm.viridis(0)
color2 = plt.cm.viridis(0.5)
color3 = plt.cm.viridis(.9)

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

lns = [p1, p2, p3]
host.legend(handles=lns, loc='best')

# right, left, top, bottom
par2.spines['right'].set_position(('outward', 60))

# no x-ticks                 
par2.xaxis.set_ticks([])

# Sometimes handy, same for xaxis
#par2.yaxis.set_ticks_position('right')

# Move "Velocity"-axis to the left
# par2.spines['left'].set_position(('outward', 60))
# par2.spines['left'].set_visible(True)
# par2.yaxis.set_label_position('left')
# par2.yaxis.set_ticks_position('left')

host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())

# Adjust spacings w.r.t. figsize
fig.tight_layout()
# Alternatively: bbox_inches='tight' within the plt.savefig function 
#                (overwrites figsize)

# Best for professional typesetting, e.g. LaTeX
plt.savefig("pyplot_multiple_y-axis.pdf")
# For raster graphics use the dpi argument. E.g. '[...].png", dpi=200)'

Android Studio - How to increase Allocated Heap Size

I increased my memory following the next Google documentation:

http://tools.android.com/tech-docs/configuration

By default Android Studio is assigned a max of 750Mb, I changed to 2048Mb.

I tried what google described but for me the only thing that it worked was to use an environment variable. I will describe what I did:

First I created a directory that I called .AndroidStudioSettings,

  • mkdir .AndroidStudioSettings

Then I created a file called studio.vmoptions , and I put in that file the following content:

-Xms256m 
-Xmx2048m 
-XX:MaxPermSize=512m 
-XX:ReservedCodeCacheSize=128m 
-XX:+UseCompressedOops 

Then I added the STUDIO_VM_OPTIONS environment variables in my .profile file:

  • export STUDIO_VM_OPTIONS=/Users/youruser/.AndroidStudioSettings/studio.vmoptions

Then I reload my .profile:

  • source ~/.profile

And finally I open Android Studio:

  • open /Applications/Android\ Studio.app

And now as you can see using the status bar , I have more than 2000 MB available for Android Studio:

enter image description here

You can customize your values according to your need in my case 2048Mb is enough.

UPDATE : Android Studio 2.0 let's you modify this file by accessing "Edit Custom VM Options" from the Help menu, just copy and paste the variables you might want to keep in order to increase it for everversion you might have on your box.

Prevent browser caching of AJAX call result

Personally I feel that the query string method is more reliable than trying to set headers on the server - there's no guarantee that a proxy or browser won't just cache it anyway (some browsers are worse than others - naming no names).

I usually use Math.random() but I don't see anything wrong with using the date (you shouldn't be doing AJAX requests fast enough to get the same value twice).

Notepad++ Multi editing

The easiest method to solve your problem (without going to a different editor or learning regex) is to record a macro.

  • Place your cursor at the start of your text, click the 'record' button in the ribbon, and then edit just that one row of text. You may only use arrow keys or ctrl+arrow keys to move around characters/words rather than clicking with your mouse. The 'home' and 'end' keys are also useful.
  • When you're finished with that one line, move your cursor (again without using the mouse) to the start of the next line.
  • Click the 'stop recording' button.
  • Click the 'play macro' button to check that it works on the next line as expected.
  • Click the 'run macro multiple times' to do it again, and again, and again... :P
One advantage of this over 'multi-editing' cursors is you don't have to manually click and place cursors on every single row. The second advantage is that you can work with tab-delimited data that doesn't have consistent size/length - just use ctrl+left/right to skip words.

Honestly, macros in N++ have saved about a year of my life.

Dealing with HTTP content in HTTPS pages

Regarding your second requirement - you might be able to utilise the onerror event, ie. <img onerror="some javascript;"...

Update:

You could also try iterating through document.images in the dom. There is a complete boolean property which you might be able to use. I don't know for sure whether this will be suitable, but might be worth investigating.

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Fetch the row which has the Max value for a column

I know you asked for Oracle, but in SQL 2005 we now use this:


-- Single Value
;WITH ByDate
AS (
SELECT UserId, Value, ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY Date DESC) RowNum
FROM UserDates
)
SELECT UserId, Value
FROM ByDate
WHERE RowNum = 1

-- Multiple values where dates match
;WITH ByDate
AS (
SELECT UserId, Value, RANK() OVER (PARTITION BY UserId ORDER BY Date DESC) Rnk
FROM UserDates
)
SELECT UserId, Value
FROM ByDate
WHERE Rnk = 1

how to save canvas as png image?

I maybe discovered a better way for not forcing the user to right click and "save image as". Live draw the canvas base64 code into the href of the link and modify it so the download will start automatically. I don't know if it's universally browser compatible, but it should work with the main/new browsers.

var canvas = document.getElementById('your-canvas');
    if (canvas.getContext) {
        var C = canvas.getContext('2d');
    }

$('#your-canvas').mousedown(function(event) {
    // feel free to choose your event ;) 

    // just for example
    // var OFFSET = $(this).offset();
    // var x = event.pageX - OFFSET.left;
    // var y = event.pageY - OFFSET.top;

    // standard data to url
    var imgdata = canvas.toDataURL('image/png');
    // modify the dataUrl so the browser starts downloading it instead of just showing it
    var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet-stream');
    // give the link the values it needs
    $('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);

});

You can wrap the <a> around anything you want.

Connecting to Postgresql in a docker container from outside

I tried to connect from localhost (mac) to a postgres container. I changed the port in the docker-compose file from 5432 to 3306 and started the container. No idea why I did it :|

Then I tried to connect to postgres via PSequel and adminer and the connection could not be established.

After switching back to port 5432 all works fine.

  db:
    image: postgres
    ports:
      - 5432:5432
    restart: always
    volumes:
      - "db_sql:/var/lib/mysql"
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
      POSTGRES_DB: postgres_db

This was my experience I wanted to share. Perhaps someone can make use of it.

How to escape a single quote inside awk

awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'

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

Here is a neat and clean way to install Python2 & Python3 on windows.

https://datascience.com.co/how-to-install-python-2-7-and-3-6-in-windows-10-add-python-path-281e7eae62a

My case: I had to install Apache cassandra. I already had Python3 installed in my D: drive. With loads of development work under process i didn't wanted to mess my Python3 installation. And, i needed Python2 only for Apache cassandra.

So i took following steps:

  1. Downloaded & Installed Python2.
  2. Added Python2 entries to classpath (C:\Python27;C:\Python27\Scripts)
  3. Modified python.exe to python2.exe (as shown in image below)

enter image description here

  1. Now i am able to run both. For Python 2(python2 --version) & Python 3 (python --version). enter image description here

So, my Python3 installation remained intact.

What exactly does stringstream do?

From C++ Primer:

The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

I come across some cases where it is both convenient and concise to use stringstream.

case 1

It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;

int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of 
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;

out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';

// final result in string format
string result = out.str() 

case 2

It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

string simplifyPath(string path) {
    string res, tmp;
    vector<string> stk;
    stringstream ss(path);
    while(getline(ss,tmp,'/')) {
        if (tmp == "" or tmp == ".") continue;
        if (tmp == ".." and !stk.empty()) stk.pop_back();
        else if (tmp != "..") stk.push_back(tmp);
    }
    for(auto str : stk) res += "/"+str;
    return res.empty() ? "/" : res; 
 }

Without the use of stringstream, it would be difficult to write such concise code.

Navigate to another page with a button in angular 2

You can use routerLink in the following manner,

<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">

or use <button [routerLink]="['./url']"> in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471

the other methods are also correct but they create a dependency on the component file.

Hope your concern is resolved.

IE prompts to open or save json result from server

I faced this while using jQuery FileUpload plugin.

Then I took a look in their documentation, most exactly in the Content-Type Negotiation section and followed their suggestion for Ruby/Rails.

render(json: <some-data>, content_type: request.format)

Which fixed the issue for me.

Quick Explanation: for old IE/Opera versions, this plugin will use an iframe with text/plain or text/html content-type, so if you force the response to json, browser will try download it. Using the same content-type as in the request will make it work for any browser.

Class not registered Error

I was getting the below error in my 32 bit application.

Error: Retrieving the COM class factory for component with CLSID {4911BB26-11EE-4182-B66C-64DF2FA6502D} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

And on setting the "Enable32bitApplications" to true in defaultapplicationpool in IIS worked for me.

I need to get all the cookies from the browser

You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.

Removing address bar from browser (to view on Android)

You can do that with the next code

 if(navigator.userAgent.match(/Android/i)){
    window.scrollTo(0,1);
 }

I hope it helps you!

One-line list comprehension: if-else variants

I was able to do this

>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
    [1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>

How to add column to numpy array

It can be done like this:

import numpy as np

# create a random matrix:
A = np.random.normal(size=(5,2))

# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))

In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.

MySQL maximum memory usage

in /etc/my.cnf:

[mysqld]
...

performance_schema = 0

table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000

query_cache_size = 0
query_cache_limit = 0

...

Good work on server with 256MB Memory.

Using multiple IF statements in a batch file

The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.

When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:

SET AND=IF

IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.

When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:

SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B

These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:

IF EXIST "somefile.txt" %THEN%
  IF EXIST "someotherfile.txt" %THEN%
    SET var="somefile.txt,someotherfile.txt"
  %NOELSE%
  %ENDIF%
%NOELSE%
%ENDIF%

IF EXIST "%~1" %THEN%
  SET "result=%~1"
%ELSE%
  SET "result="
%ENDIF%

I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.

Replace all whitespace with a line break/paragraph mark to make a word list

For reasonably modern versions of sed, edit the standard input to yield the standard output with

$ echo 't???? ß?ß??? ?? ??p??' | sed -E -e 's/[[:blank:]]+/\n/g'
t????
ß?ß???
??
??p??

If your vocabulary words are in files named lesson1 and lesson2, redirect sed’s standard output to the file all-vocab with

sed -E -e 's/[[:blank:]]+/\n/g' lesson1 lesson2 > all-vocab

What it means:

  • The character class [[:blank:]] matches either a single space character or a single tab character.
    • Use [[:space:]] instead to match any single whitespace character (commonly space, tab, newline, carriage return, form-feed, and vertical tab).
    • The + quantifier means match one or more of the previous pattern.
    • So [[:blank:]]+ is a sequence of one or more characters that are all space or tab.
  • The \n in the replacement is the newline that you want.
  • The /g modifier on the end means perform the substitution as many times as possible rather than just once.
  • The -E option tells sed to use POSIX extended regex syntax and in particular for this case the + quantifier. Without -E, your sed command becomes sed -e 's/[[:blank:]]\+/\n/g'. (Note the use of \+ rather than simple +.)

Perl Compatible Regexes

For those familiar with Perl-compatible regexes and a PCRE-capable sed, use \s+ to match runs of at least one whitespace character, as in

sed -E -e 's/\s+/\n/g' old > new

or

sed -e 's/\s\+/\n/g' old > new

These commands read input from the file old and write the result to a file named new in the current directory.

Maximum portability, maximum cruftiness

Going back to almost any version of sed since Version 7 Unix, the command invocation is a bit more baroque.

$ echo 't???? ß?ß??? ?? ??p??' | sed -e 's/[ \t][ \t]*/\
/g'
t????
ß?ß???
??
??p??

Notes:

  • Here we do not even assume the existence of the humble + quantifier and simulate it with a single space-or-tab ([ \t]) followed by zero or more of them ([ \t]*).
  • Similarly, assuming sed does not understand \n for newline, we have to include it on the command line verbatim.
    • The \ and the end of the first line of the command is a continuation marker that escapes the immediately following newline, and the remainder of the command is on the next line.
      • Note: There must be no whitespace preceding the escaped newline. That is, the end of the first line must be exactly backslash followed by end-of-line.
    • This error prone process helps one appreciate why the world moved to visible characters, and you will want to exercise some care in trying out the command with copy-and-paste.

Note on backslashes and quoting

The commands above all used single quotes ('') rather than double quotes (""). Consider:

$ echo '\\\\' "\\\\"
\\\\ \\

That is, the shell applies different escaping rules to single-quoted strings as compared with double-quoted strings. You typically want to protect all the backslashes common in regexes with single quotes.

Replace forward slash "/ " character in JavaScript string?

Area.replace(new RegExp(/\//g), '-') replaces multiple forward slashes (/) with -

SVG gradient using CSS

Thank you everyone, for all your precise replys.

Using the svg in a shadow dom, I add the 3 linear gradients I need within the svg, inside a . I place the css fill rule on the web component and the inheritance od fill does the job.

_x000D_
_x000D_
    <svg viewbox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
      <path
        d="m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z"></path>
    </svg>
    
    <svg height="0" width="0">
      <defs>
        <linearGradient id="lgrad-p" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#4169e1"></stop><stop offset="99%" stop-color="#c44764"></stop></linearGradient>
        <linearGradient id="lgrad-s" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#ef3c3a"></stop><stop offset="99%" stop-color="#6d5eb7"></stop></linearGradient>
        <linearGradient id="lgrad-g" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#585f74"></stop><stop offset="99%" stop-color="#b6bbc8"></stop></linearGradient>
      </defs>
    </svg>
    
    <div></div>

    <style>
      :first-child {
        height:150px;
        width:150px;
        fill:url(#lgrad-p) blue;
      }
      div{
        position:relative;
        width:150px;
        height:150px;
        fill:url(#lgrad-s) red;
      }
    </style>
    <script>
      const shadow = document.querySelector('div').attachShadow({mode: 'open'});
      shadow.innerHTML="<svg viewbox=\"0 0 512 512\">\
        <path d=\"m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z\"></path>\
      </svg>\
      <svg height=\"0\">\
      <defs>\
        <linearGradient id=\"lgrad-s\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#ef3c3a\"></stop><stop offset=\"99%\" stop-color=\"#6d5eb7\"></stop></linearGradient>\
        <linearGradient id=\"lgrad-g\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#585f74\"></stop><stop offset=\"99%\" stop-color=\"#b6bbc8\"></stop></linearGradient>\
      </defs>\
    </svg>\
    ";
    </script>
_x000D_
_x000D_
_x000D_

The first one is normal SVG, the second one is inside a shadow dom.

Find if current time falls in a time range

Some good answers here but none cover the case of your start time being in a different day than your end time. If you need to straddle the day boundary, then something like this may help:

TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM
TimeSpan end = TimeSpan.Parse("02:00");   // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;

if (start <= end)
{
    // start and stop times are in the same day
    if (now >= start && now <= end)
    {
        // current time is between start and stop
    }
}
else
{
    // start and stop times are in different days
    if (now >= start || now <= end)
    {
       // current time is between start and stop
    }
}

Note that in this example the time boundaries are inclusive and that this still assumes less than a 24-hour difference between start and stop.

Callback function for JSONP with jQuery AJAX

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}

How can I remove file extension from a website address?

You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:

Old page: http://something.com/profile.php?id=a&abc=1

New page: http://something.com/profile/?id=a&abc=1

If you are not satisfied leave a comment for complicated methods.

Spring RestTemplate timeout

I finally got this working.

I think the fact that our project had two different versions of the commons-httpclient jar wasn't helping. Once I sorted that out I found you can do two things...

In code you can put the following:

HttpComponentsClientHttpRequestFactory rf =
    (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
rf.setReadTimeout(1 * 1000);
rf.setConnectTimeout(1 * 1000);

The first time this code is called it will set the timeout for the HttpComponentsClientHttpRequestFactory class used by the RestTemplate. Therefore, all subsequent calls made by RestTemplate will use the timeout settings defined above.

Or the better option is to do this:

<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
    <constructor-arg>
        <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
            <property name="readTimeout" value="${application.urlReadTimeout}" />
            <property name="connectTimeout" value="${application.urlConnectionTimeout}" />
        </bean>
    </constructor-arg>
</bean>

Where I use the RestOperations interface in my code and get the timeout values from a properties file.

Preprocessing in scikit learn - single sample - Depreciation warning

Well, it actually looks like the warning is telling you what to do.

As part of sklearn.pipeline stages' uniform interfaces, as a rule of thumb:

  • when you see X, it should be an np.array with two dimensions

  • when you see y, it should be an np.array with a single dimension.

Here, therefore, you should consider the following:

temp = [1,2,3,4,5,5,6,....................,7]
# This makes it into a 2d array
temp = np.array(temp).reshape((len(temp), 1))
temp = scaler.transform(temp)

Visual Studio Code Automatic Imports

If anyone has run into this issue recently, I found I had to add a setting to use my workspace's version of typescript for the auto-imports to work. To do this, add this line to your workspace settings:

{
  "typescript.tsdk": "./node_modules/typescript/lib"
}

Then, with a typescript file open in vscode, click the typescript version number in the lower right-hand corner. When the options at the top appear, choose "use workspace version", then reload vscode.

Now auto-imports should work.

@angular/material/index.d.ts' is not a module

This can be solved by writing full path, for example if you want to include MatDialogModule follow:

Prior to @angular/material 9.x.x

import { MatDialogModule } from "@angular/material";
//leading to error mentioned

As per @angular/material 9.x.x

import { MatDialogModule } from "@angular/material/dialog";
//works fine 

Official change log breaking change reference: https://github.com/angular/components/blob/master/CHANGELOG.md#material-9

Check whether IIS is installed or not?

Check

Control Panel --> Administrative Tools --> Services --> IIS Admin

For reinstalling

How to remove and reinstall IIS 5.0, 5.1 and 6.0

Change value of input and submit form in JavaScript

You can use the onchange event:

<form name="myform" id="myform" action="action.php">
    <input type="hidden" name="myinput" value="0" onchange="this.form.submit()"/>
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" onclick="DoSubmit()" />
</form>

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

How to do HTTP authentication in android?

You can manually insert http header to request:

HttpGet request = new HttpGet(...);
request.setHeader("Authorization", "Basic "+Base64.encodeBytes("login:password".getBytes()));

Alternate table row color using CSS?

<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>

Java - get index of key in HashMap?

I was recently learning the concepts behind Hashmap and it was clear that there was no definite ordering of the keys. To iterate you can use:

Hashmap<String,Integer> hs=new Hashmap();
for(Map.Entry<String, Integer> entry : hs.entrySet()){
      String key=entry.getKey();
      int val=entry.getValue();
      //your code block  
  }

in_array multiple values

IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:

<?php

// First Array To Compare
$a1 = array('foo','bar','c');

// Target Array
$b1 = array('foo','bar');


// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
        if (!in_array($x,$b1)) {
                $b=false;
        }
};


// Actual Test on array (can be repeated with others, but guard 
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);

This relies on a closure; comparison function can become much more powerful. Good luck!

Build Android Studio app via command line

Try this (OS X only):

brew install homebrew/versions/gradle110
gradle build

You can use gradle tasks to see all tasks available for the current project. No Android Studio is needed here.

How to remove specific element from an array using python

Using filter() and lambda would provide a neat and terse method of removing unwanted values:

newEmails = list(filter(lambda x : x != '[email protected]', emails))

This does not modify emails. It creates the new list newEmails containing only elements for which the anonymous function returned True.

Set a button background image iPhone programmatically

Code for background image of a Button in Swift 3.0

buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)

Hope this will help someone.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

A typographical error in the string describing the database driver can also produce the error.

A string specified as:

"jdbc:mysql//localhost:3307/dbname,"usrname","password"

can result in a "no suitable driver found" error. The colon following "mysql" is missing in this example.

The correct driver string would be:

jdbc:mysql://localhost:3307/dbname,"usrname","password"

VBA Date as integer

Just use CLng(Date).

Note that you need to use Long not Integer for this as the value for the current date is > 32767

Is it possible to program Android to act as physical USB keyboard?

Seems someone have done it by patching the kernel. I just came across a paper titled "Exploiting Smart-Phone USB Connectivity For Fun And Profit" by Angelos Stavrou, Zhaohui Wang, Computer Science Department George Mason University, Fairfax, VA. (available freely by googling the above title). Here the two researchers are investigating the possibility of a compromised android device controlling the attached PC by having the android device presenting itself as an HID device (keyboard). As a proof of concept, it seems that they have successfully patched a kernel doing exactly what you want. They didn't provide detailed steps but anyway I just quote what they said they've done:

.....we developed a special USB gadget driver in addition to existing USB composite interface on the Android Linux kernel using the USB Gadget API for Linux[4]. The UGAL framework helped us implement a simple USB Human Interface Driver (HID) functionality (i.e. device driver) and the glue code between the various kernel APIs. Using the code provided in: “drivers/usb/gadget/composite.c”, we created our own gadget driver as an additional composite USB interface. This driver simulates a USB keyboard device. We can also simulate a USB mouse device sending pre-programmed input command to the desktop system. Therefore, it is straightforward to pose as a normal USB mouse or keyboard device and send predefined command stealthily to simulate malicious interactive user activities. To verify this functionality, in our controlled experiments, we send keycode sequences to perform non-fatal operations and show how such a manipulated device can cause damages In particular, we simulated a Dell USB keyboard (vendorID=413C, productID=2105) sending ”CTRL+ESC” key combination and ”U” and ”Enter” key sequence to reboot the machine. Notice that this only requires USB connection and can gain the ”current user” privilege on the desktop system. With the additional local or remote exploit sent as payload, the malware can escalate the privilege and gain full access of the desktop system.

How to clear APC cache entries?

My work-around for Symfony build having loot of instances at the same server:

Step 1. Create trigger or something to set a file flag (eg. Symfony command) then create marker file ..

file_put_contents('clearAPCU','yes sir i can buggy')

Step 2. On index file at start add clearing code and remove marker file.

if(file_exists('clearAPCU')){
    apcu_clear_cache();
    unlink('clearAPCU');
}

Step 2. Run app.

Preloading CSS Images

If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)

What is an IIS application pool?

The application Pools element contains configuration settings for all application pools running on your IIS. An application pool defines a group of one or more worker processes, configured with common settings that serve requests to one or more applications that are assigned to that application pool.

Because application pools allow a set of Web applications to share one or more similarly configured worker processes, they provide a convenient way to isolate a set of Web applications from other Web applications on the server computer.

Process boundaries separate each worker process; therefore, application problems in one application pool do not affect Web sites or applications in other application pools. Application pools significantly increase both the reliability and manageability of your Web infrastructure.

Clearing an HTML file upload field via JavaScript

They don't get focus events, so you'll have to use a trick like this: only way to clear it is to clear the entire form

<script type="text/javascript">
    $(function() {
        $("#wrapper").bind("mouseover", function() {
            $("form").get(0).reset();
        });
    });
</script>

<form>
<div id="wrapper">
    <input type=file value="" />
</div>
</form>

CSS position absolute full width problem

You could set both left and right property to 0. This will make the div stretch to the document width, but requires that no parent element is positioned (which is not the case, seeing as #header is position: relative;)

#site_nav_global_primary {    
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
}

Demo at: http://jsfiddle.net/xWnq2/, where I removed position:relative; from #header

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

How to justify navbar-nav in Bootstrap 3

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
 <div class="container">
<div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
</div>
<div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li><a href="#">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#contact">Contact</a></li>  
  </ul>
</div>

and for the css

@media ( min-width: 768px ) { 
    .navbar > .container {
        text-align: center;
    }
    .navbar-header,.navbar-brand,.navbar .navbar-nav,.navbar .navbar-nav > li {
        float: none;
        display: inline-block;
    }
    .collapse.navbar-collapse {
        width: auto;
        clear: none;
    }
}

see it live http://www.bootply.com/103172

Retrieve last 100 lines logs

len=`cat filename | wc -l`
len=$(( $len + 1 ))
l=$(( $len - 99 ))
sed -n "${l},${len}p" filename

first line takes the length (Total lines) of file then +1 in the total lines after that we have to fatch 100 records so, -99 from total length then just put the variables in the sed command to fetch the last 100 lines from file

I hope this will help you.

Differences between fork and exec

Fork creates a copy of a calling process. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{

  //child code

  exit(0);

}

//parent code

wait(cpid);

// end

(for child process text(code),data,stack is same as calling process) child process executes code in if block.

EXEC replaces the current process with new process's code,data,stack. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{   
  //child code

  exec(foo);

  exit(0);    
}

//parent code

wait(cpid);

// end

(after exec call unix kernel clears the child process text,data,stack and fills with foo process related text/data) thus child process is with different code (foo's code {not same as parent})

wordpress contactform7 textarea cols and rows change in smaller screens

I know this post is old, sorry for that.

You can also type 10x for cols and x2 for rows, if you want to have only one attribute.

[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->

System.Drawing.Image to stream C#

public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }

SQL Case Sensitive String Compare

You can also convert that attribute as case sensitive using this syntax :

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CS_AS

Now your search will be case sensitive.

If you want to make that column case insensitive again, then use

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CI_AS

Argument list too long error for rm, cp, mv commands

find has a -delete action:

find . -maxdepth 1 -name '*.pdf' -delete

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

Calling an executable program using awk

There are several ways.

  1. awk has a system() function that will run a shell command:

    system("cmd")

  2. You can print to a pipe:

    print "blah" | "cmd"

  3. You can have awk construct commands, and pipe all the output to the shell:

    awk 'some script' | sh

Using Position Relative/Absolute within a TD?

With regards to your second attempt, did you try using vertical align ? Either

<td valign="bottom">

or with css

vertical-align:bottom

How do I execute cmd commands through a batch file?

This fixes some issues with Blorgbeard's answer (but is untested):

@echo off
cd /d "c:\Program files\IIS Express"
start "" iisexpress /path:"C:\FormsAdmin.Site" /port:8088 /clr:v2.0
timeout 10
start http://localhost:8088/default.aspx
pause

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For UWP, I tried a different approach. I extended the ComboBox class, and processed the SelectionChanged and OnKeyUp events on the ComboBox as well as the Tapped event on the ComboBoxItems. In cases where I get a Tapped event or an Enter or Space key without first getting a SelectionChanged then I know the current item has been re-selected and I respond accordingly.

class ExtendedComboBox : ComboBox
{
    public ExtendedComboBox()
    {
        SelectionChanged += OnSelectionChanged;
    }

    protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
    {
        ComboBoxItem cItem = element as ComboBoxItem;
        if (cItem != null)
        {
            cItem.Tapped += OnItemTapped;
        }

        base.PrepareContainerForItemOverride(element, item);
    }

    protected override void OnKeyUp(KeyRoutedEventArgs e)
    {
        // if the user hits the Enter or Space to select an item, then consider this a "reselect" operation
        if ((e.Key == Windows.System.VirtualKey.Space || e.Key == Windows.System.VirtualKey.Enter) && !isSelectionChanged)
        {
            // handle re-select logic here
        }

        isSelectionChanged = false;

        base.OnKeyUp(e);
    }

    // track whether or not the ComboBox has received a SelectionChanged notification
    // in cases where it has not yet we get a Tapped or KeyUp notification we will want to consider that a "re-select"
    bool isSelectionChanged = false;
    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        isSelectionChanged = true;
    }

    private void OnItemTapped(object sender, TappedRoutedEventArgs e)
    {
        if (!isSelectionChanged)
        {
            // indicates that an item was re-selected  - handle logic here
        }

        isSelectionChanged = false;
    }
}

The import org.apache.commons cannot be resolved in eclipse juno

expand "Java Resources" and then 'Libraries' (in eclipse project). make sure that "Apache Tomcat" present.

if not follow- right click on project -> "Build Path" -> "Java Build Path" -> "Add Library" -> select "Server Runtime" -> next -> select "Apache Tomcat -> click finish

Spring .properties file: get element as an Array

If you need to pass the asterisk symbol, you have to wrap it with quotes.

In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.

In yml file I have:

websocket:
  cors: "*"

In Config class I have:

@Value("${websocket.cors}")
private String[] cors;

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How do I check if I'm running on Windows in Python?

Are you using platform.system?

 system()
        Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.

        An empty string is returned if the value cannot be determined.

If that isn't working, maybe try platform.win32_ver and if it doesn't raise an exception, you're on Windows; but I don't know if that's forward compatible to 64-bit, since it has 32 in the name.

win32_ver(release='', version='', csd='', ptype='')
        Get additional version information from the Windows Registry
        and return a tuple (version,csd,ptype) referring to version
        number, CSD level and OS type (multi/single
        processor).

But os.name is probably the way to go, as others have mentioned.


For what it's worth, here's a few of the ways they check for Windows in platform.py:

if sys.platform == 'win32':
#---------
if os.environ.get('OS','') == 'Windows_NT':
#---------
try: import win32api
#---------
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
#----------
def system():

    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.    
        An empty string is returned if the value cannot be determined.   
    """
    return uname()[0]

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

If you open the .aspx file and switch between design view and html view and back it will prompt VS to check the controls and add any that are missing to the designer file.

In VS2013-15 there is a Convert to Web Application command under the Project menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control.

PS: This should not be done in debug mode, as not everything is "recompiled" when debugging.

Some people have also reported success by (making a backup copy of your .designer.cs file and then) deleting the .designer.cs file. Re-create an empty file with the same name.

There are many comments to this answer that add tips on how best to re-create the designer.cs file.

Split string and get first value only

These are the two options I managed to build, not having the luxury of working with var type, nor with additional variables on the line:

string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);

string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);

This is what it gets:

enter image description here

Cross compile Go on OSX?

for people who need CGO enabled and cross compile from OSX targeting windows

I needed CGO enabled while compiling for windows from my mac since I had imported the https://github.com/mattn/go-sqlite3 and it needed it. Compiling according to other answers gave me and error:

/usr/local/go/src/runtime/cgo/gcc_windows_amd64.c:8:10: fatal error: 'windows.h' file not found

If you're like me and you have to compile with CGO. This is what I did:

1.We're going to cross compile for windows with a CGO dependent library. First we need a cross compiler installed like mingw-w64

brew install mingw-w64

This will probably install it here /usr/local/opt/mingw-w64/bin/.

2.Just like other answers we first need to add our windows arch to our go compiler toolchain now. Compiling a compiler needs a compiler (weird sentence) compiling go compiler needs a separate pre-built compiler. We can download a prebuilt binary or build from source in a folder eg: ~/Documents/go now we can improve our Go compiler, according to top answer but this time with CGO_ENABLED=1 and our separate prebuilt compiler GOROOT_BOOTSTRAP(Pooya is my username):

cd /usr/local/go/src
sudo GOOS=windows GOARCH=amd64 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean
sudo GOOS=windows GOARCH=386 CGO_ENABLED=1 GOROOT_BOOTSTRAP=/Users/Pooya/Documents/go ./make.bash --no-clean

3.Now while compiling our Go code use mingw to compile our go file targeting windows with CGO enabled:

GOOS="windows" GOARCH="386" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/i686-w64-mingw32-gcc" go build hello.go
GOOS="windows" GOARCH="amd64" CGO_ENABLED="1" CC="/usr/local/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc" go build hello.go

Selenium WebDriver can't find element by link text

find_elements_by_xpath("//*[@class='class name']")

is a great solution

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

Executing a stored procedure within a stored procedure

Here is an example of one of our stored procedures that executes multiple stored procedures within it:

ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete]
(
    @AssetID AS uniqueidentifier
)
AS

SET NOCOUNT ON

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

EXEC AssetLibrary_AssetDeleteAttributes @AssetID
EXEC AssetLibrary_AssetDeleteComponents @AssetID
EXEC AssetLibrary_AssetDeleteAgreements @AssetID
EXEC AssetLibrary_AssetDeleteMaintenance @AssetID

DELETE FROM
    AssetLibrary_Asset
WHERE
    AssetLibrary_Asset.AssetID = @AssetID

RETURN (@@ERROR)

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8 , ViewChild takes 2 parameters:

Try like this:

@ViewChild('nameInput', { static: false }) nameInputRef: ElementRef;

Explanation:

{ static: false }

If you set static false, the child component ALWAYS gets initialized after the view initialization in time for the ngAfterViewInit/ngAfterContentInit callback functions.

{ static: true}

If you set static true, the child component initialization will take place at the view initialization at ngOnInit

By default you can use { static: false }. If you are creating a dynamic view and want to use the template reference variable, then you should use { static: true}

For more info, you can read this article

Working Demo

In the demo, we will scroll to a div using template reference variable.

 @ViewChild("scrollDiv", { static: true }) scrollTo: ElementRef;

With { static: true }, we can use this.scrollTo.nativeElement in ngOnInit, but with { static: false }, this.scrollTo will be undefined in ngOnInit , so we can access in only in ngAfterViewInit

Programmatically Add CenterX/CenterY Constraints

Update for Swift 3/Swift 4:

As of iOS 8, you can and should activate your constraints by setting their isActive property to true. This enables the constraints to add themselves to the proper views. You can activate multiple constraints at once by passing an array containing the constraints to NSLayoutConstraint.activate()

let label = UILabel(frame: CGRect.zero)
label.text = "Nothing to show"
label.textAlignment = .center
label.backgroundColor = .red  // Set background color to see if label is centered
label.translatesAutoresizingMaskIntoConstraints = false
self.tableView.addSubview(label)

let widthConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal,
                                         toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 250)

let heightConstraint = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal,
                                          toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100)

let xConstraint = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: self.tableView, attribute: .centerX, multiplier: 1, constant: 0)

let yConstraint = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: self.tableView, attribute: .centerY, multiplier: 1, constant: 0)

NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])

Better Solution:

Since this question was originally answered, layout anchors were introduced making it much easier to create the constraints. In this example I create the constraints and immediately activate them:

label.widthAnchor.constraint(equalToConstant: 250).isActive = true
label.heightAnchor.constraint(equalToConstant: 100).isActive = true
label.centerXAnchor.constraint(equalTo: self.tableView.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: self.tableView.centerYAnchor).isActive = true

or the same using NSLayoutConstraint.activate():

NSLayoutConstraint.activate([
    label.widthAnchor.constraint(equalToConstant: 250),
    label.heightAnchor.constraint(equalToConstant: 100),
    label.centerXAnchor.constraint(equalTo: self.tableView.centerXAnchor),
    label.centerYAnchor.constraint(equalTo: self.tableView.centerYAnchor)
])

Note: Always add your subviews to the view hierarchy before creating and activating the constraints.


Original Answer:

The constraints make reference to self.tableView. Since you are adding the label as a subview of self.tableView, the constraints need to be added to the "common ancestor":

   self.tableView.addConstraint(xConstraint)
   self.tableView.addConstraint(yConstraint)

As @mustafa and @kcstricks pointed out in the comments, you need to set label.translatesAutoresizingMaskIntoConstraints to false. When you do this, you also need to specify the width and height of the label with constraints because the frame no longer is used. Finally, you also should set the textAlignment to .Center so that your text is centered in your label.

    var  label = UILabel(frame: CGRectZero)
    label.text = "Nothing to show"
    label.textAlignment = .Center
    label.backgroundColor = UIColor.redColor()  // Set background color to see if label is centered
    label.translatesAutoresizingMaskIntoConstraints = false
    self.tableView.addSubview(label)

    let widthConstraint = NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal,
        toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 250)
    label.addConstraint(widthConstraint)

    let heightConstraint = NSLayoutConstraint(item: label, attribute: .Height, relatedBy: .Equal,
        toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
    label.addConstraint(heightConstraint)

    let xConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterX, multiplier: 1, constant: 0)

    let yConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterY, multiplier: 1, constant: 0)

    self.tableView.addConstraint(xConstraint)
    self.tableView.addConstraint(yConstraint)

How to create and handle composite primary key in JPA

The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

How Can I Truncate A String In jQuery?

with prototype and without space :

 String.prototype.trimToLength = function (trimLenght) {
    return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};

Calling the base constructor in C#

public class MyException : Exception
{
    public MyException() { }
    public MyException(string msg) : base(msg) { }
    public MyException(string msg, Exception inner) : base(msg, inner) { }
}

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

What's the HTML to have a horizontal space between two objects?

CSS

div.horizontalgap {
  float: left;
  overflow: hidden;
  height: 1px;
  width: 0px;
}

Usage in HTML (for a 10px horizontal gap)

<div class="horizontalgap" style="width:10px"></div>

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

How do I create a HTTP Client Request with a cookie?

You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.

To perform a request with a cookie attached just do the following:

var requestify = require('requestify');
requestify.post('http://google.com', {}, {
    cookies: {
        sessionCookie: 'session-cookie-data'   
    }
});

NSDate get year/month/day

I'm writing this answer because it's the only approach that doesn't give you optionals back from NSDateComponent variables and/or force unwrapping those variables (also for Swift 3).

Swift 3

let date = Date()
let cal = Calendar.current
let year = cal.component(.year, from: date)
let month = cal.component(.month, from: date)
let day = cal.component(.day, from: date)

Swift 2

let date = NSDate()
let cal = NSCalendar.currentCalendar()
let year = cal.component(.Year, fromDate: date)
let month = cal.component(.Month, fromDate: date)
let day = cal.component(.Day, fromDate: date)

Bonus Swift 3 fun version

let date = Date()
let component = { (unit) in return Calendar.current().component(unit, from: date) }
let year = component(.year)
let month = component(.month)
let day = component(.day)

How to process a file in PowerShell line-by-line as a stream

If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:

# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }

# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }

# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }

UPDATE: If you are still not scared then try to use the .NET reader:

$reader = [System.IO.File]::OpenText("my.log")
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        # process the line
        $line
    }
}
finally {
    $reader.Close()
}

UPDATE 2

There are comments about possibly better / shorter code. There is nothing wrong with the original code with for and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
    $line
}

Does a favicon have to be 32x32 or 16x16?

I don't see any up to date info listed here, so here goes:

To answer this question now, 2 favicons will not do it if you want your icon to look great everywhere. See the sizes below:

16 x 16 – Standard size for browsers
24 x 24 – IE9 pinned site size for user interface
32 x 32 – IE new page tab, Windows 7+ taskbar button, Safari Reading List sidebar
48 x 48 – Windows site
57 x 57 – iPod touch, iPhone up to 3G
60 x 60 – iPhone touch up to iOS7
64 x 64 – Windows site, Safari Reader List sidebar in HiDPI/Retina
70 x 70 – Win 8.1 Metro tile
72 x 72 – iPad touch up to iOS6
76 x 76 – iOS7
96 x 96 – GoogleTV
114 x 114 – iPhone retina touch up to iOS6
120 x 120 – iPhone retina touch iOS7
128 x 128 – Chrome Web Store app, Android
144 x 144 – IE10 Metro tile for pinned site, iPad retina up to iOS6
150 x 150 – Win 8.1 Metro tile
152 x 152 – iPad retina touch iOS7
196 x 196 – Android Chrome
310 x 150 – Win 8.1 wide Metro tile
310 x 310 – Win 8.1 Metro tile

push_back vs emplace_back

A nice code for the push_back and emplace_back is shown here.

http://en.cppreference.com/w/cpp/container/vector/emplace_back

You can see the move operation on push_back and not on emplace_back.

How to use Elasticsearch with MongoDB?

This answer should be enough to get you set up to follow this tutorial on Building a functional search component with MongoDB, Elasticsearch, and AngularJS.

If you're looking to use faceted search with data from an API then Matthiasn's BirdWatch Repo is something you might want to look at.

So here's how you can setup a single node Elasticsearch "cluster" to index MongoDB for use in a NodeJS, Express app on a fresh EC2 Ubuntu 14.04 instance.

Make sure everything is up to date.

sudo apt-get update

Install NodeJS.

sudo apt-get install nodejs
sudo apt-get install npm

Install MongoDB - These steps are straight from MongoDB docs. Choose whatever version you're comfortable with. I'm sticking with v2.4.9 because it seems to be the most recent version MongoDB-River supports without issues.

Import the MongoDB public GPG Key.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Update your sources list.

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Get the 10gen package.

sudo apt-get install mongodb-10gen

Then pick your version if you don't want the most recent. If you are setting your environment up on a windows 7 or 8 machine stay away from v2.6 until they work some bugs out with running it as a service.

apt-get install mongodb-10gen=2.4.9

Prevent the version of your MongoDB installation being bumped up when you update.

echo "mongodb-10gen hold" | sudo dpkg --set-selections

Start the MongoDB service.

sudo service mongodb start

Your database files default to /var/lib/mongo and your log files to /var/log/mongo.

Create a database through the mongo shell and push some dummy data into it.

mongo YOUR_DATABASE_NAME
db.createCollection(YOUR_COLLECTION_NAME)
for (var i = 1; i <= 25; i++) db.YOUR_COLLECTION_NAME.insert( { x : i } )

Now to Convert the standalone MongoDB into a Replica Set.

First Shutdown the process.

mongo YOUR_DATABASE_NAME
use admin
db.shutdownServer()

Now we're running MongoDB as a service, so we don't pass in the "--replSet rs0" option in the command line argument when we restart the mongod process. Instead, we put it in the mongod.conf file.

vi /etc/mongod.conf

Add these lines, subbing for your db and log paths.

replSet=rs0
dbpath=YOUR_PATH_TO_DATA/DB
logpath=YOUR_PATH_TO_LOG/MONGO.LOG

Now open up the mongo shell again to initialize the replica set.

mongo DATABASE_NAME
config = { "_id" : "rs0", "members" : [ { "_id" : 0, "host" : "127.0.0.1:27017" } ] }
rs.initiate(config)
rs.slaveOk() // allows read operations to run on secondary members.

Now install Elasticsearch. I'm just following this helpful Gist.

Make sure Java is installed.

sudo apt-get install openjdk-7-jre-headless -y

Stick with v1.1.x for now until the Mongo-River plugin bug gets fixed in v1.2.1.

wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb
sudo dpkg -i elasticsearch-1.1.1.deb

curl -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
sudo mv *servicewrapper*/service /usr/local/share/elasticsearch/bin/
sudo rm -Rf *servicewrapper*
sudo /usr/local/share/elasticsearch/bin/service/elasticsearch install
sudo ln -s `readlink -f /usr/local/share/elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch

Make sure /etc/elasticsearch/elasticsearch.yml has the following config options enabled if you're only developing on a single node for now:

cluster.name: "MY_CLUSTER_NAME"
node.local: true

Start the Elasticsearch service.

sudo service elasticsearch start

Verify it's working.

curl http://localhost:9200

If you see something like this then you're good.

{
  "status" : 200,
  "name" : "Chi Demon",
  "version" : {
    "number" : "1.1.2",
    "build_hash" : "e511f7b28b77c4d99175905fac65bffbf4c80cf7",
    "build_timestamp" : "2014-05-22T12:27:39Z",
    "build_snapshot" : false,
    "lucene_version" : "4.7"
  },
  "tagline" : "You Know, for Search"
}

Now install the Elasticsearch plugins so it can play with MongoDB.

bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb/1.6.0
bin/plugin --install elasticsearch/elasticsearch-mapper-attachments/1.6.0

These two plugins aren't necessary but they're good for testing queries and visualizing changes to your indexes.

bin/plugin --install mobz/elasticsearch-head
bin/plugin --install lukas-vlcek/bigdesk

Restart Elasticsearch.

sudo service elasticsearch restart

Finally index a collection from MongoDB.

curl -XPUT localhost:9200/_river/DATABASE_NAME/_meta -d '{
  "type": "mongodb",
  "mongodb": {
    "servers": [
      { "host": "127.0.0.1", "port": 27017 }
    ],
    "db": "DATABASE_NAME",
    "collection": "ACTUAL_COLLECTION_NAME",
    "options": { "secondary_read_preference": true },
    "gridfs": false
  },
  "index": {
    "name": "ARBITRARY INDEX NAME",
    "type": "ARBITRARY TYPE NAME"
  }
}'

Check that your index is in Elasticsearch

curl -XGET http://localhost:9200/_aliases

Check your cluster health.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

It's probably yellow with some unassigned shards. We have to tell Elasticsearch what we want to work with.

curl -XPUT 'localhost:9200/_settings' -d '{ "index" : { "number_of_replicas" : 0 } }'

Check cluster health again. It should be green now.

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

Go play.

How to sum data.frame column values?

When you have 'NA' values in the column, then

sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)

Identifier not found error on function call

Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:

void swapCase(char *name);

or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.

Fastest way to convert Image to Byte array

So is there any other method to achieve this goal?

No. In order to convert an image to a byte array you have to specify an image format - just as you have to specify an encoding when you convert text to a byte array.

If you're worried about compression artefacts, pick a lossless format. If you're worried about CPU resources, pick a format which doesn't bother compressing - just raw ARGB pixels, for example. But of course that will lead to a larger byte array.

Note that if you pick a format which does include compression, there's no point in then compressing the byte array afterwards - it's almost certain to have no beneficial effect.

What is difference between INNER join and OUTER join

Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.

When to use StringBuilder in Java

Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.

Getting the current date in SQL Server?

As you are using SQL Server 2008, go with Martin's answer.

If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

SQLFiddle

Android Studio cannot resolve R in imported project?

In my case, I found that "android.R.layout.account_list" was referenced instead of "R.layout.account_list". Simply remove "android." can fix the problem. Hope this help because sometimes you may overlook when you are too focusing.

can't start MySql in Mac OS 10.6 Snow Leopard

Okay... Finally I could install it! Why? or what I did? well I am not sure. first I downloaded and installed the package (I installed all the files(3) from the disk image) but I couldn't start it. (nor from the preferences panel, nor from the termial)

second I removed it and installed through mac ports.

again, the same thing. could not start it.

Now I deleted it again, installed from the package. (i am not sure if it was the exact same package but I think it is) Only this time I got the package from another site(its a mirror).

the site:

http://www.mmisoftware.co.uk/weblog/2009/08/29/mac-os-x-10-6-snow-leopard-and-mysql/

and the link:

http://mirror.services.wisc.edu/mysql/Downloads/MySQL-5.1/mysql-5.1.37-osx10.5-x86.dmg

1.- install mysql-5-1.37-osx10.5-x86.pkg

2.- install MySQLStartupItem.pkg

3.- install MySQL.prefpanel

And this time is working fine (even the preferences panel!)

Nothing special, I don't know what happened the first two times.

But thank you all. Regards.

Flushing footer to bottom of the page, twitter bootstrap

Use this piece of code in bootstrap it's works

<div class="navbar fixed-bottom">
<div class="container">
 <p class="muted credit">Footer <a href="http://google.com">Link</a> and <a 
href="http://google.com/">link</a>.</p>
 </div>
 </div>

jQuery $("#radioButton").change(...) not firing during de-selection

You can bind to all of the radio buttons at once by name:

$('input[name=someRadioGroup]:radio').change(...);

Working example here: http://jsfiddle.net/Ey4fa/

Avoid trailing zeroes in printf()

Slight variation on above:

  1. Eliminates period for case (10000.0).
  2. Breaks after first period is processed.

Code here:

void EliminateTrailingFloatZeros(char *iValue)
{
  char *p = 0;
  for(p=iValue; *p; ++p) {
    if('.' == *p) {
      while(*++p);
      while('0'==*--p) *p = '\0';
      if(*p == '.') *p = '\0';
      break;
    }
  }
}

It still has potential for overflow, so be careful ;P

RSA encryption and decryption in Python

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

And use

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

Map to String in Java

You can also use google-collections (guava) Joiner class if you want to customize the print format

Failed to open/create the internal network Vagrant on Windows10

After a Windows 10 update my VirtualBox Host-Only Ethernet Adapter was actually gone from the OS' network adapters (view these under Control Panel -> Network and Sharing Center -> Change adapter settings). Had to reinstall VirtualBox to bring that back to the OS.

Then in the newer version of VirtualBox, the host-only adapters are under Global Tools (top right) -> Host Network Manager. Make sure the DHCP Server is enabled for the adapter.

Example config: enter image description here

SQL/mysql - Select distinct/UNIQUE but return all columns?

Try

SELECT table.* FROM table 
WHERE otherField = 'otherValue'
GROUP BY table.fieldWantedToBeDistinct
limit x

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

browser.msie error after update to jQuery 1.9.1

Instead of having the whole migration script added, you could simply add the following (extracted from the migration script)

$.uaMatch = function( ua ) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

    return {
        browser: match[ 1 ] || "",
        version: match[ 2 ] || "0"
    };
};

and then use it like so

$.uaMatch(navigator.userAgent)

PHP: maximum execution time when importing .SQL data file

you must change php_admin_value max_execution_time in your Alias config (\XAMPP\alias\phpmyadmin.conf)

answer is here: WAMPServer phpMyadmin Maximum execution time of 360 seconds exceeded

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Adding an arbitrary line to a matplotlib plot in ipython notebook

Using vlines:

import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p =  plot(x, y, "o")
vlines(70,100,250)

The basic call signatures are:

vlines(x, ymin, ymax)
hlines(y, xmin, xmax)

Magento - How to add/remove links on my account navigation?

Technically the answer of zlovelady is preferable, but as I had only to remove items from the navigation, the approach of unsetting the not-needed navigation items in the template was the fastest/easiest way for me:

Just duplicate

app/design/frontend/base/default/template/customer/account/navigation

to

app/design/frontend/YOUR_THEME/default/template/customer/account/navigation

and unset the unneeded navigation items before the get rendered, e.g.:

<?php $_links = $this->getLinks(); ?>    
<?php 
    unset($_links['recurring_profiles']);
?>

Remove empty array elements

I think array_walk is much more suitable here

$linksArray = array('name', '        ', '  342', '0', 0.0, null, '', false);

array_walk($linksArray, function(&$v, $k) use (&$linksArray){
    $v = trim($v);
    if ($v == '')
        unset($linksArray[$k]);
});
print_r($linksArray);

Output:

Array
(
    [0] => name
    [2] => 342
    [3] => 0
    [4] => 0
)
  • We made sure that empty values are removed even if the user adds more than one space

  • We also trimmed empty spaces from the valid values

  • Finally, only (null), (Boolean False) and ('') will be considered empty strings

As for False it's ok to remove it, because AFAIK the user can't submit boolean values.

Tar a directory, but don't store full absolute paths in the archive

Low reputation (too many years of lurking, sigh) so I can't yet comment inline, but I found the answer from @laktak to be the only one that worked as intended on Ubuntu 18.04 -- using tar -cjf site1.tar.bz2 -C /var/www/site1 . on my machine resulted in all the files I wanted being under ./ inside the tar.bz2 file, which is probably ok but there is some risk of inconsistent behavior across OSs when un-tarring.

SQL Server, division returns zero

Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:

SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);

bad operand types for binary operator "&" java

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

onSaveInstanceState () and onRestoreInstanceState ()

The main thing is that if you don't store in onSaveInstanceState() then onRestoreInstanceState() will not be called. This is the main difference between restoreInstanceState() and onCreate(). Make sure you really store something. Most likely this is your problem.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

You could use find along with the -exec flag in a single command line to do the job

find . -name "*.zip" -exec unzip {} \;

Simulate a click on 'a' element using javascript/jquery

Using jQuery:

$('#gift-close').click();

How do I get the width and height of a HTML5 canvas?

now starting 2015 all (major?) browsers seem to alow c.width and c.height to get the canvas internal size, but:

the question as the answers are missleading, because the a canvas has in principle 2 different/independent sizes.

The "html" lets say CSS width/height and its own (attribute-) width/height

look at this short example of different sizing, where I put a 200/200 canvas into a 300/100 html-element

With most examples (all I saw) there is no css-size set, so theese get implizit the width and height of the (drawing-) canvas size. But that is not a must, and can produce funy results, if you take the wrong size - ie. css widht/height for inner positioning.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

<p:ajax listener="#{my.handleChange}" update="id of component that need to be rerender after change" process="@this" />



import javax.faces.component.UIOutput;
import javax.faces.event.AjaxBehaviorEvent;

public void handleChange(AjaxBehaviorEvent vce){  
  String name= (String) ((UIOutput) vce.getSource()).getValue();
}

Multiplying across in a numpy array

You could also use matrix multiplication (aka dot product):

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)

numpy.dot(c,a)

Which is more elegant is probably a matter of taste.

What Java FTP client library should I use?

Check out Apache commons-net, which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!

Express.js - app.listen vs server.listen

Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.

This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Using "label for" on radio buttons

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

_x000D_
_x000D_
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
       <label for="r1_1">button text one</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
       <label for="r1_2">button text two</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
       <label for="r1_3">button text three</label>
_x000D_
_x000D_
_x000D_

Preventing iframe caching in browser

I set iframe src attribute later in my app. To get rid of the cached content inside iframe at the start of the application I simply do:

myIframe.src = "";

... somewhere in the beginning of js code (for instance in jquery $() handler)

Thanks to http://www.freshsupercool.com/2008/07/10/firefox-caching-iframe-data/

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

When should we use mutex and when should we use semaphore

Here is how I remember when to use what -

Semaphore: Use a semaphore when you (thread) want to sleep till some other thread tells you to wake up. Semaphore 'down' happens in one thread (producer) and semaphore 'up' (for same semaphore) happens in another thread (consumer) e.g.: In producer-consumer problem, producer wants to sleep till at least one buffer slot is empty - only the consumer thread can tell when a buffer slot is empty.

Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time. Mutex 'down' happens in one thread and mutex 'up' must happen in the same thread later on. e.g.: If you are deleting a node from a global linked list, you do not want another thread to muck around with pointers while you are deleting the node. When you acquire a mutex and are busy deleting a node, if another thread tries to acquire the same mutex, it will be put to sleep till you release the mutex.

Spinlock: Use a spinlock when you really want to use a mutex but your thread is not allowed to sleep. e.g.: An interrupt handler within OS kernel must never sleep. If it does the system will freeze / crash. If you need to insert a node to globally shared linked list from the interrupt handler, acquire a spinlock - insert node - release spinlock.