text:
Q: How do I pass an XTensor array by reference so that I can modify it in-place? I am using the C++ library XTensor. I want to modify an array in-place in a function.
void modifyXArray(xt::xarray<double>& arr) {
    arr += 1;
}

However when using this function:
auto tmp = xt::linspace(0, 1, 100);
modifyXArray(tmp);

I get the error:
/home/tom/src/xtensor-interp/tests/test_interpolator.cpp: In member function 'virtual void Foo_Bar_Test::TestBody()':
/home/tom/src/xtensor-interp/tests/test_interpolator.cpp:92:18: error: cannot bind non-const lvalue reference of type 'xt::xarray<double>&' {aka 'xt::xarray_container<xt::uvector<double, std::allocator<double> >, xt::layout_type::row_major, xt::svector<long unsigned int, 4, std::allocator<long unsigned int>, true>, xt::xtensor_expression_tag>&'} to an rvalue of type 'xt::xarray<double>' {aka 'xt::xarray_container<xt::uvector<double, std::allocator<double> >, xt::layout_type::row_major, xt::svector<long unsigned int, 4, std::allocator<long unsigned int>, true>, xt::xtensor_expression_tag>'}
   92 |     modifyXArray(tmp);
      |                  ^~~
In file included from /home/tom/src/xtensor-interp/XTensorInterp/XTensorInterp/interpolator.h:11,
                 from /home/tom/src/xtensor-interp/tests/test_interpolator.cpp:1:
/home/tom/src/xtensor-interp/build/Release/_deps/xtensor-src/include/xtensor/xarray.hpp:501:12: note:   after user-defined conversion: 'xt::xarray_container<EC, L, SC, Tag>::xarray_container(const xt::xexpression<E>&) [with E = xt::xgenerator<xt::detail::arange_generator<double, int, double>, int, std::array<long unsigned int, 1> >; EC = xt::uvector<double, std::allocator<double> >; xt::layout_type L = xt::layout_type::row_major; SC = xt::svector<long unsigned int, 4, std::allocator<long unsigned int>, true>; Tag = xt::xtensor_expression_tag]'
  501 |     inline xarray_container<EC, L, SC, Tag>::xarray_container(const xexpression<E>& e)
      |            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/tom/src/xtensor-interp/tests/test_interpolator.cpp:85:39: note:   initializing argument 1 of 'void modifyXArray(xt::xarray<double>&)'
   85 | void modifyXArray(xt::xarray<double>& arr) {
      |                   ~~~~~~~~~~~~~~~~~~~~^~~

I can pass in an array by reference if I mark it as const, but then I cant modify it.

A: tmp isn't an xt::xarray it's a builder that can automatically be converted to an array. When you pass it to modifyXArray it tries to do this conversion (see after user-defined conversion: 'xt::xarray_container... in the error message) but the conversion returns a temporary (rvalue) and you can't bind a temporary to a non-const reference (even if you did the temporary would be thrown away and your original variable wouldn't be modified). You need to force the conversion to an array before you pass to modifyXArray, this is as simple as not using auto:
xt::xarray<double> tmp = xt::linspace(0, 1, 100);
modifyXArray(tmp);

The conversion now happens when you construct tmp and you now have a non-temporary array that you can pass to modifyXArray


text:
Q: How to save Angular global variable in my application I am new to Angular 2 + applications. I want to use some global objects in my Angular 5 application. I have some angular components like this:

*

*MapConponenet

*LayersComponent

*ZoomComponent

My MapConponenet will be created, when application start and it will create a global map object. And my other components will use that map object.
LayerComponent and ZoomComponent needs map object and does not work without map object. So I could not decade where can I store this global map object using angular 2+ applications.

*

*Should I use a global variable?

*Should I create a service?

*Should I use a browser localstorege?

A: You can create a service file and declare the object in file .
by the injecting the service file you can easily access the object all over the project.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wrap an X amount of taxonomy posts in a separate Row in Wordpress I am trying to create a slider with taxonomy post categories and its Posts so the structure will look like this
Row 1
    First Category Title
      First category Post Title Goes Here
    Second Category Title
      Second category Post Title Goes Here
Row 2
    Third Category Title
      Third category Post Title Goes Here
    Fourth Category Title
      Fourth category Post Title Goes Here

So what i tried currently for getting the taxonomy category and its posts is teh below snippet

                    <?php
                        $post_type = 'clients';
                        $taxonomies = get_object_taxonomies(array( 'post_type' => $post_type));
                        foreach($taxonomies as $taxonomy) :
                            $terms = get_terms($taxonomy);
                            foreach($terms as $term) : ?>

<?php echo $term->name; ?>
                                <?php
                                $args = array(
                                    'post_type' => $post_type,
                                    'posts_per_page' => -1,  //show all posts
                                    'tax_query' => array(
                                        array(
                                            'taxonomy' => $taxonomy,
                                            'field' => 'slug',
                                            'terms' => $term->slug,
                                        )
                                    )
                                );
                                $posts = new WP_Query($args);
                                if($posts->have_posts()): ?>

                                <?php  while($posts->have_posts() ) : $posts->the_post(); ?>

<?php  echo get_the_title(); ?>

                                <?php endwhile; endif; ?>

                            <?php endforeach;
                        endforeach;
                    ?>

But could not manage to create the separating part with a div so i wrap every row with X amount of uls in a div.
ANy ideas how i achieve this?

A: This should get you pretty close. The key is to use iterating loops and check which iteration you're on to determine whether or not to output a new
, open or close a
, etc.
Note that one you are in a loop, you can just use the_permalink() and the_title() because the query already grabbed them, no need to echo get_the_title() etc.

<?php
    $post_type = 'clients';
    $taxonomies = get_object_taxonomies(array('post_type' => $post_type));
    foreach($taxonomies as $taxonomy) :
        $terms = get_terms($taxonomy);
        for($t=1; $t<=count($terms); $t++) {
            // if "t" is 1 or a multiple of 7, start a new row
            if($t == 1 || $t%7 == 0) { ?>
<?php }
                // if "t" is 1 or a multiple of 4, start a new list
                if($t == 1 || $t%4 == 0) { ?>
<?php } ?>

                    <a href="<?php echo get_term_link($term->term_id); ?>"><?php echo $term->name; ?>
                    <?php
                    $args = array(
                        'post_type' => $post_type,
                        'posts_per_page' => -1,  //show all posts
                        'tax_query' => array(
                            array(
                                'taxonomy' => $taxonomy,
                                'field' => 'slug',
                                'terms' => $term->slug,
                            )
                        )
                    );
                    $posts = new WP_Query($args);
                    if($posts->have_posts()) : ?>

                        <?php while($posts->have_posts() ) : $posts->the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                        <?php endwhile; ?>

                    <?php endif; ?>

            <?php // if "t" is a multiple of 3, or the very last item, close the list
            if($t%3 == 0 || $t == count($terms)) { ?>
<?php
            // if "t" is a multiple of 6, or the very last item, close the row
            if($t%6 == 0 || $t == count($terms)) { ?>
<?php
        }
    endforeach; ?>


text:
Q: Slow INSERT .. ON DUPLICATE KEY UPDATE query with InnoDB Basically I am monitoring slowest query on a website. It turns out they are something like:
INSERT INTO beststat (bestid,period,rawView) VALUES ( 'idX' , 2012 , 1 )
   ON DUPLICATE KEY UPDATE rawView = rawView+1

Basically it's a logging table. If the row is already there it updates rawView with a +1
beststat is InnoDB so I have row-level locking and consindering I do a lot of inserts-updates it should be faster than MyISAM.
Anyway that query shouldn't take so long, maybe there is something else wrong. What it could be ?
Of course I have an Unique Index on bestid, period
Additional Info
This table (beststat) currently has ~1mil record and its size is: 68MB.  I have 4GB RAM and innodb buffer pool size = 104,857,600. Mysql: 5.1.49-3
CREATE TABLE `beststat` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `bestid` int(11) unsigned NOT NULL,
 `period` mediumint(8) unsigned NOT NULL,
 `view` mediumint(8) unsigned NOT NULL DEFAULT '0',
 `rawView` mediumint(8) unsigned NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`),
 UNIQUE KEY `bestid` (`bestid`,`period`)
) ENGINE=InnoDB AUTO_INCREMENT=2020577 DEFAULT CHARSET=utf8

Notice to faster thing a litte bit i could do somethijng like:
UPDATE beststat SET rawView = rawView + 1 WHERE bestid = idX AND period = 2012;
if (mysql_affected_rows()==0)
  INSERT INTO beststat (bestid,period,rawView) VALUES ('idX',2012,1)

So most of time i would run only the first query UPDATE. But I would like to understand why the first, more concise, query is slow.

I found this interesting article... still reading

A: dealing with big # of rows, i suggest to use load date infile to make query faster.
To further improve the query time, you can consider using memory table as well.


text:
Q: Regex pattern match only the first two times General question
How do you prevent a regex match if that pattern has been matched N number of times previously?
Specific example
I have a 13 digit record identifier the user will type into a text field, such as "123-456-7891011".
The behavior I'm attempting to encapsulate is to add a dash before the 4th and 7th digits as they are typed. I have all the javascript around handling the event with no issues.
It will always be numeric - I handle that before this particular step.
I'm able to get the regex down well enough to insert the dash when I type the n+4th digit every time. What I need is for it to not do that any time after the second "-"
The closest I have in my event handler (oninput) so far is:
var addDash = /([^\-\d{3}]*\d{3})(\d+)/;
this.value = this.value.replace(addDash, "$1-$2");

For example, typing "1234567891011" results in "123-456-789-101-1", where what I want is "123-456-7891011".
There are probably other ways to handle this situation (like split and join) but for purposes of this question let's stick to answering with correct regex pattern, if such a pattern is possible. There are other things happening that would make having this pattern very useful - I just haven't had luck fathoming it out.

For clarity, this pattern will be run oninput on the text field - the match should work for any length of characters between 1 and 13:
"123456" -> "123-456"
"123456789" -> "123-456-789"
"1234567891011" -> 123-456-7891011"

A: Use callbacks.

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

A solution specific to your current need would be to alter the pattern and always go for a full match:
this.value = this.value.replace(/^(\d{3})-?(\d{3})?-?(\d*)$/, function (m, a, b, c) {
    return b ? a + "-" + b + "-" + c : a + "-" + c;
});

Job done.
If you want a more generic solution, you could use a counter variable:
var count = 0;
this.value = this.value.replace(/(\d{3})-?/g, function (m, a) {
    return ++count <= 2 ? a + "-" : m;
});

This one uses a pattern that is less accurate for what you need, but it's there to demonstrate how you could generalize to different situations where you really need to limit the number of replacements.

By the way, you have a syntax misunderstanding: [^\-\d{3}] does not mean what you think. It will match a single character that is not a digit or either of those: -, { or }. Everything inside [...] brackets defines a character class, therefore quantifiers such as {n} are meaningless there.

A: You can use a callback within replace with some logic on how to handle the delimiters. This will make it easier to get the behavior you are expecting.

var values = ['12', '123', '123-4', '123-45', '123-456', '123-456-7', '123-456-7891011'];
var addDash = /^(\d{3})-?(\d?\d?\d?)-?(\d*)/;
values.forEach(function(value) {
  value = value.replace(addDash, function(match, capture1, capture2, capture3) {
    var secondDelimiter = capture2.length == 3 ? '-' : '';
    return capture1 + '-' + capture2 + secondDelimiter + capture3;
  });

})
console.log(values)

A: Using regex without additional JS:
var addDash = /^((\d{3}\-?)(\d{3}\-?)?)(\d)$|^(\d{3})(\d)$/;
this.value = this.value.replace(addDash, "$1$5-$4$6");

Starting as the beginning of the string, match 3 digits with an optional "-", and optionally 3 more digits, followed immediately by a final digit at the end of the string. If that doesn't match, see if the string starts with 3 digits followed immediately by a final digit at the end of the string.
Get a little funky with the capture groups in the replace string to accomplish the desired format.

A: $(function() {
    var txt='1232';
    var addDash = /^(\d{3})-?(\d?\d?\d?)-?(\d*)/;
    $("#test").html(txt.replace(addDash, function(match, capture1, capture2, capture3) {
        var firstDelimiter = (capture1.length == 3 && capture2.length > 0) ? '-' : '';
        var secondDelimiter = (capture2.length == 3 && capture3.length > 0) ? '-' : '';
        return capture1 + firstDelimiter + capture2 + secondDelimiter + capture3;
    }));
})


text:
Q: How to assign subnet to a vlan on softlayer? For softlayer api SoftLayer_Network_Subnet, the description says:
Every SoftLayer ip address is associated with a subnet which is defined in the SoftLayer_Network_Subnet service. SoftLayer subnets define a group of ip addresses and are assigned to a SoftLayer_Network_Vlan.
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Subnet
I'm trying to find the api which can assign subnet to a vlan or just build relations between subnet and vlan, but with no luck.
Q1: Is there any api that can assign subnet to vlan?
Also I have another question about network/subnet/vlan. When creating a virtual server without subnet option, IP still will be  allocated to this virtual server. What method is used to determine the subnet and allocate this IP to virtual server?
Really appreciate if someone can provide information.

A: when you order a VLAN also you order its subnet, now when you order a subnet you can attach it to a vlan, you can do that for "Portable Public", "Portable Private" and "Portable Public IPv6"  subnets. As you can see you can assing a subnet to a vlan at the order moment there no any method to assing them after you performed the order.
here a simple example about the subnet order
"""
Orders a new portable public subnet

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder/
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder/

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer
# For nice debug output:
from pprint import pprint as pp

API_USERNAME = 'set me'
API_KEY = 'set me'

# Order Template with all new item configurations

orderTemplate = {
    'location': 224092,    # Singapore 1
    'packageId': 0,
    'endPointVlanId': 527900,
    'prices': [
        {
            'id': 13980
        }
    ],
    'quantity': 1,
    'itemCategoryQuestionAnswers': [
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 14,
            'answer': 1    # TOTAL_IPS_IN_30_DAYS
        },
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 15,
            'answer': 3    # TOTAL_IPS_IN_12_MONTHS
        },
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 16,
            'answer': 'Test description of your need for additional IPs'     # REASON_FOR_IPS
        },
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 9,
            'answer': 'ContactNameTest'    # CONTACT_NAME
        },
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 10,
            'answer': 'ContactJobTitleTest'    # CONTACT_JOB_TITLE
        },
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 11,
            'answer': 'contact.email@myemail.com'    # CONTACT_EMAIL
        },
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 12,
            'answer': '72878781'    # CONTACT_PHONE_NUMBER
        },
        {
            'categoryId': 313,
            'categoryCode': 'sov_sec_ip_addresses_pub',
            'questionId': 13,
            'answer': True    # CONTACT_VALIDATED
        }
    ],
    'complexType': 'SoftLayer_Container_Product_Order_Network_Subnet'
}

# Creates a new connection to the API service.
client = SoftLayer.Client(
    username=API_USERNAME,
    api_key=API_KEY
)

try:
    result = client['SoftLayer_Product_Order'].verifyOrder(orderTemplate)
    pp(result)
except SoftLayer.SoftLayerAPIError as e:
    pp('Failed ... Unable to order the new item faultCode=%s, faultString=%s'
        % (e.faultCode, e.faultString))

and this is a more complete code to order subnets of any kind:
"""
Order a new subnet.

The script order a new subnet using the same options like the portal.

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getAllObjects
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Subnet/getSubnetForIpAddress
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getNetworkVlans
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Network_Subnet
http://sldn.softlayer.com/blog/bpotter/Going-Further-SoftLayer-API-Python-Client-Part-3
http://sldn.softlayer.com/article/Object-Filters
http://sldn.softlayer.com/article/Python
http://sldn.softlayer.com/article/Object-Masks

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""

import SoftLayer
import json

# The subnet you wish to order. The available options are the
# same like in the in the Softlayer Portal.
# e.g. "1 Static Public IP Address",
# "/64 Block Static Public IPv6 Addresses", etc.
option = "Global IPv6"

# The endpoint IP address for the subnet.
# You need to configure this field if
# your order belongs to the categories
# "Static Public" or "Static Public IPv6"
# e.g. "119.81.142.114", "2401:c900:1201:9c::2".
endPointIP = "119.81.142.114"

# The VLan number for the subnet.
# You need to configure this field if
# your order belongs to the categories
# "Portable Public", "Portable Private" and
# "Portable Public IPv6".
vlanNumber = 758

client = SoftLayer.Client()
packageService = client['SoftLayer_Product_Package']
subnetService = client['SoftLayer_Network_Subnet']
orderService = client['SoftLayer_Product_Order']
accountService = client['SoftLayer_Account']

# Declaring an object filter to get the packages
# related to subnets.
objectFilter = {
    "type": {
        "keyName": {
            "operation": "in",
            "options": [{
                "name": "data",
                "value": [
                    "ADDITIONAL_SERVICES",
                    "ADDITIONAL_SERVICES_PORTABLE_IP_ADDRESSES",
                    "ADDITIONAL_SERVICES_STATIC_IP_ADDRESSES"
                ]
            }]
        }
    }
}

# Declaring an object mask to get more information about the packages
objectMask = "mask[items[id, description, prices[id, recurringFee, attributes, categories]]]"

# Getting the items and the prices available to order subnets
try:
    packages = packageService.getAllObjects(filter=objectFilter,
                                            mask=objectMask)

except SoftLayer.SoftLayerAPIError as e:
    print("Unable to list the packages. faultCode=%s, faultString=%s" %
          (e.faultCode, e.faultString))
    exit(1)

# Getting item price for the configured option to order.
optionItem = {}
optionPackage = 0
for package in packages:
    for item in package['items']:
        if item['description'] == option:
            prices = []
            if len(item['prices']) > 1:
                for price in item['prices']:
                    if len(price['attributes']) == 0:
                        if 'recurringFee' in price:
                            prices.append(price)
                            item['prices'] = price
                            break
            optionItem = item
            optionPackage = package['id']
            break
    if 'id' in optionItem:
        break

if not 'id' in optionItem:
    print("The configured option: " + option + " is not valid.")
    exit(1)

# Verifying if the configured option requires a VLan or end point IP.
requireVlan = False
requireIp = False
for category in optionItem['prices'][0]["categories"]:
    cat = category['categoryCode']
    if cat == "static_sec_ip_addresses" or cat == "static_ipv6_addresses":
        requireIp = True
    if (cat == "sov_sec_ip_addresses_pub" or
       cat == "sov_sec_ip_addresses_priv" or cat == "sov_ipv6_addresses"):
        requireVlan = True
    break

# Getting the IP address object.
ip = {}
if requireIp:
    try:
        objectMask = "mask[ipAddresses]"
        subnet = subnetService.getSubnetForIpAddress(endPointIP,
                                                     mask=objectMask)
        if not 'id' in subnet:
            print("There is no a IP address " + endPointIP +
                  " in the subnets of the account.")
            exit(1)
        else:
            for ipSubnet in subnet['ipAddresses']:
                if ipSubnet['ipAddress'] == endPointIP:
                    ip = ipSubnet
                    break
    except SoftLayer.SoftLayerAPIError as e:
        print("Unable to find the subnet. faultCode=%s, faultString=%s"
              % (e.faultCode, e.faultString))
        exit(1)

# Getting the VLan.
vlan = {}
if requireVlan:
    try:
        objectFilter = {
            "networkVlans": {
                "vlanNumber": {
                    "operation": vlanNumber
                }
            }
        }
        vlans = accountService.getNetworkVlans(filter=objectFilter)
        if len(vlans) == 0:
            print("There is no a VLan number " + str(vlanNumber) +
                  " in the account.")
            exit(1)
        else:
            vlan = vlans[0]
    except SoftLayer.SoftLayerAPIError as e:
        print("Unable to retrieve the VLans. faultCode=%s, faultString=%s" %
              (e.faultCode, e.faultString))
        exit(1)

# Creating the order template for the subnet
orderTemplate = {
    'packageId': optionPackage,
    'prices': optionItem['prices'],
    'quantity': 1,
    'complexType': 'SoftLayer_Container_Product_Order_Network_Subnet'
}

if requireVlan:
    orderTemplate['endPointVlanId'] = vlan['id']
elif requireIp:
    orderTemplate['endPointIpAddressId'] = ip['id']

try:
    # verifyOrder() will check your order for errors. Replace this with a call
    # to placeOrder() when you're ready to order. Both calls return a receipt
    # object that you can use for your records.
    result = orderService.verifyOrder(orderTemplate)
    print(json.dumps(result, sort_keys=True, indent=2, separators=(',', ': ')))
except SoftLayer.SoftLayerAPIError as e:
    print("Unable to place the order. faultCode=%s, faultString=%s" %
          (e.faultCode, e.faultString))

In regards your another question always a IP is assigned to your machine even if you did not configure any.
you can see this article about how to pick the VLAN that you want in your order:
http://sldn.softlayer.com/blog/phil/CCI-VLAN-Specification
To assing the VLAN to your machine you only can do that proccess at order time, if you want to changa the vlan after the order you need to submit an ticket to softlayer and ask them.
Once you have the VLAN you can list its subnets and pick the subnet that you want for that see:
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Vlan/getSubnets
Here an example about how to order a VSI + subnets
https://$user:$apiKey@api.softlayer.com/rest/v3/SoftLayer_Product_Order/placeOrder

Method: Post

{
   "parameters":[
      {
         "orderContainers":[
            {
               "hardware":[
                  {
                     "hostname":"testhost",
                     "domain":"softlayer.com",
                     "primaryBackendNetworkComponent":
                        {
                           "networkVlanId":971077,
                           "networkVlan":{
                              "primarySubnet":{
                                 "id":225652
                              }
                           }
                        }
                     ,
                     "primaryNetworkComponent":
                        {
                           "networkVlanId":971075,
                           "networkVlan":{
                              "primarySubnet":{
                                 "id":233232
                              }
                           }
                        }

                  }
               ],
               "location":"DALLAS05",
               "quantity":1,
               "packageId":46,
               "prices":[
                  {
                     "id":1640
                  },
                  {
                     "id":1644
                  },
                  {
                     "id":1857
                  },
                  {
                     "id":1639
                  },
                  {
                     "id":50367
                  },
                  {
                     "id":273
                  },
                  {
                     "id":2302
                  },
                  {
                     "id":55
                  },
                  {
                     "id":58
                  },
                  {
                     "id":420
                  },
                  {
                     "id":418
                  },
                  {
                     "id":21
                  },
                  {
                     "id":57
                  },
                  {
                     "id":905
                  }
               ]
            }
         ]
      }
   ]
}


text:
Q: Chrome Extensions: Running Different .js Files Depending on What Site You're On? I'm new to chrome extensions but I have a question concerning content scripts.
I want to execute a specific js file if the user accesses a specific domain, and another different js file if they access a different one.
My question is, how can I do this inside the manifest.json file?
This is what I have so far:
    "content_scripts":
         [{"matches": ["http://store.example.com/*"], "js": ["store.js"]}],
         [{"matches": ["https://purchase.example.com/*"], "js": ["purchase.js"]}]

    "permissions":["tabs", "http://store.example.com/*"]

But I keep getting an error. Thank you!!

A: The format of your content_scripts declaration is incorrect. Try this:
"content_scripts": [
    {"matches": ["http://store.example.com/*"], "js": ["store.js"]},
    {"matches": ["https://purchase.example.com/*"], "js": ["purchase.js"]}
],


text:
Q: Recursion to iteration conversion using dynamic programming     public static int n;
    public static int w;
    public static int[] s;
    public static int[] p;

    static void Main(string[] args)
    {
        n = 5;
        w = 5;

        s = new int[n + 1];
        p = new int[n + 1];
        Random rnd = new Random();

        for (int i = 1; i <= n; i++)
        {

            s[i] = rnd.Next(1, 10);
            p[i] = rnd.Next(1, 10);
        }

        Console.WriteLine(F_recursion(n, w));
        Console.WriteLine(DP(n, w));
    }

    // recursive approach
    public static int F_recursion(int n, int w)
    {
        if (n == 0 || w == 0)
            return 0;
        else if (s[n] > w)
            return F_recursion(n - 1, w);
        else
        {
            return Math.Max(F_recursion(n - 1, w), (p[n] + F_recursion(n - 1, w - s[n])));
        }
    }

    // iterative approach
    public static int DP(int n, int w)
    {
        int result = 0;

        for (int i = 1; i <= n; i++)
        {

            if (s[i] > w)
            {
                continue;
            }
            else
            {
                result += p[i];
                w = w - s[i];
            }
        }

        return result;
    }

I need to convert F_recursion function to iterative. I currently written following function DP that sometimes works but not always. I learned that problem is in  F_recursion(n - 1, w - s[n]) I have no idea how to make w - s[n] work correctly in iterative solution. If change w - s[n] and w - s[i] to only w then program always work.
In Console:
s[i] = 2 p[i] = 3
-------
s[i] = 3 p[i] = 4
-------
s[i] = 5 p[i] = 3
-------
s[i] = 3 p[i] = 8
-------
s[i] = 6 p[i] = 6
-------
Recursive:11
Iteration:7

but sometimes it works
s[i] = 5 p[i] = 6
-------
s[i] = 8 p[i] = 1
-------
s[i] = 3 p[i] = 5
-------
s[i] = 3 p[i] = 1
-------
s[i] = 7 p[i] = 7
-------
Recursive:6
Iteration:6

A: The following approach might be useful, when bigger numbers are involved (specially for s) and consequently a 2 dimensional array would be unnecessary big and only a few w values would actually be used in computing the result.
The idea: precompute possible w values, by starting at w and for each i in [n, n-1, ..., 1] determine the values w_[i], where w_[i+1] >= s[i] without duplicates.
Then iterate i_n over n and compute sub-results only for valid w_[i] values.
I chose an array of Dictionary as datastructure, since it's relatively easy to design sparse data this way.
public static int DP(int n, int w)
{
    // compute possible w values for each iteration from 0 to n
    Stack<HashSet<int>> validW = new Stack<HashSet<int>>();
    validW.Push(new HashSet<int>() { w });
    for (int i = n; i > 0; i--)
    {
        HashSet<int> validW_i = new HashSet<int>();
        foreach (var prevValid in validW.Peek())
        {
            validW_i.Add(prevValid);
            if (prevValid >= s[i])
            {
                validW_i.Add(prevValid - s[i]);
            }
        }
        validW.Push(validW_i);
    }

    // compute sub-results for all possible n,w values.
    Dictionary<int, int>[] value = new Dictionary<int,int>[n + 1];
    for (int n_i = 0; n_i <= n; n_i++)
    {
        value[n_i] = new Dictionary<int, int>();
        HashSet<int> validSubtractW_i = validW.Pop();
        foreach (var w_j in validSubtractW_i)
        {
            if (n_i == 0 || w_j == 0)
                value[n_i][w_j] = 0;
            else if (s[n_i] > w_j)
                value[n_i][w_j] = value[n_i - 1][w_j];
            else
                value[n_i][w_j] = Math.Max(value[n_i - 1][w_j], (p[n_i] + value[n_i - 1][w_j - s[n_i]]));
        }
    }

    return value[n][w];
}

It's important to understand that some space and computation is "wasted" in order to precompute possible w values and to support the sparse data structures. So this approach might perform bad for large data sets with small values in s, where most w values will be possible sub-results.
After some more thought I realized, if space is a concern, you can actually throw away the sub-results of everything except the previous outer loop iteration, since the recursion in this algorithm follows a strict n-1 pattern. However, I'm not including this into my code for now.

A: Your approach does not work because your dynamic programmig state space (which apparently is only one variable) does not match the signature of the recursive method. The goal of the dynamic programming approach should be to define and fill a state space such that all results for evaluation are available when needed. On inspection of the recursive method, notice that the recursive calls of F_recursion may change both arguments, n and w. This is an indication that a two-dimensional state space should be used.
The first argument (which apparently limits the range of items) can range from 0 to n while the second argument (which apparently is some bound for the total of an item property) can range from 0 to w.
You should define a two dimensional state space
int[,] value = new int[n,w];

for accomodation of the values. Next, you should initialize the values to undefined; you can use the value Int32.MaxValue for this, because it will behave in a suitable way if the minimum with some different value is calculated.
Next, the iterative version of the algorithm shoud use two loops which iterate in a forwad manner, unlike the recursive iteration which decreases the arguments.
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < w; j++)
    {
        // logic for the recurrence relation goes here
    }
}

In the innermost block you can use a modified version of the recurrence relation. Instead of using recursive calls, you access values which are stored in value; instead of returning values, you write the values to value.
Semantically this is the same as memoization, but instead of using actual recursive calls, the order of evaluation asserts that necessary values always exist, making additional logic unneccessary.
Once the state space is filled, you have to examine its last state (namely the part of the array where the first index is n-1) to determine the maximal value for the entire input.


text:
Q: Factory method pattern & data abstraction in C++ I try to implement the Factory Method Pattern in C++ while keeping a good level of abstraction. In the sample provided in the link, all derived classes are in the same file, but this is usually not the case.

*

*Without header files for derived classes:
To keep implementation details, I didn't provide a header file for the derived class (declaration & definition in the source file), then I don't see how to implement the factory method because the derived classes are not visible and forward declaration is not possible.

*With header files for derived classes:
I can implement the factory method, but the implementation details of derived classes leak because the private members and methods have to be declared in the header.
Maybe using the PImpl idom can help to solve the problem in case 2) but I wonder if this is correct/reasonable approach. What is the usual/best way to implement this pattern in C++ ?
Here is my code:
//graphic-api.hpp

class GraphicApi {
public:

    enum class Type {
        //OPENGL,
        //DIRECTX,
        VULKAN
    };

    virtual void render() = 0;
    virtual ~GraphicApi() {};

    static std::unique_ptr<GraphicApi> make(const Window& window, Type type);

};

//graphic-api.cpp

//need to include headers for derived classes
std::unique_ptr<GraphicApi> GraphicApi::make(const Window& window, GraphicApi::Type type) {
    switch (type) {
    case GraphicApi::Type::VULKAN:
        return std::make_unique<VulkanApi>(window);
    default:
        assert(0 && "Unsupported Graphic API");
    }
    return nullptr;
}

//vulkan-api.hpp
class VulkanApi : public GraphicApi {
public:
    VulkanApi(const Window& window);
    virtual void render() {};

private:

    // lot of private members & methods related to Vulkan API (not nice to see here)
    vk::UniqueInstance instance;
    ...
};


text:
Q: How can I get allowedConferenceSolutionTypes "eventHangout" in the Calendar creation response? When I insert calendar with allowedConferenceSolutionTypes "eventHangout" using Calendar API but a response is provided "hangoutsMeet" but as per Google Calendar API response should be provided "eventHangout".
Request for creating calendar:
POST https://www.googleapis.com/calendar/v3/calendars?key=[YOUR_API_KEY] HTTP/1.1
Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
Content-Type: application/json
{
"summary": "Event Hangout",
"conferenceProperties": {
"allowedConferenceSolutionTypes": [
"eventHangout"
]
}
}
Response:
{
"kind": "calendar#calendar",
"etag": ""ZK9fcme_JbF_CB4WYnKnXWUeuYw"",
"id": "1n9qoe2np18slfqoq1sjd0lh3o@group.calendar.google.com",
"summary": "Event Hangout",
"timeZone": "UTC",
"conferenceProperties": {
"allowedConferenceSolutionTypes": [
"hangoutsMeet"
]
}
}
How can I get allowedConferenceSolutionTypes "eventHangout" in the Calendar creation response?
it's always return "allowedConferenceSolutionTypes":["hangoutsMeet"]
Not eventHangout

A: It is not possible to set/modify the calendar's allowedConferenceSolutionTypes property.
When creating a new calendar using Calendars.insert() you need to supply a Calendar resource in the request body having the summary as a required property
If you will check other properties available for the Calendar resource, conferenceProperties is not a writable property. Hence you cannot modify that property.

See notes column to identify writable properties.


text:
Q: DataTable jQuery plugin not showing anything I've been trying to get DataTable to work with my MVC 5 project, but I've had no luck. No CSS is showing on the headers of the columns to even show a hint of DataTable working. I've been working on this for about two days now with no success. Any help is appreciated, thanks!
@model IEnumerable<BlahBlahBlah.Models.tbl_Reg_User>

@{
ViewBag.Title = "Index";
}
@section Scripts{

<link rel="stylesheet" type="text/css" href="~/Content/DataTables-1.10.3/css/jquery.dataTables.css">

}

User List

    @Html.ActionLink("Create New", "Create")

@using (Html.BeginForm("CheckBoxAction", "User"))
{
    <input type="submit" name="deactivateButton" value="Deactivate Selected Users" onclick="location.href'@Url.Action("CheckBoxAction", "User")'" />
    <input type="submit" name="activateButton" value="Activate Selected Users" onclick="location.href'@Url.Action("CheckBoxAction", "User")'" />

                    Select Users

                    @Html.DisplayNameFor(model => model.ID)

                    @Html.DisplayNameFor(model => model.department)

                    @Html.DisplayNameFor(model => model.FirstName)

                    @Html.DisplayNameFor(model => model.LastName)

                    @Html.DisplayNameFor(model => model.Email)

                    @Html.DisplayNameFor(model => model.UserName)

            @foreach (var item in Model)
            {

                        <input type="checkbox" name="ids" id="ids" value="@item.ID" />

                        @Html.DisplayFor(modelItem => item.ID)

                        @Html.DisplayFor(modelItem => item.department)

                        @Html.DisplayFor(modelItem => item.FirstName)

                        @Html.DisplayFor(modelItem => item.LastName)

                        @Html.DisplayFor(modelItem => item.Email)

                        @Html.DisplayFor(modelItem => item.UserName)

                        @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                        @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                        @if (item.suspended)
                        {
                            @Html.ActionLink("Activate", "Activate", new { id = item.ID })
                        }
                        else
                        {
                            @Html.ActionLink("Deactivate", "Deactivate", new { id = item.ID })
                        }

            }

    <input type="submit" name="deactivateButton" value="Deactivate Selected Users" onclick="location.href'@Url.Action("CheckBoxAction", "User")'" />
    <input type="submit" name="activateButton" value="Activate Selected Users" onclick="location.href'@Url.Action("CheckBoxAction", "User")'" />
}

@*<input type="button" value="Deactivate" onclick="location.href'@Url.Action("CheckBoxDeactivate", "User")'" />
    <input type="button" value="Activate" onclick="location.href'@Url.Action("CheckBoxActivate", "User")'" />*@

A: Verify if all the .css and .js file are present at the path mentioned in the View.


text:
Q: Strange behavior with complex Q object filter queries in Django Hi I am trying to write a tagging system for Django, but today I encountered a strange behavior in filter or the Q object (django.db.models.Q).
I wrote a function, that converts a search string into a Q object. The next step would be to filter the TaggedObject with these query. But unfortunately I get a strange behavior.
search for only one Tag element:
when I search (id=20) =>
Q: (AND: ('tags__tag__id', 20))
and it returns 2 Taged Objects with the ID 1127 and 132
when I search (id=4) =>
Q: (AND: ('tags__tag__id', 4))
and it returns also 2 Objects, but this time 1180 and 1127
here is the reluting SQL query:
SELECT "django_content_type"."id", "django_content_type"."name", "django_content_type"."app_label", "django_content_type"."model"
FROM "django_content_type"
WHERE ("django_content_type"."model" = slogan  AND "django_content_type"."app_label" = slogans )
ORDER BY "django_content_type"."name" ASC

SELECT "slogans_slogan"."id", "slogans_slogan"."headline", "slogans_slogan"."text", "slogans_slogan"."author"
FROM "slogans_slogan"
  INNER JOIN "htags_objecttagbridge" ON ("slogans_slogan"."id" = "htags_objecttagbridge"."object_id")
WHERE ("htags_objecttagbridge"."tag_id" = 4  AND "htags_objecttagbridge"."content_type_id" = 9 )
LIMIT 21

search for two tags with 'or' conjunction:
until here is everything fine, but when i make a little bit more complex query like (id=4) or (id=20) =>
Q: (OR: ('tags__tag__id', 4), ('tags__tag__id', 20))
then it returns 4(!) Objects 1180, 1127, 1127, 132
and the SQL:
SELECT "slogans_slogan"."id", "slogans_slogan"."headline", "slogans_slogan"."text", "slogans_slogan"."author"
FROM "slogans_slogan"
  INNER JOIN "htags_objecttagbridge" ON ("slogans_slogan"."id" = "htags_objecttagbridge"."object_id")
WHERE ((("htags_objecttagbridge"."tag_id" = 4 AND "htags_objecttagbridge"."content_type_id" = 9 ) OR "htags_objecttagbridge"."tag_id" = 20 ) AND "htags_objecttagbridge"."content_type_id" = 9 )
LIMIT 21

But the object with the ID 1127 is returned twice, but thats not the behaviour I want. Do I have to live with it, and uniqify that list or can I do something different. The representation of the Q object looks fine for me.
search for two tags 'and' conjunction
But the worst is now, when I search for (id=20) and (id=4) =>
Q: (AND: ('tags__tag__id', 20), ('tags__tag__id', 4)) then it returns no object at all. But why? The representation should be ok and the object with the id 1127 is tagged by both. What am I missing?
here is the SQL again:
SELECT "slogans_slogan"."id", "slogans_slogan"."headline", "slogans_slogan"."text", "slogans_slogan"."author"
FROM "slogans_slogan"
  INNER JOIN "htags_objecttagbridge" ON ("slogans_slogan"."id" = "htags_objecttagbridge"."object_id")
WHERE ("htags_objecttagbridge"."tag_id" = 4  AND "htags_objecttagbridge"."content_type_id" = 9  AND "htags_objecttagbridge"."tag_id" = 20 )
LIMIT 21

[edit]:
I now realize, that this SQL statement is wrong. At least not what I want, because here it wants, that one ObjectTagBridge has the id 4 and at the same time the id 20. But in my case these are 2 different
Here are also the relevant parts of the classes, that are involved:
class TaggedObject(models.Model):
    """
        class that represent a tagged object
    """
    tags = generic.GenericRelation('ObjectTagBridge',
                                   blank=True, null=True)

class ObjectTagBridge(models.Model):
    """
        Help to connect a generic object to a Tag.
    """
    # pylint: disable-msg=W0232,R0903
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    tag = models.ForeignKey('Tag')

class Tag(models.Model):
    ...

Thanks for your help

A: For problem 1 (uniqueness): you're going to want to make your query distinct.  The duplication is expected behavior for that type of query unless you make it distinct.
For problem 2, you're probably hitting a subtle but important part of how querysets work.  If you make a query like this:
mymodel.objects.filter(tags__tag__id=4, tags__tag__id=5)

You are querying for a model that has a single tag which has both id=4 and id=5, which is of course no tag.  But if you instead query like this:
mymodel.objects.filter(tags__tag__id=4).filter(tags__tag__id=5)

you get models which have some tag somewhere with id=4 and some tag somewhere with id=5.  The same will hold with Q objects -- they will need to be split into separate filter or exclude calls to not be referring to a single Tag relation.  This is documented here.


text:
Q: how to To specify initial conditions for a system of ode? I have the following system of ode:
a = {{-3, 1}, {-1, -5}}; eqns =
 Thread[{y1'[x], y2'[x]} == a.{y1[x], y2[x]} + {1, 1}];
I solved the general solution for a system of ode. However, I cannot specify the initial conditions for y(0)=(0,0)?
this is what I tried:
DSolve[{{y1[x] == y[x],
   y2[x] == y[x]}, {{y1[0], y2[x]} == {0, 0}}}, {y1[x], y2[x]}, x]
and how to plot the solution?
Thank you so much!


text:
Q: How to bind nested json configuration to options in .net core In .net core if we have to bind the configuration directly from Json configuration as shown below
{
  "AzureAdJwtSettings": {
    "Authority": "https://login.microsoftonline.com/tenantid",
  },
  "WebSecJwtSettings": {
    "Authority": "https://example.com",
  }
}

we can write something like this
configuration.Bind("AzureAdJwtSettings", options);

I am looking to find a way so that I can group my json configuration in such a way
{
  "JwtSettings": {
    "AzureAdJwtSettings": {
      "Authority": "https://login.microsoftonline.com/tenantid"
    },
    "WebSecJwtSettings": {
      "Authority": "https://example.com"
    }
  }
}

But when I try to load the configuration in my code it didn't load properly.. I am using the below code
configuration.Bind("JwtSettings.AzureAdJwtSettings", options);

I know there must be way to load nested properties but couldn't find it working...

A: As per suggested comments, the format should use colon (:) instead of dot (.) with keys for configuration option binding to work
For example
configuration.Bind("JwtSettings:AzureAdJwtSettings", options);


text:
Q: How to delete database datas while using custom adapter? I have customized listview in my AnaMenu activity and this listview has created by my database datas. I am trying to delete in my database all datas and I want to go MainActivity. When user"s click at the action bar logo.All datas will be deleted but When I try ,I get error message.My database has 4 columns.There is another important thing ; My AnaMenu activity has this. How can I fix it ?
This:(at my MainActivity.)
mDatabaseHelper = new DatabaseHelper(this);
        Cursor data = mDatabaseHelper.getData();
        sayı = data.getCount();

        if (sayı > 4){
            Intent i = new Intent(MainActivity.this,AnaMenu.class); startActivity(i);
            MainActivity.this.finish();
        }

How to create my custom adapter (at my AnaMenu activity) :
 while(data.moveToNext()){

            listDataId.add(data.getString(0));

            listData.add(data.getString(1));

            listDatanumber.add(data.getString(2));

            listDataoran.add(data.getString(3));

        }
        liste.setAdapter(oyunTextView);

    }

    class OyunTextView extends BaseAdapter {

        @Override
        public int getCount() {

            return  listData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.oyuntextview, null);
            TextView namesbox = (TextView) convertView.findViewById(R.id.isim);
            sayılar = (TextView) convertView.findViewById(R.id.sayı);
            namesbox.setText(listData.get(position));
            sayılar.setText(listDataoran.get(position));

            return convertView;
        }
    }

My database method :
public void deleteAllName(int id, String name ,String numara, String oran){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                + COL1 + " = '" + id + "'"  + COL2 + " = '" + name  + COL3 + " = '"+ numara +
                " AND "  + COL4 + " = '" + oran  + "'";
        Log.d(TAG, "deleteName: query: " + query);
        Log.d(TAG, "deleteName: Deleting " + name + " from database.");
        db.execSQL(query);
    }

It is my code for logo icon:
  private void geri() {
      for (int d = 0 ; d<listDatanumber.size() ; d++) {
        int  id = Integer.parseInt(listDataId.get(d));
          String  isim = listData.get(d);
          String number = listDatanumber.get(d);
         String oran =   listDataoran.get(d);
         mDatabaseHelper.deleteAllName(id,isim,number,oran);
     }

        Intent ii = new Intent(AnaMenu.this, MainActivity.class);
        startActivity(ii);
        AnaMenu.this.finish();

    }

A: You have to add AND condition between your matching values and also '" + name has no matching '
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                + COL1 + " = '" + id   + "' AND "
                // AND clause             ^^^^^
                + COL2 + " = '" + name + "' AND "
                //  matching '            ^
                + COL3 + " = '"+ numara +"' AND "
                + COL4 + " = '" + oran  + "'";

Note : you can just delete a row using some unique column value or can make your id as  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL


text:
Q: Spring OAuth2 redirect to original URL on successful auth I'm able to successfully complete the OAuth auth, however am struggling with working how to then send the request back to the original requested URL. An example scenario is as follows:
Incoming request to: /some-protected-resource
As the user is not authorised yet we complete the OAuth flow.
As per the AbstractAuthenticationProcessingFilter docs the user is redirected back to webapp root when I don't have a AuthenticationSuccessHandler specified however I would like to redirect them back to whatever URL they originally requested.
I've tried specifying the SavedRequestAwareAuthenticationSuccessHandler however it doesn't seem like the OAuth requests go through the ExceptionTranslationFilter.

A: The default behavior is exactly what you want to achieve, so it might be that you customized the authorization process so it redirects you to the root.
Provide more details on your configuration.


text:
Q: How to generate time in milliseconds in PostgreSQL stored procedure? I have been reading the Postgres documentation about timestamps, but I am still a little bit confused.
I need to store moments in times, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC (like those defined in Java, but I am not using Java).
If I read the documentation properly, I believe I have to use CURRENT_TIMESTAMP, because it includes the timezone. Correct?
Can someone explain how to create a stored procedure that will convert this timestamp into the milliseconds I want (and the reverse function too)?
Motivation: I understand one could use something like EXTRACT on CURRENT_TIMESTAMP when selecting rows, but this conversion would be more expensive than storing the time in milliseconds. I am ready to store my moments into a bigint. It would be faster to compare moments or to compute time differences.

A:
I understand one could use something like EXTRACT on CURRENT_TIMESTAMP when selecting rows

You don't need extract in order to get the data:
select *
from your_table
where timestamp_column >= timestamp '2007-08-24 18:34:01';

will happily use an index on moment_in_time and will be very efficient - in fact there will be no difference in performance compared to
select *
from your_table
where milliseconds_column >= 1187906400000;

Now look at the two statements and tell me for which one you immediately understand what the query will return.
If you do need those milliseconds in your application then you can always do something like this:
select some_col,
       other_col,
       extract(epoch from timestamp_column) * 1000 as millis
from your_table
where timestamp_column >= timestamp '2007-08-24 18:34:01';

And again, I'm almost 100% certain that you won't see any performance difference to:
select some_col,
       other_col,
       milliseconds_column
from your_table
where  milliseconds_column >= 1187906400000;

Plus: if you do store the milliseconds and you want to display the real date, you always need to apply an additional conversion:
select some_col,
       other_col,
       to_char(timestamp_column, 'yyyy-mm-dd') as the_date
from your_table
where timestamp_column >= timestamp '2007-08-24 18:34:01';

vs.
select some_col,
       other_col,
       to_char(to_timestamp(milliseconds_column / 1000), 'yyyy-mm-dd) as the_date
from your_table
where  milliseconds_column >= 1187906400000;

The second one one be slower than the first one, but it's more typing and makes the code harder to read.
Edit:

 how to create a stored procedure that will convert this timestamp into the milliseconds I want (and the reverse function too)?

You don't need to write your own function:

*

*convert timestamp to milliseconds: extract(epoch from current_timestamp) * 1000 + extract(milliseconds from current_timestamp)

*convert milliseconds to timestamp: to_timestamp(1187980443530 / 1000)

So to wrap it up:
Go with a timestamp column and don't worry about performance.


text:
Q: Scala encode multipart/form-data body I'm trying to send file in multipart/form-data request.
My problem is that on server side (in my case PHP) file contents are twice bigger than expected.
How should I convert the data?
My code is
val boundary = randomBoundary

val CrLf = "\r\n"
val body = (
  for (fileInfo ← files)
  yield s"--$boundary${CrLf}Content-Disposition: form-data; name=AttachedFile1; filename=${fileInfo.fileName}$CrLf$CrLf" +
    s"Content-Type: application/octet-stream$CrLf$CrLf" +
    new String(fileInfo.data) // fileInfo.data has type Array[Byte]
).mkString(CrLf) + s"$CrLf--$boundary--"

A: Don't use Strings to send binary data; Strings are UTF-8 encoded character data on the JVM.
You want an Array[Byte], which is easily emitted (to a target server) by any java.io.OutputStream.

A: I found an answer!
class DispatchTest extends FunSpec {

   import dispatch.classic./\
   import dispatch.classic.mime.Mime.MimeRequestTerms
   import dispatch.classic._

   val fi = new File("/Users/alexkvak/kr1.jpg")
   val fileContent = Files.readAllBytes(fi.toPath)

   val multiPart = new MimeRequestTerms(/\) <<*("party-file", "FileName.jpg", fileContent)

   // some post data
   multiPart << Map("fieldName" → "fieldValue")

   val r = multiPart.copy(host = new HttpHost("localhost"), path = "/upload.php")

   Http(r as_str)
}


text:
Q: Quitar parpadeo de animation timing function tenia una duda. Quería conseguir que el fondo de mi web cambiara usando keyframes. Por ello usé animation-timing-function: step-start;. El problema es que sí que cambia, pero en cada cambio hay un horrible parpadeo blanco, como si se quitara la imagen y se viera el fondo. Me gustaría que no se produciera ese parpadeo. Este es mi código de CSS:
body{
    margin: 0;
}

#container{
   position: absolute;
   width: 100%;
   min-height: 100%;
   margin: 0 auto;
   background-image: url("../IMAGES/cancha.png");
   background-size: cover;
   background-repeat: no-repeat;
   animation-timing-function: step-start;
   animation-name: animacion;
   animation-fill-mode: forwards;
   animation-duration: 10s;
}

@keyframes animacion {
  0% {
    background-image: url("../IMAGES/cancha1.png");
    animation-timing-function: steps(1, start);
  }

  7% {
    background-image: url("../IMAGES/cancha2.png");
    animation-timing-function: steps(1, start);
  }

  15% {
    background-image: url("../IMAGES/cancha3.png");
    animation-timing-function: steps(1, start);
  }

  22% {
    background-image: url("../IMAGES/cancha4.png");
    animation-timing-function: steps(1, start);
  }

  29% {
    background-image: url("../IMAGES/cancha5.png");
    animation-timing-function: steps(1, start);
  }

  36% {
    background-image: url("../IMAGES/cancha6.png");
    animation-timing-function: steps(1, start);
  }

  43% {
    background-image: url("../IMAGES/cancha7.png");
    animation-timing-function: steps(1, start);
  }

  50% {
    background-image: url("../IMAGES/cancha8.png");
    animation-timing-function: steps(1, start);
  }

  57% {
    background-image: url("../IMAGES/cancha9.png");
    animation-timing-function: steps(1, start);
  }

  63% {
    background-image: url("../IMAGES/cancha10.png");
    animation-timing-function: steps(1, start);
  }

  70% {
    background-image: url("../IMAGES/cancha11.png");
    animation-timing-function: steps(1, start);
  }

  77% {
    background-image: url("../IMAGES/cancha12.png");
    animation-timing-function: steps(1, start);
  }

  84% {
    background-image: url("../IMAGES/cancha13.png");
    animation-timing-function: steps(1, start);
  }

  91% {
    background-image: url("../IMAGES/cancha14.png");
    animation-timing-function: steps(1, start);
  }

  100% {
    background-image: url("../IMAGES/cancha.png");
    animation-timing-function: steps(1, start);
     }
  }
}

Y este mi código de HTML y JavaScript (sé que el código de javascript son solo mensajes por consola así que dudo de que sea el problema, pero lo pongo por si acaso). Supongo que el error estará en animation-timing-function: step-start; pero no sé como solucionarlo:
<!DOCTYPE html>

    <title>BASKETBALL</title>

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

En caso de que tengáis alguna duda sobre el código no dudéis en preguntármela. Gracias

Hola, que navegador estás usando? Podrías fijarte si en un navegador distinto tiene el mismo desperfecto por favor? – Genarito

Estoy usando Chromium y en Chrome me pasa lo mismo.En firefox no lo he probado porque no sé que cosas he de modificar para que funcione.
Las imágenes son todas 1000x544 y todas pesan casi lo mismo, entre 580KB y casi 600KB. Tengo un MSI con un procesador Intel i-7, así que supongo que sí que tiene la potencia suficiente para cargar las imágenes.

A: En lugar hacer una animación modificando el fondo, podrías hacer una animación modificando imágenes dentro del contenedor.
Ejemplo:

@keyframes fadeInOut {
  0% {
    opacity:1;
  }
  17.5% {
    opacity:1;
  }
  25% {
    opacity:0;
  }
  92.5% {
    opacity:0;
  }
  100% {
    opacity:1;
  }
}
#container {
  position:relative;
  height:281px;
  width:450px;
  margin:0 auto;
  overflow: hidden;
}
#container img {
  position:absolute;
  left:0;
  width: 100%;
}

#container img {
  animation-name: fadeInOut;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-duration: 8s;
}
#container img:nth-of-type(1) {
  animation-delay: 6s;
}
#container img:nth-of-type(2) {
  animation-delay: 4s;
}
#container img:nth-of-type(3) {
  animation-delay: 2s;
}
#container img:nth-of-type(4) {
  animation-delay: 0;
}

Para utilizar "n" imágenes deber hacer los siguientes cálculos:
n = 4 // Total imagenes
a = 1.4s // Tiempo que se vera una imagen
b = .6s // Tiempo desvanecimiento entre imágenes

t = (a+b)*n => 8s // Tiempo total de la animación (eg: animation-duration)
d = (a+b) => 2s // Tiempo de retardo de la animación (eg: animation-delay)

Porcentajes del Keyframes:
0%
a/t*100% => 17.5%
(a+b)/t*100% => 25%
100%-(b/t*100%) => 92.5%
100%

Fuente: Cross fading images


text:
Q: Dynamic menus from database in MVC I have read some similar topics here and on the web, but I don't think I have seen one that would classify this as a duplicate, so I am going to go ahead and post it. I am currently loading my dynamic menus from the database like so:
public void LoadMenus()
{
    var dbContext = new ContentClassesDataContext();
    var menus = from m in dbContext.Menus
                where m.MenuName != "Home" && m.MenuGroup == "RazorHome" && m.RoleID == "Facility"
                orderby m.Sequence, m.MenuName
                select m;

    var html = "";

    if (menus.Any())
    {
        html += "";

        foreach (var menu in menus)
        {
            html = html + $"{menu.MenuName}
";
        }
        html += "
";
    }

    Session["Menus"] = html;
}

LoadMenus() is in my controller class, so I am not able (to my knowledge) to use Razor syntax. I would prefer to load the menus from the view instead, so that I am able to use @Html.ActionLink(linkText, actionName, controllerName). Loading the HTML the way I am currently doing it will generate different link text depending on the current controller, so the links are not always correctly rendered. Is it possible to access the database from the view? Or perhaps to just pass in the content from the database from the controller to the view and then render the menu that way?

A: You should keep your html in the cshtml views.
You should pass the data through the viewmodel and not through the session.
1)
In the controller, get the menu data (in this example we fetch some fake data).
Create a viewmodel that can hold the menu data and pass it to the view, as shown below:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var menu = GetMenu();
        var vm = new ViewModel() {Menu = menu};
        return View(vm);
    }
    private Menu GetMenu()
    {
        var menu = new Menu();
        var menuItems = new List<MenuItem>();
        menuItems.Add(new MenuItem() { LinkText = "Home" , ActionName = "Index", ControllerName = "Home"});
        menuItems.Add(new MenuItem() { LinkText = "About", ActionName = "About", ControllerName = "Home" });
        menuItems.Add(new MenuItem() { LinkText = "Help", ActionName = "Help", ControllerName = "Home" });
        menu.Items = menuItems;

        return menu;
    }
}

2)
This is the viewmodel
public class ViewModel
{
    public Menu Menu { get; set; }
}

This view is an example of how you could render the menu data as a html menu
@model WebApplication1.Models.ViewModel

    @foreach (var item in @Model.Menu.Items)
    {

@Html.ActionLink(@item.LinkText, @item.ActionName,
              @item.ControllerName)

      }

3)
This is the example menu classes used (representing your entities from the dbcontext)
public class Menu
{
    public List<MenuItem> Items { get; set; }
}

public class MenuItem
{
    public string LinkText { get; set; }
    public string ActionName { get; set; }
    public string ControllerName { get; set; }
}

Here are some links to get you started:
http://www.codeproject.com/Articles/585873/Basic-Understanding-On-ASP-NET-MVC
http://www.asp.net/mvc/overview/getting-started/introduction/getting-started


text:
Q: Set 'data-persist' attribute through formtastic I have,
<%= semantic_form_for [:admin, @house, @note] do |f| %>

which gives me,
<form accept-charset="UTF-8" action="/admin/houses/10975/notes" class="formtastic note" id="new_note" method="post" novalidate="novalidate">

I want,
<form accept-charset="UTF-8" action="/admin/houses/10975/notes" class="formtastic note" id="new_note" method="post" novalidate="novalidate" data-persist = "garlic" >

Please take note of 'data-persist' attribute.
Is there any way to add such data-attribute to form tag through formtastic?

A: semantic_form_for accepts the same options as form_for so for your problem, the solution would be
semantic_form_for [:admin, @house, @note], html: { data: { persist: 'garlic' } }

If for some reason, it is showing data=persistgarlic instead of what you expected, try the following
semantic_form_for [:admin, @house, @note], html: { 'data-persist' => 'garlic' }


text:
Q: How do I load xml data into some paragraph elements using javascript I hava a seperate xml document named videoCatalog.xml
I want to grab the; Title, Auther, Camera, Date, Location, Longitude and Latitude and put it into the relivant elements
These are the html elements I want to put the xml data into, they all have id's:

This is my xml document:
<videoDetails>
<Video>
    <Title>Surfing with Sunny Garcia and Kalani Robb</Title>
    <Auther>Sunny Garcia and Kalani Robb</Auther>
    <Camera>GoPro Hero-1080p HD</Camera>
    <Date>2010</Date>
    <Location>On the Pipeline, Honolulu, Hawaii, USA</Location>
    <Longitude>21.284096</Longitude>
    <Latitude>-157.856162</Latitude>
</Video>
<Video>
    <Title>Brian Lopes downhill</Title>
    <Auther>Brian Lopes</Auther>
    <Camera>GoPro Hero-960p HD</Camera>
    <Date>2011</Date>
    <Location>Crankworks in Blackcomb, Whistler, Canada</Location>
    <Longitude>50.115486</Longitude>
    <Latitude>-122.947594</Latitude>
</Video>
<Video>
    <Title>Boat Racing Crash</Title>
    <Auther>Gavin Hurst</Auther>
    <Camera>GoPro Hero-720p HD</Camera>
    <Date>2009</Date>
    <Location>Lake Macfarlane, Yardea, Australia</Location>
    <Longitude>-32.127942</Longitude>
    <Latitude>136.76857</Latitude>
</Video>
</videoDetails>


text:
Q: How to resolve User defined listener com.sun.faces.config.ConfigureListener failed: java.lang.NullPointerException? we have jsf1.2 application, ejb3.0 and weblogic10.0. I am trying to deploy the application in local weblogic server but getting following exception

    <
User defined listener com.sun.faces.application.WebappLifecycleListener failed:    c   java.lang.NullPointerException. java.lang.NullPointerException
    at com.sun.faces.application.WebappLifecycleListener.contextDestroyed(WebappLifecycleListener.java:270)
    at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:459)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(Unknown Source)
    at weblogic.servlet.internal.EventsManager.notifyContextDestroyedEvent(EventsManager.java:187)
    Truncated. see log file for complete stacktrace
>
<Mar 21, 2014 2:19:09 PM IST> <Warning> <HTTP> <BEA-101162> <User defined listener com.sun.faces.config.ConfigureListener failed: java.lang.NullPointerException.
java.lang.NullPointerException
    at com.sun.faces.application.ApplicationAssociate.getInstance(ApplicationAssociate.java:171)
    at com.sun.faces.application.WebappLifecycleListener.handleAttributeEvent(WebappLifecycleListener.java:221)
    at com.sun.faces.application.WebappLifecycleListener.attributeRemoved(WebappLifecycleListener.java:194)
    at weblogic.servlet.internal.EventsManager.notifyContextAttributeChange(EventsManager.java:222)
    at weblogic.servlet.internal.WebAppServletContext.removeAttribute(WebAppServletContext.java:523)
    Truncated. see log file for complete stacktrace
>
<Mar 21, 2014 2:19:09 PM IST> <Error> <Deployer> <BEA-149231> <Unable to set the activation state to true for the application 'standardReportingEar'.
weblogic.application.ModuleException:
    at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:975)
    at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:361)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:204)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:60)
    Truncated. see log file for complete stacktrace
java.lang.AssertionError
    at com.sun.faces.application.ConverterPropertyEditorFactory$ClassTemplateInfo.loadTemplateBytes(ConverterPropertyEditorFactory.java:281)
    at com.sun.faces.application.ConverterPropertyEditorFactory$ClassTemplateInfo.<init>(ConverterPropertyEditorFactory.java:172)
    at com.sun.faces.application.ConverterPropertyEditorFactory$ClassTemplateInfo.<init>(ConverterPropertyEditorFactory.java:154)
    at com.sun.faces.application.ConverterPropertyEditorFactory.<init>(ConverterPropertyEditorFactory.java:524)
    at com.sun.faces.application.ConverterPropertyEditorFactory.getDefaultInstance(ConverterPropertyEditorFactory.java:544)
    Truncated. see log file for complete stacktrace

The config.xml from weblogic.10.0 is :
  part of it:

<app-deployment>
    <name>standardReportingEar-1</name>
    <target>AdminServer</target>
    <module-type>ear</module-type>
    <source-path>L:\au\Workspace_AU\standardReportingEar\target\standardReportingEar.ear</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <library>
    <name>jsf#1.2@1.2.3.1</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>L:\weblogic10\wlserver_10.0\common\deployable-libraries\jsf-1.2.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </library>
So in weblogic, the jsf war deployed as lib successfully.

Now web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>richfacesejb-war</display-name>
  <description>development/test version WITHOUT grops authentication</description>

    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>server</param-value>
    </context-param>
   <context-param>
     <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
     <param-value>com.sun.facelets.FaceletViewHandler</param-value>
  </context-param>
    <context-param>
      <param-name>com.sun.faces.disableVersionTracking</param-name>
      <param-value>true</param-value>
    </context-param>
  <context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
  </context-param>
  <context-param>
    <param-name>facelets.DEVELOPMENT</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <!-- glassfish does not like value 1 when using custim tags -->
    <param-name>facelets.REFRESH_PERIOD</param-name>
    <param-value>-1</param-value>
  </context-param>
  <context-param>
    <param-name>org.richfaces.SKIN</param-name>
    <param-value>blueSky</param-value>
  </context-param>
  <context-param>
    <param-name>org.richfaces.CONTROL_SKINNING</param-name>
    <param-value>enable</param-value>
  </context-param>
  <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/ErrorHandlingServlet</location>
  </error-page>
  <filter>
    <display-name>RichFaces Filter</display-name>
    <filter-name>richfaces</filter-name>
    <filter-class>org.ajax4jsf.Filter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>richfaces</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
  </filter-mapping>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
  <session-config>
    <session-timeout>240</session-timeout>
  </session-config>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ErrorHandlingServlet</display-name>
    <servlet-name>ErrorHandlingServlet</servlet-name>
    <servlet-class>com.bmw.au.jsf.ErrorHandlingServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ErrorHandlingServlet</servlet-name>
    <url-pattern>/ErrorHandlingServlet</url-pattern>
  </servlet-mapping>
  <listener>
        <listener-class>com.bmw.au.jsf.util.SessionMonitoringListener</listener-class>
</listener>
</web-app>

maven dependencies :
     <dependency>
            <groupId>com.sun.facelets</groupId>
            <artifactId>jsf-facelets</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-impl</artifactId>
<dependency>
            <groupId>com.bea.wls</groupId>
            <artifactId>wlfullclient</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.richfaces.ui</groupId>
            <artifactId>richfaces-ui</artifactId>
        </dependency>
        <dependency>
            <groupId>org.richfaces.framework</groupId>
            <artifactId>richfaces-impl</artifactId>

A: Try Cleaning and Building your project, in Netbeans: Right Click to your project > Clean and Build, in Eclipse: select your project then in the option Project > Check Build Automatically and click to Clean, and finally Deploy again your project, it works for me, let me know if it works for you.


text:
Q: move along a grid in Unity I can set four different movement directions for my player

*

*Vector2.up => (0,1)

*Vector2.down => (0,-1)

*Vector2.left => (-1,0)

*Vector2.right => (1,0)

and I have a two dimensional array that contains Cell objects
public class Cell
{
    public Cell(GameObject cellObject, bool isObstacle)
    {
        CellObject = cellObject;
        IsObstacle = isObstacle;
    }

    public GameObject CellObject { get; set; }

    public bool IsObstacle { get; set; }
}

My array is initialized by the size of the map.
private const int MAP_SIZE = 10;
private Cell[,] mapCells = new Cell[MAP_SIZE, MAP_SIZE];

I fill this array by using two loops, this will give me 100 cells.
for (int x = 0; x < MAP_SIZE; x++)
{
    for (int y = 0; y < MAP_SIZE; y++)
    {
        Vector3 newCellPosition = new Vector3(x, 0, y);
        GameObject newCellObject = Instantiate(cell, newCellPosition, cell.transform.rotation);

        bool isObstacle = false; // TEST

        Cell newCell = new Cell(newCellObject, isObstacle);
        mapCells[x, y] = newCell;
    }
}

When moving the player I want to return the Cell he has to move to. The movementDirection parameter will set the row and the column to search for.
If there is an obstacle cell the player should just move to this obstacle and stop.

public Cell GetTargetCell(Vector2 movementDirection)
{
    Cell targetCell = null;

    // get the path

    // get the closest obstacle

    return targetCell;
}

Is there an elegant way to calculate the correct target cell by a 2D direction?

A: I think the most elegant way of doing it is by using two separate for loops and the ?: operator.
//returns cell
Cell GetTargetCell(Vector2 dir)
{
    if(dir.y == 0) //if we're going horizontal
    {
        //HorizontalMovement
        for(int i = 0; i < ((dir.x==1)?mapSize-PLAYER_X:PLAYER_X); i++)
        {
            if(mapCells[(int)dir.x*i,PLAYER_Y].IsObstacle()) //if we encounter an obstacle
                return mapCells[(int)dir.x*i,PLAYER_Y]; //return cell that's an obstacle
        }

        //if we didn't encounter an obstacle
        return mapCells[(dir.x == 1)?mapSize:0,PLAYER_Y]; //return the cell
    }
    else if(dir.x == 0)
    {
        //VerticalMovement
        //copy paste the previous for loop and edit the parameters, I'm too lazy :P
    }
    else
    {
        //NoMovement
        Debug.Log("Please enter a valid Direction");
        return mapCells[0,0];
    }

}

Replace the PLAYER_X and PLAYER_Y values, with the x, and y values of the cell the player is currently in. I didn't check if the code contains any errors, but I think it should work.


text:
Q: How to show My Labels and activate respective Shortcut in Pyqt5? Here is my code, How to show My Labels and activate respective QShortcut?. Want to show my labels(both instances) and assign respective shortcut keys to labels and activate it.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class Create_workingDict(QWidget):
    def __init__(self,lblname,lblscut):
        super(). __init__()

        self.lblname = lblname
        self.lblscut = lblscut

        lbl_1 = QLabel()
        lbl_1.setText(self.lblname)
        lbl_2 = QLabel()
        lbl_2.setText(self.lblscut)

        vbox = QVBoxLayout()
        vbox.addWidget(lbl_1)
        vbox.addWidget(lbl_2)
        self.setLayout(vbox)

        self.msgSc = QShortcut(QKeySequence(f'{self.lblscut}'), self)
        self.msgSc.activated.connect(lambda: QMessageBox.information(self,'Message', 'Ctrl + M initiated'))

class Mainclass(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Sample Window")
        x = Create_workingDict("Accounts","Alt+A")
        y = Create_workingDict("Inventory", "Ctrl+B")

def main():
    app = QApplication(sys.argv)
    ex = Mainclass()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

A: Add the layout in main widget.
Then pass the layout to the function where you are creating labels and add them to layout.
Below is the modified code.
Find the details as comments in below code.
Your main window class
class Mainclass(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Sample Window")

        #CREATE THE LAYOUT HERE IN MAIN WINDOW
        vbox = QVBoxLayout()

        x = Create_workingDict("Accounts","Alt+A",vbox) #PASS THE LAYOUT OBJECT (vbox) AS AN ARGUMENT
        y = Create_workingDict("Inventory", "Ctrl+B",vbox) #PASS THE LAYOUT OBJECT (vbox) AS AN ARGUMENT

        #SET THE LAYOUT TO MAIN WINDOW
        self.setLayout(vbox)

Your function where labels created.
Observe that the functions  vbox = QVBoxLayout() and self.setLayout(vbox) are moved out of this function to main window.
class Create_workingDict(QWidget):
    def __init__(self,lblname,lblscut,vbox): #RECEIVE LAYOUT (vbox) ARGUMENT
        super(). __init__()

        self.lblname = lblname
        self.lblscut = lblscut

        lbl_1 = QLabel()
        lbl_1.setText(self.lblname)
        lbl_2 = QLabel()
        lbl_2.setText(self.lblscut)

        vbox.addWidget(lbl_1)
        vbox.addWidget(lbl_2)

        self.msgSc = QShortcut(QKeySequence(f'{self.lblscut}'), self)
        self.msgSc.activated.connect(lambda: QMessageBox.information(self,'Message', 'Ctrl + M initiated'))

A: Shortcuts work based on the context (and visibility) of the parent widget: as long as the parent is visible and the context is compatible, they will be triggered, otherwise they will not even be considered.
Be aware that the visibility is of the parent widgets (note the plural) is mandatory, no matter of the context: Qt has no API for a "global" shortcut, not only external to the application, but also within it: there is no shortcut that can automatically work anywhere in the app if (any of) its parent(s) is hidden. The context only ensures that the shortcut can only be activated if the active widget is part of the application (ApplicationShortcut), if the current active window is an ancestor of the shortcut parent (WindowShortcut), if any of the grand[...]parent widgets has focus (WidgetWithChildrenShortcut) or the current parent has it (WidgetShortcut).
Long story short: if the shortcut's parent is not visible (at any level), it will not be triggered.
Not only. In your code, both x and y are potentially garbage collected (they are not due to the fact that the lambda scope avoids destruction, but that's just "sheer dumb luck"), so that code would be actually prone to fail anyway if the activated signal would have been connected to an instance method.
If you want them to be available to the visible window, you must add their parent widgets to that window, even if they're not shown. Otherwise, just add the shortcuts to that window.
For instance:
class Mainclass(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Sample Window")
        x = Create_workingDict("Accounts","Alt+A")
        y = Create_workingDict("Inventory", "Ctrl+B")
        layout = QVBoxLayout(self)
        layout.addWidget(x)
        layout.addWidget(y)

The only and automatic way to access a global application shortcut from any window of the application is to create a QKeySequence that is checked within an event filter installed on the application.
This is a possible, but crude implementation, so, take it as it is and consider its consequences:
class ShortCutFilter(QObject):
    triggered = pyqtSignal(QKeySequence)
    def __init__(self, shortcuts=None):
        super().__init__()
        self.shortcuts = {}

    def addShortcut(self, shortcut, slot=None):
        if isinstance(shortcut, str):
            shortcut = QKeySequence(shortcut)
        slots = self.shortcuts.get(shortcut)
        if not slots:
            self.shortcuts[shortcut] = slots = []
        if slot is not None:
            slots.append(slot)
        return shortcut

    def eventFilter(self, obj, event):
        if event.type() == event.KeyPress:
            keyCode = event.key()
            mods = event.modifiers()
            if mods & Qt.ShiftModifier:
                keyCode += Qt.SHIFT
            if mods & Qt.MetaModifier:
                keyCode += Qt.META
            if mods & Qt.ControlModifier:
                keyCode += Qt.CTRL
            if mods & Qt.ALT:
                keyCode += Qt.ALT
            for sc, slots in self.shortcuts.items():
                if sc == QKeySequence(keyCode):
                    self.triggered.emit(sc)
                    for slot in slots:
                        try:
                            slot()
                        except Exception as e:
                            print(type(e), e)
                    return True
        return super().eventFilter(obj, event)

def main():
    app = QApplication(sys.argv)
    shortcutFilter = ShortCutFilter()
    app.installEventFilter(shortcutFilter)

    shortcutFilter.addShortcut('alt+b', lambda:
        QMessageBox.information(None, 'Hello', 'How are you'))
    shortcutFilter.triggered.connect(lambda sc:
        print('triggered', sc.toString())

    ex = Mainclass()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

This, obviously, means that any key press event will pass through the known python bottleneck. A better solution would be to create global QActions and addAction() to any possible top level window that could accept it.
While this approach might seem more complex, it has its benefits; for instance, you have more control on the context of the shortcut: in the case above, you could trigger Alt+B from any window, including the one shown after previously triggering it, which is clearly not a good thing.


text:
Q: Get subclass type from projection with NHibernate I am trying to do a projection on a type called Log. Log references a superclass called Company. Each company type is mapped with table per subclass.
Is it possible for me to get the type of Company when I do a projection on Log?
I currently have an Enum property (which is not mapped) on each subclass, so I can perform switches on Company types, but since it is not mapped to anything, I can't do a projection on it.
I have tried Projections.Property("log.Company.class") but that does not work :(
PS: I couldn't find a lot of appropriate tags for this question. If anyone have an idea for more specific tags, please tell me.

A: You can do the following...
session.CreateCriteria<Log>()
       .CreateAlias("Company", "company")
       .SetProjection(Projections.Property("company.class"))

But that projection can only be used for filtering and ordering; NHibernate will not return the System.Type in the result set (it returns an integer, which is used internally).
If what you need is to know the concrete type of the Company, you can do the following:
var logs = session.CreateCriteria<Log>()
                  .SetFetchMode("Company", FetchMode.Join) //avoid SELECT N+1
                  .List<Log>()

And then, to retrieve the type for each row:
foreach (var log in logs)
    string companyClassName = session.GetEntityName(log.Company);


text:
Q: C++ CppUnit Test (CPPUNIT_ASSERT) I'm trying to do up a screen scraping assignment. My cpp works, but I don't know how to integrate my unit testing. I tried to do a bool check unit test for the file validity but it's giving me this error:
error: cannot call member function 'bool ScreenScrape::getFile()' without object

screenscrape.cpp:
#include "screenscrape.h"

using namespace std;

int main()
{
    ScreenScrape ss;
    int choice;

    ...
    ...

    ss.matchPatternTest();
}

screenscrape.h:
class ScreenScrape
{
    public:
    ScreenScrape();
        void    parserTest(int choice);
        void    matchPatternTest();
        void    setIndexValue(string data, string IndexName);
        void    setIndexChange(string data);
        void    setIndexPercent(string data);
        void    setIndexDate(string data);
        bool    getFile();
    private:
        string IndexName;
        string IndexValue;
        string IndexChange;
        string IndexPercent;
        string IndexVID;
        string IndexCID;
        string IndexPID;
        string IndexDate;
};

bool ScreenScrape::getFile()
{
    string file1 = "yahoofinance.htm";
    char*  file2 = new char [file1.size()+1];   // parse file for c string conversion
    strcpy(file2, file1.c_str());               // converts to c string

    ifstream fin;

    fin.open(file2);
    if(fin.good())
        return true;
    else
        return false;
}

screenscrapetest.cpp:
#include "screenscrapetest.h"
#include "screenscrape.h"

CPPUNIT_TEST_SUITE_REGISTRATION (ScreenScrapeTest);

void ScreenScrapeTest::fileTest()
{
    CPPUNIT_ASSERT(ScreenScrape::getFile());   // test file validity
}

screenscrapetest.h:
#ifndef _SCREENSCRAPETEST_H
#define _SCREENSCRAPETEST_H
#include <cppunit/TestCase.h>
#include <cppunit/extensions/HelperMacros.h>
#include "screenscrape.h"

class ScreenScrapeTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE (ScreenScrapeTest);
    CPPUNIT_TEST (fileTest);
    CPPUNIT_TEST_SUITE_END ();
    public:
        void fileTest();
};
#endif

I tried to declare "ScreenScrape ss;" under screenscrapetest.h, use an object (ss) to call getFile() but it's giving me multiples of this error:
/home/user/NetBeansProjects/Assignment1/screenscrape.h:259: multiple definition of `ScreenScrape::getFile()'

I only want to check for file validity with unit testing. Any help will be appreciated.
Thanks in advance!
Regards,
Wallace

A: bool ScreenScrape::getFile() is not static, so cannot be called as a static function. You'll need to either (a) declare it as static or (b) create an instance of ScreenScrape and call getFile() from it.
Looking at the code, it's not obvious why this function is a method of the class but perhaps it's still in the early stages of development. It can also be refactored to remove lots of redundant code:
bool ScreenScrape::getFile()
{
    std::ifstream fin("yahoofinance.htm");
    return fin.good();
}

Don't forget your include guards in screenscrape.h:
#ifndef SCREENSCRAPE_H
#define SCREENSCRAPE_H
// Class declaration here...
#endif//ndef SCREENSCRAPE_H

And consider moving the implementation of getFile to the cpp source file. These two steps will prevent you getting the "multiple declaration" errors.
This will fix your compilation errors, but checking for file validity is not a responsibility of a unit test. Unit tests should not interact with the filesystem.

A: If you're going to be calling ScreenScrape::getfile()rather than ss.getfile(), then getfile() needs be defined as static.  The error you're getting is because non-static methods need to be called on a specific object.
It's difficult to track down the error with your version that defines a ScreenScrape object and then uses that to call getfile(); you obviously haven't included all the relevant code since your screenscrape.h file doesn't have 259 lines, and you also haven't shown the revised code in which you "use an object (ss) to call getFile()".


text:
Q: Restangular post incorrectly created a singular of wage_schedules I'm using restangular with AngularJS 1.5 and Rails 5.x and have the following;
Restangular.all('wage_schedules').post($scope.wage_schedule).then (response) ->
  $state.go "wage_schedules"

When this request gets to my Rails backend the params includes "wage_schedul" and it's missing the 'e' on the end. At first I thought it was Ruby on Rails and the inflection file but after playing around with that it still didn't work.
Is Restangular changing my wage_schedules to wage_schedul and how would I train it to correctly singularise 'wage_schedules' to 'wage_schedule'?
When I check my payload sent to the server from Restangular I can see that it's already called 'wage_schedul' without the 'e' on the end.
If I swap the syntax to
Restangular.all('jobs').post($scope.wage_schedule).then (response) ->
  $state.go "wage_schedules"

Then I get job: {} in my post payload. So Restangular must be misinterpretting the conversion of wage_schedules to wage_schedule.

A: The answer was to use a package:
https://github.com/blakeembrey/pluralize and configure it to be used with Restangular.
angular
  .module('paisApp')
  .config ['RestangularProvider', (RestangularProvider) ->
    RestangularProvider.setRequestInterceptor( (elem, operation, what) ->
      retElem = elem
      if operation == 'post' || operation == 'put'
        wrapper = {}
        singular = pluralize.singular(what)

        # Check if we have already applied a root node
        if elem[singular] == undefined
          wrapper[singular] = elem
          retElem = wrapper
      return retElem
    )
  ]


text:
Q: Unable to contact valid Reprository Publisher on Solaris11 on my just install Solaris11 on Oracle VM, I got this at startup: Unable to contact valid reprository publisher. application/pkg/server:default failed AUTO-RESPONSE: The service has been placed into the maintenance state.
Is there anyone with experience in Solaris 11 who could shed some light on what could be done.
Thanks

A: The application/pkg/server:default service instance is not enabled by default.  How was this VM installed?
It sounds like there was some configuration performed.
Are you certain that was the name of the service that failed?


text:
Q: CanvasAuthorize and VerificationException I'm executing this piece of code:
    [CanvasAuthorize(Permissions = "user_about_me")]
    public ActionResult About()
    {
        var fb = new FacebookWebClient();

        dynamic result = fb.Get("me");

        ViewData["Firstname"] = result.first_name;
        ViewData["Lastname"] = result.last_name;

        return View();
    }

And I get the following exception.. Any idea?
Server Error in '/' Application.
Operation could destabilize the runtime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Security.VerificationException: Operation could destabilize the runtime.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[VerificationException: Operation could destabilize the runtime.]
   SimpleJson.SimpleJson.ParseValue(Char[] json, Int32& index, Boolean& success) +107
   SimpleJson.SimpleJson.TryDeserializeObject(String json, Object& object) +212
   SimpleJson.SimpleJson.DeserializeObject(String json) +84
   Facebook.SimpleJsonSerializer.DeserializeObject(String json) +112
   Facebook.FacebookSignedRequest.TryParse(String secret, String signedRequestValue, Int32 maxAge, Double currentTime, Boolean throws) +3096
   Facebook.FacebookSignedRequest.Parse(String secret, String signedRequestValue) +445
   Facebook.FacebookSignedRequest.GetSignedRequest(String appSecret, HttpContextBase httpContext) +931
   Facebook.FacebookSession.GetSession(String appId, String appSecret, HttpContextBase httpContext, FacebookSignedRequest signedRequest) +1031
   Facebook.FacebookSession.GetSession(String appId, String appSecret, HttpContextBase httpContext) +128
   Facebook.Web.FacebookWebContext.get_Session() +317
   Facebook.Web.FacebookWebContext.IsAuthenticated() +136
   Facebook.Web.FacebookWebContext.IsAuthorized(String[] permissions) +186
   Facebook.Web.Mvc.CanvasAuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext, IFacebookApplication settings) +572
   Facebook.Web.Mvc.FacebookAuthorizeAttributeBase.OnAuthorization(AuthorizationContext filterContext) +182
   System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor) +149
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +831
   System.Web.Mvc.Controller.ExecuteCore() +136
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +233
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +68
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
   System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult ) +42
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +142
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.<>c_DisplayClasse.b_d() +61
   System.Web.Mvc.SecurityUtil.b_0(Action f) +31
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +56
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +110
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +690
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +194

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1  I

A: Try this:
[CanvasAuthorize(Permissions = "user_about_me")]
public ActionResult About()
{
    CanvasAuthorizer auth = new CanvasAuthorizer();
    FacebookWebClient client = new FacebookWebClient(auth.FacebookWebRequest.Session.AccessToken);

    dynamic result = client.Get("me");

    ViewData["Firstname"] = result.first_name;
    ViewData["Lastname"] = result.last_name;

    return View();
}