text:
Q: Saving dictionaries to file (numpy and Python 2/3 friendly) I want to do hierarchical key-value storage in Python, which basically boils down to storing dictionaries to files. By that I mean any type of dictionary structure, that may contain other dictionaries, numpy arrays, serializable Python objects, and so forth. Not only that, I want it to store numpy arrays space-optimized and play nice between Python 2 and 3.
Below are methods I know are out there. My question is what is missing from this list and is there an alternative that dodges all my deal-breakers?

*

*Python's pickle module (deal-breaker: inflates the size of numpy arrays a lot)

*Numpy's save/savez/load (deal-breaker: Incompatible format across Python 2/3)

*PyTables replacement for numpy.savez (deal-breaker: only handles numpy arrays)

*Using PyTables manually (deal-breaker: I want this for constantly changing research code, so it's really convenient to be able to dump dictionaries to files by calling a single function)

The PyTables replacement of numpy.savez is promising, since I like the idea of using hdf5 and it compresses the numpy arrays really efficiently, which is a big plus. However, it does not take any type of dictionary structure.
Lately, what I've been doing is to use something similar to the PyTables replacement, but enhancing it to be able to store any type of entries. This actually works pretty well, but I find myself storing primitive data types in length-1 CArrays, which is a bit awkward (and ambiguous to actual length-1 arrays), even though I set chunksize to 1 so it doesn't take up that much space.
Is there something like that already out there?
Thanks!

A: After asking this two years ago, I starting coding my own HDF5-based replacement of pickle/np.save. Ever since, it has matured into a stable package, so I thought I would finally answer and accept my own question because it is by design exactly what I was looking for:

*

*https://github.com/uchicago-cs/deepdish

A: I recently found myself with a similar problem, for which I wrote a couple of functions for saving the contents of dicts to a group in a PyTables file, and loading them back into dicts.
They process nested dictionary and group structures recursively, and handle objects with types that are not natively supported by PyTables by pickling them and storing them as string arrays. It's not perfect, but at least things like numpy arrays will be stored efficiently. There's also a check included to avoid inadvertently loading enormous structures into memory when reading the group contents back into a dict.
import tables
import cPickle

def dict2group(f, parent, groupname, dictin, force=False, recursive=True):
    """
    Take a dict, shove it into a PyTables HDF5 file as a group. Each item in
    the dict must have a type and shape compatible with PyTables Array.

    If 'force == True', any existing child group of the parent node with the
    same name as the new group will be overwritten.

    If 'recursive == True' (default), new groups will be created recursively
    for any items in the dict that are also dicts.
    """
    try:
        g = f.create_group(parent, groupname)
    except tables.NodeError as ne:
        if force:
            pathstr = parent._v_pathname + '/' + groupname
            f.removeNode(pathstr, recursive=True)
            g = f.create_group(parent, groupname)
        else:
            raise ne
    for key, item in dictin.iteritems():
        if isinstance(item, dict):
            if recursive:
                dict2group(f, g, key, item, recursive=True)
        else:
            if item is None:
                item = '_None'
            f.create_array(g, key, item)
    return g

def group2dict(f, g, recursive=True, warn=True, warn_if_bigger_than_nbytes=100E6):
    """
    Traverse a group, pull the contents of its children and return them as
    a Python dictionary, with the node names as the dictionary keys.

    If 'recursive == True' (default), we will recursively traverse child
    groups and put their children into sub-dictionaries, otherwise sub-
    groups will be skipped.

    Since this might potentially result in huge arrays being loaded into
    system memory, the 'warn' option will prompt the user to confirm before
    loading any individual array that is bigger than some threshold (default
    is 100MB)
    """

    def memtest(child, threshold=warn_if_bigger_than_nbytes):
        mem = child.size_in_memory
        if mem > threshold:
            print '[!] "%s" is %iMB in size [!]' % (child._v_pathname, mem / 1E6)
            confirm = raw_input('Load it anyway? [y/N] >>')
            if confirm.lower() == 'y':
                return True
            else:
                print "Skipping item \"%s\"..." % g._v_pathname
        else:
            return True
    outdict = {}
    for child in g:
        try:
            if isinstance(child, tables.group.Group):
                if recursive:
                    item = group2dict(f, child)
                else:
                    continue
            else:
                if memtest(child):
                    item = child.read()
                    if isinstance(item, str):
                        if item == '_None':
                            item = None
                else:
                    continue
            outdict.update({child._v_name: item})
        except tables.NoSuchNodeError:
            warnings.warn('No such node: "%s", skipping...' % repr(child))
            pass
    return outdict

It's also worth mentioning joblib.dump and joblib.load, which tick all of your boxes apart from Python 2/3 cross-compatibility. Under the hood they use np.save for numpy arrays and cPickle for everything else.

A: I tried playing with np.memmap for saving an array of dictionaries. Say we have the dictionary:
a = np.array([str({'a':1, 'b':2, 'c':[1,2,3,{'d':4}]}])

first I tried to directly save it to a memmap:
f = np.memmap('stack.array', dtype=dict, mode='w+', shape=(100,))
f[0] = d
# CRASHES when reopening since it looses the memory pointer

f = np.memmap('stack.array', dtype=object, mode='w+', shape=(100,))
f[0] = d
# CRASHES when reopening for the same reason

the way it worked is converting the dictionary to a string:
f = np.memmap('stack.array', dtype='|S1000', mode='w+', shape=(100,))
f[0] = str(a)

this works and afterwards you can eval(f[0]) to get the value back.
I do not know the advantage of this approach over the others, but it deserves a closer look.

A: I absolutely recommend a python object database like ZODB. It seems pretty well suited for your situation, considering you store objects (literally whatever you like) to a dictionary - this means you can store dictionaries inside dictionaries. I've used it in a wide range of problems, and the nice thing is that you can just hand somebody the database file (the one with a .fs extension). With this, they'll be able to read it in, and perform any queries they wish, and modify their own local copies. If you wish to have multiple programs simultaneously accessing the same database, I'd make sure to look at ZEO.
Just a silly example of how to get started:
from ZODB import DB
from ZODB.FileStorage import FileStorage
from ZODB.PersistentMapping import PersistentMapping
import transaction
from persistent import Persistent
from persistent.dict import PersistentDict
from persistent.list import PersistentList

# Defining database type and creating connection.
storage = FileStorage('/path/to/database/zodbname.fs')
db = DB(storage)
connection = db.open()
root = connection.root()

# Define and populate the structure.
root['Vehicle'] = PersistentDict() # Upper-most dictionary
root['Vehicle']['Tesla Model S'] = PersistentDict() # Object 1 - also a dictionary
root['Vehicle']['Tesla Model S']['range'] = "208 miles"
root['Vehicle']['Tesla Model S']['acceleration'] = 5.9
root['Vehicle']['Tesla Model S']['base_price'] = "$71,070"
root['Vehicle']['Tesla Model S']['battery_options'] = ["60kWh","85kWh","85kWh Performance"]
# more attributes here

root['Vehicle']['Mercedes-Benz SLS AMG E-Cell'] = PersistentDict() # Object 2 - also a dictionary
# more attributes here

# add as many objects with as many characteristics as you like.

# commiting changes; up until this point things can be rolled back
transaction.get().commit()
transaction.get().abort()
connection.close()
db.close()
storage.close()

Once the database is created it's very easy use. Since it's an object database (a dictionary), you can access objects very easily:
#after it's opened (lines from the very beginning, up to and including root = connection.root() )
>> root['Vehicles']['Tesla Model S']['range']
'208 miles'

You can also display all of the keys (and do all other standard dictionary things you might want to do):
>> root['Vehicles']['Tesla Model S'].keys()
['acceleration', 'range', 'battery_options', 'base_price']

Last thing I want to mention is that keys can be changed: Changing the key value in python dictionary. Values can also be changed - so if your research results change because you change your method or something you don't have to start the entire database from scratch (especially if everything else is still okay). Be careful with doing both of these. I put in safety measures in my database code to make sure I'm aware of my attempts to overwrite keys or values.
** ADDED **
# added imports
import numpy as np
from tempfile import TemporaryFile
outfile = TemporaryFile()

# insert into definition/population section
np.save(outfile,np.linspace(-1,1,10000))
root['Vehicle']['Tesla Model S']['arraydata'] = outfile

# check to see if it worked
>>> root['Vehicle']['Tesla Model S']['arraydata']
<open file '<fdopen>', mode 'w+b' at 0x2693db0>

outfile.seek(0)# simulate closing and re-opening
A = np.load(root['Vehicle']['Tesla Model S']['arraydata'])

>>> print A
array([-1.        , -0.99979998, -0.99959996, ...,  0.99959996,
    0.99979998,  1.        ])

You could also use numpy.savez() for compressed saving of multiple numpy arrays in this exact same way.

A: This is not a direct answer. Anyway, you may be interested also in JSON. Have a look at the 13.10. Serializing Datatypes Unsupported by JSON. It shows how to extend the format for unsuported types.
The whole chapter from "Dive into Python 3" by Mark Pilgrim is definitely a good read for at least to know...
Update: Possibly an unrelated idea, but... I have read somewhere, that one of the reasons why XML was finally adopted for data exchange in heterogeneous environment was some study that compared specialized binary format with zipped XML. The conclusion for you could be to use possibly not so space efficient solution and compress it via zip or another well known algorithm. Using the known algorithm helps when you need to debug (to unzip and then look at the text file by eye).


text:
Q: why collapse menu not dropping down? I'm using bootstrap3 when I create collapse menu, the menu was not dropping down.

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="collapseMenu" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>

Games

A: You need add to TS file a property to show hide
  navbarCollapsed = true;

    toggleNavbarCollapsing() {
        this.navbarCollapsed = !this.navbarCollapsed;
    }

Update your HTML use (click)="toggleNavbarCollapsing()

            <button type="button" class="navbar-toggle collapsed" (click)="toggleNavbarCollapsing()" data-toggle="collapse" data-target="collapseMenu" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>

Games

Demo: https://stackblitz.com/edit/angular-bootstrap3-toggle

A: first install jquery
npm i jquery --save
then add following code in angular.json file
enter code here

"scripts": [
 "node_modules/jquery/dist/jquery.min.js",
 "node_modules/bootstrap/dist/js/bootstrap.min.js"
 ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't call function from required file in PHP From comment.php:
require_once "../../lib/vendor/Tsugi/Core/LTIX.php";
$LTI = requireData(array('user_id'));

From included file, LTIX.php:
 public static function requireData($needed) {There's a function here}

Fatal error: Call to undefined function requireData() in /tsugi/mod/video/comment.php
requireData() is only defined once in the whole site, so I don't think it's a name overlap problem.
Am I unable to call it because it's public or static? Is there some other reason a function call from an included file mightn't work?
Update:
With LTIX::requireData(array('user_id')), I get
Fatal error: Class 'LTIX' not found in /Applications/MAMP/htdocs/tsugi/mod/video/comment.php on line 8


text:
Q: Generating a select tag with rails with range of numbers with steps What is the simplest way to write a rails select tag that will generate a select for the numbers 1-15 stepped in .5 increments?
I know this has to be simple but i'm struggling with the syntax, i know there has to be a more elegant way to write it than how i did.
thanks!

A: select_tag "sizes", options_for_select( (4..15).step(0.5).map{|n| n%1 == 0 ? n.to_i : n} )

A: select_tag "sizes", options_for_select((4..15).step(0.5))

This is how i wrote it... but is this the best way to approach?
also, if i wanted the 4.0/5.0/6.0 etc to read 4/5/6 as whole numbers, is there a way to do/include this on one line?

A: The options_for_select method does what you want, but only if you can seed it with the correct data. This means you need an array with the appropriate values in it. For example:
options_for_select((0..28).to_a.collect { |v| v.to_f / 2 + 1 })


text:
Q: Mapping objects between the domain and database When mapping between database objects and domain objects, which "layer" of my application should this functionality reside in?
Say I have:

*

*DAL - has a reference to core domain

*Service - has a reference to DAL and core domain

Where is the mapping more appropriately placed in this scenario?

A: Your DAL would be a good place in this scenario, as it already references your core where your domain entities should live. It can do the fetching of data, and convert it to domain objects before returning.
In this way you can encapsulate the knowledge of the DB objects to the DAL layer, which is a good thing. If you ever need to change your DB out, you only need to modify this layer. The rest of the application only knows about the Domain.

A: If you want to follow the principle that says a layer only need to know about the next layer down (idea taken from the Law of Demeter) the best practice would be to place the translation code in the Service Layer.
However, as the core domain could be considered itself another layer in the middle of your service and data access layer, and considering the service layer talks directly with the DAL (breaking the LoD principle), probably the simpler and more pragmatic solution (as @wblanks says) could be to put the translation code in the data access layer.


text:
Q: java:2 dimensional array with color components and histogram interval i have created a method that should plot a histogram from an image...i have a 2 dimension array:
int[][] myHistogram=new int[colorComponentOfImage][bin256];

than i started to read pixel information and extract color like this:
int pixel[]=new int[width*height];
myImage.getRGB(0,0,width,height,pv,0,width);

now how can i fill the array with the colors that i get from the image??? or i'm extracting wrong the colors??
thx in advance
p.s. this is the rest of the code(method to fill the Histogram array):
public void setHistogram(int[][] myHistogram) {
    this.hist = myHistogram;
    for (int i = 0; i < this.bin256; i++) {
        for (int j = 0; j < this.colorcomponents; j++) {
            this.max = (this.max > this.hist[j][i]) ? this.max : this.hist[j][i];
        }
    }
}

and this is the method to plot the histogram:
public BufferedImage plotHistogram(int width, int height) {

    BufferedImage image = null;

    if (this.colorcomponents >= 3) {
        /**
         * extended RGB algorithm first channel:red second channel: green
         * third channel: blue fourth channel: the alpha value is being
         * ignored
         */
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        Polygon[] poly = new Polygon[3];

        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, width, height);

        /**
         * only first three bands are used
         */
        for (int i = 0; i < 3; i++) {
            poly[i] = new Polygon();
            if (i == RED) {
                graphics.setColor(Color.red);
            }

            else if (i == GREEN) {
                graphics.setColor(Color.green);
            }

            else if (i == BLUE) {
                graphics.setColor(Color.blue);
            }

            float xInterval = (float) width / (float) bins;
            float yInterval = (float) height / (float) max;
            poly[i].addPoint(0, height);

            for (int j = 0; j < bins; j++) {
                int x = (int) ((float) j * xInterval);
                int y = (int) ((float) this.hist[i][j] * yInterval);

                poly[i].addPoint(x, height - y);
            }

            poly[i].addPoint(width, height);
            graphics.fill(poly[i]);
        }

        Area red = new Area(poly[RED]);
        Area green = new Area(poly[GREEN]);
        Area blue = new Area(poly[BLUE]);

        red.intersect(green);
        green.intersect(blue);
        blue.intersect(new Area(poly[0]));

        graphics.setColor(new Color(255, 255, 0));
        graphics.fill(red);

        graphics.setColor(new Color(0, 255, 255));
        graphics.fill(green);

        graphics.setColor(new Color(255, 0, 255));
        graphics.fill(blue);

        graphics.setColor(Color.black);
        blue.intersect(new Area(poly[2]));
        graphics.fill(blue);
    }
    return image;
}

if i call the plotHistogram the array hist is empty...

A: Honestly I didn't read through your plotHistogram, but in my understanding myHistogram will have 3 or 4 arrays, each containing one more array with 256 items in it. Each of this is a counter which has to be initialized with 0s.
Then you define the following 4 constants:
final int RED_CHANNEL = 0;
final int BLUE_CHANNEL = 1;
final int GREEN_CHANNEL = 2;
final int ALPHA_CHANNEL = 3;

...
// then on each pixel you give values to to red, green, blue and increment the corresponding counter.
myHistogram[RED_CHANNEL][red]++;
myHistogram[GREEN_CHANNEL][green]++;

etc...
When you processed through the whole image you should have the histogram in your myHistogram array.
Btw.:
instead of doing this:
  if (i == RED) {
    graphics.setColor(Color.red);
  } else if (i == GREEN) {
    graphics.setColor(Color.green);
  }else if (i == BLUE) {
    graphics.setColor(Color.blue);
  }

I would define an array of Colors like
`final Color[] plotColours = new Colors[] {Color.RED, Color.GREEN, Color.BLUE};
and than you can
graphics.setColor(plotColours[i]);

where i is comming from:
/**
* only first three bands are used
*/
for (int i = 0; i < 3; i++) { ...

A: Ok. As I understand your myImage is an BufferedImage.
Javadoc of BufferedImage is helpful here.
As I understand this method returns exactly width*height amount of integers. Each integer contains information about one pixel. It is possible 'cause they shift in (with the >> operator) the RGBA values into one int value.
so to extract the exact RGBA you have to do something like:
int alpha = ((rgb >> 24) & 0xff);
int red = ((rgb >> 16) & 0xff);
int green = ((rgb >> 8) & 0xff);
int blue = ((rgb ) & 0xff);

where rgb is one int from the array returned by myImage.getRGB(...);
Maybe you should consider using the getRGB(int x, int y) method and process the returned int values as described above.
Is it clear or was I was too verbose??? :)


text:
Q: Get Schema error when making Data sync in Azure
*

*I finished setup for the making Azure hub and installing Client Agent and Database .

*Then define dataset.
That time whatever database i chose and click get latest schema, got the error.
Error is

The get schema request is either taking a long time or has failed.

*When check log ,it said like below :

Getting schema information for the database failed with the exception "There is already an open DataReader associated with this Command which must be closed first.
  For more information, provide
  tracing id 'xxxx' to customer support.

Any idea for this?

A: the current release has maximum of 500 tables in sync group. also, the drop down for the tables list is restricted to this same limit.
here's a quick workaround:
script the tables you want to sync
create a new temporary database and run the script to create the tables you want to sync
register and add the new temporary database as a member of the sync group
use the new temporary database to pick the tables you want to sync
add all other databases that you want to sync with (on-premise databases and hub database)
once the provisioning is done, remove the temporary database from the sync group.


text:
Q: In Cognito, how can I rollback my old email after the request of changing a new wrong email I am using Cognito in my service and I want to enable my service to change email address.
In my frontend, I added code like this.
    const email = 'foo@example.com'; // input
    const user = await Auth.currentAuthenticatedUser();
    await Auth.updateUserAttributes(user, { email });

I found this updateUserAttributes not only send verification email, but also change email address and set Email verified false before verification success.
When a user send wrong email address, I think, the user will no longer login, because the user cannot access to verification code and login old email.
Is there functions like rollback old email address in Cognito?

A: After some digging, I found the related issue

I found this updateUserAttributes not only send verification email, but also change email address and set Email verified false before verification success.

Unfortunately, this is Cognito side problem, and now there is no way to solve it fundamentally.
In the issue, Can-Sahin approach may help you.


text:
Q: How to make a simple ajax call in Magento 2.1.0 I have added a simple button in one of my phtml file.
<input type='button' name='emq_zip_btn' class='emq_zip_btn' value='Go'>

I have added one custom js file ("emq.js") from a custom module (Ved_Mymodule) :
require([
    "jquery",
    "jquery/ui"
], function($v){
//<![CDATA[
    $v = jQuery.noConflict();
    $v(document).ready(function()
    {
        console.log('jquery loaded from emq.js');
        $v(".emq_zip_btn").on('click',function(e)
        {
            console.log('clicked');
        });
    });
//]]>
});

When I click on the above button then "clicked " is printed in the console i.e. jQuery is working properly.
Here is a controller file from a custom module Ved_Mymodule:
Ved\Mymodule\Controller\Index\Index.php:
<?php

namespace Ved\Mymodule\Controller\Index;

use Ved\Mymodule\Model\NewsFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Index extends Action
{
    /**
     * @var \Tutorial\SimpleNews\Model\NewsFactory
     */
    protected $_modelNewsFactory;

    /**
     * @param Context $context
     * @param NewsFactory $modelNewsFactory
     */
    public function __construct(
        Context $context,
        NewsFactory $modelNewsFactory
    ) {
        parent::__construct($context);
        $this->_modelNewsFactory = $modelNewsFactory;
    }

    public function execute()
    {

    }
}

Ved/Mymodule/etc/frontend/routes.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/
App/etc/routes.xsd">
    <router id="standard">
        <route id="news" frontName="news">
            <module name="Ved_Mymodule" />
        </route>
    </router>

My question is how to return a data from this controller method and then access it via jQuery i.e. How to make a simple ajax call after that button clicked.

A: below is the example how to do this, Please modify it according to your requirement.
I used js template for this.
Following example will create drop down in your phtml file using ajax functionality.
In your JS
define([
        'jquery',
        'underscore',
        'mage/template',
        'jquery/list-filter'
        ], function (
            $,
            _,
            template
        ) {
            function main(config, element) {
                var $element = $(element);
var YOUR_URL_HERE = config.AjaxUrl;
                $(document).on('click','yourID_Or_Class',function() {
                        var param = 'ajax=1';
                            $.ajax({
                                showLoader: true,
                                url: YOUR_URL_HERE,
                                data: param,
                                type: "POST",
                                dataType: 'json'
                            }).done(function (data) {
                                $('#test').removeClass('hideme');
                                var html = template('#test', {posts:data});
                                $('#test').html(html);
                            });
                    });
            };
        return main;
    });

In Controller
public function __construct(
        Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {

        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        if ($this->getRequest()->isAjax())
        {
            $test=Array
            (
                'Firstname' => 'What is your firstname',
                'Email' => 'What is your emailId',
                'Lastname' => 'What is your lastname',
                'Country' => 'Your Country'
            );
            return $result->setData($test);
        }
    }

IN your phtml file
<style>
.hideme{display:none;}
</style>
<script type="text/x-magento-init">
        {
            "*": {
                "[Namespace]_[Modulename]/js/YOURFILE": {
                    "AjaxUrl": "<?php echo $block->getAjaxUrl(); ?>",
                }
            }
        }
</script>
<div id='test' class="hideme">
    <select>
      <% _.each(posts, function(text,value) { %>
         <option value="<%= value %>"><%= text %></option>
      <% }) %>
     </select>
</div>

getAjaxUrl should be function in your block file, which return you the url
Hope that helps.


text:
Q: PHP Directory-specific Content and Redirects I have this code
$pageEx = explode("/", $_SERVER['PHP_SELF']);
            $pageLn = count($pageEx);
            $currentdir = $pageEx[$pageLn - 2];

            switch($currentdir) {
                case "admin":
                    if(!$this->loggedIn) {
                        header("Location: index.php");
                    }
                    if($this->userData['user_level'] < 3) {
                        header("Location: ../index.php");
                    }
                break;

                case "mgmt":
                    if(!$this->loggedIn) {
                        header("Location: index.php");
                    }
                    if($this->userData['user_level'] < 2) {
                        header("Location: ../index.php");
                    }
                break;

                case "user":
                    if(!$this->loggedIn) {
                        header("Location: index.php");
                    }
                    if($this->userData['user_level'] < 1) {
                        header("Location: ../index.php");
                    }
                break;
            }

and was just wondering whether there's a shorter way I could do it?
The code works, but its a lot of code for something so simple.
It checks the directory they're in then if they aren't the right user_level it redirects them to the index page.
Edit: Done it.
$pageEx = explode("/", $_SERVER['PHP_SELF']);
            $pageLn = count($pageEx);
            $currentdir = $pageEx[$pageLn - 2];

            /*
                User Level Required => Directory
            */
            $permissions = array(
                1 => 'user',
                2 => 'mgmt',
                3 => 'admin'
            );

            foreach($permissions as $perms => $key) {
                if(!$this->loggedIn) {
                    header("Location: ../index.php");
                }
                if($currentdir == $key) {
                    if($perms > $this->userData['user_level']) {
                        header("Location: ../index.php");
                    }
                }
            }

A: How about this?
$pageEx = explode("/", $_SERVER['PHP_SELF']);
$pageLn = count($pageEx);
$currentdir = $pageEx[$pageLn - 2];

if(!$this->loggedIn) {
    header("Location: index.php");
}

$permissions = array(
    'admin' => 3,
    'mgmt' => 2,
    'user' => 1,
);

if($this->userData['user_level'] < $permissions[$currentdir]) {
    header("Location: ../index.php");
}

UPDATE: I just noticed you wanted to do a LESS THAN... so I updated the code to reflect the way it works in your code.

A: You might cringe at this, but you could get it down to 6 lines if the long if statement doesn't bother you...
$pageEx = explode("/", $_SERVER['PHP_SELF']);
$currentdir = $pageEx[count($pageEx) - 2];

if(!$this->loggedIn)
    header("Location: index.php");
elseif(($currentdir == "admin" && $this->userData['user_level'] < 3) || ($currentdir == "mgmt" && $this->userData['user_level'] < 2) || ($currentdir == "user" && $this->userData['user_level'] < 1))
    header("Location: ../index.php");

Note the change to an elseif because--and correct me if I'm mistaken--either the user is not logged in and gets redirected to index.php or the user is logged in and might get directed to ../index.php. If they were separate if statements, it seems there could end up being two Location headers.


text:
Q: How can I capture the log from process sync? I want to use process to print log to richtextbox, but it does not work, I don't know why.
When I use LogWithColor, It will block the program, can't print anything.
When I use richTextBox1.AppendText, or richTextBox1.Text +=, It will print, but will auto close the program, do not print "Finished." And VS2019 Debuger can't get inside, It will cause Exception:
System.InvalidOperationException"(In System.Windows.Forms.dll)
        public readonly string ffmpegExe = @"C:\Users\jared\AppData\Local\ffmpeg-4.4-full_build\bin\ffmpeg.exe";

        private void OutputHandler(object sendingProcess, DataReceivedEventArgs oneLine)
        {
            // LogWithColor(richTextBox1, Color.Black, oneLine.Data); // does not work
            // richTextBox1.AppendText(oneLine.Data); // it print, but I don't know why the program will be closed auto
        }
        private void ErrorHandler(object sendingProcess, DataReceivedEventArgs oneLine)
        {
            LogWithColor(richTextBox1, Color.Red, oneLine.Data); // does not work
            // richTextBox1.AppendText(oneLine.Data); // it print, but I don't know why the program will be closed auto
        }

        private delegate void LogWithColorDelegate(RichTextBox rtb, Color color, string text);
        private void LogWithColor(RichTextBox rtb, Color color, string text)
        {
            if (InvokeRequired)
            {
                if (rtb.IsHandleCreated)
                {
                    rtb.Invoke(new LogWithColorDelegate(LogWithColor),
                        new object[] { rtb, color, text });
                }
            }
            else
            {
                rtb.AppendText(Environment.NewLine);
                rtb.SelectionColor = color;
                rtb.AppendText(text);

                // rtb.Text += Environment.NewLine + text; // still does not work
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ffmpegExe) || !File.Exists(ffmpegExe))
            {
                return;
            }
            LogWithColor(richTextBox1, Color.Black, "Start..."); // work properly.
            using (Process p = new Process())
            {
                // RunCommand(p, ffmpegExe, "-h");
                // ffmpeg.exe -h
                p.StartInfo.FileName = ffmpegExe;
                p.StartInfo.Arguments = "-h";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.EnableRaisingEvents = true; // update for user9938 comment

                p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                p.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler);

                p.Start();
                p.BeginOutputReadLine();
                p.BeginErrorReadLine();
                p.WaitForExit();
            }
            LogWithColor(richTextBox1, Color.Black, "Finished.");
        }

A: The issue is because you're waiting for the process execution completion using the UI thread. It will block the UI/main thread until the process has exited. However, the process will never exit because you're redirecting the output/error data and the listener thread is blocked. Please, read more about WaitForExit.
There are some solutions to solve the issue. You can use for example the ThreadPool, a Task or a new Thread. But, if you're using C# 5 and .NET Framework 4.5 or greater, I would recommend you to use the async/await.
Here is a code snip using asynchronous programming:
private async void button1_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(ffmpegExe) || !File.Exists(ffmpegExe))
    {
        return;
    }

    LogWithColor(richTextBox1, Color.Black, "Start...");

    await Task.Run(() =>
    {
        using (var p = new Process())
        {
            p.StartInfo = new ProcessStartInfo(ffmpegExe, "-h")
            {
                UseShellExecute = false,
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                CreateNoWindow = true,
            };

            p.EnableRaisingEvents = true;

            p.OutputDataReceived += (_, data) =>
            {
                LogWithColor(richTextBox1, Color.Black, data.Data);
            };

            p.ErrorDataReceived += (_, data) =>
            {
                LogWithColor(richTextBox1, Color.Red, data.Data);
            };

            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.WaitForExit();
        }
    });

    LogWithColor(richTextBox1, Color.Black, "Finished.");
}

private void LogWithColor(RichTextBox rtb, Color color, string text)
{
    if (text == null)
    {
        return;
    }

    if (InvokeRequired)
    {
        Invoke(new Action(() => LogWithColor(rtb, color, text)));
        return;
    }

    rtb.AppendText(Environment.NewLine);
    rtb.SelectionColor = color;
    rtb.AppendText(text);
}


text:
Q: Msdeploy, can sync but not delete I'm trying to setup automatic deployment using msbuild.
I succeeded having a msdeploy sync call to successfully publish a zip package created with msbuild.
However when I try to perform a msdeploy delete call prior to the sync operation it fails with

ERROR_USER_NOT_AUTHORIZED_FOR_DEPLOYMENTPROVIDER

Is there any permissions or additional IIS delegation rules that should be set compared to the one used for the sync call ?
The msdeploy -verb:sync works correctly:
  Total changes: 676 (672 added, 0 deleted, 4 updated, 0 parameters changed, 55787329 bytes copied)
  Syncing done.

Howerver the msdeploy -verb:delete fails:
  Info: Using ID '138cbadf-3449-4574-8e3f-0a3bd13fe751' for connections to the remote server.
EXEC : error Code: ERROR_USER_NOT_AUTHORIZED_FOR_DEPLOYMENTPROVIDER [c:\PATH\Deploy.proj]
  More Information: Could not complete an operation with the specified provider ("auto") when connecting using the Web Management Service. This can o
  ccur if the server administrator has not authorized the user for this operation. auto http://go.microsoft.com/fwlink/?LinkId=178034
    Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_USER_NOT_AUTHORIZED_FOR_DEPLOYMENTPROVIDER.

As you can see I'm using a msbuild proj file to to this. The msdeploy calls are performed with the <Exec> rule :
<Target Name="Publish" >
        <Message Importance="High" Text="Deleting from $(PublishServer) ..." />
        <!-- THIS FAILS: -->
        <Exec
          WorkingDirectory="$(MsDeployBinaryFolder)\"
          Command=""$(MsDeployBinary)" -verb:delete -dest:auto,computerName="https://$(PublishServer):8172/msdeploy.axd?Site=$(IisAppHostName)",authType=Basic,userName=$(UserName),password='$(Password)' -allowUntrusted -disableLink:ContentExtension -disableLink:AppPoolExtension"
        />
        <Message Importance="High" Text="Deletion done." />

        <Message Importance="High" Text="Syncing to $(PublishServer) ..." />
        <!-- THIS WORKS: -->
        <Exec
          WorkingDirectory="$(MsDeployBinaryFolder)\"
          Command=""$(MsDeployBinary)" -verb:sync -source:package="$(ArchiveDir)\$(SiteName)\$(SiteName).zip" -dest:auto,computerName="https://$(PublishServer):8172/msdeploy.axd?Site=$(IisAppHostName)",authType=Basic,userName=$(UserName),password='$(Password)' -allowUntrusted -setParam:"IIS Web Application Name"="$(IisAppHostName)/$(IisSiteName)""
        />
        <Message Importance="High" Text="Syncing done." />
  </Target>

Any idea why sync can add and alter files while delete fails ?

A: Ok, got it working using the -dest:issApp instead of the -dest:auto provider.
Curiously enough, I can not use the -dest:iisApp provider when syncing from a source package without getting an event error:

Microsoft.Web.Deployment.DeploymentException: Source (sitemanifest)
  and destination (iisApp) are not compatible for the given operation.

So I use the -dest:auto for syncing and the -dest:iisApp for deleting.
<Exec
          WorkingDirectory="$(MsDeployBinaryFolder)\"
          Command=""$(MsDeployBinary)" -verb:delete -dest:iisApp="$(IisAppHostName)/$(IisSiteName)",computerName="https://$(PublishServer):8172/msdeploy.axd?Site=$(IisAppHostName)",authType=Basic,userName=$(UserName),password='$(Password)' -allowUntrusted -disableLink:ContentExtension -disableLink:AppPoolExtension"
        />


text: Q: Google Maps API doesn't work on Safari 9 Google Maps API doesn't work in Safari 9 (seemingly all devices), however, it does work in Safari 10 (and all other relevant browsers). I have no experience with Safari. Does anybody know how to fix this?


text:
Q: How to persist permission in android API 19 (KitKat)? In my application I store the path of image in my SQlite db for further use. The path that I get is
content://com.android.providers.media.documents/document/image%3A71964

When I retrieve this path from the database and try to retrieve the image from that path android throws
java.lang.SecurityException: Permission Denial: opening provider
com.android.providers.media.MediaDocumentsProvider
from ProcessRecord{42c84ec8 23911:com.gots.gb/u0a248} (pid=23911, uid=10248)
requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS

According https://developer.android.com/guide/topics/providers/document-provider.html#permissions I need to persist permission by adding the following code
final int takeFlags = intent.getFlags()
        & (Intent.FLAG_GRANT_READ_URI_PERMISSION
        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(uri, takeFlags);

When I added this code to my ImageAdapter class which extends BaseAdapter android throws
08-21 02:14:38.530: W/System.err(24452): java.lang.SecurityException:
No permission grant found for UID 10248 and Uri
content://com.android.providers.media.documents/document/image:71964

This is the relevant part of my ImageAdapter code
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView ;

    if (convertView == null){
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);

    }
    else{
        imageView = (ImageView)convertView ;
    }

    InputStream is = null;
    Bitmap bitmap = null ;

    try {

        Log.d(TAG,String.valueOf(list.get(position)));
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        final int takeFlags = intent.getFlags()
                & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // Check for the freshest data.

        if (Build.VERSION.SDK_INT >= 19){
            mContext.getContentResolver().takePersistableUriPermission(list.get(position), takeFlags);
        }

        is = mContext.getContentResolver().openInputStream(list.get(position));

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8;
        bitmap = BitmapFactory.decodeStream(is,null, options);
        is.close();
        imageView.setImageBitmap(bitmap);

        return imageView;

    }
    catch (Exception e) {
        e.printStackTrace();

        return null;
    }

what am I doing wrong?
Thanks

A: I believe I've solved it. The request intent:
Intent intent;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
    intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
}else{
    intent = new Intent(Intent.ACTION_GET_CONTENT);
}
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.form_pick_photos)), REQUEST_PICK_PHOTO);

and onActivityResult
...
// kitkat fixed (broke) content access; to keep the URIs valid over restarts need to persist access permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    final int takeFlags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
    ContentResolver resolver = getActivity().getContentResolver();
    for (Uri uri : images) {
        resolver.takePersistableUriPermission(uri, takeFlags);
    }
}
...

I haven't tested this pre-kitkat, my phone is running 5.1, can anyone verify this on older phones?

A: The code listed below,
// kitkat fixed (broke) content access; to keep the URIs valid over restarts need to persist access permission
if(Utils.isKitkat())
{
    final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION);
    ContentResolver resolver = getActivity().getContentResolver();
    for (Uri uri : images)
    {
        resolver.takePersistableUriPermission(uri, takeFlags);
    }
}

worked fine for me, anyway I noticed that the max number of persistable uri granted to my app is limited to 128. If I select more than 128 uri, I get the error:
java.lang.SecurityException: Permission Denial: opening provider........

just when I try to process an image for which I wasn't able to persist the permission. Can you figure out any solution?


text:
Q: diagonal problem in octagon
 I have not understand the question clearly.  Can you give me hints (with figure) so I can move on .

A: Take a look at a single vertex. How many diagonals can be drawn from that vertex? Of those, how many are not parallel to any side of the octagon (that is, how many belong to $B$)? What does this tell you, given the rotational symmetry of the figure?
As an alternate approach, we may determine these explicitly with combinatorics and pictures. There are $8$ vertices, so $\binom{8}{2}=28$ line segments that connect pairs of vertices. Of these, $8$ are edges, leaving $28-8=20$ diagonals. The diagonals that are not parallel to any edge are those between opposite vertices (only $4$ such diagonals) and those between vertices with a common neighbor ($8$ of these, forming two squares). Hence, $B$ has $12$ diagonals, and $A$ has $20-12=8$ diagonals (which you can actually draw in sequence without lifting your pencil).


text:
Q: Why 960 grid doesn't divide into "fours"? I've just wanted to start my adventure with a CSS framework, but I have a problem, which I'm not able to overcome. I've added 960.css and my own stylesheet.css but it persistently won't divide the content into "fours".
HTML

<title>Grid test</title>
<link rel="stylesheet" type="text/css" href="css/960.css" />
<link rel="stylesheet" type="text/css" href="stylesheet.css" />

Logo

Home

Products

Services

About

Contact

Feature

Column One

Column Two

Column Three

© Copyright 2011

CSS
*{
font-family: Arial, Verdana, sans-serif; color: #665544;
text-align: center;}
#nav, #feature, .article, #footer {
  background-color: #efefef;
  margin-top: 20px;
  padding: 10px 0px 5px 0px;}
#feature, .article {
  height: 100px;}
li {
  display: inline;
  padding: 5px;}


text:
Q: Spectral decomposition of the operator $L^2\to L^2,f\mapsto\int f$ Let $(E,\mathcal E,\mu)$ be a probability space, $$L^2_0(\mu):=\left\{f\in L^2(\mu):\int f\:{\rm d}\mu\right\}$$ and $$U:L^2(\mu)\to L^2(\mu)\;,\;\;\;f\mapsto\int f\:{\rm d}\mu=\langle 1,f\rangle_{L^2(\mu)}1.$$ Note that $U$ is a nonnegative self-adjoint linear operator on $L^2(\mu)$ with $\mathcal N(U)=L^2_0(\mu)$. Moreover, if $(f_i)_{i\in I}$ is an orthonormal basis (whose existence is ensured by Zorn's lemma) of $L^2(\mu)$, then $$\sum_{i\in I}\langle Uf_i,f_i\rangle_{L^2(\mu)}=\sum_{i\in I}\left|\langle1,f_i\rangle_{L^2(\mu)}\right|^2=\left\|1\right\|_{L^2(\mu)}^2=1\tag1$$ by Parseval's identity. So, if $|I|\le|\mathbb N|$, then $U$ is trace-class (cf. When is $L^2(\mu)$ separable?)

Assuming that $L^2(\mu)$ is separable, we can infer (from general theory of compact self-adjoint operators on a Hilbert space) the existence of an orthonormal basis $(e_i)_{i\in I}$ of $L^2(\mu)$, $I=\mathbb N\cap[0,\dim L^2(\mu)]$, and a nonincreaing $(\lambda_i)_{i\in I}$ with $$Uf_i=\lambda_if_i\;\;\;\text{for all }i\in I.\tag2$$ Moreover, if $I_0:=\left\{i\in I:\lambda_i=0\right\}$, then $(f_i)_{i\in I_0}$ is an orthonormal basis of $\mathcal N(U)=L^2_0(\mu)$ and $(f_i)_{i\in I\setminus I_0}$ is an orthonormal basis of $\overline{\mathcal R(U)}={\mathcal N(U)}^\perp$.
Question: Is there an explicit form of the eigenvalues $\lambda_i$? And how can we determine the square-root $Q^{1/2}$ and an orhonormal basis of $L^2_0(\mu)$?

Clearly, we know that $$Q^{1/2}\sum_{i\in I}\lambda_i^{1/2}f_i\otimes f_i,\tag3$$ but I guess there is a simpler expression for $Q^{1/2}$ in the present case.
Remark: All the considerations above are an attempt to find a generalization of the following question: Can we generalize the following result on the spectral gap of a reversible Markov transition matrix?.

A: In this answer, there is no assumption that $L^2(\mu)$ is separable.
Note that $U^2=U$ (this is due to the assumption $\mu(E)=1$).  Therefore, the minimal polynomial of $U$ exists and divides $x^2-x=x(x-1)$.  Thus, $U$ has at most two eigenvalues $0$ and $1$.  Note that $L^2(\mu)=\ker U\oplus\operatorname{im}U$.  The eigenspaces of $U$ w.r.t. the eigenvalues $0$ and $1$ are $\ker U$ and $\operatorname{im}U$, respectively.  So each $f\in L^2(\mu)$ is decomposed as
$$(f-Uf)+(Uf)$$
with $f-Uf\in \ker U$ and $Uf\in\operatorname{im}U$.
By the way, it is possible that $U$ has only one eigenvalue $1$.  If for example $\mathcal{E}=\{\emptyset,E\}$, then $U$ has only one eigenvalue $1$.  ($U$ always has $1$ as an eigenvalue because the characteristic function $\chi_E$ is an eigenfunction of $U$ with eigenvalue $1$.)
Regarding a square root of $U$, since $U^2=U$, $U$ is a square root of itself.  In fact, it is the only square root of $U$ which is self-adjoint and has non-negative spectrum.


text:
Q: Use paramiko to enter IO to remote CLI program I have a command line Python program which takes user input and adds it to a config file. When run it prompts the user to enter one config value at a time. The user enters the value and hits enter to get prompted for the next value. Examples of these values are as follows:
Please enter configured host IP:
Please enter the username for the account:
Please enter password for the user:

This program runs on a remote server and is executed as one part of a manual process. I'm trying to automate this process and am using the paramiko library to run this command. I use exec_command to run it. Can I send the values that the program prompts for using paramiko and if so, how?

A: This is what I did:
ssh_stdin, ssh_stdout, ssh_stderr = self.ssh.exec_command(
    'sudo python3 {}initialSetup.py'.format(self.backup_directory),
    60)
ssh_stdin.write('1.2.3.4\n')
ssh_stdin.write('username\n')
ssh_stdin.write('password\n')

See here for details.


text:
Q: Including content into an add_shortcode() function my_html.php
<?php

global $wp;
$op = get_option( 'mcc_d' );
$post_title = get_the_title();

isset( $this->op['mcc_d_text'] ) ? $mcc_d_text = $this->op['mcc_d_text'] : $mcc_d_text = '';

$html = '
';
    $html .= 'some content';
$html .= '
';

And this is the shortcode.php file:
<?php
if ( ! defined( 'ABSPATH' ) ) {exit;}

include( PLUGIN_PATH . 'parts/my_html.php' );

function mcc_d_shortcode() {
    global $html;
    return $html;
}

add_shortcode( 'mcc_d_content', 'mcc_d_shortcode');

What doesn't work here is the shortcode output ($html), it's empty even when I make $html global (which what I'm trying to avoid)... what am I doing wrong here?


text:
Q: Extract first ocurrence of an item in column A based on column B using SQL I have the following data, and I would like to create a result set that includes the rows that are the change in Item and the first ocurrence of Code == 1. Note that the first Code seen after a chnage in Item does not always have to be 1 (see the *):
The input data:

 DateTime                Item   Code
*2016-12-02 16:34:00     1      1
 2016-12-02 16:35:00     1      4
 2016-12-02 16:36:00     1      1
 2016-12-02 16:37:00     1      1
 2016-12-02 16:38:00     1      7
 2016-12-02 16:39:00     1      5
 2016-12-02 16:40:00     1      6
 2016-12-02 16:41:00     2      5
*2016-12-02 16:42:00     2      1
 2016-12-02 16:43:00     2      4
 2016-12-02 16:44:00     2      1
 2016-12-02 16:45:00     2      5
 2016-12-02 16:46:00     2      8
 2016-12-02 16:47:00     2      1
 2016-12-02 16:48:00     5      7
 2016-12-02 16:49:00     5      7
*2016-12-02 16:50:00     5      1
 2016-12-02 16:51:00     5      1
 2016-12-02 16:52:00     5      4
 2016-12-02 16:53:00     5      3
*2016-12-02 16:54:00     1      1
 2016-12-02 16:55:00     1      1
 2016-12-02 16:56:00     1      1
 2016-12-02 16:57:00     1      8
 2016-12-02 16:58:00     1      9
 2016-12-02 16:59:00     1      3
 2016-12-02 17:00:00     1      2
 2016-12-02 17:01:00     1      4

Expected output data:

 DateTime                Item   Code
*2016-12-02 16:34:00     1      1
*2016-12-02 16:42:00     2      1
*2016-12-02 16:50:00     5      1
*2016-12-02 16:54:00     1      1

I am using SQL Server 2012 Express. If anyone has recommendations of a good reference to learn these things, that would be great too.

A: You can use difference of ROW_NUMBERs to get the determine where the value of Item has changed and then another ROW_NUMBER from that to get the first occurrence of Code = 1:
WITH CteGrp AS(
    SELECT *,
        grp = ROW_NUMBER() OVER(ORDER BY Datetime) -
                ROW_NUMBER() OVER(PARTITION BY Item ORDER BY Datetime)
    FROM #Tbl
),
Cte AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(PARTITION BY Item, grp ORDER BY Code, Datetime)
    FROM CteGrp
)
SELECT
    Datetime, Item, Code
FROM Cte
WHERE rn = 1
ORDER BY Datetime;

ONLINE DEMO

The first CTE is a common solution to Grouping Islands of Contiguous Dates. Here is an article by Jeff Moden for explanation:

*

*Group Islands of Contiguous Dates (SQL Spackle)

A: WITH cte AS (
    SELECT
        [DateTime]
        , Item
        , Code
        , ROW_NUMBER() OVER (PARTITION BY Item ORDER BY [DateTime]) AS RowNum
)
SELECT
    [DateTime]
    , Item
    , Code
FROM
    cte
WHERE
    RowNum = 1
    AND Code = 1;

A: Try this
select min( dateTime) dateTime, item, code from (
    select dateTime, item, code from theTableName where code = 1
) code_1s
group by item, code

EDIT
To get every instance of an item where a new sequence has started .. and code = 1 is the flag for the new sequence instance ... it is a simple select statement with a where clause.
 select dateTime, item, code from theTableName where code = 1


text:
Q: Single SQL Server query to delete records in two tables I am creating a stored procedure in SSMS that would delete records in two tables at the same time (my main concern is that one of them will be deleted and if something crashes the other record is left in the database). I will pass the OrderID to my procedure.
I have two tables
Table 1: Orders
OrderID
OrderPrice

Table 2: OrdersLines
OrderID
ProductID

First I created the below procedure ant it looks like it works, but I am afraid that if something crashes I might end up with a deleted OrderLine, but not the order.
CREATE PROCEDURE [dbo].[OrdersDelete]
    (@OrderId INT)
AS
BEGIN
    DELETE FROM atbv_Sales_OrdersLines
    WHERE OrderID = @OrderId

    DELETE FROM atbv_Sales_Orders
    WHERE OrderID = @OrderId
END

So now I have created a new query, that uses inner join to assure that both records are deleted, but it says that the OL and O are invalid objects. Code below:
CREATE PROCEDURE [dbo].[OrdersDelete]
    (@OrderId INT)
AS
BEGIN
    DELETE OL, O
    FROM atbv_Sales_OrdersLines
    INNER JOIN atbv_Sales_Orders
    WHERE OL.OrderID = O.OrderID AND OL.OrderID = @OrderId
END

I would like to hear your solutions. Maybe I was right the first time, but can someone explain this to me?

A: Your first solution is perfectly acceptable with transaction:
CREATE Procedure [dbo].[OrdersDelete]
(@OrderId int)
AS
BEGIN
BEGIN TRAN
    DELETE FROM atbv_Sales_OrdersLines WHERE OrderID = @OrderId
    DELETE FROM atbv_Sales_Orders WHERE OrderID = @OrderId
COMMIT -- if we didn't encounter any errors - commit transaction. otherwise it will be rolled back automagically
END


text: Q: How to share MS Project macro? I have created a macro in my MS- Project. I am admin. Now how can I make it available to be used by other MS- Project users of my enterprise? Macro is created in Global file/template.


text:
Q: Add smileys and emoticons In FireBase Chat application I am using FireBase for chat application. I need to add smileys and emoticons in my chat application.Is it possible to do it with Firebase object.
Please help me to find this solution.

A: It's possible to store image like explained in this post : How to store and view images on firebase?
But personnaly, in your case, I would choose rather to store a simple string like :wink: and parse it on the client side to replace it with the correct image...

A: Emoticons are actually unicode characters and can be stored by their actual value.
So for example a smile face is 1F642.
There's a wiki on that topic and I think it has a chart and cross reference on it.
Edit for completeness, some quick MacOS example code, but the concept applies to lots of different code bases.
Read a character from firebase, say 1F642, which is a smiley
and then stuff it into a string that will allow it to be a unicode char.
Then, assign that string to a text field that supports unicode; NSTextField in this case.
NSString *smiley = @"\U0001F642";
self.myTextField.stringValue = smiley;


text:
Q: How to send data from BroadcastReceiver to an Activity in android? I am writing an application to listen the SMS inbox in Android with one Activity and one BroadcastReceiver.Once the SMS comes the Receiver is showing Alert message...But i want to send the message information from Receiver to Activity.I don't know how to achieve this.Anybody knows it please help me...

A:
I am writing an application to listen
  the SMS inbox in android with one
  activity and one BroadcastReceiver.

Please do not do this. This is not part of the Android SDK. Your application will break on some phones. Your application may break in future editions of Android.
But i want to send the message information from Receiver to Activity.
Send another broadcast Intent, this one a private one for use within your own application, where the Activity has registered a BroadcastReceiver (via registerReceiver()) for your private Intent.

A: You can add 'extras' to the Intent you use to start the Activity using the putExtra methods and retrieve the values using the getExtras method.
This mechanism should be used to pass small (meta-, or parameter-like) data to activities. For bigger data structures it is common to pass an Uri that identifies the data.


text:
Q: Where can I find Aerith Project source code (This question may seem off-topic but its related to my project,so please don't downvote)
While reading Filthy Rich Clients by Romain Guy and Chet Hasse, I saw the description of Aerith project and when I googled it, I found that the project's source code can be downloaded at http://www.aerith.dev.java.net/.But this link is dead.
Do you, Java programmers,have that code or please can tell me the source where I can download it.
Thanks.Waiting for a favourable response.

A: Better late than never. Have you checked this github repository - https://github.com/jsuper/aerith?


text:
Q: How to calculate the following fourier transform? How do I calculate the fourier transform of $x^2 * e^{-x^2}$
If I let $f(x) = x^2$ and $g(x) = e^{-x^2}$, my attempt has been to calculate the fourier transform of $f$ and $g$ seperately and plug them into the convolution theorem formula
$transform(f*g) = \sqrt{2\pi} * transform(f) * transform(g)$
Is this the correct way to go about it, am I using the convolution theorem correctly?

A: For any good enough function $\phi$ (like $e^{-x^2}$)
$$
\int_{\mathbb{R}}x\,\phi(x)\,e^{ix\xi}\,dx=\frac1i\int_{\mathbb{R}}\phi(x)\,\frac{d}{d\xi}\,e^{ix\xi}\,dx=\frac1i\,\frac{d}{d\xi}\int_{\mathbb{R}}\phi(x)\,e^{ix\xi}\,dx.
$$
Use twice.


text:
Q: NSTimeZone values and locale I've got Time Zone: Central European Summer Time in OS X (automatically based on location). When running my code on simulator I'm getting these results:
NSTimeZone *tz = [NSTimeZone localTimeZone]; // Gives me Local Time Zone (Europe/Warsaw (CEST) offset 7200 (Daylight))

NSString *tzString = [tz localizedName:NSTimeZoneNameStyleShortStandard
                                locale:[NSLocale currentLocale]]; // Gives me CET

Same with EDT / EST - when I set current time as EDT in System -> Preferences then appropriate methods return EST..
Am I missing something?

A: The Standard in NSTimeZoneNameStyleShortStandard specifically means the non-DST name for the time zone.
If you want to use the DST name or not depending on DST status as of some date, you'd probably have to use -isDaylightSavingTimeForDate: to decide on NSTimeZoneNameStyleShortStandard versus NSTimeZoneNameStyleShortDaylightSaving.

A: Apple warns of the use of the abbrevations for timezones. Better use the known offset to compute with
+timeZoneForSecondsFromGMT:
Use the property -daylightSavingTimeto check day light saving status.


text:
Q: In r, create a new variable in a dataframe based on lookup table with several potential matching variables I want to add a new variable cnty to dataset ANES based on matches from a lookup table. I have read through a number of related questions on here, tweaking them as well, without success.
I have a survey dataset ANES spanning many years. During different time periods, the survey used different codes to identify county of interview. The variables associated with county are named variously a1 a2 b c and fips. The fips number is what I want to pass to anes$cnty. Some observations have entries one of the aforementioned variables, and some have more than one. Some have none and will result in NA. There are more than 45,000 obs and many variables but an abridged table looks like this:
    ##ANES
    # year   female   educ  marital  partyID  a1    a2   b     c     fips
    # 1958   1        4     1        R        241   NA   NA    NA      NA
    # 1958   0        2     1        R         41   NA   NA    NA      NA
    # 1964   1        1     0        D        NA    NA   571   NA      NA
    # 1968   0        3     1        D        NA    NA   13    71041   NA
    # 1968   0        4     0        D        NA    NA   721   31007   NA
    # 1994   1        1     1        R        NA    NA   NA     NA    13089

I also have a lookup table df with 216 counties. It matches a1, a2, b, c, and fips with the county name.
    # LOOKUP
    #  a1     a2     b      c      fips
    #  241    41    131   23082    26163
    #  981     NA   571   54041    47081
    #  NA      NA     13   71041    06081
    #  451     NA     721   31007   19013
    #  NA      NA     374    44044   13089

What I am interested in is the fips -- each observation in the lookup has a fips. I am looking for code that will create anes$cnty variable and pass the fips from the lookup to cnty based on whatever variable (a1,a2,b,c,fips) that the ANES row has.
The desired result:
##ANES
    # year   female   educ  marital  partyID  cnty
    # 1958   1        4     1        R        26163
    # 1958   0        2     1        R        26163
    # 1964   1        1     0        D        47081
    # 1968   0        3     1        D        06081
    # 1968   0        4     0        D        19013
    # 1994   1        1     1        R        13089

Any suggestions would be appreciated.
As noted I have deployed numerous attempts based on suggestions from related questions here, and I'm not getting anywhere. My most recent attempt:
    anes$cnty <- ifelse(is.na(anes$a2),  as.character(lookup[match(anes$a2, lookup$a2), 'fips']),
                        ifelse(is.na(anes$a1), as.character(lookup[match(anes$a1, lookup$a1), 'fips']),
                               ifelse(is.na(anes$b), as.character(lookup[match(anes$b, lookup$b), 'fips']),
                                      ifelse(is.na(anes$c), as.character(lookup[match(anes$c, lookup$c), 'fips']),
                                             ifelse(is.na(anes$fips), as.character(lookup[match(anes$fips, lookup$fips), 'fips']), anes$cnty )))))


text:
Q: the function clone() does not work in Internet Explorer ( works in firefox) I would like to clone item of type (sortable-accordion), which u can see here:
http://jqueryui.com/demos/accordion/sortable.html.
I add cloned Item using the function clone(), as you can see here:
$("#cloneElement").click(function(){
  var newElem = $('#acc-0').clone(true).attr('id', 'acc-1').addClass("clonedDiv");
 newElem.insertBefore($("#acc-0"));
}

the div I clone looks like this:

    Section

  <fieldset  style="clear: both">
    <input type="text" name="section[]" id="section" value="">
    <textarea name="content[]" id="content" class="text ui-corner-all"></textarea>
   </fieldset>

And this is jquery button I use to add new element
<input type="radio" id="cloneElement" name="cloneElement" />

When i click on the button, the element will be cloned and added and I can see it in firefox.
This does not work in Internet Exploerer. When I click on the button nothing happend :( Why it does not work in Exploerer?


text:
Q: Switch ignores predefined case and jumps to default case First, I want to explain briefly what I am doing. I am making a disassembler, but the problem is in the prefix recognizer routine. The following function receives a byte and compare it with the prefix table. It must display a string according to the prefix. For example CS override byte display 'CS '.
But there's a problem. It works fine with almost every prefix, except LOCK, REP, and REPNE. When you enter their values to the function, it displays "UNDEF" (default case if the value has no entry in the switch statement)
But the compiler is wrong: I have a case for the three prefixes (LOCK, REP, and REPNE). I can't understand why it takes the default case ignoring the predefined cases. I have looked in the internet, but I can't find an answer to my problem.
#include <stdio.h>

///Prefixes lock and repeat (group one)

#define prefix_lock  0xF0
#define prefix_repne 0xF2
#define prefix_rep 0xF3

///Prefixes segmet override (group two)
#define prefix_cs_override      0x2E
#define prefix_ss_override      0x36
#define prefix_ds_override      0x3E
#define prefix_es_override      0x26
#define prefix_fs_override      0x64
#define prefix_gs_override      0x65

///Branch hints goes here.

///Operand-size override (group three)
#define prefix_operand_size_override    0x66

///Address-size override (group four)
#define prefix_address_size_override    0x67

int show_prefixe(FILE *my_output, char prefix){
    switch(prefix){
        case prefix_lock:
            fprintf(my_output, "LOCK ");
            break;
        case prefix_repne:
            fprintf(my_output, "REPNE ");
            break;
        case prefix_rep:
            fprintf(my_output, "REP ");
            break;
        case prefix_ss_override:
            fprintf(my_output, "SS ");
            break;
        case prefix_cs_override:
            fprintf(my_output, "CS ");
            break;
        case prefix_ds_override:
            fprintf(my_output, "DS ");
            break;
        case prefix_es_override:
            fprintf(my_output, "ES ");
            break;
        case prefix_fs_override:
            fprintf(my_output, "FS ");
            break;
        case prefix_gs_override:
            fprintf(my_output, "GS ");
            break;
        case prefix_operand_size_override:
            fprintf(my_output, "OP ");
            break;
        case prefix_address_size_override:
            fprintf(my_output, "ADDR ");
            break;
        default:
            fprintf(my_output, "UNDEF ");
            break;
    }
}

int main()
{
    FILE *output;
    output = fopen("C:\\prefix.asm", "wb");
    show_prefixe(output, prefix_rep);
    fclose(output);
    return 0;
}

Is the compiler wrong? Can it has a bug? I am using MinGW in Codeblocks.
Thanks for your help

A: Try passing unsigned char to your function. The problem should be that 0xF3 for example is 243 and you are using a (signed) char which can not support such a value.
int show_prefixe(FILE *my_output, unsigned char prefix) { ...

Further, your function is supposed to return something, so say you return 0 in the end of the switch statement.


text:
Q: Alternative to GROUP BY to consolidate repeating values in single column I'm using DB2 which apparently doesn't let you use the GROUP BY clause when it's returning more than one column. I have records that have repeating values for ID and name, for example:
EmpID  |  -   name  -   |  code
___________________________________
111111    |    Williams   |   1
---------------------------------
111111    |    Williams   |   2
----------------------------------
111112    |    Davis      |   3
---------------------------------
111113    |    Gomez      |   1
----------------------------------
111113    |    Gomez      |   3
----------------------------------

(Excuse my formatting) I need to get a single instance of each employee with a code (doesn't matter which code instance gets omitted as long as one shows up per employee).
Normally I could do:
SELECT * FROM employees GROUP BY EmpID;

DB2 doesn't let you do this for some reason. It says " The grouping is inconsistent." You can do:
SELECT EmpID from employees GROUP BY EmpID;

but if you introduce more return values then it gives you the error.
I tried looking into using a subquery and derived tables but I'm not sure how to compose it to select only one code value and exclude the records with a repeating employee value. If anyone has an answer or could point me to another thread that addresses this problem I would appreciate it very much.

A: It is required in most databases to GROUP BY each column in the SELECT list that is not in an aggregate function that is why you received an error message.
For your situation if it does not matter what code value is returned, then you can use an aggregate function and group by:
SELECT EmpID, name, MIN(code) code
FROM employees
GROUP BY EmpID, name;

See Demo
The group by is applied to both the EmpId and name, while the aggregate function is applied to the code column.

Note that due to that EmpID and name are functionally dependent on each other (as far as we can see from the sample you posted and the "repeating values" comment), the following two queries will return the same, identical results as the above query:
--- GROUP BY EmpID
------------------
SELECT EmpID, MIN(name) name, MIN(code) code
FROM employees
GROUP BY EmpID;

--- GROUP BY name
-----------------
SELECT MIN(EmpID) EmpID, name, MIN(code) code
FROM employees
GROUP BY name;


text:
Q: Исправить логику Задача: мне на вход дается число n, дело в том что это число можно получить следующим образом:
Допустим берем начальное значение x, следующее значение x + 1, следующее x + 2 и так далее.
x - натуральное число, то есть минимальное значение x = 1
Если поочередно складывать x + (x + 1) + (x + 2) + ... x + m, то гарантируется, что когда-нибудь мы получим n, основная проблема заключается в том, что количество таких членов неизвестно((
Задача заключается в том, что требуется найти минимальное значение x, при котором это задача выполнится(повторяю - гарантирутся, что оно выполнится)
Для этого я не смог вывести математику и написал перебор:
n = int(input())
nold = n
i = 0
iold = i
x = 1
xold = x
while True:
    n = n - (x + i)
    i += 1
    if n < 0:
        i = 0
        x = xold + 1
        xold = x
        n = nold
    elif n == 0:
        break
print(x)

Но, как я и ожидал программа работает слишком медленно с большими числами, можете помочь?
Было бы хорошо, если бы Вы помогли мне разобраться с математикой

A: n = 35  # 48, 50

# ax + c = n
a = 1
x = 0
c = 0

a_i = 1
c_i = 0

while (n - c) / a >= 1:
    if ((n - c) / a).is_integer():
        a_i = a
        x = (n - c) // a
        c_i = c
    c += a
    a += 1

if c != 0:
    print(' + '.join([str(x)] + ['({0} + {1})'.format(x, coeff) for coeff in range(1, a_i)]), '=', n)
else:
    print(x, '=', n)

# 2 + (2 + 1) + (2 + 2) + (2 + 3) + (2 + 4) + (2 + 5) + (2 + 6) = 35
# 8 + (8 + 1) + (8 + 2) + (8 + 3) + (8 + 4) = 50
# 15 + (15 + 1) + (15 + 2) = 48

Еще вариант:
import math

n = 3  # 34, 36, 1569

c = int(math.sqrt(n)) + 1
a = c + 1
c_n = sum(range(1, a))

if c_n == n:
    x = 1
else:
    x = n
    for c_i in range(c, 0, -1):
        if ((n - c_n) / (c_i + 1)) % 1 == 0:
            c = c_i + 1
            x = (n - c_n) // c
            break
        c_n -= c_i

if c != 0:
    print(' + '.join([str(x)] + ['({0} + {1})'.format(x, c_i) for c_i in range(1, c)]), '=', n)
else:
    print(x, '=', n)

# 1 + (1 + 1) = 3
# 7 + (7 + 1) + (7 + 2) + (7 + 3) = 34
# 1 + (1 + 1) + (1 + 2) + (1 + 3) + (1 + 4) + (1 + 5) + (1 + 6) + (1 + 7) = 36
# 259 + (259 + 1) + (259 + 2) + (259 + 3) + (259 + 4) + (259 + 5) = 1569

A: Можно немного поднатужиться, и нати все такие разложения заданного числа z. Понятно, что задача переформулируется так:
"для заданного числа zнайти такие целые n и x , что верно
z=n*x + (n-1)*n/2".  Преобразовывая, понимаем, что
x = z/n - (n-1)/2. Или другими словами n является делителем числа 2*z.
Тогда задача сводится к следующему:
найти из всех делителей числа 2*z, такие, которые удовлетворяют целочисленному уравнению  z=n*x + (n-1)*n/2".
Здесь берем код для построения списка всех делителей числа, и в итоге получаем такое решение:
Все решение сводится к следующему коду:
z = int(input("n="))

divisors_l = divisors(z*2)

for n in divisors_l[1:]:
    x = z//n - (n-1)//2
    if x<0: break
    print(f"x={x}")
    if z == n*x + (n-1)*n//2:
        print(f"yes! n={n}, x={x}")
        expantion(x,n,z)

Я использовал также код для разложения в ряд автора @slippyk.
все остальное - использование "стандартных" функций))
полный код приведен ниже.
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 22:20:39 2019

@author: Vasil
"""

from collections import Counter

def get_ls(n):
    """Разложить число на множители"""
    #result = [1]
    result = []
    i = 2
    while i*i <= n:
        if n % i == 0:
            n //= i
            result.append(i)
        else:
            i += 1
    if n > 1:
        result.append(n)
    return result

def divisors(n):
    ls = get_ls(n)
    kkk = dict(Counter(ls)).items()

    d = [k for k, _ in kkk]
    m = [v for _, v in kkk]
    k = [0 for _ in range(len(set(ls)))]

    result = []
    ln = range(len(m))

    try:
        while True:
            r = 1
            for i1, i2 in zip(d, k):
                r *= i1 ** i2
#            print(r)
            result.append(r)

            k[0] += 1
            for i in ln:
                if k[i] > m[i]:
                    k[i] = 0
                    k[i+1] += 1  # IndexError
    except IndexError:
        pass
    return sorted(result)

#divisors_l = divisors(int(input("n=")))

def expantion(x,c,n):
    if c != 0:
        print(' + '.join([str(x)] +  \
            ['({0} + {1})'.format(x, c_i) for c_i in range(1, c)]),
            '=', n)
    else:
        print(x, '=', n)

z = int(input("n="))

divisors_l = divisors(z*2)

for n in divisors_l[1:]:
    x = z//n - (n-1)//2
    if x<0: break
    print(f"x={x}")
    if z == n*x + (n-1)*n//2:
        print(f"yes! n={n}, x={x}")
        expantion(x,n,z)

Это решение дает например:
n=1569
x=784
yes! n=2, x=784
784 + (784 + 1) = 1569
x=522
yes! n=3, x=522
522 + (522 + 1) + (522 + 2) = 1569
x=259
yes! n=6, x=259
259 + (259 + 1) + (259 + 2) + (259 + 3) + (259 + 4) + (259 + 5) = 1569

или для 50:
n=50
x=25
x=11
yes! n=4, x=11
11 + (11 + 1) + (11 + 2) + (11 + 3) = 50
x=8
yes! n=5, x=8
8 + (8 + 1) + (8 + 2) + (8 + 3) + (8 + 4) = 50
x=1

A: Ответ @VasylKolomiets также интересен тем, что можно сделать некоторые выводы о том, какими должны быть z, n и x, сокращая время на перебор.
посмотрите на формулу x = z/n - (n-1)/2
Чтоб х было целым должны выполняться условия:

*

*n четным быть не может, а потому перебирать требуется только нечетные. Более того, нас интересуют только простые, чтоб потом проверить частное от деления z на них. А когда ищем простые, то гораздо быстрее будет двигаться по числам из ряда (2*3*m)+-1

*поскольку х должен быть больше нуля, z>(n-1)n/2, или 2z>n(n-1), то есть n должен быть меньше sqrt(2z)+1, так что от него и можем стартовать перебор.

*наконец, z обязан нацело делиться на n, то есть нужно просто идти по ряду простых чисел в поисках делителей. Идти потребуется от самого большого из возможных n (помним, что задача найти наименьший х, а это достигается при наибольшем n), то есть стартуем от n = sqrt(2z)+1 вниз, к 1
Поставьте, пож., плюсик @VasylKolomiets, поскольку это выводы из его расчета.


text:
Q: SharePoint 2010 CAML Query fails when indexed columns used I have an SPQuery that has been working fine until my list hit 500 items:
q.Query = "<Where><Eq><FieldRef Name='DefectID' /><Value Type='Counter'>" + DefectID + "</Value></Eq></Where>";

This was successfully returning 1 item where DefectID matched my provided value.
Once the list hits 500 items, the query returns 0 items, no error message, no exception. If I delete 1 item and take the list down to 499 items, it works again.
The list had individual item permissions, but as part of my debugging I have reset the role inheritance of the list and also every item in the list.
I have tried providing a row limit of 2, and 2000, same result.
Have tried Query override throttling, same result. Changed the web app throttle limits to way above my lists number of items, and change the large query window to 24hrs, same result.
The column I am querying has an index on it (I am expecting about 30k+ items per year in this list). If I delete the index the query then works when items in the list are > 500. If I create the index again, the query then returns 0.

A: I've just been looking around this to see if I could help and came across this article from Microsoft: http://msdn.microsoft.com/en-us/library/ee558807.aspx.  It seems to indicate that only under certain conditions are indexed columns used to your advantage.  Admittedly this is a slightly different scenario from what you've described (it uses the ContentIterator class) but thought it may add to the mix. :)

A: I solved a similar problem by switching my CAML comparison value type query against the WorkflowInstanceID from Type="Text" to Type="Guid". Perhaps you could change your value type to Integer like so:
    q.Query = "<Where><Eq><FieldRef Name='DefectID' /><Value Type='Integer'>" + DefectID + "</Value></Eq></Where>";

It seems an indexed Lookup is better queried as an Integer:
http://blackninjasoftware.com/2009/05/12/why-should-indexing-a-sharepoint-field-break-your-caml-query/
So, why not try the same solution for your Counter field as well?

A: Check the RowLimit on the query. If not set, then set it and see what happens.
The RowLimit Gets or sets a limit for the number of items returned in the query per page.
Ex.
<RowLimit>600</RowLimit>

A: We used 'Number' for the type and this resolved the 500 limit issue.


text:
Q: Rails 3: Can't get this jquery working on my form I found a jquery snippet of code for counting down the characters when you type in a form. I've tried adding it to my application.js file but its not working. When I type in the textarea the number 350 doesn't change.
I've already installed jquery-rails and I use <%= javascript_include_tag :all %> so that shouldn't be the issue. Here's what I have in my application.js
$('textarea').keyup(function(){
    ta = $(this);
    if(ta.val().length >= 350){
        ta.val( ta.val().substr(0, 350) );
    } else {
        $("#counter span").text(350-ta.val().length);
    }
});

setInterval('$("#counter span").text(350-ta.val().length);', 350);

In my view I have :
<%= form_for @post, :validate => true, :html => {:multipart => true} do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>

      <%= f.label :title, 'Title:' %>

    <%= f.text_field :title %>

    <%= f.label :image, "Choose image"%>

    <%= image_tag(@post.image_url(:avatartiny).to_s) if @post.image? %>
    <%= f.file_field :image %>
    <%= f.hidden_field :image_cache %>

    <%= f.label :content %>

    <%= f.text_area :content %>

350 characters remaining.

    <%= f.submit "Submit" %>

<% end %>

And in my custom.css I have:
textarea {
   width:400px;
   height:400px;
   border:1px solid #999;
   border-radius:3px;
   padding:7px;
}

#counter span { font-weight:700 }

Here is what my html source says:
    <form accept-charset="UTF-8" action="/posts" class="new_post" data-validate="true"
enctype="multipart/form-data" id="new_post" method="post" novalidate="novalidate">
<input name="utf8" type="hidden" value="✓" /><input
 name="authenticity_token" type="hidden" value="V6J0VERvuoKvQ5kXXgBuU5aC6VsKQ7W6RF30IKy9D7E="/>

      Title:

<input data-validate="true" id="post_title" name="post[title]" size="30" type="text" />

Choose image

<input data-validate="true" id="post_image" name="post[image]" type="file" />
<input id="post_image_cache" name="post[image_cache]" type="hidden" />

Content

<textarea cols="40" id="post_content" name="post[content]" rows="20"></textarea>

350 characters remaining.

A: Wrap your textarea binding in a document.ready binding:
$(function() {
    $('textarea').keyup(function(){
        ta = $(this);
        if(ta.val().length >= 350){
            ta.val( ta.val().substr(0, 350) );
        } else {
            $("#counter span").text(350-ta.val().length);
        }
    });
});

Does that work?

A: There's nothing wrong with your javascript so maybe try putting your code inside a
$(document).ready(function(){

});

block.


text:
Q: $onInit not getting called for typescript angularjs controller In the below Controller the $onInit() is never called. Please let me know how to ensure $onInit is called. Is there something I need to do bind $onInit for this controller.
Do I need to bind the $onInit to the this object rather than having it as class level function.
import * as angular from "angular";
import { IChangePasswordService } from '../../partials/ChangePassword/IChangePasswordService'

declare var module: any;
declare var require: any;
export interface IEmailChangePassword extends ng.IScope {
    initialPasswordChange: Function;
 }

export class EmailChangePasswordController implements ng.IOnInit {

    static $inject = ["$scope", "$mdDialog", "$timeout", "$location", "$state", "ChangePasswordService","common.svcs.modalService"];
    $mdDialog: any;
    $timeout: any;
    state: string = 'getInput';
    $scope: IEmailChangePassword;
    modalService: any;
    ChangePasswordService: IChangePasswordService;
    $location: ng.ILocationService;
    $state: any;

    constructor($scope: IEmailChangePassword, $mdDialog: any, $timeout: any, $location: ng.ILocationService, $state: any, ChangePasswordService: IChangePasswordService, modalService:any) {
        this.$mdDialog = $mdDialog;
        this.$scope = $scope;
        $scope.initialPasswordChange = this.initialPasswordChange.bind(this);
        this.$timeout = $timeout;
        this.modalService = modalService;
        this.ChangePasswordService = ChangePasswordService;
        this.$location = $location;
        this.$state=$state;
    }

    $onInit(): void {
       console.log("inside On Init");
    }

    public initialPasswordChange(): void {
       ...

    }
}

module.exports = function (app) {
    app.controller("EmailChangePasswordController", EmailChangePasswordController);
}

I am using Typescript with angularjs here. Thank you so much in advance.

A: $onInit is a hook of component lifecycle in AngularJS.
https://docs.angularjs.org/guide/component
It will fire when you'll have this controller assigned to a component, and use
this component somewhere.
You should have component like:
export class EmailChangePasswordComponent {
    controller = EmailChangePasswordController;
    templateUrl = "email-change-password.html";
}

You should register it:
app.component("emailChangePassword", EmailChangePasswordComponent)

You can assign this component to state in a config:
$stateProvider.state("stateName", {
    url: "/stateUrl",
    component: "emailChangePassword"
});

Or just use in html:
<email-change-password></email-change-password>

And $onInit will fire when state is initialized, or when component is being renderd.
Difference between constructor and $onInit is that $onInit will fire only when Element is constructed (you can manipulate DOM element by $element) and when all bindings (inputs to component) are initialized.


text:
Q: I am trying categorize data based on multiple column in pandas? I have following new_correlation dataframe which contain following input
| Engagement Index | High Impact |
|------------------|-------------|
| 3.14             | 48.0        |
| 4.15             | 31.0        |
| 4.20             | 40.0        |

My condition is
def priority_driver(corr, high_impact):
    if corr > 0.4 & high_impact > 40:
        return 'Sustenance'
    elif corr > 0.4 & high_impact < 40:
        return 'Improvement'
    elif corr < 0.4 & high_impact > 40:
        return 'Distraction'
    elif corr < 0.4 & high_impact < 40:
        return 'Low Focus'

I tried new_correlation['Priority of action'] = new_correlation.apply(lambda x: priority_driver(x['Engagement Index'], x['High Impact']), axis =1)
This gives me

TypeError: ("unsupported operand type(s) for &: 'float' and 'float'", 'occurred at index 0')

Required output:
| Engagement Index | High Impact | Priority of action |
|------------------|-------------|--------------------|
| 0.72             | 48.0        | Sustenance         |
| 0.74             | 31.0        | Improvement        |
| 0.78             | 40.0        | Sustenance         |

A: You should write
if (corr > 0.4) & (high_impact > 40)

Alternatively, this should also work (and IMO is more readable):
if corr > 0.4 and high_impact > 40

A: Note that there is also a possibility to do that with with numpy select which would look something like that :
import pandas as pd

df = pd.DataFrame({'A' : pd.np.random.choice([.2, .3, .4, .5, .6, .7], 200),
                   'B' : pd.np.random.randint(30, 50, 200)})

conds = [ (df['A'] >= .4) & (df['B'] >= 40),
          (df['A'] >= .4) & (df['B'] < 40),
          (df['A'] <= .4) & (df['B'] >= 40),
          (df['A'] <= .4) & (df['B'] < 40) ]

cond_resp = ['Sustenance', 'Improvement', 'Distraction', 'Low Focus']

df['C'] = np.select(conds, cond_resp)


text:
Q: Can you easily switch between using amazon's load balancer service and doing your own on ec2? If you have clients who are using your service, and pointing to your domain like:
api.example.com

If I use route 53 to manage the dns for the domain, am I able to seamlessly choose if I want to use amazon's load balancers or do this myself by running haproxy?  (servers are on ec2 also ofcourse).
Or will this require a dns change that will bring things down for a while?

A: It would require a DNS change, but you could run both in parallel while the DNS rolls over so it's seamless for end-users. You can also drop the TTL on the DNS record to something like 60 seconds to minimize the rollover time.


text:
Q: React doesn't rerender component if already rendered once I have a component called ChildComponent which I call from ParentComponent as below. Point to be noted:

*

*There is a button "Show Child".

*On the first Click of this button it should do a fresh rerender of the child component. But on Subsequent clicks, it should not even Call ChildComponent but instead fetch the dom from this.refs. For this I am using return this.refs.chid which gives error

Below is the code.
ParentComponent= React.creatClass({
  getInitialState: function(){
    return {
      rendered: false
    }
  },
  render_or_cache: function(){
    if (this.state.rendered){
      return this.refs.child;
    }
    else {
      return <ChildComponent/>
    }
  },
  onbuttonclick: function(){
    this.setState({rendered: true})
  },
  render:function(){
    return (

        {this.render_or_cache()}

      <button onClick={this.onbuttonclick()}>Show Child Again</button>
    )
  }
})

ChildComponent= React.creatClass({
  render:function(){
    return (

Some Text from Child

    )
  }
})

A: You have to store your component inside state
Try out this
Code:
ParentComponent= React.creatClass({
getInitialState: function(){
   return {
             childComponent :[]
          }
},

onbuttonclick: function(){
   this.setState({childComponent.concat(<ChildComponent/>)})
}
render:function(){

return (

           {this.state.childComponent}

     <button onClick={this.onbuttonclick()}>Show Child Again</button>
)}
})

ChildComponent= React.creatClass({
render:function(){

return (

Some Text from Child

)}
})

A: You have some inconsistencies in your term usage.
Mounting is when a component didn't use to exist, and then exists. Mounting starts from initial state and includes a render.
Rerendering happens when the properties/state of a component change, but the component hierarchy does not change. This preserves the component state.
I'm not sure how you're trying to accomplish what you say by returning this.refs.child. A simple way to accomplish a single-time effect like this is to simply conditionally render the element, like so:
render:function(){
const child = (this.state.rendered) ? <ChildComponent/> : ""

return (

           {child}

     <button onClick={this.onbuttonclick()}>Show Child Again</button>
)}
})

Do note that in this approach, changing rendered from true to false will cause ChildComponent to unmount, losing the state of that component instance. I imagine in most cases this would be wanted behavior.

A:
When to Use Refs
There are a few good use cases for refs:
Managing focus, text selection, or media playback. Triggering
  imperative animations. Integrating with third-party DOM libraries.
  Avoid using refs for anything that can be done declaratively.
For example, instead of exposing open() and close() methods on a
  Dialog component, pass an isOpen prop to it.

https://facebook.github.io/react/docs/refs-and-the-dom.html
For your purpose you can use conditional rendering by checking your state and deciding which component you should render.
https://facebook.github.io/react/docs/conditional-rendering.html
Hope it helps.

A: It seems to me that you're jumping hoops to achieve something that React already does really well; determine when to re-render your component and when to update the DOM.
If you know better than React when to re-render a component, you can define a shouldComponentUpdate(nextProps, nextState) method on your component that takes the next props and state of your component and returns true or false based on your own rules.
See the lifecycle methods in the React documentation: https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate


text:
Q: Unmatched app urls when trying to publish to Chrome Store I'm getting the following error when I try to publish:
This hosted web app has one or more app urls not owned by the developer.
The web_url of this hosted web app is not owned by the developer.
I am getting the green warning box as described in:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=1520
However, I'm hitting the refresh button and no joy in the solving the problem.  I've published a lot of apps scripts in the past and never had this issue.

A: You have to register your url with the Google webmaster tools program and they will give you code to fix this. In case you have already done that, just go and verify again. It happened to me as well and I had to verify the site again. It works!


text:
Q: Как запретить работу скрипта? Как по нажатию на input запретить или разрешить выполнение скрипта?
<input class="checkbox" type="checkbox" id="news" name="news" value="1">
Скрыть новости

$('.boxx').each(function(){
   if($(this).find('a').hasClass('viewsfull')){
   $(this).hide()
   }
})

A: Мне кажется, вы немного не поняли задачу. Код выполняется единожды, а не постоянно. Когда вы скрываете новости, это одно действие, и когда оно завершено, ничего фактически не происходит. Чтобы показать снова новости, вам нужно еще один раз выполнить скрипт, который покажет новости.
Например вы ставите обработчик события на checkbox news:
$('#news').on('change', function(){
...здесь ваш код...
})

Этот скрипт будет выполнятся каждый раз, когда вы ставите и убираете галочку в checkbox. И после выполнения браузер не будет выполнять никаких скриптов, до тех пор, пока не получит следующее событие.
Писать еще один обработчик события не нужно, нам нужно в этом-же определить, нажата галочка или нет:
$('#news').on('change', function(){
    if($(this).is(':checked')){
         //галочка нажата, скрываем новости
    }else{
         //галочка не нажата, показываем новости
    }
})

Далее мы ставим ваш код:
$('#news').on('change', function(){
    if($(this).is(':checked')){
         //галочка нажата, скрываем новости
         $('.boxx').each(function(){
            if($(this).find('a').hasClass('viewsfull')){
               $(this).hide()
            }
         })
    }else{
         //галочка не нажата, показываем новости
    }
})

А если мы нажимаем уже второй раз, $("this").is(':checked') будет уже не верно, и там нужно новости показать, возьмем тот-же код, но заменим hide() на show()
$('#news').on('change', function(){
    if($(this).is(':checked')){
         //галочка нажата, скрываем новости
         $('.boxx').each(function(){
            if($(this).find('a').hasClass('viewsfull')){
               $(this).hide()
            }
         })
    }else{
         //галочка не нажата, показываем новости
         $('.boxx').each(function(){
            if($(this).find('a').hasClass('viewsfull')){
               $(this).show()
            }
         })
    }
})

Рабочий пример:

$('#news').on('change', function() {
  if ($(this).is(':checked')) {
    //галочка нажата, скрываем новости
    $('.boxx').each(function() {
      if ($(this).find('a').hasClass('viewsfull')) {
        $(this).hide()
      }
    })
  } else {
    //галочка не нажата, показываем новости
    $('.boxx').each(function() {
      if ($(this).find('a').hasClass('viewsfull')) {
        $(this).show()
      }
    })
  }
})

<input class="checkbox" type="checkbox" id="news" name="news" value="1">
Скрыть новости

Новость

Есть еще одна функция, которая упростит скрипт: toggle() Она скрывает объекты, если они видимы и показывает, если они скрыты. Т.е все можно упростить до такого:
$('#news').on('change', function(){
         $('.boxx').each(function(){
            if($(this).find('a').hasClass('viewsfull')){
               $(this).toggle()
            }
         })
})

Pavel Mayorov также указал на то, что проще использовать селектор :has, чтобы сразу найти блоки, имеющие ссылку с определенным классом:
$('#news').on('change', function(){
         $('.boxx:has(a.viewsfull)').toggle()
})

A: Чтоб код выполнялся только при условии, то создайте это условие.
Например вы можете накинуть функцию на событие, например изменение в input.

$('#input').on('input', function() {
  console.log(this.value);
});

<input id="input" type="text">


text:
Q: Changing the original collection while looping in vba I have a collection like this:
Dim BrokerCol as New Collection
'Added some data to the Collection
BrokerCol .Add temp_broker, BROKER_NAME

And I am looping through the collection like this:
For Each collectionitem In BrokerCol
 If ((collectionitem.Bid - bid_average) / bid_average) < pThresholdValue Then
     'Want to change something here in BrokerCol instead of Collection Item
 Else
Next collectionitem

As said, above I want to change something in the BrokerCol instead of changing the Collection Item. How do I do that?
I tried this:
BrokerCol.Item(CollectionItem).Bid = 1

It gives me an 'Type Mismatch' Error. Not sure how to solve this.

A: Have you tried just using
collectionitem.bid = 1

It's the same object as is in the collection.

A: What are you trying to change in the BrokerCol?  Isn't that a standard vb collection?


text:
Q: SVG to stretch at the biggest dimension and then fill the rest I have a SVG that I want to use as a background for body.
What CSS should I use if I want my background to stretch at the biggest dimension and then fill the rest, like this:

*

*Case 1: If the browser's viewwidth > viewheight, to make svg take the height of viewport, keep the aspect ratio(it' s 1:1), and then repeat on the horizontal untill the body is fully covered.

*Case 2:  If the browser's viewwidth < viewheight(usually mobile version of a website), to make svg take the width of viewport, keep the aspect ratio(it' s 1:1), and then repeat on the vertical untill the body is fully covered.

I am trying to obtain this without JS, but if it's not possible, JS is a way to go too. Thank you!

A: You'll need JS for the viewport comparisons but from there you can use cover or contain for the background-size prop.


text:
Q: Azure Keyvault library to Atlassian Confluence plugin pom.xml I am trying to combine these 2 tutorials - Confluence Hello World Macro & Azure keyvault quick start:
https://developer.atlassian.com/server/framework/atlassian-sdk/create-a-confluence-hello-world-macro/
https://learn.microsoft.com/en-us/azure/key-vault/secrets/quick-create-java?tabs=azure-cli
After having added the 2 Azure dependencies to the pom.xml of the maven project and running atlas-mvn clean package I receive an error message about 3 banned dependencies.
I looked for the newest Azure packages at the maven portal. Then it was reduced to one.
Found Banned Dependency: org.slf4j:slf4j-api:jar:1.7.25
Then I added added exclusions to the dependency section:
This resulted that the build ran successfully, however, the Confluence plugin produces a runtime error:
java.lang.NoClassDefFoundError
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/Logger
at com.azure.security.keyvault.secrets.SecretClientBuilder.(SecretClientBuilder.java:110)
Can you please help, how can I achieve this?

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-security-keyvault-secrets</artifactId>
    <version>4.3.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.4.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

A:
error: java.lang.NoClassDefFoundError Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/Logger at com.azure.security.keyvault.secrets.SecretClientBuilder.(SecretClientBuilder.java:110)

The above error indicates that JVM is not able to found org/slf4j/Logger class in your application's path.The simplest reason for this error is the missing Slf4j.jar file.

*

*If the problem is caused due to the missing slf4j.jar file then you can fix it by adding a relevant version of slf4j.jar into your path.

*Use the latest version of the jar in which version of the JAR file you should add will depend upon the application.

In  Maven , you can also add the following dependency in your pom.xml file to download sl4j.jar
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.36</version>
</dependency>

Reference:
java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory - Stack Overflow