text:
Q: Child view is never visible I'm building our UI programmatically and am having a bit of trouble getting elements to render for children views.
I am setting up the apps Window by instantiating my initial view controller and the view that it needs.
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let initialView = StartupView(frame: CGRect.zero)
        let startupViewController = StartupViewController(startupView: initialView);

        window = UIWindow(frame: UIScreen.main.bounds);
        window!.rootViewController = startupViewController;
        window?.backgroundColor = UIColor.white
        window!.makeKeyAndVisible();

        return true
    }
}

The StartupView class instantiates a single UIButton that it adds to itself and sets constraints to specify the height/width and center align it horizontally and vertically.
class StartupView : UIView {

    // views
    var newAccountButton: UIButton!

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.configureView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.configureView()
    }

    override func updateConstraints() {
        self.newAccountButton.translatesAutoresizingMaskIntoConstraints = false
        self.newAccountButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        self.newAccountButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        self.newAccountButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
        self.newAccountButton.widthAnchor.constraint(equalToConstant: 50).isActive = true

        print("\(self.newAccountButton.titleLabel?.text ?? "Unknown") is \(self.newAccountButton.frame)")
        super.updateConstraints()
    }

    func configureView() {
        // New account button setup
        newAccountButton = UIButton(frame: CGRect.zero)
        newAccountButton.titleLabel?.text = "Create Account"

        self.addSubview(newAccountButton)
    }
}

The StartupView is given to its ViewController. It would seem that the ViewController constraints assigned to the StartupView are working because I've verified that my StartupView does size itself to equal that of the ViewController view. When I run the simulator though, I don't see the UIButton.
class StartupViewController: UIViewController {
    var startupView: StartupView!

    init(startupView: StartupView) {
        self.startupView = startupView
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.startupView = StartupView(frame: CGRect.zero)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.startupView)

        self.startupView.translatesAutoresizingMaskIntoConstraints = false

        self.startupView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        self.startupView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        self.startupView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.startupView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

        self.startupView.updateConstraints()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Am I doing the constraints wrong? Or does the order in which I add nested views matter?
Edit
This is a screenshot of the view debugger.

I can see the button in the layout (highlighted) but I can't see the actual button being rendered. Writing print("\(self.newAccountButton.titleLabel?.text): \(self.newAccountButton.frame)") writes out the title of the button and it's frame but nothing is rendered.

A: I think instead of overriding updateConstraints, you can simply do this:
Edit
Final solution (not accessing the label directly) after discussing in chat with OP:
    func configureView() {
        // New account button setup
        newAccountButton = UIButton(frame: CGRect.zero)
        newAccountButton.setTitleColor(self.tintColor, for: UIControlState.normal)

        newAccountButton.setTitle("Create Account", for: UIControlState.normal)

        self.addSubview(newAccountButton)
        self.newAccountButton.translatesAutoresizingMaskIntoConstraints = false
        self.newAccountButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        self.newAccountButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        self.newAccountButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
        self.newAccountButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
    }

A: I think in your app delegate, you have to define size of your StartupView. Currently it's set to zero
let initialView = StartupView(frame: CGRect.zero).


text:
Q: xPath inside xPath? This xml below retrieve results from a query and have an embedded XML document of responseText element.
    <resultsResponse>
    <errors/>
    <responseformat>xml</responseformat>
    <responseText><![CDATA[<?xml version="1.0" encoding="UTF-8"?><records><record><slice><![CDATA[40224]]]]>><![CDATA[</slice></record><record><slice><![CDATA[40224]]]]>><![CDATA[</slice></record><record><slice><![CDATA[40224]]]]>><![CDATA[</slice></record></records>]]>
    </responseText>
    </resultsResponse>

I want to get slice attribute, but i don't know exactly how can do that without make two xpaths separately.
Any chance to get slice information using only one xpath query? Like turn responseText into a node tree?
What I'm doing now: use a xPath Query to get the responseText attribute: //responseText. It returns:
<?xml version="1.0" encoding="UTF-8"?> <records><record><slice><![CDATA[40224]]></slice></record><record><slice><![CDATA[40224]]></slice></record><record><slice><![CDATA[40224]]></slice></record></records>

after i have to keep this new xml inside of a variable and apply another xPath Query to get slice elements: //slice
40224
40224
40224

The problem is: Is mandatory to use xPath query just one time and without code (just using xPath expressions).

redpajama_set_name: RedPajamaStackExchange


text:
Q: EJB injection into non managed objects we are upgrading our web application to Oracle WebLogic 12c with EJB 3.x, and we got an issue.
This is the scenario...
We have a simple EJBs that we are going to call MyService, defined with its bean and local/remote interfaces defined by the EJB 3.x annotations.
Here is a pseudo code of the scenario:
class MyListener implements ServletContextListener {

    @EJB private MyService myService;

    public void contextInitialized(ServletContextEvent arg0) {
        // Here myService is correctly instantiated, so we do something...
    }

}

Now we have to move the contextInitialized method logic inside an utility class, so the new scenario will be:
class MyUtility {

  @EJB private MyService myService;

  public void doSomething() {
      // Here myService is NULL!!!!!
  }

}

class MyListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent arg0) {
        new MyUtility().doSomething();
    }

}

I have read a lot of documentation about that problem, and I discovered that only some kind of classes are scanned by the Application Server to resolve the injected EJBs ( Java EE 6, 5, 7 | List of managed beans or classes: EJBs , JSF beans and ..? ).
Is there a workaround to force the scanning of a custom class like mine with WebLogic?
Thank you very much.

A: There is an option to wrap you Injection into a CDI-Component and to use this one in your code. CDI has the capability to work in standalone java, as soon as you configured it well.
Another helpful option can be the fact, that CDI supports EJB-injection too (in some usecases):
CDI.current().select(MyService.class).get();
BUT: EJBs has their own Transaction-Management. So I would prefer the wrapping into a cdi-component to get more controll in it.


text:
Q: decode dean edwards javascript packer with a php class Class file http://pastebin.com/apGPiAXd
I found a php port that encodes and decodes the dean edwards packer for javascript. Located here http://joliclic.free.fr/php/javascript-packer/en/. I am not interested in the encoding aspect of this class, but the decoding part. I would like to take something like this
eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('4.8=9(a){1 b=e f();1 c=4.g("*");5(1 i=0;i<c.6;i++){2(c[i].3.h(" ")>=0){1 d=c[i].3.k(" ");5(1 j=0;j<d.6;j++){2(d[j]==a){b.7(c[i])}}}l 2(c[i].3==a){b.7(c[i])}}m b}',23,23,'|var|if|className|document|for|length|push|getElementsByClassName|function|||||new|Array|getElementsByTagName|indexOf|||split|else|return'.split('|'),0,{}))
and place it in a variable and run it through the class to be decoded. I am not sure how to get the javascript into the class to be decoded? So maybe something like this:
require 'class.JavaScriptPacker.php';
$packed_javascript = $_GET["js"];

/* run $packed_javascript through class*/

return $decoded_javascript;

A: You can simple open up a developer console in your browser (ctrl+j in chrome, or firebug etc), paste your packed JS code into the console and before you hit enter, simply replace "eval" with "console.log" or "alert".
I know this post is old but I just had the same problem and thought I'd post my solution. You're welcome.

A: here is unpacked java script of above . is that u want??
document.getElementsByClassName=function(a)
    {
    var b=new Array();
    var c=document.getElementsByTagName("*");
    for(var i=0;
    i<c.length;
    i++)
        {
        if(c[i].className.indexOf(" ")>=0)
            {
            var d=c[i].className.split(" ");
            for(var j=0;
            j<d.length;
            j++)
                {
                if(d[j]==a)
                    {
                    b.push(c[i])
                }
            }
        }
        else if(c[i].className==a)
            {
            b.push(c[i])
        }
    }
    return b
}

Reference

A: Old question but here is simple decode writen in php
<?php

$a = "eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('4.8=9(a){1 b=e f();1 c=4.g("*");5(1 i=0;i<c.6;i++){2(c[i].3.h(" ")>=0){1 d=c[i].3.k(" ");5(1 j=0;j<d.6;j++){2(d[j]==a){b.7(c[i])}}}l 2(c[i].3==a){b.7(c[i])}}m b}',23,23,'|var|if|className|document|for|length|push|getElementsByClassName|function|||||new|Array|getElementsByTagName|indexOf|||split|else|return'.split('|'),0,{}))";

$pos = strpos($a, '}(');
$a = substr($a, $pos);
$pos = strpos($a, ",'");
$b = substr($a, 0, $pos);
$c = substr($a, $pos+2);
$pos = strpos($c, "'.");
$c = substr($c, 0, $pos);

$items = explode('|', $c);

//var_dump($items);

for ($i = count($items); $i >= 0; $i--) {
    $b = str_replace($i, $items[$i], $b);
}

$b = str_replace("\'", "'", $b);

echo ' procedure: ';
echo $b;

?>


text:
Q: Same input that gives different output? I'm trying to code a function that takes a boolean equation as its input, and gives the answer of the equation as its output. For example:

Input: (!T|T)&F

Output: F

However, in some scenarios, (when there are parentheses, the same input would sometimes give True, sometimes False). For example:

Input: (T|T)&T

sometimes gives T, sometimes F. I'm new at programming, and I'm not sure I understand how memory works exactly, can someone please check my code and explain what's happening?
#include <iostream>
#include <cstring>
using namespace std;

bool boolFunc(char* input, long len){
    // Base cases
    if(len == 2 && *input == '!'){
        if(*(input+1) == 'T') return false;
        if(*(input+1) == 'F') return true;
    }

    else if(len == 1){
        if(*input == 'T')
            return true;
        else
            return false;
    }
    //
    else{
        for (long i = len-1; i >= 0; i--) {
            //for equations with '(' and ')'
            if(*(input + i) == ')'){
                for (long j = i-1; j >= 0; j--) {
                    if(*(input + j) == '('){
                        if(*(input + j - 1) == '&')
                            return boolFunc(input, j-1) && boolFunc(input+j+1, i-j-1);
                        else
                            return boolFunc(input, j-1) || boolFunc(input+j+1, i-j-1);
                    }
                }
            }

            if(*(input + i) == '&'){
                return boolFunc(input, i) && boolFunc(input+i+1, len-i-1);
            }
            if(*(input + i) == '|'){
                return boolFunc(input, i) || boolFunc(input+i+1, len-i-1);
            }

        }
    }
    return false;
}

int main(){

    char input[500] = {'\0'};
    cin.getline(input, 500);
    if(boolFunc(input,strlen(input)))
        cout << "T" << endl;
    else
        cout << "F" << endl;

    return 0;
}


text:
Q: Faster way to combine dictionaries that has same id Lets say i have the following lists of dictionaries that have the same attribute id. I want to know which is the faster and correct way to combine them according to the id value.
 perperson = [
  {'id':1, 'firstName':'test','lastName':'testlast'},
  {'id':2, 'firstName':'test2','lastName':'testlast2'},
  {'id':3, 'firstName':'test3','lastName':'last3'},
]

peremail = [
  {'id':1, 'email':'test@test'},
  {'id':2, 'email':'test2@test2'},
  {'id':3, 'email':'test3@test3'},
]

result
 comdined= [
  {'id':1, 'firstName':'test','lastName':'testlast','email':'test@test'},
  {'id':2, 'firstName':'test2','lastName':'testlast2','email':'test2@test2'},
  {'id':3, 'firstName':'test3','lastName':'last3','email':'test3@test3'},
]

A: Convert one of the list to a dict and then perform a lookup
Ex:
perperson = [
  {'id':1, 'firstName':'test','lastName':'testlast'},
  {'id':2, 'firstName':'test2','lastName':'testlast2'},
  {'id':3, 'firstName':'test3','lastName':'last3'},
]

peremail = [
  {'id':1, 'email':'test@test'},
  {'id':2, 'email':'test2@test2'},
  {'id':3, 'email':'test3@test3'},
]
peremail_t = {i.pop('id'): i for i in peremail}    # Easy look-up

comdined = [{**i, **peremail_t[i['id']]} for i in perperson]
print(comdined)

Output:
[{'email': 'test@test', 'firstName': 'test', 'id': 1, 'lastName': 'testlast'},
 {'email': 'test2@test2',
  'firstName': 'test2',
  'id': 2,
  'lastName': 'testlast2'},
 {'email': 'test3@test3', 'firstName': 'test3', 'id': 3, 'lastName': 'last3'}]

OR update inplace
Ex:
for i in perperson:
    i.update(peremail_t[i['id']])

A: If you are dealing with large amounts of table-like data in lists of dictionaries, then consider using a Pandas dataframe instead. Merging dataframes by id is very simple, it will be faster if the tables are large, and it gives you more way to deal with potential issues like mismatched ids.
import pandas as pd
merged = pd.DataFrame(perperson).merge(pd.DataFrame(peremail), on="id")

You can use merged.to_dict("records") if you need to convert it back to dictionaries.
If you  don't want to use pandas, here is a generator that can merge an arbitrary number of lists of dictionaries which may not be sorted and may have mismatched ids (equivalent to an 'outer' merge in pandas). This is likely to be slower than converting the lists to dictionaries but as efficient as possible using lists.
def join_by_key(key, *lists):
    lists = [sorted(L, key=lambda d: d[key]) for L in lists]
    while lists:
        min_key = min(L[0][key] for L in lists)
        r = {}
        for L in lists:
            if L[0][key] == min_key:
                r.update(L.pop(0))
        yield r
        lists = [L for L in lists if L]

print(list(join_by_key("id", perperson, peremail)))

A: here is my proposal a simple loop:
perperson = [{'id':1, 'firstName':'test','lastName':'testlast'},
{'id':2, 'firstName':'test2','lastName':'testlast2'},
{'id':3, 'firstName':'test3','lastName':'last3'},
]

peremail = [
{'id':1, 'email':'test@test'},
{'id':2, 'email':'test2@test2'},
{'id':3, 'email':'test3@test3'},
]

for n,j in zip(perperson,peremail):
    n['email']=j['email']

print(perperson)

her is the output
[{'lastName': 'testlast', 'id': 1, 'firstName': 'test', 'email': 'test@test'},      {'lastName': 'testlast2', 'id': 2, 'firstName': 'test2', 'email': 'test2@test2'}, {'lastName': 'last3', 'id': 3, 'firstName': 'test3', 'email': 'test3@test3'}]

A: Considering that all dictionaries have an 'id' key and the lists are ordered by 'id' values:

def combine_dicts(dict_1, dict_2):
    if dict_1['id'] == dict_2['id']:
        for k in dict_2:
            if k in dict_1:
                continue
            else:
                dict_1.update({k:dict_2[k]})
    return dict_1

for dict1, dict2 in zip(perperson, peremail):
    combine_dicts(dict1, dict2)


text:
Q: Cant get the title from the following json I have this code into my app that returns some job feed in json format:
My code looks as below:
JobFeed.find().sort('-created').exec(function (err, feeds) {
    if (err) {
        return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
        });
    } else {

        _.forEach(feeds, function (row, key) {
            console.log(row.data.title); // showing undefined
        });

        res.jsonp(feeds);
    }
});

and the json looks like below:
  { data:
   { isSaved: null,
     client:
      { lastContractTitle: null,
        feedbackText: '4.78 Stars, based on 13 feedbacks',
        paymentVerificationStatus: 1,
        lastContractPlatform: null,
        totalFeedback: 4.7819242373,
        location: [Object],
        lastContractRid: 0,
        edcUserId: 3728985,
        totalReviews: 13,
        companyRid: 0,
        spentTier: '$7,500+',
        companyName: null },
     amount: { amount: 0, currencyCode: 'USD' },
     createdOn: '2016-10-13T06:30:54+00:00',
     skills: [ [Object], [Object], [Object], [Object] ],
     enterpriseJob: false,
     ciphertext: '~01026b31d972ed826b',
     proposalsTier: null,
     description: 'Hello! We\'re currently searching for a developer with',
     category2: 'Web, Mobile & Software Dev',
     type: 2,
     tierText: 'Intermediate ($$)',
     relevance:
      { hoursInactive: 0,
        id: 208660674,
        publishTime: '1476340265000',
        recommendedEffectiveCandidates: 2,
        effectiveCandidates: 3,
        uniqueImpressions: 0 },
     isApplied: null,
     engagement: '30+ hrs/week',
     recno: 208660674,
     title: 'Server-side and Client-side Game Developer for Indie MMO',
     freelancersToHire: 0,
     maxAmount: { amount: 0, currencyCode: 'USD' },
     duration: 'More than 6 months',
     subcategory2: 'Game Development',
     sticky: false,
     stickyLabel: '',
     feedback: null },
  id: 57ffcdbf717ca50cf0b4cbc1 }
{ data:
   { isSaved: null,
     client:
      { lastContractTitle: null,
        feedbackText: 'No feedback yet',
        paymentVerificationStatus: 1,
        lastContractPlatform: null,
        totalFeedback: 0,
        location: [Object],
        lastContractRid: 0,
        edcUserId: 0,
        totalReviews: 0,
        companyRid: 0,
        spentTier: '$100+',
        companyName: null },
     amount: { amount: 0, currencyCode: 'USD' },
     createdOn: '2016-10-13T06:30:51+00:00',
     skills: [ [Object], [Object], [Object] ],
     enterpriseJob: false,
     ciphertext: '~01c59efb9135ed91d0',
     proposalsTier: null,
     description: 'Hello! We\'re currently searching for a developer with',
     category2: 'Web, Mobile & Software Dev',
     type: 2,
     tierText: 'Entry Level ($)',
     relevance:
      { hoursInactive: 0,
        id: 208660673,
        publishTime: '1476340266000',
        recommendedEffectiveCandidates: 18,
        effectiveCandidates: 74,
        uniqueImpressions: 0 },
     isApplied: null,
     engagement: 'Less than 10 hrs/week',
     recno: 208660673,
     title: 'Wordpress & Stripe developer',
     freelancersToHire: 0,
     maxAmount: { amount: 0, currencyCode: 'USD' },
     duration: 'More than 6 months',
     subcategory2: 'Web Development',
     sticky: false,
     stickyLabel: '',
     feedback: null },
  id: 57ffcdbf717ca50cf0b4cbc2 }
{ data:
   { isSaved: null,
     client:
      { lastContractTitle: null,
        feedbackText: 'No feedback yet',
        paymentVerificationStatus: 5,
        lastContractPlatform: null,
        totalFeedback: 0,
        location: [Object],
        lastContractRid: 0,
        edcUserId: 0,
        totalReviews: 0,
        companyRid: 0,
        spentTier: 'Less than $100',
        companyName: null },
     amount: { amount: 2000, currencyCode: 'USD' },
     createdOn: '2016-10-13T06:30:18+00:00',
     skills: [ [Object], [Object] ],
     enterpriseJob: false,
     ciphertext: '~0101449f91585e8e16',
     proposalsTier: null,
     description: 'I need a Christmas card app before 15th Dec.n',
     category2: 'Web, Mobile & Software Dev',
     type: 1,
     tierText: 'Intermediate ($$)',
     relevance:
      { hoursInactive: 0,
        id: 208660669,
        publishTime: '1476340233000',
        recommendedEffectiveCandidates: 7,
        effectiveCandidates: 52,
        uniqueImpressions: 0 },
     isApplied: null,
     engagement: null,
     recno: 208660669,
     title: 'Christmas Card iPhone App',
     freelancersToHire: 0,
     maxAmount: { amount: 0, currencyCode: 'USD' },
     duration: null,
     subcategory2: 'Mobile Development',
     sticky: false,
     stickyLabel: '',
     feedback: null },
  id: 57ffcdbf717ca50cf0b4cbc3 }
{ data:
   { isSaved: null,
     client:
      { lastContractTitle: null,
        feedbackText: '4.88 Stars, based on 102 feedbacks',
        paymentVerificationStatus: 1,
        lastContractPlatform: null,
        totalFeedback: 4.8843944128,
        location: [Object],
        lastContractRid: 0,
        edcUserId: 0,
        totalReviews: 102,
        companyRid: 0,
        spentTier: '$25,000+',
        companyName: null },
     amount: { amount: 100, currencyCode: 'USD' },
     createdOn: '2016-10-13T06:30:00+00:00',
     skills:
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ],
     enterpriseJob: false,
     ciphertext: '~01a04eab3b05372652',
     proposalsTier: null,
     description: 'Hello! We\'re currently searching for a developer with',
     category2: 'Writing',
     type: 1,
     tierText: 'Entry Level ($)',
     relevance:
      { hoursInactive: 0,
        id: 208660668,
        publishTime: '1476340202000',
        recommendedEffectiveCandidates: 2,
        effectiveCandidates: 6,
        uniqueImpressions: 0 },
     isApplied: null,
     engagement: null,
     recno: 208660668,
     title: 'Filipino Blog/Content Writers For a Filipino Site (Using WordPress)',
     freelancersToHire: 3,
     maxAmount: { amount: 0, currencyCode: 'USD' },
     duration: null,
     subcategory2: 'Article & Blog Writing',
     sticky: false,
     stickyLabel: '',
     feedback: null },
  id: 57ffcdbf717ca50cf0b4cbc4 }

The foreach that I have, seems to iterate through each of items, but there is no way I can get the title for each item. Any Help?

A: I'm not really sure what you're trying to do, but something like this should work if the data is indeed what you have on your comments:
feeds.forEach(function(feed){
  console.log(feed.data.title);
});

If you want faster performance, use the regular for loop. I tested this out on my project. Let me know if this doesn't work.


text:
Q: To save sensitive information in the Android internal storage what security steps we have to care about? I want to store encrypted auth information ( username, password ) to the internal device storage and when necessary I wanna decode that username and password. What's the best practice to avoid hacking that sensitive information which is stored in the internal storage ( share preference ). Is there a secure way to store them so that root user or hacker not able to decode that information?

A: Someone with root access will most likely always be able to decode information stored on their device. For best practices on how to avoid that, or at least make it diffcult, have a look at this Android Developer page:
https://developer.android.com/training/articles/keystore
But even they say in the first sentence

...to make it more difficult to extract from the device...


text:
Q: Error: Duplicate md-option values are not allowed in a select. Duplicate value "0.5 track by $index" found i'm following the instruction for ng-repeat in this link
Angular ng-repeat Error "Duplicates in a repeater are not allowed."
but in my case i use the ng-repeat in my combobox
here's my code for view(slim format)
md-input-container flex="50"
  label Period
  md-select name="type" ng-model="period"
    md-option ng-repeat=" period in periods track by $index" value="{{period.value}} track by $index"
      | {{period.name}}

and this is my controller(coffee script format)
  $scope.periods = [{ "id": 1 ,"value": 1.0 , "name": "amtopm" }, { "id": 2 , "value": 0.5 , "name": "amtoam" }, { "id": 3 , "value": 0.5 , "name": "pmtopm" }]

is this possible to resolve??
my error
Error: Duplicate md-option values are not allowed in a select. Duplicate value "0.5 track by $index" found.
at SelectMenuController.self.addOption (http://localhost:3000/assets/angular-material/angular-material.self-7da646f…0d815a4ab7457c1721ae7fe722ebb2b821ed2e8edb4651da9af5159.js?body=1:17597:15)
at setOptionValue (http://localhost:3000/assets/angular-material/angular-material.self-7da646f…0d815a4ab7457c1721ae7fe722ebb2b821ed2e8edb4651da9af5159.js?body=1:17769:18)
at Object.postLink (http://localhost:3000/assets/angular-material/angular-material.self-7da646fa80d815a4ab7457c1721ae7fe722ebb2b821ed2e8edb4651da9af5159.js?body=1:17719:7)
at http://localhost:3000/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1:1248:18
at invokeLinkFn (http://localhost:3000/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1:9935:9)
at nodeLinkFn (http://localhost:3000/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1:9336:11)
at compositeLinkFn (http://localhost:3000/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1:8621:13)
at publicLinkFn (http://localhost:3000/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1:8501:30)
at lazyCompilation (http://localhost:3000/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1:8845:25)
at boundTranscludeFn (http://localhost:3000/assets/angular/angular.self-7f8df3e3ebe7623e233b951726e7da238883fa9e7a98b987ac7aecccf5f00510.js?body=1:8638:16) <md-option ng-repeat=" period in periods track by $index" value="{{period.value}} track by $index" tabindex="0" class="ng-scope" data-ng-animate="1">


text:
Q: Using Recursion to get lists of original list in Python returns error I am given a task to use recursion so that any list that is given to it say p would be return in the desired output as shown at the end without disturbing or altering the contents of p. When I run this function it says that local variable (y) is referenced without assignment i.e. len(y)==0 but I have already assigned y outside the function init. Can someone help identify what's wrong?
y=[] #To copy contents of x in it so that x is not modified
z=[] # To return it as a list required in the question
p=[1,2,3]

def inits(x):

    if len(y)==0 and len(z)==0:
        y=[i.copy for i in x] #Copying contents of x into x so that it remains unchanged

    if len(z)==len(x)+1: #z list is one plus x list because it has [] in it
        print(z)

    else:
        z.append(y.copy())
        if len(y)!=0: #This is done so that when y=[] it does not return error for y.pop(-1)
            y.pop(-1)
        inits(x)

inits(p)

#Desired Output
[[1,2,3],[1,2],[1],[]]

A: If you don't need the last empty element then feel free to remove the else block.
Your y variable is also not needed as for me
z = []  # To return it as a list required in the question

def foo(param):
    if len(param):
        z.append([i for i in param])
        foo(param[0:-1])
    else:
        z.append([])

foo([1, 2, 3])
print(z)

[[1, 2, 3], [1, 2], [1], []]


text:
Q: PostgreSQL русский словарь для полнотекстового поиска Я пытаюсь добавить русский словарь для полнотекстового поиска в PostgreSQL.
Преобразовал в UTF-8:
iconv -f koi8-r -t utf-8 < ru_RU.aff > /usr/local/Cellar/postgresql/9.4.1/share/postgresql/tsearch_data/russian.affix
iconv -f koi8-r -t utf-8 < ru_RU.dic > /usr/local/Cellar/postgresql/9.4.1/share/postgresql/tsearch_data/russian.dict

и попытался создать новый словарь:
CREATE TEXT SEARCH DICTIONARY russian_ispell (
 TEMPLATE = ispell,
 DictFile = russian,
 AffFile = russian,
 StopWords = russian
);

Но получил сообщение об ошибке:
ERROR: invalid byte sequence for encoding "UTF8": 0xd1
CONTEXT: line 341 of configuration file "/usr/local/Cellar/postgresql/9.4.1/share/postgresql/tsearch_data/russian.affix": "SFX Y хаться шутся хаться"

Как я можно исправить эту ошибку?
Спасибо.

A: Попробуйте https://code.google.com/p/hunspell-ru/ - этот словарь полнее и не требует конвертации в utf-8. Postgres также поддерживает этот формат.


text:
Q: Nestjs call POST in controller from GET in another Controller I am having API Call, GET from one controller.
based on the response, I need to call another Controller POST
I am having issue doing that using redirect(), I am getting "Cannot Get" because the second API call is POST method.
async retrieveOrgUnit(@RequestHeader(HeadersDto) headers: HeadersDto, @Param() params: OrganizationGetUnitDto, @Body() offerDto, @Res() response: Response, cpg: ChargingProvisioningGateway) {
let result = await cpg.organizationUnit.getOrgUnitProfile({
    path: {
        customerExternalId: params.orgId,
        orgUnitExternalId: params.orgId
    },
    body: {}
}).then(async res => {
    res.status
    if( res.data.status === 22){
        **await response.redirect(307, '/offer')**
      }
    return res.data
  }).catch(err => {
    Logger.log('Failed, Error: ' + err);
    return err.status ? err.status : err.data ? err.data : err
  })

if you could see in response.redirect(307, '/offer') I am calling another controller that is calling POST API, but the method is being GET.
any advice how to do that?!

A: Redirects follow special rules, but generally you cannot change FROM a GET to a different HTTP method, only from other HTTP methods TO a GET. I would suggest just injecting the route's related service class to this current class, and calling the service directly instead of making an HTTP request to your own server and increasing the request timing.


text:
Q: Solution curves for the equation $y'=max(x,y)$, the larger of the two values $x$ and $y$ How do I find and sketch the solution curves for the equation $y'=max(x,y)$? I don't even know what is a closed function form of the expression max(x,y), let alone going about solving the differential equation?! Could someone provide a graphical output of the solution curves? Wolframalpha doesn't seem to be able to do it, and I don't have any mathematical software handy.
Any ideas?

A: The form (locally!) of the solution of
$$y'=\max\{x,y\}$$
obviously depends on which side of the line $y=x$ your solution is moving.
In Northwest we have $y'=y$, so a solution looks like $y=Ce^x$ for some constant $C$. We note that, if $C\le 1/e$, then it can be written in the form $C=Ae^{-A}$. This can easily be proven by studying the image of the function $xe^{-x}$. This is important for us, because with $C=Ae^{-A}$ we can rewrite the solution in the form
$$
y=Ce^x=Ae^{(x-A)},
$$
which will pass through the point $(x,y)=(A,A)$.
In Southeast we have $y'=x$, so a solutions looks like $y=\frac12x^2+C$ for some constant $C$.
A solution of your equation will switch from one form to the other every time it crosses the line $y=x$. A solution will be determined by an initial point $P$. If $P=(a,b)$ is in the Northwest, the solution begins to follow the curve
$$
y=be^{x-a}=be^{-a}e^x.
$$
If here $be^{-a}> e^{-1}$, it is easy to show that the solution will never cross the boundary $y=x$, i.e. the solution will be completely in the NW-side. If we have $be^{-a}=1/e$, then the curve will just graze the line $y=x$ without crossing it (see the figure below).
If $be^{-a}<1/e$, we can follow the earlier idea, and rewrite the NW-solution
in the form $y=Ae^{(x-A)}$, and the solution will eventually reach the boundary at the point $(A,A)$. Remembering that then $y'(A)=A$, we can deduce that if $A<1$, then at this point we will be crossing over from NW to SE (when $x$ increases). OTOH, if $A>1$, then we will be crossing from SE to NW side.
If we cross over to SE at the point $(A,A)$, then the solution
$$
y=\frac12x^2+\frac{2A-A^2}2
$$
is the way to go. This intersects the line $y=x$ at the points $(A,A)$
and $(2-A,2-A)$. Here we can limit ourselves to $A\ge1$, as then we can say that
the crossing point $(2-A,2-A)$ lies to the left of $(A,A)$. So the type of solutions that switch sides are of the form
$$
y=\begin{cases}
(2-A)e^{(x-2+A)},&\text{when $x\le 2-A$,}\\
\frac12x^2+\frac{2A-A^2}2,&\text{when $2-A\le x\le A$,}\\
Ae^{(x-A)},&\text{when $x\ge A.$}
\end{cases}
$$
Obviously there are no solutions that would stay forever in the Southeast - those parabolas will always reach the boundary line.
In the figure below three solutions are shown. The solution $y=e^{x-1}$ that just touches the grey boundary line. The curious solution corresponding to $A=2$ above that first follows the negative $x$-axis, then follows the parabola $y=x^2/2$ to the point $(2,2)$, and then switches to exponential growth. The third depicted solution starts below the $x$-axis, crosses the boundary at $(-2,-2)$, follows the parabola $y=(x^2-8)/2$ to the point $(4,4)$, and then continues exponentially.

Note that all the solutions are everywhere differentiable, as $\max\{x,y\}$ is continuous on the entire plane. They won't be twice differentiable unless they stay in NW. This is because the SE-solution has second derivative equal to $1$ everywhere, and a NW-solution has second derivative equal to $A$ at the crossing point $(A,A)$.


text:
Q: How to create a global variable in ATS? Basically, I am looking for something more or less equivalent to the following C code:
int theGlobalCount = 0;

int
theGlobalCount_get() { return theGlobalCount; }

void
theGlobalCount_set(int n) { theGlobalCount = n; return; }

A: You could use a neat trick: declare a mutable global variable, and make a ref (aka mutable reference) point to it (no GC is required to make this work!). Then, implement functions to provide access to the mutable reference.
local

var theGlobalCount_var : int = 0
val theGlobalCount = ref_make_viewptr (view@ theGlobalCount_var | addr@ theGlobalCount_var)

in // in of [local]

fun
theGlobalCount_get () : int = ref_get_elt (theGlobalCount)

fun
theGlobalCount_set (n: int): void = ref_set_elt (theGlobalCount, n)

end // end of [local]

Note that declarations inside local-in are visible only to code inside in-end. Therefore, neither theGlobalCount_var nor theGlobalCount are visible outside the scope of the local.
Full code: glot.io

A: You can also use the extvar feature to update an external global variable (declared in the target language). This is very useful if you compile ATS to a language that does not support explicit pointers (e.g., JavaScript). Here is a running example that makes use of this feature:
http://www.ats-lang.org/SERVER/MYCODE/Patsoptaas_serve.php?mycode_url=http://pastebin.com/raw/MsXhVE0A


text:
Q: How to move a domain from one project to another in Google Cloud Domains I have mistakenly registered a domain in the wrong project from Google Cloud > Network Services > Cloud Domains.
Is there a way for me to move it in another project?

A: Google Domains is not project based. Domains are managed by the identity of the domain owner.
Google Cloud Domains is in preview and is project based. At this time, there is no method to move a registered domain from one project to another. You can export the domain to Google Domains. Note: The DNS servers for a domain can be located in any project and do not need to be in the same project as Google Cloud Domains. Before exporting the domain, check to see if your domain is already being managed by Google Domains here. You will need to be using the same identity that owns the registered domain. If the domain appears, go to the other project, create the DNS servers and then enter the servers into Google Domains on the DNS tab under Name Servers. You can also change the DNS servers while in Google Cloud Domains. Select "EDIT DNS DETAILS" at the top of the Google Cloud Domains console window.
If you mean that you created the DNS server in one project and you need to move the DNS server to another project then follow these steps. Create a new DNS server in the desired project, duplicate the DNS server resource records and then update the DNS server entries in Google Domains. Wait at least 24 hours and then delete the old DNS server.
If you mean that your registered your domain under the wrong Google Account (email identity), then you can transfer the domain to the desired Google Account. Login to Google Domains with the account that you own the domain. In the interface follow the Transfer a domain out section. Get the authorization code. In another browser window, login with the desired account and transfer in the domain using the transfer authorization code.


text: Q: openssl/bio.h file not found when build the application in Xcode 5.0.2 I am using Xcode 5.0.2 and i am trying to build my application, but i am getting openssl/bio.h file not found exception. I added libcrypto.a file into the Xcode directory and also set the header search paths for project. Still i am getting same issue.Can anyone help me on this.Thanks in advance.


text:
Q: Understanding httr's response object I'm following this example to use httr to send POST request:
How can I POST a simple HTML form in R?
How would I go about storing the resulting table of values into a dataframe? I don't quite understand how to find the values in the response object.

A: Seems like you probably want rvest::html_table:
library(rvest)
content(resp) %>%
   html_table() %>%
   `[[`(1)
## A tibble: 370 x 8
#   CUSIP     `SECURITY TYPE`   RATE   `MATURITY DATE` `CALL DATE`   BUY  SELL `END OF DAY`
#   <chr>     <chr>             <chr>  <chr>           <lgl>       <dbl> <dbl>        <dbl>
# 1 912796EK1 MARKET BASED BILL 0.000% 12/18/2014      NA             0   100.         100.
# 2 912796EL9 MARKET BASED BILL 0.000% 12/26/2014      NA           100.  100.         100.
# 3 912796EM7 MARKET BASED BILL 0.000% 01/02/2015      NA           100.  100.         100.
# 4 912796DF3 MARKET BASED BILL 0.000% 01/08/2015      NA           100   100          100.
# 5 912796EP0 MARKET BASED BILL 0.000% 01/15/2015      NA           100.  100.         100.
# 6 912796EQ8 MARKET BASED BILL 0.000% 01/22/2015      NA           100   100          100.
# 7 912796ER6 MARKET BASED BILL 0.000% 01/29/2015      NA           100   100          100.
# 8 912796DG1 MARKET BASED BILL 0.000% 02/05/2015      NA           100   100          100.
# 9 912796EU9 MARKET BASED BILL 0.000% 02/12/2015      NA           100.  100.         100.
#10 912796EV7 MARKET BASED BILL 0.000% 02/19/2015      NA           100.  100.         100.
## … with 360 more rows

From the linked question for clarity:
library(httr)
url <- "https://www.treasurydirect.gov/GA-FI/FedInvest/selectSecurityPriceDate.htm"
fd <- list(
    submit = "Show Prices",
    priceDate.year  = 2014,
    priceDate.month = 12,
    priceDate.day   = 15
)
resp<-POST(url, body=fd, encode="form")


text:
Q: Algebra Distance Question Dara drove from home to the airport to pick up her friend and then came back home on the same route. Her average speed on the way to the airport was 55 miles per hour (mph), and her average speed on the way back home was 45 mph. If the total driving time was 1 hour and 20 minutes, how far, in miles, is the airport from Dara's home?
A) 29.7
B) 33
C) 100/3
D) 66
How do you solve such problems relating to distance given time and rate? Previously seen on SAT.
I understand d=rt but I can't get the set up to be correct. I learned this before but I can't recall how to do it.

A: Lets let
$x = $ Distance from Dara's home to airport
$t_{1} =$ Time it took Dara to get from her home to the airport
$t_{2} =$ Time it took Dara to get from the airport to  her home
$s_{1} =$ Average speed one her way to the airport
$s_{2} =$ Average speed coming back to the airport
So we know that
$$Speed = \frac{distance}{time}$$
So when Dara was going on her way to the airport
$$s_{1} = \frac{x}{t_{1}}$$
We know that $s_{1} = 55\, mph$
We can rearrange this formula to get
$$t_{1} = \frac{x}{s_{1}} = \frac{x}{55}$$
Similarly when Dara is coming back from the airport
$$s_{2} = \frac{x}{t_{2}}$$
We know that $s_{2} = 45\, mph$
We can rearrange this formula to get
$$t_{2} = \frac{x}{s_{2}} = \frac{x}{45}$$
We are also given that the total time is 1 hour and 20 minutes.
This means $t_{total} = t_{1} + t_{2}=$ 80 minutes
Now by plugging in the equations we found for $t_{1}$ and $t_{2}$ we end up with
$$80 = \frac{x}{55} + \frac{x}{45}$$
By finding a common denominator we get
$$80 = \frac{45x +55x}{45*55}$$
Now we can solve for $x$
$$x= \frac{80*45*55}{45+55}=1980\,\frac{min*mile}{h}*\frac{1\,h}{60\, min}=33\,miles$$

A: Let $t_1$ be the time it took Dara to drive from home to the airport, and $t_2$ be the time it took her to drive back home. Then
$$t_1 + t_2 = \left (1 + \frac{20}{60} \right)\, \mathrm h. \tag{1}$$
Let $d$ be the distance from home to the airport. Then
$$d = 55\, \text{mi}/\text{h} \cdot t_1$$
but also
$$d = 45\, \text{mi}/\text{h} \cdot t_2$$
and so
$$55\, \text{mi}/\text{h} \cdot t_1 = 45\, \text{mi}/\text{h} \cdot t_2. \tag{2}$$
From equations $(1)$ and $(2)$ you should be able to find $t_1$ and $t_2$, and thus also $d$.


text:
Q: git branch depulicated and overwrote common ancestor to make a linear history I tried my hand in branches for git, and seemed to have flubbed it. Somehow  the topic branch is just part of the linear history of the master branch. I think it is easiest to explain by showing what git log --all --graph --pretty=format:'%h -%Creset%d%Creset %s (%ct)' returns.

This is what my current git log graph looks like, with SHA-1 - (branch head) message (UNIX time). The message is just the order in which I had committed. There are three branches: master, hooks, debug.
* 7177766 - (master) feat: 9 (1473806908)
| * db62937 - (hooks) feat: 8 (1473803597)
| * b3e410e - feat: 7 (1473803486)
|/
* ad358b5 - docs: 2 (1472707528)
* 63562a6 - feat: 1 (1472707509)
* c90dd7c - init: 0 (1472707503)
* 3570d3e - (debug) dbug: 6 (1472713561)
* 63eec96 - dbug: 5 (1472712406)
* 62ab5a6 - dbug: 4 (1472712076)
* 68a46ff - dbug: 3 (1472712076)
* 2936b65 - feat: 1 (1472712076)
* 16eaa61 - init: 0 (1472711864)

What I thought it would look like, and how I am visualizing the workflow in my head.
*    7177766 - (master) feat: 9 (1473806908)
| *  db62937 - (hooks) feat: 8 (1473803597)
| *  b3e410e - feat: 7 (1473803486)
|/
*    ad358b5 - (origin/master) docs: 2 (1472707528)
|  * 3570d3e - (debug) dbug: 6 (1472713561)
|  * 63eec96 - dbug: 5 (1472712406)
|  * 62ab5a6 - dbug: 4 (1472712076)
|  * 68a46ff - dbug: 3 (1472712076)
| /
|/
*    63562a6 - feat: 1 (1472707509)
*    c90dd7c - init: 0 (1472707503)

The "true" first commit should be init: 0 (1472707503) SHA-1 c90dd7c (that which shows up in the master branch log), so SHA-1 16eaa61 shouldn't exist (the first commit seen on the debug branch log). Alongside with the "true" second commit feat: 1 (1472707509) SHA-1 63562a6 and not SHA-1 2936b65.
It looks like I somehow messed up creating the branch for debug. I should note that chronologically, the debug branch was made after already committing docs: 2. I'm not sure exactly what I did, but after committing docs: 2 I probably git checkout 63562a6 and made a debug branch from there.

In short, I am not sure how I got debug to make new init: 0 and feat: 1 commits, on top of put adding itself to the linear history. Does anyone know how I can fix this, and perhaps what mistake I made so that I might avoid it in the future?
EDIT: Looking through the reflog it looks like there is ample opportunity for me to have messed it up with a rebase. Still hunting down a solution.
ad358b5 HEAD@{52}: checkout:           moving from debug to master
3570d3e HEAD@{53}: commit    (amend):  dbug: 6
6a228cc HEAD@{54}: commit:             dbug: 6
63eec96 HEAD@{55}: commit    (amend):  dbug: 5
a5c79e6 HEAD@{56}: rebase -i (finish): returning to refs/heads/debug
a5c79e6 HEAD@{57}: rebase -i (pick):   dbug: 5
62ab5a6 HEAD@{58}: rebase -i (pick):   dbug: 4
68a46ff HEAD@{59}: rebase -i (pick):   dbug: 3
2936b65 HEAD@{60}: rebase -i (pick):   feat: 1
16eaa61 HEAD@{61}: commit    (amend):  init: 0
477d2d0 HEAD@{62}: commit    (amend):  init: 0
00329f0 HEAD@{63}: commit    (amend):  init: C0
227c974 HEAD@{64}: rebase -i (edit):   init: 0
567c85f HEAD@{65}: rebase -i (edit):   init: 0
d901ba4 HEAD@{66}: rebase -i (start):  checkout d901ba4
95fc103 HEAD@{67}: rebase -i (finish): returning to refs/heads/debug
95fc103 HEAD@{68}: rebase -i (pick):   dbug: 5
58b536b HEAD@{69}: rebase -i (pick):   dbug: 4
a285cf6 HEAD@{70}: rebase -i (pick):   dbug: 3
db852f6 HEAD@{71}: commit    (amend):  feat: 1
5001e98 HEAD@{72}: rebase -i (edit):   feat: 1
e29b722 HEAD@{73}: commit    (amend):  init: 0
6a99fad HEAD@{74}: rebase -i (edit):   init: 0
46ccd71 HEAD@{75}: rebase -i (edit):   init: 0
0584490 HEAD@{76}: rebase -i (start):  checkout 0584490
63af029 HEAD@{77}: commit:             dbug: 5
ca45966 HEAD@{78}: commit:             dbug: 4
11b3ca6 HEAD@{79}: commit:             dbug: 3
63562a6 HEAD@{80}: checkout:           moving from 63562a6 to debug

A: It's difficult to see what exactly happened without being able to see your full repo.  Based on your reflog, I think you edited a commit during rebase -i which was then recommitted on top of the older one.
When you rebase, commits get new hashes because the datetime is used as part of the inputs to the hashing algorithm so it's hard to see the contents.  You can verify what's actually in the commit with git show.
To fix it, you can try rebasing again on the oldest common commit and picking the correct commits.  Before doing that, make sure to add a tag or branch so you can get back your initial state.  It's a risky process though, so be careful!


text:
Q: IE8 & FF XHTML error or badly formed span? I recently have found a strange occurrence in IE8 & FF.
The designers where using js to dynamically create some span tags for layout (they were placing rounded corner graphics on some tabs). Now the xhtml, in js, looked like this:  and worked perfectly!
As we all know dynamically rendering elements in js can be quite processor intensive  so I moved the elements from js into the page source, exactly as above.
... and it didn't work... not only didn't it work, it crashes IE8.The fix was simple, put the close span in ie:
I am a bit confused by this.
Firstly as far as I am aware  is perfectly valid XHTML!
Secondly it works dynamically, but not in XHTML?!?!?
Can anyone shed any light on this or is it simply another odd occurrence of browsers?

A: The major browsers only support a small subset of self-closing tags.  (See this answer for a complete list.)
Depending on how you were creating the elements in JS, the JavaScript engine probably created a valid element to place in the DOM.

A: I had similar problem with a tags in IE.
The problem was my links looked like that (it was an icon set with the css, so I didn't need the text in it:

Unfortunately in IE these links were not displayed at all. They have to be in

format (leaving empty text didn't work as well so I put   there). So what I did is I add an few extra JS lines to fix it as I didn't want to change all my HTML just for this browser (ps. I'm using jQuery for my JS).
if ($.browser.msie) {
    $('a.icon').html('&nbsp');
}

A: IE in particular does not support XHTML. That is, it will never apply proper XML parsing rules to a document - it will treat it as HTML even with proper DOCTYPE and all. XHTML is not always valid SGML, however. In some cases (such as
) IE can figure it out because it's prepared to parse tagsoup, and not just valid SGML. However, in other cases, the same "tagsoup" behavior means that it won't treat /> as self-closing tag terminator.
In general, my advice is to just use HTML 4.01 Strict. That way you know exactly what to expect. And there's little point in feeding XHTML to browsers when they're treating it as HTML anyway...

A: See I think that one of the answers to Is writing self closing tags for elements not traditionally empty bad practice? will answer your question.

A: XHTML is only XHTML if it is served as application/xhtml+xml — otherwise, at least as far as browsers are concerned, it is HTML and treated as tag soup.
As a result,  means "A span start tag" and not "A complete span element". (Technically it should mean "A span start tag and a greater than sign", but that is another story).
The XHTML spec tells you what you need to do to get your XHTML to parse as HTML.
One of the rules is "For non-empty elements, end tags are required". The list of elements includes a quick reference to which are empty and which are not.


text:
Q: Vlc.DotNet.Core taking snapshot while streaming I am using Vlc.DotNet.Core for multicast video streaming. Also, I want to take snapshots. For testing, I am working on a simple program that calling snapshot function for every 2 seconds. However snapshot function is not working, when TakeSnapshot function called, it is not calling OnMediaPlayerSnapshotTaken event.
Besides that, I made a snapshot tests for Vlc.DotNet.Forms library and its working quite well.
The simple code I am working on is given below :
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Vlc.DotNet.Core;

namespace SnapshotTest
{
    class Program
    {
        static void Main(string[] args)
        {
            VlcStreamerSnapshotText myObject = new VlcStreamerSnapshotText();

            myObject.streamFile();
        }
    }
    class VlcStreamerSnapshotText
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();

        static Vlc.DotNet.Core.VlcMediaPlayer mediaPlayer;

        public bool streamFile(string source = "")
        {
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 2000;
            aTimer.Enabled = true;

            var currentDirectory = Directory.GetCurrentDirectory();
            var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "x86" : "x64"));

            var options = new string[]
            {
                "--no-snapshot-preview",
                "--no-audio"
                //"--no-video"
                // VLC options can be given here. Please refer to the VLC command line documentation.
        };

            mediaPlayer = new Vlc.DotNet.Core.VlcMediaPlayer(new DirectoryInfo(libDirectory.FullName), options);

            string[] mediaOptions = new string[]
            {
                ":sout=#duplicate{dst=rtp{sdp=rtsp://127.0.0.1:1000/},dst=display}",
                ":sout-all",
                ":sout-keep"
            };

            //string[] mediaOptions = new string[] { string.Concat("--sout=#duplicate{dst=rtp{sdp=rtsp://", IpAddress, ":", "1000", "/}} --sout-all --sout-keep") };

            mediaPlayer.SetMedia(new Uri("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_h264.mov"), mediaOptions);

            mediaPlayer.SnapshotTaken += OnMediaPlayerSnapshotTaken;

            bool playFinished = false;
            mediaPlayer.PositionChanged += (sender, e) =>
            {
                Console.Write("\r" + Math.Floor(e.NewPosition * 100) + "%");
            };

            mediaPlayer.EncounteredError += (sender, e) =>
            {
                Console.Error.Write("An error occurred");
                playFinished = true;
            };

            mediaPlayer.EndReached += (sender, e) =>
            {
                playFinished = true;
            };

            Task.Factory.StartNew(() => mediaPlayer.Play());
            //mediaPlayer.Play();

            // Ugly, sorry
            while (!playFinished)
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(500));
            }
            return true;
        }

        ManualResetEvent m_mreSnapshot = new ManualResetEvent(false);
        private readonly object m_snapLock = new object();
        private bool m_SnapshotIsTaken = false;
        public bool GetSnapshot()
        {
            m_SnapshotIsTaken = false;
            if (mediaPlayer == null)
            {
                return false;
            }

            string currentTime = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            string uniqueId = generateID(string.Empty);
            string snapName = string.Format("{0}_{1}.png", currentTime, uniqueId);

            string tempFilePathCand = Path.GetTempPath();

            if (!tempFilePathCand.EndsWith("\\"))
                tempFilePathCand = tempFilePathCand + "\\" + snapName;
            else
                tempFilePathCand = tempFilePathCand + snapName;

            FileInfo snapPathInfo = new FileInfo(tempFilePathCand);
            //mediaPlayer.Manager.TakeSnapshot();
            mediaPlayer.TakeSnapshot(snapPathInfo);

            m_mreSnapshot.WaitOne(TimeSpan.FromSeconds(2));
            if (m_SnapshotIsTaken)
                return true;

            return false;
        }

        private string generateID(string tip)
        {
            return string.Format(@"{0}_{1}", tip, Guid.NewGuid().ToString("N"));
        }

        void OnMediaPlayerSnapshotTaken(object sender, VlcMediaPlayerSnapshotTakenEventArgs e)
        {
            mediaPlayer.SnapshotTaken -= OnMediaPlayerSnapshotTaken;
            m_SnapshotIsTaken = true;
            mediaPlayer.SnapshotTaken += OnMediaPlayerSnapshotTaken;
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            GetSnapshot();
        }
    }
}

So, What am I missing?

A: Maybe a bug in Vlc.DotNet: https://github.com/ZeBobo5/Vlc.DotNet/issues/447
Are you using Vlc.DotNet v3?


text:
Q: Combine several post request into one, transform this batch and return answers for these post requests I'm not good at work with request, but my current project require this. Now my server works like this:
from aiohttp import web

@routes.post('/')
async def my_func(request):
    post = await request.json()
    answer = '... do something on GPU ...'
    return web.json_response(answer)`

But I want combine several requests into one and do my function on GPU only once. And after that return responses for all requests (may be in the loop). I can change aoihttp to different package if it necessary for solving.
For example, post request contains fields: {'id':1, 'data':'some data 1'}.
(1) I want wait 5 requests, combine data to list ['some data 1', ..,'some data 5']
(2) and then apply my function to this list (it returns me list of answers ['answer 1', ..,'answer 5']
(3) And after that I want make response for each request like this {'id':1, 'answers':'answer_1'}
I don't now how to realize steps (1) and (3).

A: You can keep a cache of requests (questions) and responses (answers) and a background task that checks said cache; when the questions cache length reaches 5 you run the GPU function and populate the answers cache.
Each request waits until the answers cache has the data it needs.
server.py
import asyncio
from aiohttp import web

def gpu_func(items):
    """Send a batch of 5 questions to GPU and return the answers"""
    answers = {}
    for item in items:
        answers[item["id"]] = "answer for data: " + item["data"]
    return answers

async def gpu_loop(app):
    """Check questions cache continuously and when we have 5 questions process them and populate answers cache"""
    while True:
        if len(app.cache["questions"]) >= 5:
            print("running GPU function")
            answers = gpu_func(app.cache["questions"][:5])
            print("got %d answers from GPU" % len(answers))
            app.cache["answers"].update(answers)
            app.cache["questions"] = app.cache["questions"][5:]
        await asyncio.sleep(0.05)  # sleep for 50ms

async def handle(request):
    """Main request handler: populate questions cache and wait for the answer to be available in the answers cache"""
    data = await request.post()
    print("got request with data ", data)
    request.app.cache["questions"].append(data)
    # can implement here a time limit using a counter (sleep_delay*counter = max time for request)
    while True:
        if data["id"] in request.app.cache["answers"]:
            break
        await asyncio.sleep(0.05)
    answer = request.app.cache["answers"].pop(data["id"], "unknown")
    return web.Response(text=answer)

# create background task (gpu_loop)
async def start_background_tasks(app):
    app.gpu_loop = asyncio.create_task(gpu_loop(app))

# stop background task on shutdown
async def cleanup_background_tasks(app):
    app.gpu_loop.cancel()
    await app.gpu_loop

def main():
    app = web.Application()
    app.cache = {"questions": [], "answers": {}}
    app.add_routes([web.post("/", handle)])
    app.on_startup.append(start_background_tasks)
    app.on_cleanup.append(cleanup_background_tasks)
    web.run_app(app)

if __name__ == "__main__":
    main()

client.py
import aiohttp
import asyncio

async def make_request(session, num):
    """Make a single request using the existing session object and custom number"""
    url = "http://127.0.01:8080"
    data = {"id": num, "data": "question %d" % num}
    response = await session.post(url, data=data)
    text = await response.text()
    return text

async def main():
    """Make 20 consecutive requests with a delay of 20 ms between them"""
    tasks = []
    session = aiohttp.ClientSession()
    for i in range(20):
        print("making request %d", i)
        task = asyncio.ensure_future(make_request(session, i))
        tasks.append(task)
        await asyncio.sleep(0.02)
    responses = await asyncio.gather(*tasks)
    for response in responses:
        print(response)
    await session.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Depending on concurrency (how often the requests are being made from the client side) and processing time (how long it takes to process a group of requests) you might need to tweak the timing (sleep) and cache limit (how many requests to keep in the cache).
Hope this gets you started.


text:
Q: C++ version conflict for using nlohmann/json in drake I recently found out that nlohmann/json runs on C++ 11. Otherwise it gives some syntax error due to a deprecated line from using a higher C++ version.
bazel-out/k8-opt/bin/examples/collaboration_station/_virtual_includes/manipulation_station/drake/examples/manipulation_station/include/json.hpp:2149:30: error: redundant redeclaration of 'constexpr' static data member 'nlohmann::detail::static_const<T>::value' [-Werror=deprecated]
 constexpr T static_const<T>::value;
                              ^~~~~
bazel-out/k8-opt/bin/examples/collaboration_station/_virtual_includes/manipulation_station/drake/examples/manipulation_station/include/json.hpp:2145:24: note: previous declaration of 'nlohmann::detail::static_const<T>::value'
     static constexpr T value{};

I was able to run a normal c++ file with nlohmann by using the key term
bazel run --cxxopt='-std=c++11

However, if I incorporate drake into my example, it does not run (most likely due to a low C++ version)
In order to test out nlohmann/json, I took their json.hpp file located under json/single_include/nlohmann/json.hpp on their github page. I made sure to #include the json file.
Is there an easy way to incorporate nlohmann/json or any other type of json reader into drake?

A: Although this didn't solve the nlohmann problem, this is an alternative to parse a json file in Drake. If you ever find it annoying to recompile your c++ file every time you change a variable, using a json file may be useful.
In your BUILD.bazel file under deps, write
"@jsoncpp",

Then in your .cc file, include the followings:
#include <fstream>
#include <jsoncpp/json/json.h>
#include "drake/common/find_resource.h"

Now write your json parsing function
Json::Value json_parser(){
  Json::Reader reader;
  Json::Value root;
  drake::log()->info("json parser activated.");

  // User does not have to specify /home/your_name/
  std::ifstream myfile(FindResourceOrThrow("drake/path_to_file/config.json"));
  myfile >> root;
  drake::log()->info("reading json config file completed.");
  return root;

  // Example of accessing **outside** of this function
  // Json::Value root = json_parser();
  // cout << root["name"].asString() << endl;
}

For this example, the name of the json file is "config.json". Feel free to change it to whatever you want.


text:
Q: Passing and setting booleans - Java/Android I have a class like so:
public class Achievements(){

    boolean score100_Earned_Offline;
    boolean score1000_Earned_Offline;

    final String score100 = "xxxxxxxxxx" //where xxxxxxxxxx would be replaced with the achievement's Google Play Games ID
    final  String score1000 = "xxxxxxxxxx" //where xxxxxxxxxx would be replaced with the achievement's Google Play Games ID
}

In my Game class, I check the state of the achievements every tick and act on them as necessary like so (assume all methods to be valid and defined - this is cut down to provide the code necessary to the question).......
public class Game(){

    public void checkAchievements(Achievements achievements){

        if (score>=100){
            unlockAchievement(achievements.score100, achievements.score100_Earned_Offline);
        }

        if (score>1000){
            unlockAchievement(achievements.score100, achievements.score1000_Earned_Offline);
        }
    }

    public void unlockAchievement(String achievementToUnlock, boolean thisAchievementOfflineFlag){

        //If user is signed in, then we are ready to go, so go ahead and unlock the relevant achievement....
        if (checkSignedIn()){
            Games.Achievements.unlock(getApiClient(), achievementToUnlock);
        //Otherwise, I want to do is set the relevant flag to true so it can be checked when the user does eventually log in
        else{
            thisAchievementOfflineFlag=true;
        }
    }
}

Pass by value
In the 'unlockAchievement' method, the boolean 'thisAchievementOfflineFlag' does get set to true if the user is not logged in, however, it doesn't effect the actual boolean that was originally sent into the method (which as you can see is defined in my 'Achievements' class).  I'm guessing this is because Java is Pass by Value and is therefore, creating a local copy of the variable which is valid inside the method only.  I did try using Boolean too (wrapper class) but got the same results.
Other ways to achieve this?
I've currently got it set up so I can define each achievement as an enum so each one will have it's own copy of the boolean flag.  However, I'm aware that it's not recommended to use enums in Android so if there is a better way that I am missing, I would rather avoid them.
Please note that I don't want to use if checks or switch statements as this is taking place in a game-loop.
Any suggestions appreciated

A: This is all because Java's implementation of Boolean (also, for example String) is immutable for safety reasons. You can see it here: http://www.explain-java.com/is-string-mutable-in-java-why-wrapper-classes-immutable-in-java/
You can solve your problem by introducing an object wrapper for that boolean:
public class BooleanWrapper {

    private boolean value;

    public void set(boolean value) {
        this.value = value;
    }

    public boolean get() {
        return value;
    }
}

Now, this object reference will be passed by value but will still point to the same BooleanWrapper object on the heap. You can simply use getters and setters to change the inner boolean value.
Then your code would become:
public void unlockAchievement(String achievementToUnlock, BooleanWrapper thisAchievementOfflineFlag){
    if (checkSignedIn()){
        Games.Achievements.unlock(getApiClient(), achievementToUnlock);
    else {
        thisAchievementOfflineFlag.set(true);
    }
}

Java is pass-by-value:
When you pass boolean then you for sure passed it by value, while it is a primitive type. When you pass Boolean, you would think it's an object and that you can change it's state, but actually you cannot because Boolean is implemented as an immutable object (as already said). You can confirm this just by reading the code of java.lang.Boolean.
But if you create  your own wrapper class, and in a sense, you control whether you implement it in immutable or mutable way. BooleanWrapper I wrote lets you change the state of that object. And when you pass an object such as this one to the method, it's passed by value. That means that another reference is created, but it points to the same object on heap (see image below).

A: You could use an AtomicBoolean, which will have pass-by-reference semantics.


text:
Q: overloading operator<< vs. namespaces I have a problem with overloading operator<< combined with namespaces. I have read the related posts, but still do not understand what is going on in my case..
The following code compiles OK:
file test_matrix.hpp:
#ifndef TEST_MATRIX_HPP
#define TEST_MATRIX_HPP

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
namespace ublas = boost::numeric::ublas; // shortcut name

namespace VecMat {
    typedef ublas::matrix<double> MatrixD; // matrix of doubles

    template<class MT>
    std::ostream & operator<< (std::ostream & os,
                               const ublas::matrix_expression<MT> & M)
    {
        // Note: the matrix_expression<MT> has only one method "()", which
        // returns "& MT" or "const & MT" - a ref. to the included matrix object.
        typename MT::const_iterator1 it1;
        typename MT::const_iterator2 it2;
        for (it1 = M().begin1(); it1 != M().end1(); ++it1) {
            for (it2 = it1.begin(); it2 != it1.end(); ++it2) {
                os << *it2 << "\t";
            }
        os << std::endl;
        }
        return os;
    }
}; // namespace VecMat
#endif

file test_oper.cpp:
#include "test_matrix.hpp"
using std::cout;
using std::endl;
using VecMat::MatrixD;
using VecMat::operator<<;

// ---------------------------------------------------------------------------
// would be in a header file
void test1 ();
namespace Main {
    void test2 ();
}
// ---------------------------------------------------------------------------

void test1 ()
{
    MatrixD X(10,3);
    VecMat::operator<<(cout << endl, X) << endl;
    cout << "X =" << endl << X << endl;
}

void Main::test2 ()
{
    MatrixD X(10,3);
    VecMat::operator<<(cout << endl, X) << endl;
    cout << "X =" << endl << X << endl;
}

Note that the using VecMat::operator<<; line is needed - without it, I get an error on the last line of test1() (using gcc 4.5):

test_oper.cpp||In function 'void test1()':|
  test_oper.cpp|22|error: no match for 'operator<<' in '((std::basic_ostream*)std::operator<<

Should not the compiler find the operator self using ADL, since the argument is of type VecMat::MatrixD?
My main problem, however, starts when I add a new class with its own operator<< to the Main namespace:
file test_other.hpp:
#ifndef TEST_OTHER_HPP
#define TEST_OTHER_HPP
#include <ostream>

namespace Main {
    class Foo {
        int n;
    };
    std::ostream & operator<< (std::ostream & os, Foo const & foo);
}
#endif

If I then '#include "test_other.hpp"' from either of the two original files, the .cpp file won't compile, with the same error as above, only in the last line of test2()

test_oper.cpp||In function 'void Main::test2()':|
  test_oper.cpp|29|error: no match for 'operator<<' in '((std::basic_ostream*)std::operator<<

If I put Foo into a different namespace (either VecMat or a new one), it compiles OK. Does it mean that the compiler looks first into Main, finds one operator<< there (for Foo), and therefore stop searching and complains that it has found the wrong operator? Again, I would have thought that it would look into VecMat first, since the argument is of type VecMat::MatrixD?
I would appreciate both an explanation of what is going on and a recommendation how to resolve it in a cleanest possible way.
Thanks a lot.
Michal
PS: I posted the question also elsewhere and there it was suggested (http://www.cplusplus.com/forum/general/47766/#msg259246) to add the using VecMat::operator<<; line also inside the Main namespace. This solves it - but I would still like to know why do I need those lines and whether this is the best/recommended solution.

A: typedef doesn't introduce a new type. So VecMat::MatrixD is not a new type, it's an alias to boost::numeric::ublas::matrix<double>, therefore the associated namespaces used in ADL are those of boost::numeric::ublas::matrix<double>.


text:
Q: Create a file C++ (cross-platform solution for Unix and Windows) Is there a way from C++ code to use (fstream, FILE, etc.) to create a file on both Unix and Windows?
If not what you can do in order to have your code run on both Unix and Windows?

A: ofstream out(path);

or
FILE *fp = fopen(path, "w");

will create the file path if it does not exist.

A: fopen("foo.txt", "w"); // write-only
fopen("foo.txt", "w+"); // write+read
fstream filestr;
filestr.open ("foo.txt", fstream::out | fstream::trunc); // write-only
filestr.open ("foo.txt", fstream::in | fstream::out | fstream::trunc); // write+read

All of these will create the file, or truncate it if it already exists.


text:
Q: What is logarithm & how log table can be constructed by me? I'm studying properties of logarithm but I don't understand how base e works. Base 10 looks simple while doing calculations of numbers having multiple of 10. As other numbers are not multiple of 10 how one can calculate without using log table. That's why I want know how log table is constructed & how base e works ? I'm very basic user, I don't get integration, derivatives & summations. Please give answer theoretically or using row concepts. Since I want to construct log table by myself.

A: "Logarithm" is the inverse to "exponential".  In particular, if $y= a^x$, then $log_a(y)= x$.  For example, it is true that $10^{0.30102}= 1.9999$ (approximately 2) so log(2) is approximately log(1.9999)= .30102.  If you really want to construct a table of logarithms, base 10, using paper and pencil, as mathematicians several hundred years ago, be prepared to do some tedious arithmetic (as they did)!  log(0.01) is easy- 0.01= 1/100= $10^{-2}$ so log(0.01)= -2.  log(0.02) is harder.  You can simplify a bit by arguing that log(0.02)= log(2/100)= log(2)- log(100)= log(2)- 2 so you just need to find log(2) (in fact, many tables of logarithms just give logarithms of numbers from 1 to 10).  log(2) is the x such that $10^x= 2$.  If we did not know that $10^{0.30102}$ is approximately 2, we could work it out by noting that $10^{0.3}= (10^3)^{1/10}= 1000^{1/10}$ and start calculating that value, then noting that $10^{0.4}= 10^{2/5}= 100^{1/5}$ and seeing that the first is less than 2 while the second is larger than 2- so the logarithm is between .3 and .4.  So look at $10^{3.5}$.  As I said, be prepared for so long tedious calculation.


text:
Q: VBA : Manipulate selected Picture with external script I have a dotx/docx document with many pictures and need to manipulate many of them in the same way. Therefore I have written a Python script which will perform the image manipulation on a jpg file.
All I need to do now is to write a VBA script which will save the currently selected picture as jpg file, call the Python script and replace the picture in the document. And then assign this macro to a keyboard shortcut.
My VBA code is currently:
Sub ManipulateImage()
    Dim sel As Word.Selection
    Dim shp As InlineShape

    Set sel = Selection
    If sel.Type = wdSelectionInlineShape Then
        Set shp = sel.InlineShapes(1)
        Debug.Print "**"
        'Save as picture
    End If

    'Manipulate saved picture
    Shell "mypythonscript.py imgfile"

    'Replace picture
    'sel.PasteSpecial?

End Sub

I currently can't figure out how to save the InlineShape object as jpg image using VBA. If I do it manually, I can simply right click the picture and select "Save as Picture".

A: You can use the following code for saving inline shapes in Word VBA:
Private Sub saveImage(shp As InlineShape, path As String)

    Dim s As String
    Dim i As Long
    Dim j As Long

    Dim r As Range

    Set r = shp.Range.Duplicate
    r.start = r.start - 1
    r.End = r.End + 1

    ''shp.range.WordOpenXML does not always contain the binary data
    ''s = shp.Range.WordOpenXML

    s = r.WordOpenXML

    i = InStr(s, "<pkg:binaryData>") + 16

    If i = 16 Then
        MsgBox "No binary data found"
        Exit Sub
    End If

    j = InStr(i, s, "</pkg:binaryData>")

    s = Mid$(s, i, j - i)

    Dim DecodeBase64() As Byte
    Dim objXML As Object 'MSXML2.DOMDocument
    Dim objNode As Object 'MSXML2.IXMLDOMElement

    Set objXML = CreateObject("MSXML2.DOMDocument")

    'create node with type of base 64 and decode
    Set objNode = objXML.createElement("b64")
    objNode.DataType = "bin.base64"
    objNode.Text = s
    DecodeBase64 = objNode.nodeTypedValue

    Set objNode = Nothing
    Set objXML = Nothing

    Open path For Binary As #1
       Put #1, 1, DecodeBase64
    Close #1

End Sub

See Save InlineShape picture to file in Word VBA for more information.


text:
Q: NERDTree] How can I map double click to NERDTreeCustomOpen? This might be a simple question for NERDTree users.
I'm trying to use NERDTree, and I found two ways to open files in NERDTree window, press <CR> as enter and double-click the file with the mouse (same as with pressing o).
I wanted to open new file in the window at vertical right side (keep original file opened), and finally I could customize NERDTreeCustomOpenArgs. However, the way to open files with double-click seems to be different, so I want to remap double-click to NERDTreeCustomOpen, not to NERDTree-o.
I've tried to map the double-click as shown here and here, but it has not worked for me.


text:
Q: Como criar um link clicável dentro outro Tenho um sistema onde preciso criar um link clicável href dentro de uma div que também é clicável.
Em resumo queria saber se existe alguma forma de criar um "link clicável B" dentro de um "link clicável A". Sendo que o "link interno B" tenha seu clique independente do 'link A".
EX:
   Conteúdo do 2º link

A: Infelizmente, não é possível. Colocar um anchor dentro de outro é contra a especificação:

12.2.2 Links aninhados são ilegais
Link e anchor definidos pelo elemento A não devem ser aninhados; um
  elemento A não deve conter outros elementos A. (tradução livre)

Você poderá, no máximo, colocá-los lado a lado, na mesma hierarquia.

A: Vou da um resposta que eu não te recomendo fazer. Mas ela pode resolver o seu problema em último caso.
Vc pode colocar um <object> dentro do seu  e partir dai construir seu menu. Assim vc consegue fazer um hake e colocar um link dentro do outro.
Mas antes veja que segundo as normas da W3C isso não deve ser feito: http://w3c.github.io/html/single-page.html#the-a-element
Mas se quiser fazer mesmo assim isso deve resolver seu problema. Mais uma vez não recomendo, mas fica como uma referência.

OBS: os links não funcionam dentro do Snippet, mas na sua página vai dar certo...

#menuHomeMaster {
    display: inline-block;
    width: 150px;
    height: 20px;
    overflow: hidden;
    transition: height 300ms ease;
}
#menuHomeMaster:hover {
    height: 60px;
}
object {
    display: inline-block;
    width: 150px;
}
a object a:hover {
    font-weight: bold;
}
a:hover {
    color: green;
}
Denúncia/Sugestão
    <object>link 1</object>
    <object>link 2</object>

Uma fonte de referência para esse caso: https://stackoverflow.com/questions/9882916/are-you-allowed-to-nest-a-link-inside-of-a-link

A: Como já foi dito, não é recomendável usar a tag  desta maneira, mas dá uma olhada nesse Fiddle se quiser usar assim:
https://jsfiddle.net/gyurjf5k/
Dá pra chegar no resultado que você precisa usando preventDefault() e depois abrindo o link que você deseja.
document.querySelectorAll('a.clique').forEach(i => {

  i.addEventListener('click', ev => {

        ev.preventDefault();

    window.open(ev.currentTarget.getAttribute('href'), 'janela');

   //No seu código, em vez de window.open,
   //você pode usar location.href = ev.currentTarget.getAttribute('href')

  })

});


text:
Q: Which compression types are supported by zless? I just learned about the amazing zless command which allows me to write zless file.txt.gz instead of the more verbose gunzip -c file.txt.gz | less - in fact less is often configured to do this uncompression under the hood saving you even the z.
Unfortunately, zstd compression doesn't seem to be supported by zless.
I went on a search to find out which compression formats are supported by zless and to my surprise I couldn't find out even after an extend google search. The best I could find was:

zmore is a filter that allows the viewing of files compressed with Lempel-Ziv encoding.  Such files generally have a Z or gz extension (both the compress(1) and gzip(1) formats are supported)

Now xz isn't explicitly mentioned in the above, but it still seems to be supported.
Does anyone know which formats are supported exactly? In contrast to most modern software where you can find the source code on Github/lab - I haven't really figured out yet how to find source code for these traditional unix tools.
For zstd one needs to use zstdless which does the job - albeit with 3 more characters.


text:
Q: Multi-project failed to build in Gradle-4.2.1 I am migrating my project to use Multi-project structure . Currently I am using Gradle-4.2.1. When I configure the gradle throws below exception
Exception:
FAILURE: Build failed with an exception.

*

*What went wrong:
Could not normalize path for file 'D:\User\Project2:Subproject1'.

The filename, directory name, or volume label syntax is incorrect

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

*Get more help at https://help.gradle.org
CONFIGURE FAILED in 0s
My project structure
-root
    -Project1
    -build.gradle
-buildProject
-build.gradle
-settings.gradle

-Project2
-build.gradle
    -Subproject1
    -build.gradle
    -Subproject2
    -build.gradle

-Project3
-build.gradle

Below is the settings.gradle looks like
includeFlat 'Project1'
includeFlat 'Project2'
includeFlat 'Project2:Subproject1'
includeFlat 'Project2:Subproject2'
includeFlat 'Project3'
I have below questions.
Am I am using correct gradle version (supports multi-project structure)?
Is My project structure correct?
Any other changes needed to in the settings.gradle to build the project successfully?

A: I think you should use include "Project2:Subproject1", not includeFlat, in order to include nested subprojects. If you read the official documentazion here, you can read
The includeFlat method takes directory names as an argument. These directories need to exist as siblings of the root project directory. The location of these directories are considered as child projects of the root project in the multi-project tree
include works fine with nested subprojects:
The project path is assumed to be equal to the relative physical file system path. For example, a path 'services:api' is mapped by default to a folder 'services/api'
I hope this can help you to solve the problem!


text:
Q: Rebuilding Locator with ILocatorWorkspace2? Trying to use ArcObjects to rebuild locators in an IWorkspace, but enounter 'COMException was unhandled' error when trying to use the 'rebuildlocator' method on ILocatorWorkspace2.
Here is the code I am using:
    private static IWorkspace ws;

    IWorkspaceFactory2 wsf = new SdeWorkspaceFactoryClass();
    ws = wsf.Open(propertySet, 0);

    private static void RebuildLocators()
    {
        System.Object obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriLocation.LocatorManager"));

        ILocatorManager locManager = (ILocatorManager)obj;
        ILocatorWorkspace2 locWs = (ILocatorWorkspace2)locManager.GetLocatorWorkspace(ws);

        IEnumLocatorName enumlocName = locWs.get_LocatorNames(esriLocatorQuery.esriLocator, "Address");
        ILocatorName locName = enumlocName.Next();
        //IEnumLocator enumloc = locWs.get_Locators(esriLocatorQuery.esriLocator, "Address");
        //ILocator loc = (ILocator)enumloc.Next();

        while (locName != null)
        {
            locWs.RebuildLocator(locName.Name, null);
            locName = (ILocatorName)enumlocName.Next();
        }
    }

I have tried to pass both the ILocator.Name and ILocatorName.Name, but I suspect the problem might be the ITrackCAncel.
Has anyone had success with rebuilding locators with ILocateWorkspace2?

A: After further investigation, this code does work. The problem I was having was trying to rebuild a locator which was moved from ArcSDE 9.x to our Development ArcSDE 10.x database. ArcGIS 9.x Locators must be recreated in 10
http://help.arcgis.com/en/arcgisdesk...w000000.htm%20


text:
Q: Persisting div toggle state with cookies Using the code sample below, how could I utilize the jquery cookie plugin so that the toggle state of each div element persist beyond the browser session.
Thanks.
<!DOCTYPE html>

          Header Text 1

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

          Header Text 2

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: Just thinking about what you'll need, the first thing that you need to do is give each of your "wrapper" sections an ID. This ID identifies each toggleable section across page views. It does not need to be the same as the id attribute, but it would likely be easiest if the wrapper ID was the same as the id attribute value of the corresponding div.wrapper element.
Then, assuming that you want all sections to be visible initially, your cookie can store a list of IDs of sections that are hidden. This way, having no cookie means that there are no hidden sections, hence all sections are visible initially.
Each time the user hides a section, you update the cookie value to include the ID of the newly-hidden section. Each time the user unhides a section, you update the cookie value to exclude the ID of the now-visible section.
Finally, on page load, you iterate through the IDs in the cookie, hiding the sections that are listed.
Here is code to help you get started:
<!DOCTYPE html>

 Header Text 1

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

 Header Text 2

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

It is far from a classy/polished solution, but I have tested it, and it works.
I used this jQuery cookie plug-in.


text:
Q: Correctly Specifying "Logical Conditions" (in R) I am using the R programming language - I am trying to follow the answer from this stackoverflow post (Argument passing in R to functions of several real variables) that shows how to perform "multi objective constrained optimization".
I created some data for this example:
#load libraries
library(dplyr)

# create some data for this example
a1 = rnorm(1000,100,10)
b1 = rnorm(1000,100,5)
c1 = sample.int(1000, 1000, replace = TRUE)
train_data = data.frame(a1,b1,c1)

I then defined a function ("funct_set") with "4 objectives" (f[1], f[2], f[3], f[4]) which are to be minimized for a set of "seven inputs" ([x1], [x2], [x3], x[4], x[5], x[6], x[7]):
#load libraries
    library(dplyr)
    library(mco)

#define function

funct_set <- function (x) {
    x1 <- x[1]; x2 <- x[2]; x3 <- x[3] ; x4 <- x[4]; x5 <- x[5]; x6 <- x[6]; x[7] <- x[7]
    f <- numeric(4)

    #bin data according to random criteria
    train_data <- train_data %>%
        mutate(cat = ifelse(a1 <= x1 & b1 <= x3, "a",
                            ifelse(a1 <= x2 & b1 <= x4, "b", "c")))

    train_data$cat = as.factor(train_data$cat)

    #new splits
    a_table = train_data %>%
        filter(cat == "a") %>%
        select(a1, b1, c1, cat)

    b_table = train_data %>%
        filter(cat == "b") %>%
        select(a1, b1, c1, cat)

    c_table = train_data %>%
        filter(cat == "c") %>%
        select(a1, b1, c1, cat)

    #calculate  quantile ("quant") for each bin

    table_a = data.frame(a_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[5],1,0 )))

    table_b = data.frame(b_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[6],1,0 )))

    table_c = data.frame(c_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[7],1,0 )))

    f[1] = -mean(table_a$quant)
    f[2] = -mean(table_b$quant)
    f[3] = -mean(table_c$quant)

    #group all tables

    final_table = rbind(table_a, table_b, table_c)
    # calculate the total mean : this is what needs to be optimized

    f[4] = -mean(final_table$quant)

    return (f);
}

Next, I define a series of 4 "restrictions" (i.e. logical conditions/constrains) used in the optimization:
#define restrictions

restrictions <- function (x) {
    x1 <- x[1]; x2 <- x[2]; x3 <- x[3]; x4 <- x[4]; x5<- x[5] ; x6 <- x[6]; x7 <- x[7]
    restrictions <- logical(4)
    restrictions[1] <- (x3 - x1 >= 0)
    restrictions[2] <- (x4 - x2 >= 0)
    restrictions[3] <- (x7 - x6 >= 0)
 restrictions[4] <- (x6 - x5 >= 0)
    return (restrictions);
}

Finally, I run the optimization algorithm that attempts to simultaneously minimize all 4 objectives with respect to the restrictions:
#run optimization

optimization <- nsga2(funct_set, idim = 7, odim = 4 ,   constraints = restrictions, cdim = 4,

                      generations=150,
                      popsize=100,
                      cprob=0.7,
                      cdist=20,
                      mprob=0.2,
                      mdist=20,
                      lower.bounds=rep(80,80,80,80, 100,200,300),
                      upper.bounds=rep(120,120,120,120,200,300,400)
)

The above code works fine.
Problem : I noticed that in the output of this code, the optimization algorithm is not respecting the restrictions. For example:

In the above picture, I have identified some rows where the logical conditions specified in the restrictions are violated.
Does anyone know why this is happening? Have I incorrectly specified the restrictions? Can someone please show me how to fix this?
Thanks

A: UPDATE:
I think I was able to resolve this problem - now the "logical conditions" are respected in the final output:
#load libraries
library(dplyr)
library(mco)

#define function

funct_set <- function (x) {
    x1 <- x[1]; x2 <- x[2]; x3 <- x[3] ; x4 <- x[4]; x5 <- x[5]; x6 <- x[6]; x[7] <- x[7]
    f <- numeric(4)

    #bin data according to random criteria
    train_data <- train_data %>%
        mutate(cat = ifelse(a1 <= x1 & b1 <= x3, "a",
                            ifelse(a1 <= x2 & b1 <= x4, "b", "c")))

    train_data$cat = as.factor(train_data$cat)

    #new splits
    a_table = train_data %>%
        filter(cat == "a") %>%
        select(a1, b1, c1, cat)

    b_table = train_data %>%
        filter(cat == "b") %>%
        select(a1, b1, c1, cat)

    c_table = train_data %>%
        filter(cat == "c") %>%
        select(a1, b1, c1, cat)

    #calculate  quantile ("quant") for each bin

    table_a = data.frame(a_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[5],1,0 )))

    table_b = data.frame(b_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[6],1,0 )))

    table_c = data.frame(c_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[7],1,0 )))

    f[1] = mean(table_a$quant)
    f[2] = mean(table_b$quant)
    f[3] = mean(table_c$quant)

    #group all tables

    final_table = rbind(table_a, table_b, table_c)
    # calculate the total mean : this is what needs to be optimized

    f[4] = mean(final_table$quant)

    return (f);
}

gn <- function(x) {
    g1 <- x[3] - x[1]
    g2<- x[4] - x[2]
    g3 <- x[7] - x[6]
    g4 <- x[6] - x[5]
    return(c(g1,g2,g3,g4))
}

optimization <- nsga2(funct_set, idim = 7, odim = 4 , constraints = gn, cdim = 4,

                      generations=150,
                      popsize=100,
                      cprob=0.7,
                      cdist=20,
                      mprob=0.2,
                      mdist=20,
                      lower.bounds=rep(80,80,80,80, 100,200,300),
                      upper.bounds=rep(120,120,120,120,200,300,400)
)

Now, if we take a look at the output:
#view output
optimization

All the logical conditions (i.e. the "constraints") are now respected!
Note: if possible, I would still be interested in seeing alternate ways to solve this problem
Thanks everyone!


text:
Q: Jquery callback function working only with debugger Following is my jquery function :
function logIn() {
    debugger;
    $.ajax({
        type: "POST",
        url: '@Url.Action("LogIn", "Login")',
        success: function (result) {
            debugger;
            if (result == "Ok") {
                debugger;
                var url = $("#RedirectTo").val();
                location.href = url;
            }
        },
        dataType: "json",
        traditional: true
    });
}

And following is my LogIn function in controller :
    [HttpPost]
    public ActionResult LogIn()
    {
        int userId = userService.LoginUser("a@b.com", "abc");
       // return View("../Home/Index");
        return Json("Ok");
    }

It works fine if I debug the jquery function. However if I remove debuggers, control does not come in success portion of function. I am not sure what is wrong here.
I also tried replacing jquery function as follows but it is also not working :
function logIn() {
        debugger;
        $.ajax({
            type: 'POST',
            url: '@Url.Action("LogIn", "Login")'
        }).done(function (data) {
            debugger;
            var url = $("#RedirectTo").val();
            location.href = url;
        })
          .fail(function () { alert("error"); })
          .always(function () { alert("complete"); });
    }

Can someone help me here?

A: It Happens when your server is not returning the proper JOSN.
first try
 $.ajax({
    type: "POST",
    url: '@Url.Action("LogIn", "Login")',
    success: function (result) {
       console.log(result);
    },

});

And check if output is a proper JSON or not,
you can also try manually parsing the JSON using $.parseJSON()
hope it helps.


text:
Q: CDF of a r.v. with a negative power in its PDF I need to compute a CDF knowing the PDF of a random variable, so nothing fancy.

I find the constant c by stating that:

I find $c = 0.5114$
But when I want to determine the CDF and its bounds, I have a problem

My CDF becomes negative, and for a non-negative function, it is quiet a problem
Do you see the problem and could you give me a hint ? Thanks in advance !

A: The CDF is an antiderivative of the PDF but generally not the "trivial" one given to us by the elementary calculus rules. To illustrate this, instead of doing your problem, I will do a related problem, namely finding the CDF of a random variable with PDF $f(x)=\begin{cases} 0 & x<0 \\ e^{-x} & x \geq 0 \end{cases}$. Then the CDF is
$$F(x)=\int_{-\infty}^x f(y) dy=\begin{cases} 0 & x<0 \\ \int_0^x e^{-y} dy & x \geq 0 \end{cases}.$$
We compute this integral:
$$\int_0^x e^{-y} dy = -e^{-x}-(-1)=1-e^{-x}.$$
Note the term from the endpoint $0$, which is necessary in order to keep $F$ from being negative, since the "trivial" antiderivative is indeed negative.
Essentially the same thing happens in your problem: there will be a term from the endpoint $1$ which keeps $F$ from being negative.


text:
Q: Discrepancy when using group by clause I see a discrepancy in the count because of the group by clause, please advise how to go about this.
Total records in the table are 4638 when I do count(you_id), but when I run this script I'm getting only 4544 records.
SELECT
    thumbnails,
    CR1,
    monetize,
    c_id,
    you_id,
    vendor,
    ratio * 100 AS percent
FROM
(
    SELECT thumbnails, c_id,you_id, vendor,CR1,monetize,timestamp,
           count(*) AS total, RATIO_TO_REPORT(total) OVER() AS ratio
    FROM testing
    GROUP by 1,2,3,4,5,6,7
);


text:
Q: Javascript animation not working after php header changed My javascript animation works when I'm in localhost/project/login.php, but after check invalid username/password my header will turn into localhost/project/login.php?login=error my javascript animation will stop working. please help.
This is my PHP. which does the validation for my login page and shows the error message if the username/password is incorrect.
<?php
    if (!$link){
        die("Could not connect: ".mysql_error());
        exit();
    } else {
        $result = mysqli_query($link, "select * from users where username = '$username' and password = '$password'");

        $row = mysqli_fetch_array($result);
        if($row['username'] == $username && $row['password'] == $password){
            //echo "Login Success!! Welcome ";
            if ($row['role'] == 0){
                header('Location: lecturer.php');
            } else if ($row['role'] == 1) {
                header('Location: student.html');
            }
        }else{
            header('Location: login.php?login=error');
        }
    }

?>

This is the HTML for my project.
<!DOCTYPE html>

    <title>Login</title>
    <link rel="stylesheet" type="text/css" href="projectCss/logincss.css">

    UCSI Consultation Management System

Login

"We must use time as a tool, not as a couch."

- John F.Kennedy

            <svg viewBox="0 0 320 300">
                <defs>
                    <linearGradient inkscape:collect="always" id="linearGradient" x1="99" y1="193.49992" x2="99"
                    y2="193.49992" gradientUnits="userSpaceOnUse">
                    <stop style="stop-color:#ff2600;" offset="0" id="stop876" />
                    <stop style="stop-color:#1c227a;" offset="1" id="stop878" />
                </linearGradient>
            </defs>
            <path
            d="m 40,120.00016 239.99984,-3.2e-4 c 0,0 24.99263,0.79932 25.00016,35.00016 0.008,34.20084 -25.00016,35 -25.00016,35 h -239.99984 c 0,-0.0205 -25,4.01348 -25,38.5 0,34.48652 25,38.5 25,38.5 h 215 c 0,0 20,-0.99604 20,-25 0,-24.00396 -20,-25 -20,-25 h -190 c 0,0 -20,1.71033 -20,25 0,24.00396 20,25 20,25 h 168.57143" />
        </svg>
        <form action="loginprocess.php" method="POST">

                Username
                <input type="text" id="user" name="user" required>
                Password
                <input type="password" id="pass" name="pass" required>
                <input type="submit" id="submit" value="login">

            <?php
            $fullUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            if(strpos($fullUrl, 'login=error') == true){
             echo "
Invalid username/password!
";
             exit();
         }
         ?>
     </form>


text:
Q: How to remove the URL of a page in an address bar? So everytime I click the href, there's a popup page which is add_form.php that will appear, and there's a form inside of it.
This is my code:
Add

I just want to know, how to remove the URL of the current page inside the address bar where in this is the output every time I click the <href> link.
http://127.0.0.1/no%20page%20reload/add_form.php

The above URL points to localhost. I don't want to see the URL on that popup page. So that everytime I print the current page, there's no URL included or displayed on the printed page.

A: To modify current URL you can use :
1.The pushState() if you want to add a new modified URL to history entries.
2.The replaceState() method if you want to update/replace current history entry
window.history.pushState({}, document.title, "/" + NewURL );