text:
Q: Why do I get a "! Missing \right. inserted." message? What's wrong with this?
Error message: "! Missing \right. inserted." (But I don't see it. Everythink works!)
\begin{multline}
U=\sum\limits_{n=0}^{\infty}\sum\limits_{k=0}^{\infty}\left[(a_{nk}\cos n\varphi + b_{nk}\sin n\varphi)\cos\frac{a\mu_{nk}t}{R} \\
+(c_{nk}\cos n\varphi + d_{nk}\sin n\varphi)\sin\frac{a\mu_{nk}t}{R}\right] J_n\left(\mu_{nk}\frac{\varrho}{R}\right)
\end{multline}

A: Just for fun:
\documentclass{article}
\usepackage{amsmath}

\newcommand{\bracketed}[1]{\left[\vphantom{\let\\=\relax #1}\right. #1 \left.\vphantom{\let\\=\relax #1}\right]}

\begin{document}
\begin{multline}
U=\sum\limits_{n=0}^{\infty}\sum\limits_{k=0}^{\infty}\bracketed{(a_{nk}\cos n\varphi + b_{nk}\sin n\varphi)\cos\frac{a\mu_{nk}t}{R} \\
+(c_{nk}\cos n\varphi + d_{nk}\sin n\varphi)\sin\frac{a\mu_{nk}t}{R}} J_n\left(\mu_{nk}\frac{\varrho}{R}\right)
\end{multline}
\end{document}

A: Don't overuse \left and \right to auto-size large parentheses. Not only will this get you into trouble if these directives span a line break -- as is the case in your example code -- it will quite often also fail to generate the typographically appropriate sizes for the parentheses. For the case at hand, I believe \Bigl( and \Bigr) is far more appropriate.
I would also like to suggest to you that you use a split environment instead of a multline environment, as there's a fairly natural way to align the two rows to make their common structures more readily apparent. Finally, consider using inline-fraction notation for the three expressions that contain R in the denominator. Oh, and do get rid of the two \limits directives: they do nothing here except add code clutter.

\documentclass{article}
\usepackage{amsmath} % for 'split' env.
\begin{document}
\begin{equation}
\begin{split}
U=\sum_{n=0}^{\infty} \sum_{k=0}^{\infty}
\Bigl[&(a^{}_{nk}\cos n\varphi + b^{}_{nk}\sin n\varphi)
\cos(a\mu^{}_{nk}t/R) \\
{}+{}&(c^{}_{nk}\cos n\varphi + d^{}_{nk}\sin n\varphi)
\sin(a\mu^{}_{nk}t/R)\Bigr]
J_n(\mu^{}_{nk}\varrho/R)
\end{split}
\end{equation}
\end{document}


text:
Q: How to load .dat files to oracle database I have .DAT files extracted from telecom switch.
I want to upload this file to an Oracle server using IBM data-stage ETL tool.
Unfortunately these files are not readable format.
This is a picture of the .DAT file when opened in notepad:

A: Not all .dat files are the same and it's hard to determine from the screenshot what the format is.
If you extracted that from a telecom switch, you will need to contact the telecom vendor to ask if they have a data provider for the file format and use that provider to make a connection to the .dat file from within your ETL tools.
If they don't have a provider, which is entirely plausible, you will need to extract the data in another format such as .csv. Again, contact the vendor to see if that is an option

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merge many-to-one list of objects I have two database tables currently, representing a many-to-one relationship. Activities, which have an ID (integer, autoincrement, primary key) and a name (varchar(255), not null); and ActivitySlugs, which have an ID (same as above), a slugname (not null varchar), and an activity_id (foreign key to Activities.id).
Currently I'm supposed to get a list of all activities and all of their slugs (as one list), so that it looks something like this:
[
    {id: 1, name: "long name", slugs: ["nick", "names"]},
    {id: 2, name: "foobar", slugs: ["foo", "bar"]}
]

The naive solution (and about the only one I can think of) is to do a "SELECT *" on each table, and then merge them, but then I get data that looks like this:
activities = [
    {id: 1, name: "long name"},
    {id: 2, name: "foobar"}
]
slugs = [
    {id: 1, slugname: "nick", activity_id: 1},
    {id: 2, slugname: "names", activity_id: 1},
    {id: 3, slugname: "foo", activity_id: 2},
    {id: 4, slugname: "bar", activity_id: 2}
]

So then I can iterate over both and add them:
activities.forEach(function(activity) {
    slugs = [];
    activitySlugs.forEach(function(slug) {
        if (slug.activity_id == activity.id) {
            slugs.push(slug.name);
        }
    });
    activity.slugs = slugs;
);

This feels clumsy, slow, and unrefined. It certainly won't scale at all. Unfortunately, I can't seem to find a better way to get them to merge as a many-to-one with an array like this.

A: You can construct an id2activity map to access any activity by its id:
var id2activity = {};
activities.forEach(function(activity) {
    activity.slugs = [];
    id2activity[activity.id] = activity;
);

activitySlugs.forEach(function(slug) {
    id2activity[slug.activity_id].slugs.push(slug.name);
});

A: Since a slug can only belong to one activity, you should iterate over slugs and attach to a certain activity object instead.
var activities = [
    {id: 1, name: "long name"},
    {id: 2, name: "foobar"}
];
var slugs = [
    {id: 1, slugname: "nick", activity_id: 1},
    {id: 2, slugname: "names", activity_id: 1},
    {id: 3, slugname: "foo", activity_id: 2},
    {id: 4, slugname: "bar", activity_id: 2}
];

slugs.forEach(function(slug) {
    var a = activities.filter(function(a){return a.id==slug.activity_id;});
    // should check if it exists - assume that it does
    if (a[0].slugs == undefined) {
      a[0].slugs = [slug.id];
    } else {
      a[0].slugs.push(slug.id);
    }
});


text:
Q: Show that $\min(U,1-U)$ and that $\max(U,1-U)$ are uniform Let $U$ be uniform on $(0,\ 1)$. Show that $\min(U,\ 1-U)$ is uniform on $(0,\ 1/2)$ and that $\max(U,\ 1-U)$ is uniform on $(1/2,\ 1)$.
I'm not sure how to approach... the only hint i have is that a Random Variable U is Uniform on (0,1) if for all 0<=u<=1, P[U<=u]=u
the only thing that I have seen is that the function min(U,1-U)=U for all 0<=U<=1/2 and that is is quite like the behave of a uniform variable on (0,1/2) but not sure is that's proof enough

A: If $X = max(U, 1-U)$ then it's distribution function is
$F_X = Pr(X \leq x)$ $ = Pr\{ max(U, 1-U)  \leq x \}$
You should note that the maximum between two numbers is less than x iff both numbers are below x, so
$F_X =  Pr\{ max(U, 1-U)  \leq x \} = Pr\{U \leq x , (1 -U ) \leq x\} = Pr\{(1-x) \leq U \leq x \}$
This event has zero probability if x is below $\frac{1}{2}$ (in that case you would be asking for the probability of an impossible event, since $0.5 \leq 1- x$ and $x \leq 0.5$). In terms of distributions, then, you would have:
$F_X  = Pr\{(1-x) \leq U \leq x \} = [F_U(x) - F_U(1-x)].I_{(x \geq 0.5)}$
Taking derivatives (since they exist except in a finite number of points), you can find $X$ density:
$f_X = [f_U(x) +f_U(1-x)].I_{(x \geq 0.5)} = [I_{(0,1)}(x)+I_{(0,1)}(1-x)].I_{(x \geq 0.5)}$
Since $I_{(0,1)}(x)=I_{(0,1)}(1-x)$, you finally get:
$f_X = 2.I_{(0,1)}(x).I_{(x \geq 0.5)}=2.I_{(0.5,1)}(x)$
So the maximum is distributed uniformly between $0.5$ and $1$.
For the minimum, you have that $min(U,1-U) = 1 - max(U,1-U)$ you have just proven that the maximum is uniform between $.5$ and $1$, so this equality means that the minimum is uniform between $0$ and $.5$ (being a linear function of a uniform r.v.)


text:
Q: It has different defaultgateway between masters and workers I have installed K8s cluster with master1 and worker1
They has each different default gateway.
It could communicate between pods on same node.
It couldn't communicate between pods on master and pods on worker.
I configured calico overlay between nodes for communication.
Could you know how to communicate between pods on master and pods on worker?
master gateway: 10.41.2.1
worker gateway: 10.41.84.1


text:
Q: Python Inheritance and __getattr__ & __getattribute__ I have fought with this all day long and done plenty of Google searches. I am having what appears to be an inheritance problem.
I have a class named BaseClass that does some simple things for me like set logging defaults, hold the log, and manage Read Only attributes. In the past I have had no issues with this class but I can say I've only been using python for a couple of months now. Additionally, there are a couple of caveats I suspect are important:

*

*All past inheritance has been a single inheritance. In other words I have inherited BaseClass but the class that inherits BaseClass is NOT then inherited by another class. In today's problem, I inherit BaseClass into BaseFormData which is then inherited into July2013FormData which is then inherited into Jan2014FormData. So obviously there are more layers now.

*I have not been attempting to override __getattr__ or __getattribute__ in any of the classes that inherited BaseClass in the past. Today I am. BaseClass has a __getattribute__ method of its own in order to manage the getting of Read Only attributes. The BaseFormData class has a __getattr__ method because I'd read this was the right way to provide access to data without having to explicitly declare all attributes. The form data being loaded up has a dozen or more pieces of data in it (depending on the version) so I'm explicitly declaring some properties that are vital or aliased while leaving the rest to handled by __getattr__.

Here is the __getattribute__ from BaseClass:
def __getattribute__(self, attr):
        try:
            # Default behaviour
            return object.__getattribute__(self, attr)
        except:
            try:
                return self.__READ_ONLY[attr]
            except KeyError:
                lcAttr = php_basic_str.strtolower(attr)
                return self._raw[lcAttr]

The lines that use self._raw are there solely because classes that inherit BaseClass often times use _raw. There is no _raw that BaseClass requires. Ideally the reference to _raw would only appear in the __getattr__ or __getattribute__ of the inheriting class. However, I need to use __getattribute__ in BaseClass in order to get the Read Only functionality working properly.
And the __getattr__ from BaseFormData:
def __getattr__(self, name):
        """
        Return a particular piece of data from the _raw dict
        """

        # All the columns are saved in lowercase
        lcName = s.strtolower(name)

        try:
            tmp = self._raw[lcName]
        except KeyError:
            try:
                tmp = super(BaseFormData, self).__getattribute__(name)
            except KeyError:
                msg = "'{0}' object has no attribute '{1}'. Note that attribute search is case insensitive."
                raise AttributeError(msg.format(type(self).__name__, name))

        if tmp == 'true':
            return True
        elif tmp == 'false':
            return False
        else:
            return tmp

Here is the error I'm receiving:
File "D:\python\lib\mybasics\mybasics\cBaseClass.py", line 195, in __getattribute__
    return self.__READ_ONLY[attr]

RuntimeError: maximum recursion depth exceeded while calling a Python object

The short version is that I have fought all day with this because with a tweak here or there I get differing response. Most of the time __getattr__ from BaseFormData is never called. Other times I get this recursion error. Other time I can get it to work but then I add something small and everything breaks again.
There is something that I'm clearly missing with regards to inheritance and the order in which __getattribute__ and __getattr__ are called. I've done a lot of tweaking of the code today and if memory serves I can't have a __getattribute__ in BaseFormData as well as BaseClass but I don't remember the error off the top of my head.
I'm guessing the recursion issue stems from this line in __getattr__:
tmp = super(BaseFormData, self).__getattribute__(name)

Obviously, what I'm wanting to do is look in the current class first, then go to the BaseClass __getattribute__ in order to check for Read Only attributes.
Any help is greatly appreciated.
----------- Results of a few tweaks.... -----------
So I changed BaseFormClass __getattr__ to __getattribute__ and it seemed to run before BaseClass's __getattribute__ which makes sense.
However it led to infinite recursion which I thought might be due to the order certain things happened in the __init__ of BaseFormClass and children classes of BaseFormClass. Then it seemed to be due to __READ_ONLY being created too late and I fixed that as well.
Ultimately, _raw is in the children class not in BaseClass so I removed any reference to _raw in BaseClass's _getattribute__. I took rchang's suggestion about changing self to object and this helped in BaseClass's __getattribute__ but seemed to cause issues in BaseFormData's. I have gotten the "get" portion to work from the interpreter with the code below:
BaseClass:
def __getattribute__(self, attr):
        try:
            # Default behaviour
            return object.__getattribute__(self, attr)
        except:
            return self.__READ_ONLY[attr]

BaseFormClass:
def __getattribute__(self, name):
        # All the columns are saved in lowercase
        lcName = s.strtolower(name)

        try:
            # Default behaviour
            return object.__getattribute__(self, name)
        except:
            try:
                tmp = object.__getattribute__(self, '_raw')[lcName]
            except KeyError:
                try:
                    tmp = BaseClass.__getattribute__(self, name)
                except KeyError:
                    msg = "'{0}' object has no attribute '{1}'. Note that attribute search is case insensitive."
                    raise AttributeError(msg.format(type(self).__name__, name))

            if tmp == 'true':
                return True
            elif tmp == 'false':
                return False
            else:
                return tmp

Ironically this has created another __getattribute__ issue though. When I attempt to overwrite a Read Only attr the log warning fires but then fails on a call to self.__instanceId. This log warning worked fine yesterday (when I could get the classes to instantiate without error). And I can instantiate the class like this:
a = Jan2014Lead(leadFile)

and get the Instance ID like this:
a.__instanceId
Out[7]: '8c08dee80ef56b1234fc4822627febfc'

Here's the actual error:
File "D:\python\lib\mybasics\mybasics\cBaseClass.py", line 255, in write2log
    logStr = "[" + self.__instanceId + "]::[" + str(msgCode) + "]::" + msgMsg

  File "cBaseFormData.py", line 226, in __getattribute__
    raise AttributeError(msg.format(type(self).__name__, name))

AttributeError: 'Jan2014Lead' object has no attribute '_BaseClass__instanceId'. Note that attribute search is case insensitive.

----------- Got it working but seems hacky.... -----------
So the error above is from looking for _BaseClass__instanceId in _READ_ONLY but __instanceId is in _READ_ONLY. So I simply trimmed the attr string passed to remove _BaseClass from the beginning.
This seems like a hack though. Is there a standard way to do this?

A: I think your're hitting infinite recursions because __getattribute__ is trying to directly look up attributes of self and therefore results in __getattribute__ calling itself in those except blocks.  See this SO question:
How is the __getattribute__ method used?
Maybe try the following (just extend the same technique using object.__getattribute__ that you're using in the try block to the except block too)?
def __getattribute__(self, attr):
        try:
            # Default behaviour
            return object.__getattribute__(self, attr)
        except:
            try:
                # return self.__READ_ONLY[attr]
                return object.__getattribute__(self, __READ_ONLY)[attr]
            except KeyError:
                lcAttr = php_basic_str.strtolower(attr)
                # return self._raw[lcAttr]
                return object.__getattribute__(self, _raw)[lcAttr]

A: I can't say I ever fully figured this out to my satisfaction. However, the BaseClass __getattirbute__ method required a change in the order in which things were being called:
def __getattribute__(self, attr):
        if attr in self.__READ_ONLY:
            return self.__READ_ONLY[attr]
        else:
            # Default behaviour
            return object.__getattribute__(self, attr)

Then I needed another change to the __getattribute__ in BaseFormClass:
def __getattribute__(self, name):
        # All the columns are saved in lowercase
        lcName = s.strtolower(name)

        try:
            # Default behaviour
            return object.__getattribute__(self, name)
        except:
            name = s.str_replace('_' + type(self).__name__, '', name)
            lcName = s.strtolower(name)

            try:
                tmp = object.__getattribute__(self, '_raw')[lcName]
            except KeyError:
                #tmp = BaseClass.__getattribute__(self, name)
                tmp = super(BaseFormData, self).__getattribute__(name)

            if tmp == 'true':
                return True
            elif tmp == 'false':
                return False
            else:
                return tmp

There are really just 2 changes here. The easy one first, I removed the raise and let the BaseClass handle that. The harder to describe change is the one where I strip out the class name using s.str_replace. Without this line Python was often looking for something like _BaseClass__{some attr} in the _READ_ONLY dict. However, it was only named {some attr} within the _READ_ONLY dict. So I strip the _BaseClass_ portion out.
Obviously this is a hack. I'm not sure if implementing some form of aliasing wouldn't be better than stripping it out. Possibly more explicit? Either way it seems like a hack to get around Python's built-in method for keeping attributes unique among classes.
I imagine there is a better way to do this and this will likely get completely rewritten in a year or so to reflect that better way.


text:
Q: How to pass data to IFTTT WebHook? I have a task to add row into Google Sheet when WebHook received. Now I'm trying to setup IFTTT but have some problem
It says that I should use URL like https://maker.ifttt.com/trigger/{event}/with/key/{my_key} and that is ok I can do it. But it needs to send some data in request and the only way my system can do it appends it to query string like https://maker.ifttt.com/trigger/{event}/with/key/{my_key}?name1=Alex&name2=Helen
But IFTTT doesn't see my data. it says that it can see data in attached JSON but I can't use JSON.
So is there any way to pass my data to IFTT in a query string or shell I forgot IFTTT and investigate how to connect directly to Google Sheet?

A: IFTTT Maker webhooks can only take data with keys of "value1", "value2", and "value3". Try sending it with:
https://maker.ifttt.com/trigger/{event}/with/key/{my_key}?value1=Alex&value2=Helen

A: Try using https://bitly.com/ which will shorten and convert the query params to a path param. That worked for me.

A: First thing first, Web hooks are designed to accept data using POST method only and here you are sending data using GET, which is obviously not going to work, i guess.
Second, in order to get it work, one way is to use cURL request and send your JSON in Body with POST method.


text:
Q: How to fix error 'not found husky-run' when committing new code? When committing on a project that uses Husky, I get an error that says not found husky-run
I checked the package.json and it has husky as a dependency, and I can see the pre-commit hook configuration for Husky in the package.json. So I don't know what to do to fix this. Additionally, other members on my team can commit and husky works for them.
I also tried rm -rf node_modules && npm install and then committing again, but still, I get the same error.
Anyone else have ideas on how to fix this?

A: To fix this there are two methods, depending on which version of Husky you are already on.
If you're using Husky v4 or lower, do the following:
rm -rf .git/hooks
npm install

For Husky v7 or greater, do the following:
# For NPM
 npm install husky@7 --save-dev \
      && npx husky-init \
      && npm exec -- github:typicode/husky-4-to-7 --remove-v4-config

# For Yarn
 yarn add husky@7 --dev \
  && npx husky-init \
  && npm exec -- github:typicode/husky-4-to-7 --remove-v4-config
# or
 yarn add husky@7 --dev \
  && yarn dlx husky-init --yarn2 \
  && npm exec -- github:typicode/husky-4-to-7 --remove-v4-config

At this point you should be able to commit and have your hooks working again.
If anything goes wrong, please read the documentation for migration from 4 to 7.

A: I simply had to add a prepare script to my package.json:
"scripts": {
  ...
  "prepare": "husky install",
  ...
}

Then run yarn install or npm install and husky will be initialized. This will make sure people who check out your repo will also be able to run husky.

A: just a "yarn install" solved this for me

A: This worked for me:
add a file ~/.huskyrc if you don't have one already

*

*touch ~/.huskyrc

*open ~/.huskyrc

*paste the following:

# ~/.huskyrc
# This loads nvm.sh and sets the correct PATH before running hook
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

A: To fix this in husky version 6 run:
yarn husky install

A: Do not delete .get/hooks hooks won't work.
According migrating manual from 4 to 6 version :
For npm usage execute
 npm install husky@6 --save-dev \
      && npx husky-init \
      && npm exec -- github:typicode/husky-4-to-6 --remove-v4-config

For yarn usage:
 yarn add husky@6 --dev \
  && npx husky-init \
  && npm exec -- github:typicode/husky-4-to-6 --remove-v4-config

and
yarn add husky@6 --dev \
  && yarn dlx husky-init --yarn2 \
  && npm exec -- github:typicode/husky-4-to-6 --remove-v4-config

If any errors while the process you can simply revert changes by executing:
rm -rf .husky && git config --unset core.hooksPath

Explanation what's going on:
husky init sets up Git hooks and updates your package.json scripts (you may want to commit your changes to package.json before running husky init).
husky-4-to-6 creates hooks based on your husky v4 config. If --remove-v4-config is passed, previous config will be deleted (recommended).

A: just this 'yarn add husky@6 --dev' inside your terminal

A: If it may help anyone experiencing this issue and using yarn, uninstalling and reinstalling the husky package has fixed it in my case.
(Please check if you would need -W flag else remove it from the commands)
uninstall:
 yarn remove husky -W

install:
 yarn add husky@^4.2.5 -W //to install a specific version

 (or)

 yarn add husky -W //to install the latest version

A: I occur this problem because the .git folder is at a different level from the package.json file, I resolved it by referencing this document:
https://typicode.github.io/husky/#/?id=custom-directory
Just like this:
// package.json
{
  "scripts": {
    "prepare": "cd .. && husky install front/.husky"
  }
}


text:
Q: There do not alert the jQuery size In my HTML body I have three div like bellow:
This is my index.js:

$(function(){

  alert($('.box').size());
});
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>selector</title>

    box1

    box2

    box3

But there do not show the size of jQuery objects.

A: The size() method is deprecated in jQuery 1.8,
You should use length property to check its count:
alert($('.box').length);

In jQuery document:

Returns: Integerversion
  deprecated: 1.8, removed: 3.0

You can see it was removed in jQuery 3.0, so you can not use it in your CDN 3.3.1.

A: I hope this will help you.

$(function(){
  alert($('.box').size());
});

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>selector</title>

    box1

    box2

    box3


text:
Q: How to share sessions in mounted express apps I have a fairly complex express based web application that is split up into a few sub apps which are also express apps (using app.use()). How can I seamlessly use the same session between all parts of the app?

A: the middleware bundled with Connect are "self aware" in that they will not duplicate work they've already done. So for example if you have req.session already, and both the "root" app, and a mounted app utilize the session() middleware, the root app's session will work, and the other will be ignored. So it should work as-is.


text:
Q: Python save a list of dictionaries to json file ordered by dictionary field value I have a list of dictionaries. One of the fields of the dictionaries is "name". I am saving this list of dictionaries to file: with the command
json.dump(myList, fileName, indent=4)

but it is not being saved as I would like to. Since list data-structure is a structure that allows sorting, how can I save it as json array ordered by a field of the dictionary elements?
For example consider this list of dictionaries:
l =[{'name':'c', 'val' : 9},{'name': 'a', 'val': 10}, {'name': 'b', 'val': 10}, {'name': 'aa', 'val': 10}]

I would like as output a jsons like:
[
    {
        "name": "a",
        "val": 10
    },
    {
        "name": "aa",
        "val": 10
    },
    {
        "name": "b",
        "val": 10
    },
    {
        "name": "c",
        "val": 9
    }
]

A: You can sort by a specific key using the builtin sorted command. I think there are plenty of examples of this on here, but specifically for your problem:
l = sorted(l, key=lambda l: l['name'])
print(l)
# [{'name': 'a', 'val': 10},
#  {'name': 'aa', 'val': 10},
#  {'name': 'b', 'val': 10},
#  {'name': 'c', 'val': 9}]


text:
Q: (AngularJS) ng-options not populating despite ng-model and previously working syntax Solved: Two part issue. As pointed out by Veera the model was not being stored correctly in the controller, and the major issue was to do with the Smart Table injection in the module declaration.

Previously my code below managed to produce a list from a drop down menu in ng-options. After several seemingly unrelated changes were made it is now not working and I cannot for the life of me figure out why.
I understand a lot of people have an issue with ng-model in the select element so unless I've made a mistake and missed some syntax there I do not think this is the issue as it was working.
I am trying to populate the list with a "Ref Number" from an array in the controller. There may be some typos in variable names and data where I've changed them from the ones I'm using in my actual project.

var reqWebApp = angular.module('reqWebApp', ['smart-table']);

    reqWebApp.controller('reqAppController', function reqAppController($scope) {
        $scope.requests = [
           {
                ref : "000455",
                status : "requested",
                prod : "BLEH",
                prodRef : "NAH8754",
                prodSite : "BLEHTON"
            }
            {
                ref : "003005",
                status : "requested",
                prod : "REDACTED",
                prodRef : "NA78546",
                prodSite : "REDVILLE"
            }
        ];
});
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Pre-Acceptance</title>

Pre-Accept Existing Request |

                    Ref No.

                    <select ng-model="references"
                            ng-options="request.ref for request in requests">
                        <option value=""></option>
                    </select>

    <button type="button" onclick="location.href='../home/homepage.html'">ACCEPT</button>
    <button type="button" onclick="location.href='../home/homepage.html'">HOME</button>

Thanks for anyone's time to look through it.
Connor

A: Change ng-model as object and declare in controller
HTML
 <select ng-model="selected.selectedReference"
  ng-options="request.ref for request in requests">
   <option value=""></option>
 </select>

JS
 $scope.selected = {};


text:
Q: ImageIcon loading getting slower and slower In my java GUI application, I have some components that need to scale repeatedly, and I am doing this with the following code:
Image newImage = myimage.getScaledInstance(width, height, Image.SCALE_REPLICATE);

ImageIcon newIcon = new ImageIcon(newImage);

this.setIcon(newIcon);

this.setSize(width,height);

//increment width, height

At first this works fine, but after many iterations (a couple hundred) the new ImageIcon() constructor is taking an inordinate amount of time (about 1 second), based on some simple time checks.  The rest of the code is speedy.
Why does this happen after many iterations, and how can I make it stop slowing down as iterations increases?  (Loading the images in a background thread won't work, because loading the images is not a constant-time operation).

A: Have a look at The Perils of Image.getScaledInstance(). It might not be the problem here, but you won't know until trying alternatives.

A: I recall previous Q/A's where image loading was leading to memory issues.  I think you need to pursue the theory that this is a memory leak:

*

*Confirm that this is the problem by running your JVM with GC logging enabled, and see if there's some correlation between the log messages and the observed slowdown.  (It should take a minute or so to confirm, one way or another.)

*Use your favourite memory profiler to try to track down the leak.


text:
Q: Is there anything I can do at the software level against HDCP? I connected my android tablet (mini-HMDI) to my monitor (DVI) and I get:

*

*weird colors

*mis-aligned image

*error message

http://postimage.org/image/5tdvmb5pz/
I tested the tablet on a new fancy tv with hdmi port at the local electonics store, it worked well. I also tested the monitor with a desktop pc through dvi, it worked well.
So I suspect (after reading about it) that the High-bandwidth Digital Content Protection is the guilty. So my monitor (1920x1080, DVI, VGA) probably does not support HDCP. And because the tablet recognizes that, it sends bad quality image on purpose (which of course is not encrypted, but annoying).
Note that I do not want to play any protected/encrypted/copyrighted content, just browse the web, read email, etc.
Is there anything that can be done in software (Linux kernel) so that the tablet is usable with that monitor?
(I have read in some forum/blogpost that HDCP is purely hardware driven, the software stack cannot even be aware of it. Is that true? Is there no way that I can couple these otherwise compatible devices?)

A: I would have expected you to get no image if it was HDCP, because it's an encrypted channel - no decryption of an encrypted feed = no useable image, not just a less than perfect one.
With HDCP the feed is supposed to remain encrypted until it reaches the TV/Monitor. I would not expect to find a software solution - software can indicate that HDCP is required, but without a root access no other software could override another piece to say not to encrypt an output. I would expect the output to normally be unencrypted, and only encrypted if the software demands it - so, for example, my desktop outputs just fine over HDMI to DVI normally, but won't play back BluRays using the bundled software as that demands HDCP.
HDCP decryption units are not that common, anyway - it would almost certainly be much cheaper to pick up a cheap Android stick computer, which is silent and sufficient for some basic websurfing, email, etc.


text:
Q: Rearrangement of Laplacian function It is known that  if $\nabla u$,  in the sense of distributions, is a function that satisfies $\|\nabla u\|_{L^2(\mathbb{R}^n)}<\infty$, then its Symmetric decreasing rearrangement $\nabla u^\ast$ satisfies
$$
\|\nabla u^\ast\|_{L^2(\mathbb{R}^n)}\leq\|\nabla u\|_{L^2(\mathbb{R}^n)}.
$$
Is there some inequality for the higher-order derivative of $u$, for example is there any relation between $\|\Delta u^\ast\|_{L^2(\mathbb{R}^n)}$ and $\|\Delta u\|_{L^2(\mathbb{R}^n)}$?

A: Hint see that $$\Delta u=div(\nabla u)$$ Apply the given inequality  first for each partial derivative then on the gradient.


text:
Q: After an "adb reboot" how to check some other events are complete before the device is ready I am running automated testing on Android device connected to my laptop over USB.
My script starts with two "adb shell" commands before it runs the test as below:
    ::Hey device, wakeup and open the home screen
    adb shell input keyevent 26
    adb shell input touchscreen swipe 240 480 480 640 100
    ...
    (here starts the test cases)

Now, I would like to add "adb reboot" at the very beginning of the script so that my device reboots and starts clean. But the issue is after reboot my device goes following sequences before becoming ready:

*

*Device reboot

*Starts connecting to the MDM server (Mobile Device Manager)

*While connecting screen plays an progress animation

*After successfully connected to the MDM, device become ready

I have tried:
adb reboot
adb wait-for-device shell input keyevent 26

But my problem is that adb wait-for-device shell input keyevent 26 runs right after reboot (sequence #1 above) and after going thru sequences #2,3 & 4, my script does nothing.
How can I check that sequences 2,3 & 4 are complete ?


text: Q: Direct Installation of .IPA file in iOS devices how websites like DIAWI, which helps installing .IPA file directly, works? I would like to install apps without depending third arty websites. I think if somebody helps i am able to implement it self.


text:
Q: Get element id from extern Javascript I have an extern form from API display in a modal. I want to close the modal when it's submitted.
My modal

    <button id="button">Close</button>

My script

I can't modify the form from the API. When I inspect it in my web browser I see the submit button has the id submitButton. But, my function doesn't work with this id. I don't know how to make my modal work with the API script.

A: Well one thing I can see is your getElementById(submitButtonLoading) doesn't have doesn't have quotes around it.

Hope this helps. Cheers!

A: As Leo said, you are missing quotes in
document.getElementById(submitButtonLoading).

But it calls for an element with id = "submitButtonLoading" and you don't have it as I see from your code that you ided as "button"
<button id="button">Close</button>

Change it to:
<button id="submitButtonLoading">Close</button>


text:
Q: innerHTML and use of Array I have several div tags trainingData0, trainingData1, trainingData2, etc   that I am trying to use innerHTML to update text.
I am trying to refer to them with a for loop but it doesn't work.  (even though trainingDataDiv does hold the correct value ie trainingData0 which DOES work if I type trainingData0.innerHTML )
Any advice? Thanks in advance.

---------------
for (var i=0; i<15; i++)
    {
        var trainingDataDiv = "trainingData" + i;
        trainingDataDiv.innerHTML = data;
    }

A: Answer by Robby Cornelissen in comments of my question :)
for (var i=0; i<15; i++)
{
    var trainingDataDiv = document.getElementById("trainingData" + i);
    trainingDataDiv.innerHTML = data;
}

A: So you don't have to change your max number when you change the number of elements:

//Get all elelemtns with ids that start with trainingData
var trainingDataDivs = document.querySelectorAll("[id^='trainingData']");
var data = "I'm training Data";

//iterate the elements we found earlier and update the data
for(var i = 0;  i < trainingDataDivs.length; i++)
{
    trainingDataDivs[i].innerHTML = data;
}

I'm not training

For more info see Attribute selectors and querySelectorAll


text:
Q: ASP.net 5.0 - WebAPI Authorize & ErrorCode 302 instead of 401 I have a ASP.net 5.0 (MVC 6) Website and use this website also for some mobile apps. I  have a controller that returns json data.
The User has to Authenticate to see this data so I use the [Authorize] attribute for the Controller.
I expected to get an Error 401 for not authorized requests nur I get an redirect (302) to the loginpage.
In the Mobile Client a set the header to only accept "application/json" data but I still get the redirect to the login page.
I developed an solution that works but I'm not very happy with it. It works but it is a kind of hack.
Is there a better solution to handle this?
Here my solution (Configure method in Startup class)
        //....Some Code
        app.Use(async (context, next) =>
        {
            await next.Invoke();

            if (context.Response.StatusCode == 302)
            {
                StringValues contentType;
                if (context.Request.Headers.TryGetValue("Accept", out contentType)
                    && contentType.Contains("application/json"))
                {
                    context.Response.StatusCode = 401;
                    if (env.IsDevelopment())
                        await context.Response.WriteAsync("No Access");
                }
            }
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

A: This should be solved by the client. The client have to send a X-Requested-With header with the value XMLHttpRequest.
So this should be a part of the headers section in the HTTP request:
X-Requested-With: XMLHttpRequest

Now you'll get your 401's without hacks.


text:
Q: Understanding GlobalActor, is it guaranteed it won't execute on Main Thread I'm learning usages of async-await and along with that read about the Global Actors. I know MainActor is GlobalActor, and if we annotate a method with @mainActor, the method will be executed on Main Thread. Similar to that if we create a custom GlobalActor, do we know which thread it will use to perform.
@globalActor actor CustomGlobalActor {
     static let shared = CustomGlobalActor()
 }

@CustomGlobalActor func performTask() async -> Output {
    .....
}

Also, additional questions:

*

*Can we use it interchangeably to perform time consuming tasks in background thread?

*Is it connected to Global Queues in any manner?

A: A few observations:

*

*A "global actor" (as defined in SE-0316) is just a named actor that is accessible globally. If you define your own global actor, you can access that particular actor by that name globally throughout your app.
I know you know this, but the main actor is a global actor, too. It is just a special, predefined, one that happens to rely upon the main thread. (It is analogous to the fact that GCD's "main queue" is just a special dispatch queue that happens to use the main thread.)
But, note, when one starts worrying about what thread a particular task on an particular actor is using, it is irrelevant whether that actor is a global actor or not. We're only concerned about actor behavior at that point. For the purposes of this conversation, we don't particularly care if the actor is a global actor or not. Just that it is an actor.

*Probably needless to say at this point, the "global" of a "global actor" has nothing to do with GCD "global" dispatch queues. They are completely different concepts.

*You say:

Similar to that if we create a custom GlobalActor, do we know which thread it will use to perform.

This is splitting hairs, but, no, other than the main actor (which is tied to the main thread), actors in general are not tied to a particular thread. (Swift concurrency strives to abstract us await from thread-level details, anyway.)
Just as one should avoid conflating threads and GCD dispatch queues, the same is true with actors. If you have three tasks that you have submitted to some non-main actor, you have no assurances that they will run on the same thread. You only know that whatever thread they do run on, the different tasks on that actor will not actively run at the same as the other tasks on that same actor. Because the tasks on a particular actor will not run in parallel, they may well end up running on the same thread, one after another. But they may not.
If you are interested in these details, see WWDC 2021 Swift concurrency: Behind the scenes.

*Yes, in practice, a task running on a non-main actor (whether it happens to be a global actor or not) can be used to get a time-consuming synchronous task (such as some computationally-intensive process) off the main thread.
But that is not the primary purpose of actors. They're more for allowing us to manage some mutable shared state across different tasks. See WWDC 2021 Protect mutable state with Swift actors.
So, if you have a computationally intense calculation that you want to get off the main thread, yes, you can theoretically use an actor. And if you want that actor to be a global actor, you can do that, too (though that is less common). But if all you want to do is to get some computationally intense process off the main thread, you might just use a detached task, and call it a day. Actors are more about managing state across tasks than getting something off the main thread.


text:
Q: How to create custom variables in the wp-config I would like to add some custom config variables in the wp-config.php file (not in the functions.php). Then, I need to access to these variables in my templates.
What is the way to do that ?

A: Why do you need this?
In wp-config you can set defines. They will be accesible everywhere without needing to use globals. Define something: define('MY_DEFINE_NAME', 'THE_VALUE');.
Then in your templates you can show the value like this: echo MY_DEFINE_NAME;
Or set the value to a variable: $var = MY_DEFINE_NAME;.


text:
Q: Pyspark Split array of 'key:value' string elements to a struct and extract some values when found I have a DataFrame with this schema:
root
 |-- id: string (nullable = false)
 |-- data_zone_array: array (nullable = true)
 |    |-- element: string (containsNull = true)

It actually contains an array data_zone_array containing several more or less predictable string values (or none at all), where their keys and values are separated by :; looking like this show(5) output:
id  |   data_zone_array
1   |   ['name:john', 'surname:wick', 'group:a', 'group:b', 'group:c']
2   |   ['name:joe', 'surname:linda', 'surname:boss', 'group:d', 'group:b']
3   |   ['name:david', 'group:a', 'age:7']
4   |   ['name:mary', 'surname:gilles']
5   |   ['name:charles', 'surname:paul', 'group:d', 'group:b', 'group:c', 'age:6', 'unplanned_attribute_165:thisvalue']

I want to :

*

*Extract some of those values according to a list of keys (such as name and surname) - knowing that their destination types are predictable (name will always be a unique string and surname an array of strings)

*Place all other found attributes in a struct containing string arrays. Note that there will be unpredictable attributes such as unplanned_attribute_165.

It would give this kind of schema:
root
 |-- id: string (nullable = false)
 |-- name: string (nullable = true)
 |-- surname: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- other_attributes: struct (nullable = true)
 |    |-- <attrx>: array (containsNull = true)
 |    |    |-- element: string(containsNull = true)
 |    |-- <attry>: array (containsNull = true)
 |    |    |-- element: string(containsNull = true)
 |    |-- ......

With records like:
id  |   name        |   surname             |   other_attributes
1   |   'john'      |   ['wick']            |   {group:['a','b','c']}
2   |   'joe'       |   ['boss', 'linda']   |   {group:['b', 'd']}
3   |   'david'     |   <null>              |   {group: ['a'], age:['7']}
4   |   'mary'      |   ['gilles']          |   <null>
5   |   'charles'   |   ['paul']            |   {group: ['b','c','d'], age:['6'], unplanned_attribute_165:['thisvalue']}

Any idea on how to perform such operations?

A: Here's one way of doing.
First, explode the column data_zone_array and extract keys and values into separate columns key and value by splitting on :.
Then, group by id and key and collect list of values associated with each key. And group by again by id to create map key -> [values].
Finally, select keys you want as columns and filter the reste of the keys from the map using map_keys + filter + transform to create the other_attributes column.
import pyspark.sql.functions as F

df1 = (df.withColumn("data_zone_array", F.explode("data_zone_array"))
       .withColumn("key", F.split("data_zone_array", ":")[0])
       .withColumn("value", F.split("data_zone_array", ":")[1])
       .groupBy("id", "key").agg(F.collect_list("value").alias("values"))
       .groupBy("id").agg(F.map_from_arrays(F.collect_list("key"), F.collect_list("values")).alias("attributes"))
       .select("id",
               F.col("attributes")["name"].alias("name"),
               F.col("attributes")["surname"].alias("surname"),
               F.expr("""transform(
                          filter(map_keys(attributes), k -> k not in('name', 'surname')),
                           x -> struct(x as key, attributes[x] as value)
                      )""").alias("other_attributes")
               )
       )

df1.show(truncate=False)
# +---+---------+-------------+------------------------------------------------------------------------+
# |id |name     |surname      |other_attributes                                                        |
# +---+---------+-------------+------------------------------------------------------------------------+
# |5  |[charles]|[paul]       |[{group, [d, b, c]}, {age, [6]}, {unplanned_attribute_165, [thisvalue]}]|
# |1  |[john]   |[wick]       |[{group, [a, b, c]}]                                                    |
# |3  |[david]  |null         |[{group, [a]}, {age, [7]}]                                              |
# |2  |[joe]    |[linda, boss]|[{group, [d, b]}]                                                       |
# |4  |[mary]   |[gilles]     |[]                                                                      |
# +---+---------+-------------+------------------------------------------------------------------------+


text:
Q: Поиск и удаление в vim по шаблону Есть json файл в котором встречаются последовательности:
[
0.0,
0.0,
0.0
...
]

Как удалить такие массивы с 0.0?

A: Собственно такие массивы можно найти с помощью такого паттерна:
\[\(0\.0\|,\| \|\n\)\+\]

Ну а дальше: как вам заблагарассудиться, например если хотите их заменить на пустой массив, то:
%s/\[\(0\.0\|,\| \|\n\)\+\]/\[\]


text:
Q: How to select from one table non existing data in second table? I have 2 tables :
tab1
tab2
Here's the rows included in those table
tab1
item| num
a   | 2
a   | 3
b   | 1
b   | 3

tab2
num
 1
 2
 3
 4
 5

There is a reference between the num in tab1 and num in tab2.
How to select nums from tab2 that dont exist in tab1 with the item column?
Here is the desired result:
item | num
a    | 1
a    | 4
a    | 5
b    | 2
b    | 4
b    | 5

A: One approach would be anti-join, using a "calendar" table containing all possible num/item values:
SELECT DISTINCT
    t1a.item,
    t2.num
FROM tab2 t2
CROSS JOIN tab1 t1a
LEFT JOIN tab1 t1b
    ON t1b.item = t1a.item AND
       t1b.num = t2.num
WHERE
    t1b.item IS NULL
ORDER BY
    t1a.item,
    t2.num;

Demo


text:
Q: Deploy multiple instances of the same application on JBoss I want to deploy multiple instances of the same Seam/EJB3 application that differ only in their database settings on the same JBoss server instance. That way I want to provide different demo instances of this application.
Is this possible at all? And if it is what do I need to change in the configuration of JBoss and the application instances themselves (I could use ant to build different versions of the application with different configuration files if needed).

A: Yes that should be possible. Just remember to also change the application.xml so that each instance gets its own name.


text:
Q: How to find count from two joined tables We have to find count for each risk category for impact level as shown in last result part
Risk Table
RiskID  RiskName
----------------------

1   Risk1
2   Risk2
3   Risk3
4   Risk4
5   Risk5
6   Risk6
7   Risk7
8   Risk8
9   Risk9
10  Risk10
11  Risk11

Category Table
Cat_ID  Cat_Name
--------------------------

1   Design
2   Operation
3   Technical

Risk_Category table
Risk_ID     Category_ID
------------------------

1       1
1       2
2       1
3       1
3       3
4       1
5       2
6       1
7       3
8       1
9       3
10      3

Risk_Impact_Assessment table
Risk_ID     Impact_Level    Impact_Score
---------------------------------------------

1       High        20
2       Medium      15
3       High        20
4       Low     10
5       High        20
6       High        20
7       High        20
8       Low     10
9       Medium      15
10      Low     15
11      Medium      15

Result should be like this
Cat_Name    Impact_Level_High   Impact_Level_Medium Impact_Level_Low
-------------------------------------------------------------------------------------

Design          1           1           2
Operation       2
Technical       2               2           1

A: You probably want to use the group by clause, along with case, eg.:
select
 Cat_Name,
 sum(case when Impact_Level = 'High' then 1 else 0 end) as [Impact_Level_High],
 sum(case when Impact_Level = 'Medium' then 1 else 0 end) as [Impact_Level_Medium],
 sum(case when Impact_Level = 'Low' then 1 else 0 end) as [Impact_Level_Low]
from [Risk_Impact_Assessment]
...
group by Cat_Name;

(I left out all the joins, I assume you can write these no problem)
You can use this trick to accomplish a lot of cool things, including parametric sorting and (just like here) complicated aggregate functions with little work.


text:
Q: Get OleDbDataReader  object to accept null values when reading from a spreadsheet Is there a way to have an OleDbDataReader accept null values when reading from an excel spreadsheet? We have the following columns:
ID | CourseCode | CourseHours | State | EffectiveDate | ExpirationDate
Occasionally the CourseHours column will be blank. This screws up my code since instead of reader[2] being null, reader[2] = State.
This is the method I am using right now but it seems a bit cumbersome.
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    OleDbCommand command = new OleDbCommand(queryString, connection);
    connection.Open();
    reader = command.ExecuteReader();

    while (reader.Read())
    {
        string Id = "";
        string courseCode = "";
        string hours = "";
        string state = "";
        string effectiveDate = "";
        string expirationDate = "";
        string method = "";

        //Add manadatory values
        Id = reader[0].ToString();
        courseCode = reader[1].ToString();

        int value = 0;
        if (int.TryParse(reader[2].ToString(), out value))
        {
            hours = value.ToString();
            state = reader[3].ToString();
            effectiveDate = reader[4].ToString();

            //Check for null in expiration date
            if (!DBNull.Value.Equals(reader[5]))
            {
                expirationDate = reader[5].ToString();
            }
        }
        else
        {
            state = reader[2].ToString();
            effectiveDate = reader[3].ToString();

            //Check for null in expiration date
            if (!DBNull.Value.Equals(reader[5]))
            {
                expirationDate = reader[5].ToString();
            }
        }


text:
Q: Resize Height of Object/Embed with jQuery? I have an object/embed on my page:
<object type="application/x-shockwave-flash" width="100%" height="{$height}" id="chat_shell"
        data="js/8wayrun/irc/lightIRC.swf?host={$server}{$params}{$extras}{$styles}">
    <param name="movie" value="js/8wayrun/irc/lightIRC.swf" />
    <param name="allowfullscreen" value="true" />
    <param name="wmode" value="transparent" />
    <param name="flashvars" value="host={$server}{$params}{$extras}{$styles}" />
</object>

When I click a button, it activates some jQuery scripting...
$('#chat_shell').animate({ height: $('#chat_shell').height() + slideHeight }, slideSpeed);

But instead, when I click the button, I get the following error:

Uncaught TypeError: Cannot read property '0' of undefined

Why is this happening and how do I fix it? I know a possible solution is to wrap the object/embed into a DIV, set the height to 100% and then edit the height of the DIV; but that is an inelegant solution and often has compatibility problems as height should really never be set to 100%.

A: Have you tried checking that  $('#chat_shell').height() works on it's own?
I tried out your code on a flash element on my site and it worked fine, so it would lead me to believe the issue is arising from elsewhere.
Have you checked the event handler for your button fires properly?
Have you checked that JQuery is initializing properly?
Have you tried other browsers?


text:
Q: JMS sending slow I have JMS configured on glass fish domain that facilitates communication between two applications on two domains. How can i look into the JMS queue after the issue has happened. One message was sent very slow and took like 6 secs and then 14 seconds and in between everything else was fine. i want to know what delayed it to this extent usually it is in millisecs.
the server.log only has entry when the msgs server starts and when it shuts down so its not useful.
there are some broker files in the imq directory but some are log.txt files with close and accepting connection. Is there any way to know what was happening at that time in the queue that it took so much time
Thanks

A: There could be multiple reasons for the delays. Such as the number of messages sent and the rate that they are being consumed. Most likely it is related to the MDB consuming the messages (on the consumer application). Make sure that you have enough MDBs running concurrently on the consumer domain. (This is all configurable on the web server admin on the activation spec)
Other issue could be the connectivity, but in case there was a connectivity problem you would have seen something in the logs most likely.

A: Check your MDB code, the consumers. You may have a code which needs more time to execute, thus blocking resources (threads) on the server for some time (e.g external system call with longer timeouts etc).


text:
Q: Git changes based on another branch? I am so confused by git right now. I have created two branches, one of which is created from master, and the other is created from that branch... like this :
master -> Branch1
            |
          Branch2

Branch2 is feature work that relies on some changes from Branch1.
I created these branches as follows :
git checkout -b Branch1
git checkout -b Branch2 Branch1

But when I make changes in Branch2, and then switch back to Branch1, the diff still shows the changes, and if I commit, and push, it will push all the changes to Branch1.
Where the hell did I go wrong? And how do I fix this mess?
EDIT :
Adding .git/config for reference...
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = <REPO URL>
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[branch "BRANCH1"]
    remote = origin
    merge = refs/heads/BRANCH1
[branch "BRANCH2"]
    remote = origin
    merge = refs/heads/BRANCH2


text:
Q: Hibernate criteria - single object fetched I'm working on a Grails project using Hibernate (GORM). I have the following Domain Models:
ClientContact {
   static hasMany = [owners: Person]
   static belongsTo = [Person]
}

Person {
   static hasMany = [clientContacts: ClientContact]
}

When I try to retrieve all the ClientContacts with a specific owner (Person), I'm running into some funny issues.  I'm using the following query criteria:
def query = {
   owners {
      eq("id", Long.parseLong(params.ownerId))
   }
}
def criteria = ClientContact.createCriteria()
def results = criteria.list(params, query)

The problem is when I iterate through each of my ClientContacts in the results, they only have the one owner - when in fact, most have many other owners.  What gives?  I know hibernate/GORM uses lazy fetching, but I thought it would fetch all of the other owners on a ClientContact when I tried to access them.
Any thoughts?  I would like to continue using the list() function since it provides some nice paging features.

A: I know this thread is very old, but I just encountered exactly the same problem today and the solution seems to be usage of aliases, so instead:
def query = {
        owners {
                eq("id", Long.parseLong(params.ownerId))
        }
}

one can try:
def query = {
        createAlias("owners", "o")
        eq("o.id", Long.parseLong(params.ownerId))
}

The first query creates left outer joins and the second creates inner joins. Please see this link for more detailed description: http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html

A: Two quick observations:

*

*The [Grails Documentation](http://grails.org/doc/1.0.x/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.2.1.3 Many-to-many) says that a many-to-many association has to be manually coded, the default scaffolding won't do it.

*You may need to use the eqId() criterion - see createCriteria

A: id and version are special properties of all GORM classes.  You don't need to specify them in the class declaration, and you can't use the standard criterion with them.
You definitely need to use the eqID criterion
   def query = {
          owners {
                eqId(Long.parseLong(params.ownerId))
          }
   }
   def criteria = ClientContact.createCriteria()
   def results = criteria.list(params, query)


text:
Q: add a row to a specific table created dynamically by user I am creating a site to manipulate data on multiple tables that are created with jquery.... most tables will be added by the user when they are on the page.
I am also very new to jquery and javascript - so I may be missing something basic here.
I have been able to get buttons created along with the table headers and then added classes to both the table and the button. I would like to be able to add editable rows and columns to each table by clicking on the correlating button, however I cannot find a way to link the two together whether it is by class or some other means.
Here is the code that I have that adds the table:
$("button.agentPerson").on("click", function() {
  var $newAgent = $('input.agentPerson').val();

  if ($('input.agentPerson').val() !== "") {
    $("div.commissionInfo").append("

Address	Contract Date	Production
<button>New Deal</button>

");

    $("tbody:last-child").addClass($newAgent);
    $("button:last-child").addClass($newAgent);
    $("select.addToThis").append($('<option>', {
      value: $newAgent,
      text: $newAgent,
    }));

  }
});

I have also on the page a dropdown which I would eventually want to be able to hide all tables beside the one chosen. I figure that will be simple once I figure out how to link the two together through classes.
Thank you. If you need any further code please let me know.
I just found the .closest and .parent methods, but I cannot get them to work either.
Here is my most recent attempt to get a button to append to a table.
$("body").on("click", "button", function(event) {
  var $theTable = $(this).closest("tbody");

  $theTable.append("

");
});

A: You could do this way:
Store current $newAgent into data-table attribute of a button;
Add current $newAgent class to the table;
Then you can target the table with a button by data-table attribute and class.

var $newAgent;
$(".addTable").click(function(){
  if ( $('input.agentPerson').val() !== "" && $('input.agentPerson').val() !== $newAgent) {
    $newAgent = $('input.agentPerson').val();
    $("div.commissionInfo").append("

Address	Contract Date	Production

<button data-table='"+$newAgent+"' class='appendRow'>New Deal</button>");

    $("select.addToThis").append($('<option>', {
      value: $newAgent,
      text: $newAgent,
    }));

  }else{
    // throw an error if the field is empty or isn't updated after last table
    // alert for demo:
    alert('please update field!');
  }
})

$("body").on("click", "button.appendRow", function(event) {
  var $theTable = $("table."+$(this).attr('data-table')+" tbody");
  $theTable.append("
blah	blah	blah
");
});

<input class=agentPerson value="blah"/>
<button type="button" class="addTable">Add table</button>

Explantion:

*

*+ (Reference) in the example above is used to merge two strings togrther. Like 'Hello ' + 'world' will be equal to 'Hello world'

*data-table (Reference) is just an attribute of an element and is not related to
 elements (it can be data-something). E.g: data-something can be accessed by:

*

*$(element).data('something'); (it's more usefull in certain cases)

*$(element).attr('data-something'); (better to use in this case)


text:
Q: Grub2 boot loader doesn't appear on boot Okay, install goes smoothly every time.  No issues on that end.  I let Ubuntu decide where to place the boot loader.  It's usually /dev/sda.
The issue I have is the boot loader. Grub, does not show up when I boot my machine.  It automatically boots into Ubuntu without any action from my part.  So I do not see a Grub2 prompt.
Should I have installed the boot loader into a different partition to get the Grub menu appear on boot?

A: Hold the shift key down as you boot and you will get a menu.
If you want to change that behavior, you need to edit /etc/default/grub
# Graphical
gksu gedit /etc/default/grub

# Command line
sudo -e /etc/default/grub

And comment out GRUB_HIDDEN_TIMEOUT=0 (add a # at the front of the line)
Like this
#GRUB_HIDDEN_TIMEOUT=0

See : https://help.ubuntu.com/community/Grub2#Hidden
Save your edit and then run
sudo update-grub

If you wish, you can install StartUpManager which gives you a graphical method of configuring grub


text:
Q: OpenGL send me a Stack Underflow error when i am trying to use shaders (Java) I am developping a game with lwjgl 3 in java and it was working fine but when i want to use shaders, OpenGL send a STACK_UNDERFLOW error (1284).
I am using 3 buffers: vertex buffer, color buffer, index buffer;
My old code:
private int vbo;
private int cbo;
private int ibo;
private FloatBuffer buffer;
private FloatBuffer colorBuffer;
private IntBuffer indexBuffer;

private IcoSphere sphere;
int radius = 200;

@Override
public void init() {
    sphere = new IcoSphere(9, radius);
    sphere.generate();
    generateBuffer();
}

private void generateBuffer() {
    buffer = BufferUtils.createFloatBuffer(sphere.getVertexCount() * 3);
    colorBuffer = BufferUtils.createFloatBuffer(sphere.getFacesCount() * 4 * 4);
    indexBuffer = BufferUtils.createIntBuffer(sphere.getFacesCount());

    Random r = new Random();
    OpenSimplexNoise noise = new OpenSimplexNoise();

    ArrayList<Vector3f> vertex = sphere.getVertex();
    float[] v = new float[vertex.size() * 3];
    for (int i = 0; i < vertex.size(); i++) {
        vertex.get(i).normalize();
        vertex.get(i).mul(sphere.getRadius() + (float) noise.eval(
                vertex.get(i).x * 8,
                vertex.get(i).y * 8,
                vertex.get(i).z * 8
            ) * 12);
        v[i * 3 + 0] = vertex.get(i).x;
        v[i * 3 + 1] = vertex.get(i).y;
        v[i * 3 + 2] = vertex.get(i).z;
    }
    buffer.put(sphere.getVertexArray());

    indexBuffer.put(sphere.getIndexArray());

    for (int i = 0; i < sphere.getFacesCount(); i++) {
        colorBuffer.put(new float[] {
                r.nextFloat(), r.nextFloat(), r.nextFloat(), 1,
                r.nextFloat(), r.nextFloat(), r.nextFloat(), 1,
                r.nextFloat(), r.nextFloat(), r.nextFloat(), 1
        });
    }

    buffer.flip();
    colorBuffer.flip();
    indexBuffer.flip();

    createBuffer();
}

private void createBuffer() {
    vbo = glGenBuffers();
    cbo = glGenBuffers();
    ibo = glGenBuffers();

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, cbo);
    glBufferData(GL_ARRAY_BUFFER, colorBuffer, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

@Override
public void update() {

}

@Override
public void render() {
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexPointer(3, GL_FLOAT, 0, 0);

    glBindBuffer(GL_ARRAY_BUFFER, cbo);
    glColorPointer(4, GL_FLOAT, 0, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

    glDrawElements(GL_TRIANGLES, sphere.getFacesCount() * 3, GL_UNSIGNED_INT, 0);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
}

My new code after adding shaders:
GlUtils.glCall(() -> ..); is for catching opengl errors.
private int vbo;
private int cbo;
private int ibo;
private FloatBuffer buffer;
private FloatBuffer colorBuffer;
private IntBuffer indexBuffer;

private IcoSphere sphere;
int radius = 200;

@Override
public void init() {
    sphere = new IcoSphere(9, radius);
    sphere.generate();
    generateBuffer();
}

private void generateBuffer() {
    buffer = BufferUtils.createFloatBuffer(sphere.getVertexCount() * 3);
    colorBuffer = BufferUtils.createFloatBuffer(sphere.getFacesCount() * 4 * 4);
    indexBuffer = BufferUtils.createIntBuffer(sphere.getFacesCount());

    Random r = new Random();
    OpenSimplexNoise noise = new OpenSimplexNoise();

    ArrayList<Vector3f> vertex = sphere.getVertex();
    float[] v = new float[vertex.size() * 3];
    for (int i = 0; i < vertex.size(); i++) {
        vertex.get(i).normalize();
        vertex.get(i).mul(sphere.getRadius() + (float) noise.eval(
                vertex.get(i).x * 8,
                vertex.get(i).y * 8,
                vertex.get(i).z * 8
            ) * 12);
        v[i * 3 + 0] = vertex.get(i).x;
        v[i * 3 + 1] = vertex.get(i).y;
        v[i * 3 + 2] = vertex.get(i).z;
    }
    buffer.put(sphere.getVertexArray());

    indexBuffer.put(sphere.getIndexArray());

    for (int i = 0; i < sphere.getFacesCount(); i++) {
        colorBuffer.put(new float[] {
                r.nextFloat(), r.nextFloat(), r.nextFloat(), 1,
                r.nextFloat(), r.nextFloat(), r.nextFloat(), 1,
                r.nextFloat(), r.nextFloat(), r.nextFloat(), 1
        });
    }

    buffer.flip();
    colorBuffer.flip();
    indexBuffer.flip();

    createBuffer();
}

private void createBuffer() {

    vbo = glGenBuffers();
    cbo = glGenBuffers();
    ibo = glGenBuffers();

    GlUtils.glCall(() -> glBindBuffer(GL_ARRAY_BUFFER, vbo));
    GlUtils.glCall(() -> glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW));
    GlUtils.glCall(() -> glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0));

    GlUtils.glCall(() -> glBindBuffer(GL_ARRAY_BUFFER, cbo));
    GlUtils.glCall(() -> glBufferData(GL_ARRAY_BUFFER, colorBuffer, GL_STATIC_DRAW));
    GlUtils.glCall(() -> glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 0));

    GlUtils.glCall(() -> glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo));
    GlUtils.glCall(() -> glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL_STATIC_DRAW));

    GlUtils.glCall(() -> glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
    GlUtils.glCall(() -> glBindBuffer(GL_ARRAY_BUFFER, 0));

}

@Override
public void update() {

}

@Override
public void render() {
    Shader.MAIN.bind();

    GlUtils.glCall(() -> glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0));

    GlUtils.glCall(() -> glEnableVertexAttribArray(0));
    GlUtils.glCall(() -> glEnableVertexAttribArray(1));

    GlUtils.glCall(() -> glDrawElements(GL_TRIANGLES, indexBuffer));

    GlUtils.glCall(() -> glDisableVertexAttribArray(0));
    GlUtils.glCall(() -> glDisableVertexAttribArray(1));

    Shader.MAIN.unbind();
}

My shaders:
Frag
#version 410

out vec4 vertColor;

void main(){
    gl_FragColor = vertColor;
}

Vert
#version 410

layout (location=0) in vec3 position;

void main()
{
    gl_Position = vec4(position, 1.0);
}

A: When you use a shader program, then you can draw the mesh the same way as you did it before, by using the client side capabilities.
All you have to do is to use glEnableVertexAttribArray and glVertexAttribPointer instead of glEnableClientState, glVertexPointer and glColorPointer:
Create the buffers:
vbo = glGenBuffers();
cbo = glGenBuffers();
ibo = glGenBuffers();

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);

glBindBuffer(GL_ARRAY_BUFFER, cbo);
glBufferData(GL_ARRAY_BUFFER, colorBuffer, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL_STATIC_DRAW);

Draw the mesh
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);

glBindBuffer(GL_ARRAY_BUFFER, cbo);
glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 0);

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glDrawElements(GL_TRIANGLES, sphere.getFacesCount() * 3, GL_UNSIGNED_INT, 0);

glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);

What you actually do is to use default Vertex Array Object (0) for the specification. Note, the default VAO (0) is just valid in a compatibility profile OpenGL Context.

That can be improved by using a named Vertex Array Object. Note, you have to use a named VAO in a core profile OpenGL Context:
private int vao;

vao = glGenVertexArrays();
vbo = glGenBuffers();
cbo = glGenBuffers();
ibo = glGenBuffers();

glBindVertexArray(vao);

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);

glBindBuffer(GL_ARRAY_BUFFER, cbo);
glBufferData(GL_ARRAY_BUFFER, colorBuffer, GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, false, 0, 0);

glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL_STATIC_DRAW);

glBindVertexArray(0);

The vertex array specification is stated in the vertex array object. Thus there is no need  ofglDisableVertexAttribArray.
Furthermore the Index buffers (GL_ELEMENT_ARRAY_BUFFER) is stated in the VAO, too. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); would break the binding.
Now it is sufficient to bind the VAO when the mesh is drawn:
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, sphere.getFacesCount() * 3, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);

You have 2 color attributes, the vertex coordinate and the color. This 2 attributes are the input to the Vertex Shader. The vertex coordinate is used to set gl_Position. The color has to be passed to the Fragment Shader. It is an output of the vertex shader and an input to the fragment shader. In the fragment shader the color is written to the output fragColor. The output of the fragment shader is written to the frambuffer:
Vertex Shader:
layout (location=0) in vec3 position;
layout (location=1) in vec4 color;

out vec4 vertColor;

void main()
{
    vertColor = color;
    gl_Position = vec4(position, 1.0);
}

Fragment Shader:
#version 410

in vec4 vertColor;
out vec4 fragColor;

void main()
{
    fragColor = vertColor;
}


text:
Q: Components containing public dialog: MatDialog, in constructor fails to load After upgrading from Angular 5.2 to 6
The app fails to load components components containing public dialog: MatDialog in the constructor.
building/serving using --prod flag. (Works fine using ng serve and ng build.)
Console error when using --aot:
Error: Uncaught (in promise): TypeError: factory is not a function

package.json
"@angular/animations": "6.0.0",
"@angular/cdk": "6.0.1",
"@angular/common": "6.0.0",
"@angular/compiler": "6.0.0",
"@angular/core": "6.0.0",
"@angular/flex-layout": "6.0.0-beta.15",
"@angular/forms": "6.0.0",
"@angular/http": "6.0.0",
"@angular/material": "6.0.1",
++

Update, the problem exists in all components where we "inject" a angular service.
 constructor(private dialog: MatDialog) { }
 constructor(private bottomSheet: MatBottomSheet) { }


text:
Q: Virtualenvwrapper creating project in wrong directory? I'm extremely new to Python and virtualenv, so I apologize if this is an obvious question.  I've got a C drive and a D drive on my pc running windows 10.  I have the python and scripts path set to the proper location on the D drive.
In console, i did a pip install virtualenv and pip install virtualenvwrapper-win.  After that i navigated to a folder on my  D drive where i want my projects.  When I ran mkvirtualenv HelloWorld, it seems to have created the virtualenvironment in my C:/users/me folder.  Additionally, the virtual env was not activated by default and I was not moved to the correct directory in my console.
How can I ensure that mkvirtualenv creates new virtual environments in the correct folder on my D drive?  And what am I doing wrong to not activate virtual env after creation?

A: On VirtualEnvWrapper's documentation, they say "optionally":

WORKON_HOME (Optional)
Add an environment variable WORKON_HOME to
  specify the path to store environments. By default, this is
  %USERPROFILE%\Envs.

That %USERPROFILE% part is why you're seeing a directory named Envs created at C:/users/me.
I'm not posting this to act like a know-it-all; this tripped me up too as I just glazed right over it.
I did some research and it turns out in Windows CMD, you can do something like:
set WORKON_HOME=%cd%

where `%cd% is your current directory. You'd think that this would set the environment variable permanently, but no, it doesn't. It's only temporary.
I also tried:
mkvirtualenv -a C:\Django venv

but the path was just ignored and was still created in %USERPROFILE%\Envs.
To set the WORKON_HOME environment variable permanently on your Windows machine, you have to go into the environment variables (search how to get there if you don't know how) and do the following:

After you have set your WORKON_HOME directory, in Windows CMD prompt, you can then do (notice my current path is at C:\Django):
C:\Django>mkvirtualenv venv

This is what will appear on the  screen:
Using base prefix 'c:\\python35'
New python executable in C:\Django\venv\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(venv) C:\Django>

A: When you do mkvirtualenv name it's creating the virtualenv in the current directory you're in in the shell. To create it in the place you want you either need to specify the path or navigate there and create the virtualenv


text:
Q: How to convert this Values in SQL? I have values like
3'023
'464
2'652
21.6%
'64

I am using the following SQL code to change into shown below;
UPDATE table
SET Adjusted_value_tst = REPLACE(LTRIM(RTRIM(value)), '''', '.')
WHERE [Value] LIKE '%''%';

Results:
3.023
0.464
2.652
21.6%
0.64

This is correct for 3 decimal values. But, I am supposed to convert '64 to 0.064
Please help me how should I modify my query in order to convert values like
3'023 to 3.023 and '64 to 0.064
Thanks
Bob

A: Just remove the ' and then divide by 1000:
SELECT *, REPLACE(N,'''','') / 1000.0
FROM (VALUES ('3''023'),('''464'),('2''652'),('''64')) V(N);

If you have to have it to 3 decimal places then use CONVERT to change the value to a decimal(12,3) or similar.
Edit:
It seems the OP doesn't know the syntax for an UPDATE. This would be:
UPDATE YourTable
SET YourColumn = REPLACE(YourColumn,'''','') / 1000.0;

Edit 2:
The OP has more scenarios than were initial described. This should (edit now it does) work, provided there aren't more scenarios we aren't aware of...:
UPDATE YourTable
SET YourColumn = ISNULL(CONVERT(varchar(20),CONVERT(decimal(12,3),TRY_CONVERT(decimal(12,3),REPLACE(YourColumn,'''','')) / 1000)), YourColumn);

This involves several nested CONVERTs. It's not exactly "pretty", however, it is quite simple. The need for the outer CONVERT after the intial TRY_CONVERT is so that the value only has 3 decimal places. A decimal(12/3) / decimal(4,0) would result in a scale of max(6, s1 + p2 + 1) = max(6, 3 + 4 + 1) = max(6,8) = 8, which is more than the OP wants. So the value '3'023' would have ended up as the value '3.02300000'. Precision, scale, and Length (Transact-SQL)

A: If there is always exactly one ' in the data you can locate it with charindex(). From there you can calculate the length of the portions left and right to the '. If the right length is less than 3, you can use stuff() and replicate() to insert as much 0s as needed. If the left portion's length is less than 1, prepend a 0 (else nothing, i.e. an empty string). Then do your replace() as you already did. (Of course you can also do it the other way round, first replace an then do the aforementioned.)
UPDATE elbat
       SET adjusted_value_tst = replace(CASE
                                          WHEN charindex('''',
                                                         rtrim(ltrim(adjusted_value_tst))) < 2 THEN
                                                           '0'
                                                         ELSE
                                                           ''
                                                       END
                                                       +
                                                       stuff(rtrim(ltrim(adjusted_value_tst)),
                                                             charindex('''',
                                                                       rtrim(ltrim(adjusted_value_tst)))
                                                             + 1,
                                                             0,
                                                             replicate('0',
                                                                       3
                                                                       - len(rtrim(ltrim(adjusted_value_tst)))
                                                                       + charindex('''',
                                                                                rtrim(ltrim(adjusted_value_tst))))),
                                                      '''',
                                                      '.');

SQL Fiddle

A: Not sure if this helps, but you can build a conversion table of the unique (Distinct) values which need to be converted, then lookup the proper value in your Update statement.
I have exported data to Excel to get a better handle on my data, then run some formula with an output column. Imported it back into Sql and performed an update from the conversion.  But whatever you do before changing the data, back up the table.


text:
Q: Using VPN router and VPN access point or VPN switch to allow using VPN for any wireless or Ethernet capable devices? I wanted to pre-order a game on Nintendo Switch, but I am not sure if they checked my IP and tell that I am not Oct 29 in USA yet... even thought I already set my region to Asia and my timezone to Asia.  So I cannot pre-order it yet.  (the current USA time is Oct 28, and the current Asia time is Oct 29).
So is it true that I can use some VPN router, VPN access point, or VPN switch to make myself use VPN even when Nintendo Switch has no VPN function?  I think for my Mac or PC or smartphone, they are more ready to use VPN, but Nintendo Switch or my smart TV (such as the Samsung ones) may not have VPN functions.
But in general I saw VPN routers being sold on Amazon, but not VPN Access Point or VPN Switches.  It seems like it has to be a router, be it Wireless or non-Wireless.  But my experience is that if I use an access point, my MacBook can set up a web server, and any computer on any access point at home can connect to it, but if my MacBook is connected to a wireless router, then only devices connected to this wireless router can access the website, because the router makes it having its "own little world"... even if I turn off the firewall, it may have its own world of DHCP server and local IP address, I am not sure, but access point just make it as if it is one big happy family. (as if everybody is plugged into the same 64 port Ethernet switch).
So is there a wireless access point or switch that can do VPN?  I saw the term VPN server and think it means that, except the VPN server function is on a router device... so it is not access point or plain switch.


text:
Q: Multiple variables in a for loop           else
    {
        r=Power(s,n-1);
        System.out.println(r);
        int d=r.length;
        char ch=s.charAt(n);
        int v=d+1;
        p[v]=Character.toString(ch);
        String q = p[v];

        for(i=d+2,j=0;i<2d+3,j<d;i++,j++)
        {
            p[i]=r[j].concat(q);
        }
}

A syntax error is shown and var j is not recognized even after declaration... pls help me.

A: The problem is the condition of the loop. The correct should be:
for(i=d+2,j=0;i<2d+3 && j<d;i++,j++){ ...

or
for(i=d+2,j=0;i<2d+3 || j<d;i++,j++){ ...

There is no meaning in putting a comma separating two boolean conditions in java.
And as seen in the comments, variables j and i are not declared.


text:
Q: Angular Material md-tabs with ui-router does not load initial tab Use case
I have an application that uses both, angular-material (v1.0.0) and ui-router (v0.2.15) and try to have a parent state that has child states which are shown within md-tabs/md-tab.
Problem
I get it working but without the initial tab to be loaded. Only after clicking on the tabs, their state gets loaded.
Code

angular.module('demoApp', ['ui.router', 'ngMaterial'])

  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider.state('tabs', {
      url: '/tabs',
      template: '
' +
                '
Tabs View
' +
                '  <md-tabs>' +
                '    <md-tab label="Foo" ui-sref="tabs.foo">' +
                '    </md-tab>' +
                '    <md-tab label="Bar" ui-sref="tabs.bar">' +
                '    </md-tab>' +
                '  </md-tabs>' +
                '  <md-content ui-view></md-content>' +
                '
'
    });
    $stateProvider.state('tabs.foo', {
      url: '/tabs/foo',
      template: 'Hello from Foo'
    });
    $stateProvider.state('tabs.bar', {
      url: '/tabs/bar',
      template: 'Hello from Bar'
    });
    $urlRouterProvider.when('/tabs', '/tabs/foo');
    $urlRouterProvider.otherwise('/tabs');
  })

;
<!DOCTYPE html>

  <link rel="stylesheet" href="https://rawgit.com/angular/bower-material/v1.0.0/angular-material.css">

  <meta charset="utf-8">
  <title>Example</title>

See my example at jsbin.

A: If you open the jsbin output to another window, so that you can watch the url, you will see that redirect to /foo doesn't work.

*

*You have to configure first the urlRouterProvider and afterwards the stateProvider.

*Also, from the ui-router wiki:

When using url routing together with nested states the default
  behavior is for child states to append their url to the urls of each
  of its parent states.

So /tabs/foo has to become /foo, the same with /tabs/bar.
( if you want absolute urls you can use url: '^/foo', )
So your code becomes:
angular.module('demoApp', ['ui.router', 'ngMaterial'])

.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when('/tabs', '/tabs/foo');
    $urlRouterProvider.otherwise('/tabs');

    $stateProvider.state('tabs', {
        url: '/tabs',
        template: '
' +
        '
Tabs View
' +
        '  <md-tabs>' +
        '    <md-tab label="Foo" ui-sref="tabs.foo">' +
        '    </md-tab>' +
        '    <md-tab label="Bar" ui-sref="tabs.bar">' +
        '    </md-tab>' +
        '  </md-tabs>' +
        '  <md-content ui-view></md-content>' +
        '
'
    });
    $stateProvider.state('tabs.foo', {
        url: '/foo',
        template: 'Hello from Foo'
    });
    $stateProvider.state('tabs.bar', {
        url: '/bar',
        template: 'Hello from Bar'
    });
});

Working jsbin

A: For more control, use a controller function on the parent state and set a default tab in a angular.value()
angular.module('demoApp', ['ui.router', 'ngMaterial'])
  .value('home_tab', 'tabs.foo')
  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider.state('tabs', {
      url: '/tabs',
      template: '
' +
                '
Tabs View
' +
                '  <md-tabs>' +
                '    <md-tab label="Foo" ui-sref="tabs.foo">' +
                '    </md-tab>' +
                '    <md-tab label="Bar" ui-sref="tabs.bar">' +
                '    </md-tab>' +
                '  </md-tabs>' +
                '  <md-content ui-view></md-content>' +
                '
',
      controller: ['$state','home_tab', function($state, home_tab){$state.go(home_tab);}]
    });
    $stateProvider.state('tabs.foo', {
      url: '/tabs/foo',
      template: 'Hello from Foo'
    });
$stateProvider.state('tabs.bar', {
  url: '/tabs/bar',
  template: 'Hello from Bar'
});
$urlRouterProvider.otherwise('/tabs');

})

A: Check below js fiddle may be it solves your issue
    "https://jsfiddle.net/v8kk5fqq"


text:
Q: How to build a class in C++ to use in Python? PyMethodDef from Python.h allows to specify Cpp-built functions to use in Python. However, there is much doubt if this can be applied for Cpp-built classes and I can't find anything like PyClassDef which could presumably help me to do so. All I've managed to find concerns class methods, but not the class itself. Is it possible to build a class in C++ with regular Python-C-API to use as a regular class in Python?

A: You can use pybind11 to implement python call c++ native class.
Link here pybind11 class
it's easier use than cpython.


text:
Q: Firebase Realtime Database Not Saving Data online only Offline So I made a web application in firebase using the integrated realtime database. I am a beginner in firebase but have had it work in the past. Basically I can save data in the DB while using my files offline but after I have deployed all my files the data will not save.
Key Points.
I have installed and used all necessary Libraries.
Have deployed over and over again.
Pretty sure code is correct since offline it saves correctly. here is a small snippet of JS file
Thank you in advance.
 var database = firebase.database();
function clickimage()
{

    var id = document.getElementById("id");
    var marca = document.getElementById("marca");
    var tipo = document.getElementById("tipo");
    var desc = document.getElementById("desc");
    var depa = document.getElementById("depa");
    var precio = document.getElementById("precio");

    firebase.database().ref("Ingresado").push({
        producto: {
            numero_id: id.value,
            marca: marca.value,
            tipo: tipo.value,
            descripcion: desc.value,
            departamento: depa.value,
            precio: precio.value
        }
    }).key;

}


text:
Q: What is the correct way to create white-space on a page with CSS/HTML? I'm creating a site with, instead of different pages, one page with continuous scrolling where the links point to anchor points further down the page...
I've been creating space between the 'content areas' on the page with line breaks in the HTML ( etc) but that seems awfully antiquated and just 'wrong'... is that the best practice way of doing it?
Cheers!

A: Try min-height:100% on your content areas. This should force them to be at least one window-height tall.

A: HTML paragraphs? The space between them can be determined with margin-top or margin-bottom.

Content A

Content B


text:
Q: Define API url in a redux reactjs application Searching around the web but didn't find really an example of explanation for it. Where and how should we define a 'global' api url in a redux application?
As we could have many action holders it would be nice to have just one global var containing the api url we're working with.

A: Maybe not a definitive answer, but you can use libraries like axios which wrap an API for your application.
I personally create a config file in my application and have it export a config object which has these application-wide properties.