text:
Q: Troubleshooting slow Jenkins Jenkins is extremely slow when viewing job pages (over 3 minutes, with a cold disk cache). The main page displays fine; the problem is only when viewing pages for individual jobs.
I think that the problem started with a recent update of Jenkins+plugins, but how can I go about troubleshooting a problem like this?
How can I troubleshoot a problem like this?

A: Reproduce the problem
First, make sure you can reproduce the problem. It helps with testing. If a performance problem only occurs when the cache is cold, then clearing the disk cache (instructions for Linux) can help.
Disable or downgrade plugins
Jenkins' "Manage Plugins" (under the Manage Jenkins section) lets you individually disable and downgrade plugins. If you suspect a particular plugin is causing problems, this can help you confirm.
Use strace
strace can show the system calls that Jenkins is doing. First, get the main Jenkins PID:
root@server:~# ps -ef | grep jenkins
jenkins    589     1  0 17:03 ?        00:00:00 /usr/bin/daemon --name=jenkins --inherit --env=JENKINS_HOME=/home/jenkins --output=/var/log/jenkins/jenkins.log --pidfile=/var/run/jenkins/jenkins.pid --umask=027 -- /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1
jenkins    591   589  7 17:03 ?        00:00:51 /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1

(The pid is 591 in this case.)
Next, run strace.  Because Jenkins is multi-threaded, you'll want to add -f to trace all threads.
strace -p 591 -f

If you're lucky, you'll find an obvious cause of slowdown. (In my case, one of the threads was repeatedly opening each previous build's build.xml for the particular job I was trying to view.)
Use jstack
strace monitors system calls and tells you what a process is doing; jstack shows the call stack for a process, which helps tell you why it's doing it (what it's trying to accomplish).
jstack takes a pid and needs to run as the same user as the process you're inspecting. (See here for more details.)
sudo -u jenkins jstack 591

This displays quite a lot of information: stack traces for each of Jenkins' threads, numerous entries for library and framework code such as request handlers and XML, etc. Somewhere in there, though, you should be able to find the stack trace for the particular request handler that's running slow and some portion of the stack trace that indicates what it's trying to do.


text:
Q: How do I build a docker image that has the same tag as the base image? I have a case where I want to create a docker image from some base image making a couple of modifications along the way (as you do) and I'm looking for some way to preserve the base image tag.
Let me elaborate with an example.
I want to build a new logstash image, with this Dockerfile:
FROM docker.elastic.co/logstash/logstash:5.5.2
RUN /opt/logstash/bin/logstash-plugin install logstash-input-jdbc
RUN mkdir /opt/logstash/vendor/jdbc
RUN curl -Lo /opt/logstash/vendor/jdbc/postgresql-42.1.1.jar https://jdbc.postgresql.org/download/postgresql-42.1.1.jar

I would like the resulting image to also end up with tag 5.5.2, just like the original base image.
I know I can simply tag it from the command line once the build is done, but I am looking for some way (if one exists) to either:

*

*"extract" this tag from the Dockerfile, so i can use it in the docker build -t option

*pass some variable into the Dockerfile that can be used in place of the 5.5.2 image tag

Thanks for your help & ideas!

A: You need to use build arguments in your docker file
ARG LOGSTASH_VERSION
FROM docker.elastic.co/logstash/logstash:${LOGSTASH_VERSION}
RUN /opt/logstash/bin/logstash-plugin install logstash-input-jdbc
RUN mkdir /opt/logstash/vendor/jdbc
RUN curl -Lo /opt/logstash/vendor/jdbc/postgresql-42.1.1.jar https://jdbc.postgresql.org/download/postgresql-42.1.1.jar

Then pass the value using docker build command line
docker build --build-arg LOGSTASH_VERSION=5.5.2 .....

redpajama_set_name: RedPajamaStackExchange


text:
Q: Blender: Impossible Cube I'm working on a graphics project trying to create an impossible cube in 3D. An impossible cube looks like that:

The trick behind this is two of the edges which are 'cut' and a picture taken from a specific angle to give the illusion of the impossibility.

Well I'm trying to make this but instead of a static image, I want to be able to animate it (rotate around) maintaining the impossible properties.
I have managed to make a cube in blender as you can see in the screenshot below:

I would like to hear your suggestions as to how I can achieve the desired effect. An idea would be to make transparent the portion of the edge that has an edge(or more) behind it, so that every time the camera angle changes, the transparent patch moves along.
It doesn't have to be done in Blender exclusively so any solutions in OpenGL etc are welcome.
To give you an idea of what the end result should be, this is a link to such an illustration:
3D Impossible Cube Illusion Animation

A: It's impossible (heh). Try to imagine rotating the cube so that the impossibly-in-front bit moves to the left. As soon as it would "cross" the current leftmost edge, the two properties of "it's in front" and "it's in the back" will not be possible to fulfill simultaneously.

A: If you have edge culling enabled, but clipping (depth-testing) disabled, and draw primitives in the right order, you should get the Escher cube without any need for cuts.  This should be relatively easy to animate.


text:
Q: How could the path to an include file cause different behaviour/warnings from g++? If I compile with g++ -Itemp I get a warning but if I compile without -Itemp I get no warning.
I have triple checked that the three header files in /temp/exodus are identical to those in /usr/local/include/exodus.
g++ -Wall -Wextra  -std=c++2a -c /root/exodus/test/src/test_MB.cpp -H -Itemp

g++ -Wall -Wextra  -std=c++2a -c /root/exodus/test/src/test_MB.cpp -H

Here is a diff of the output (-H to verify the header include locations).
07:20:08 root@de1:~/exodus/test/src# diff temp_warning usr_local_include --color=always
13,14c13,14
< . temp/exodus/program.h
< .. temp/exodus/exodus.h
---
> . /usr/local/include/exodus/program.h
> .. /usr/local/include/exodus/exodus.h
244c244
< ... temp/exodus/exomacros.h
---
> ... /usr/local/include/exodus/exomacros.h
248,261d247
< In file included from temp/exodus/exodus.h:39,
<                  from temp/exodus/program.h:3,
<                  from /root/exodus/test/src/test_MB.cpp:4:
< /root/exodus/test/src/test_MB.cpp: In member function 'exodus::var ExodusProgram::test_ioconv(exodus::ExodusProgramBase::in, exodus::ExodusProgramBase::in)':
< temp/exodus/exomacros.h:124:12: warning: logical not is only applied to the left hand side of comparison [-Wlogical-not-parentheses]
<   124 | #define eq ==
<       |            ^~
< /root/exodus/test/src/test_MB.cpp:14:27: note: in expansion of macro 'eq'
<    14 |  if (not ovar.iconv("MB") eq ivar)
<       |                           ^~
< /root/exodus/test/src/test_MB.cpp:14:6: note: add parentheses around left hand side expression to silence this warning
<    14 |  if (not ovar.iconv("MB") eq ivar)
<       |      ^~~~~~~~~~~~~~~~~~~~
<       |      (                   )

A: It's platform-defined, but most likely when you use -isystem to point at headers instead of -I or use #pragma GCC system_header in header, your flavor of gcc environment would suppress the warning out of erroneous reasoning - it  does not refer to entities from "system" headers, so it really can't output this:
< temp/exodus/exomacros.h:124:12: warning: logical not is only applied to the left hand side of comparison [-Wlogical-not-parentheses]
<   124 | #define eq ==

From online docs:

Macros defined in a system header are immune to a few warnings
wherever they are expanded.


text:
Q: Notifications stopped working after iOS 15.5 update - possible bug? My girl has an iPhone 6S, which received an update a few weeks ago - the iOS 15.5. After the update was installed notifications from all apps (WhatsApp, Signal, Gmail, Skype etc.) she would normally use stopped completely (push notification popups and sound).
I'm not familiar with Apple's products at all so I started digging. Focus is disabled, notifications for all the mentioned apps are enabled, no "Do not disturb" is enabled.
Important: Notifications work if the app is on the screen, e.g. if WhatsApp is opened and visible, whenever someone calls or sends a message, it will appear as a normal push notification. Once WhatsApp is off screen, push notifications stop.
I read that iOS 15 introduced redesigned notifications but since things were working fine up to 15.4 included I'm confident to point a finger at some change(s) 15.5 has introduced.

A: Troubleshooting this can be very complicated. When only some notifications arrive, it's a lot more likely there are temporary network issues.

*

*https://appleid.apple.com/
I like to test things like Apple ID push alerts. If those TFA approvals arrive, you know your device is online and Apple systems are working well.
If not, you might have to do things like restart the device and uninstall / reinstall the app or make it look like it's been uninstalled for 24 hours to reset the permissions dialog for apps.

*

*https://developer.apple.com/library/archive/technotes/tn2265/_index.html
We're not seeing any bugs affecting the build but it's hard to know if you got one or the install just didn't land well on your device. At work, we do use an app to check on things, but it's macOS only.

*

*https://twocanoes.com/products/mac/push-diagnostics/


text:
Q: Display exponential values as float in Polars I have some float columns in Polars df. Some values displays like 9.4036e15. How I can display it with normal digital view?

A: You could .apply(str)
>>> df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 9.4036e15]})
>>> df.select(pl.all().apply(str))
shape: (3, 2)
┌─────┬────────────────────┐
│ a   | b                  │
│ --- | ---                │
│ str | str                │
╞═════╪════════════════════╡
│ 1   | 4.0                │
├─────┼────────────────────┤
│ 2   | 5.0                │
├─────┼────────────────────┤
│ 3   | 9403600000000000.0 │
└─────┴────────────────────┘

My first thought was to cast to a string - but it keeps the scientific notation:
>>> df.select(pl.all().cast(pl.Utf8))
shape: (3, 2)
┌─────┬───────────┐
│ a   | b         │
│ --- | ---       │
│ str | str       │
╞═════╪═══════════╡
│ 1   | 4.0       │
├─────┼───────────┤
│ 2   | 5.0       │
├─────┼───────────┤
│ 3   | 9.4036e15 │
└─────┴───────────┘


text:
Q: Laravel return collection as key/value automatically? In my app I have a key/value pair of permissions in a table that is set as a hasMany to my users:
public function permissions()
{
    return $this->hasMany('Permissions');
}

Rather than a collection with just an array I would like it returned as a key value array so that I can just access the permissions like:
$user->permissions->blah;

I tried doing some post processing but when I modified the permissions attribute directly or created a new one perms it than treated it as a modified attribute which messes up any actual saves I may need to do.
Is there a way to accomplish this on the fly or have some hook within the Permission or User model directly?

A: Yes Correct.
Illuminate\Database\Eloquent\Model
  /**
         * Dynamically retrieve attributes on the model.
         *
         * @param  string  $key
         * @return mixed
         */
        public function __get($key)
        {
            return $this->getAttribute($key);
        }

public function getAttribute($key)
    {
        $inAttributes = array_key_exists($key, $this->attributes);

        // If the key references an attribute, we can just go ahead and return the
        // plain attribute value from the model. This allows every attribute to
        // be dynamically accessed through the _get method without accessors.
        if ($inAttributes || $this->hasGetMutator($key))
        {
            return $this->getAttributeValue($key);
        }

        // If the key already exists in the relationships array, it just means the
        // relationship has already been loaded, so we'll just return it out of
        // here because there is no need to query within the relations twice.
        if (array_key_exists($key, $this->relations))
        {
            return $this->relations[$key];
        }

        // If the "attribute" exists as a method on the model, we will just assume
        // it is a relationship and will load and return results from the query
        // and hydrate the relationship's value on the "relationships" array.
        if (method_exists($this, $key))
        {
            return $this->getRelationshipFromMethod($key);
        }
    }

Actually
$user->permissions equal $user->permissions()->get()
If you want to do post process let create a new function like:
public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = \Hash::make($value);
    }

OR
public function getPasswordAttribute()
    {
        return $this->attributes['password'] ;
    }

A: This function is for creating Eloquent relationships.
If you want to get custom responses then you need to create new method that returns values exactly like you want to see them.

A: Attribute Accessor
Here is how I would do it. First create a protected/private data member on the model to hold the key/value pairs. This will prevent Eloquent from attempting to save this as model attribute.
protected $permValues = [];

Next create an attribute accessor so that we can build they key/value array if it doesn't yet exist.
public getPermissionValuesAttribute()
{
    if (empty($this->permValues))
    {
        $this->permValues = $this->permissions->lists('value', 'key');
    }

    return $this->permValues;
}

This makes things almost as you'd like them to be.
$model->permissionValues['blah'];

Magic Methods
You can take this a step further by creating a class to hold the permission set and defining __set and __get magic methods.
protected $permSet;

public getPermissionSetAttribute()
{
    if (empty($this->permSet))
    {
        $this->permSet = new PermissionSet($this->permissions);
    }

    return $this->permSet;
}

I'll let you fill in the blanks on the PermissionSet class but the end result would work exactly as you'd like it to.
$model->permissionSet->blah;


text:
Q: How to allow linebreaks between double surnames of an authoryear-style citation call-out When citing with double surnames in 'Harvard style'  with the natbib package, it sometimes happens to have the start of the citation at the end of one line. It seems that natbib doesn't allow line-brakes inside a double surnames (even when there is a space between the names).
So the question arises, how is it possible to avoid this problem? An example, of the practical consequence of this behavior can be seen below:

I'm new to LaTeX, use a complex thesis template, and don't know how to reduce the margins, in order to reproduce the situation in the screenshot before. Therefore the minimal example code requires further alignment settings. Would be very thankful if you consider a try to solve the problem.
\documentclass[11pt]{article}

\usepackage[authoryear, comma]{natbib} %
\usepackage{verbatim,filecontents} %

\begin{filecontents*}{\jobname.bib}

    @article{mochales2009,
        author = {Mochales Palau, Raquel and Ieven, Aagje},
        title = {Funny Article About the Name of the Elephant},
        journal = {Elephant Intelligence and Human Reactions},
        year = {2009},
        numpages = {22},
        publisher = {Serious Publisher},
        address = {Western Pacific, Easter Islands},
    }

\end{filecontents*}

\setlength{\textwidth}{9.5cm}
\begin{document}

Other argumentation based issues are ambiguity of theory, ambiguity of
argumentation itself and subjectivity of the interpretation of written
arguments \citep[p. 21]{mochales2009}. They used the structured part of
the Araucaria corpus.

\bibliographystyle{plainnat}
\bibliography{\jobname}
\end{document}

A: Slightly kludgy, but it works [!]: Insert an \allowbreak directive after the first part of the surname, i.e., write the author field as
author = {Mochales\allowbreak Palau, Raquel and Ieven, Aagje},

The output of the full MWE is as follows:

\documentclass[11pt]{article}

\usepackage[authoryear, comma]{natbib}
\usepackage{verbatim,filecontents}
\usepackage[colorlinks,allcolors=blue]{hyperref} % just for this example

\begin{filecontents*}{mybib.bib}
@article{mochales2009,
        author = {Mochales\allowbreak Palau, Raquel and Ieven, Aagje},
        title = {Funny Article About the Name of the Elephant},
        journal = {Elephant Intelligence and Human Reactions},
        year = {2009},
        numpages = {22},
        publisher = {Serious Publisher},
        address = {Western Pacific, Easter Islands},
}
\end{filecontents*}

\setlength{\textwidth}{9.5cm}
\begin{document}

Other argumentation based issues are ambiguity of theory, ambiguity of
argumentation itself and subjectivity of the interpretation of written
arguments \citep[p.~21]{mochales2009}. They used the structured part of
the Araucaria corpus.

\bibliographystyle{plainnat}
\bibliography{mybib}
\end{document}


text:
Q: Drastically different feature importance between very same data and very similar model for catboost Let me first explain about data set that I am using.
I have three set.

*

*train with shape of (1277, 927), target is present about 12% of time

*Eval set with shape of (174, 927), target is present about 11.5% of time

*Hold out set with shape of  (414, 927), target is present about 10% of time

This set is also building using time slices. Train set is oldest data. Hold out set is newest data. and Eval set is in middle set.
Now I am building two models.
Model1:
# Initialize CatBoostClassifier
model = CatBoostClassifier(
    # custom_loss=['Accuracy'],
    depth=9,
    random_seed=42,
    l2_leaf_reg=1,
    # has_time= True,
    iterations=300,
    learning_rate=0.05,
    loss_function='Logloss',
    logging_level='Verbose',
)

## Fitting catboost model
model.fit(
    train_set.values, Y_train.values,
    cat_features=categorical_features_indices,
    eval_set=(test_set.values, Y_test)
    # logging_level='Verbose'  # you can uncomment this for text output
)

predicting on hold out set.
Model2:
model = CatBoostClassifier(
    # custom_loss=['Accuracy'],
    depth=9,
    random_seed=42,
    l2_leaf_reg=1,
    # has_time= True,
    iterations= 'bestIteration from model1',
    learning_rate=0.05,
    loss_function='Logloss',
    logging_level='Verbose',

)

## Fitting catboost model
model.fit(
    train.values, Y.values,
    cat_features=categorical_features_indices,
    # logging_level='Verbose'  # you can uncomment this for text output
)

Both model is identical except iterations. First model has fix 300 round, but it will Shrink model to bestIteration. Where second model uses that bestIteration from model1.
However, When I compare feature importance. It looks drastically difference.
  Feature  Score_m1  Score_m2     delta
0      x0  3.612309  2.013193 -1.399116
1      x1  3.390630  3.121273 -0.269357
2      x2  2.762750  1.822564 -0.940186
3      x3  2.553052       NaN       NaN
4      x4  2.400786  0.329625 -2.071161

As you can see one of feature x3 which was on top3 in first model, dropped off in second model. Not only that but there is large shift in weights between models for given feature. There are about 60 features that are present in model1 are not present in model2. And there about 60 features that present in model2 are not present in model1. delta is difference between Score_m1 and Score_m2. I have seen where model changes score little bit not this drastic. AUC and LogLoss doesn't change that much when I use model1 or model2.
Now I have following questions regarding this situation.

*

*Is this models are instable due to small number of sample and large number of features. If this is case, how to check for this?

*Are there feature in this model are just not giving that much information regarding model outcome and there is random change that it is creating split. If this case how to check for this situation?

*This catboost is right model for this situation ?
Any help regarding this issue will be appreciated

A: Yes.  Trees in general are somewhat unstable.  If you remove the least important feature, you can get a very different model.
Having more data reduces this tendency.
Having more features increases this tendency.
Tree algorithms are random by nature, so the results will be different.
Things to try:

*

*Run the model a large number of times but with different random seeds.  Use the results to determine which feature seems to be the least important.  (How many features do you have?)

*Try to balance your training set.  This might require you to upsample the rarer cases.

*Get more data.  Maybe you'll have to combine your train and test set and use the holdout as the test.


text:
Q: Why is Socket.io not connecting in my React Native app I am creating a react native app and and I'm trying to connect my client app to my server.  I am using socket-io and I'm unsuccessful in connecting the two so far.  Here is my code on the client:
import SocketIOClient from 'socket.io-client';

(...)

if (result.type === "success") {
    console.log("Here 1");
    this.socket = SocketIOClient('http://localhost:1997');
    this.socket.emit('test', 'Hello world!');
    console.log("Here 2");
}

And this code outputs "Here 1" "Here 2"
My Server code is as following:
let express = require('express');
let http = require('http')
let socketio = require('socket.io');

var app = express();
var server = http.Server(app);
var websocket = socketio(server);

let port = 1997;
server.listen(port, () => console.log('listening on *:' + port));

websocket.on('connection', (socket) => {
    console.log("Client joined on " + socket.id);

    websocket.on('test', function(data){
        console.log('Data Receieved: ' + data);
    });
});

This code outputs "listening on *:1997" and then nothing else even when the client code runs.  Please help I'm not sure what I'm doing wrong.

A: I had the same issue and changing "localhost" to the actual ip, worked like a charm for me.
So change
this.socket = SocketIOClient('http://localhost:1997');

To
this.socket = SocketIOClient('http://192.168.xxx.xxx:1997');

I got the answer from here:
Using Socket.io with React Native and not working


text:
Q: I have an array of objects, inside each object is key called scores, and I need to find the sum of each score and push it into an array My console shows me the total of all the scores but I would like it to print 32 and 35 instead of 65. The end result is I want to push each total into an array.

var peopleArray = [
    {
        name: "Hector Valdes",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "1",
            "2", "5",
            "4", "1"
        ]
    }, {
        name: "Tyler Williams",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "2",
            "2", "5",
            "4", "1"
        ]
    }
]

let total = 0;

for (i = 0; i < peopleArray.length; i++){
        for(j=0; j < peopleArray[i].scores.length; j++){
            total += Number(peopleArray[i].scores[j]);
            console.log(total);
        };
    };

A:

var peopleArray = [
    {
        name: "Hector Valdes",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "1",
            "2", "5",
            "4", "1"
        ]
    }, {
        name: "Tyler Williams",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "2",
            "2", "5",
            "4", "1"
        ]
    }
]

let total = peopleArray.map(i => {
  return i.scores.reduce((a, b) => parseInt(a) + parseInt(b), 0)
})
console.log(total)

A: You can use map to loop thru each peopleArray element. Use reduce to sum the scores.
One option in converting a string to number by adding + before the string.

var peopleArray = [{"name":"Hector Valdes","photo":"","scores":["5","1","4","4","5","1","2","5","4","1"]},{"name":"Tyler Williams","photo":"","scores":["5","1","4","4","5","2","2","5","4","1"]}];
var total = peopleArray.map(o => o.scores.reduce((c, v) => +c + +v));

console.log(total);

A: Try this
const result = peopleArray.map((value) => {
    return {
        name: value.name,
        score: value.scores.reduce((total, score) => total + Number(score), 0)
    }

})
console.log(result);

A: Try this,

you need to move total in the first loop then just need to add a new total object in array

var peopleArray = [
    {
        name: "Hector Valdes",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "1",
            "2", "5",
            "4", "1"
        ]
    }, {
        name: "Tyler Williams",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "2",
            "2", "5",
            "4", "1"
        ]
    }
];
console.log(peopleArray);
for (i = 0; i < peopleArray.length; i++){
     let total = 0;
     for(j=0; j < peopleArray[i].scores.length; j++){
        total += Number(peopleArray[i].scores[j]);
     };
     peopleArray[i]['total'] = total;
     console.log(total);
};
console.log(peopleArray);

A: Try this, Hope it helps..
let scoresArr = peopleArray.map(data => {
return data.scores.reduce((a,b) => parseFloat(a) + parseFloat(b), 0)
})

console.log(scoresArr)


text:
Q: Where is the source code for CSharpSyntaxVisitor virtual method *declarations* such as VisitQualifiedName, VisitAwaitExpression etc? Looking at the online source for CSharpSyntaxVisitor there are just a small number of default members.
Implementing a CSharpSyntaxWalker, which derives from CSharpSyntaxVisitor, there are many virtual methods to override, for visiting syntax elements in C#.
Where are these defined/declared?
CSharpSyntaxVisitor is implemented as a partial class, but searching on github I was unable to locate where the basic version of the class is extended with the syntax elements.
Can someone please help point me to where this stuff is defined?

A: You'll find them in Syntax.xml.Main.Generated.cs. This code used to be generated by a tool, from a file called Syntax.xml.
These days, it looks like it's generated using a Source Generator. The source generator is called SourceGenerator, and the bit which generates the additional partial class for CSharpSyntaxVisitor containing those extra Visit methods is here. It still reads its input from Syntax.xml.


text:
Q: Operational amplifier output buffer I made a simulation for a simple output buffer to use more current for an operational amplifier. The goal is to achieve a precise output voltage at moderate speed (This is considerd a DC application) but a maximum current of 1.1A. The amplifier is controlled by V3 which is a DAC in the real application. The DAC provides voltages from 0 to 2.5V.
I decided to use a current mirror (Q4, Q5, Q3, Q6) to provide the current for controlling the output transistors (Q7, Q9, Q1, Q8, Q10, Q2). Some negative feedback resistors are used to prevent asymmetric current through the output transistors.
At this point the circuits works in the DC simulation but the output voltage can't get any higher than 15V. This is where I need help because it would be nice to use the full output range if possible which not much more parts.

Edit 1:
Thanks for all the Answers so far. I modified the design to use a much simpler one with less transistors (See the picture below). This is from the LT application note where I modified the input to structure to map positive inputs to positive outputs and shift the input by (Explained above why).

I can get DC analysis to work in ngspice but not transient analysis. Here is the DC analysis result for the output voltage over the input voltage V1.

DC Analysis looks good and the power dissipation for the resistors is as expected to shared over them. In the real circuit a tweaking of the feedback resistors might be needed. Transient analysis looks like this and I have no clue why.

I think that is a simulator problem because in theory the circuit should work when prototyping. Maybe you guys have some ideas. I tried simulating much longer but that doesn't change the result.
Edit 2:
Now I measured the open loop gain to get the phase of the output. The output is in phase with the input at around 535 kHz.

A: If you look at the data sheets for the transistors used you will see that there will be roughly 0.7 volts dropped across Q5 in saturation, 0.367 volts dropped across the 1 Ω emitter resistors and about 0.7 volts dropped across the base-emitter regions of Q1, Q7 and Q9: -

This roughly tells me that with a positive supply of 17 volts, the maximum peak positive voltage on the output into a 13 Ω load is going to be about 15.23 volts.
To get a higher peak output voltage requires either a fundamental change in the way your output stage is wired OR using bootstrap circuits but, bootstrap circuits will only work well when there is an AC content to your signal.
Alternatively, you could use DC-to-DC converters to raise the driver voltage supply 1.5 to 2 volts above the positive rail and 1.5 to 2 volts below the negative rail.

A: That is a very complex circuit for only 1.1 A of output current.  A search for opamp output boost schematic yields dozens of circuits with higher output current and voltage and way fewer parts.

Jim Williams published several app notes that are well known.
Power Gain Stages for Monolithic Amplifiers
Boost op amp output without sacrificing drift and gain specs
Solve oscillation problems when implementing op-amp power-booster stages
High-powered booster circuits enhance op-amp output
To reduce the operating headroom, change the output transistor configuration to common emitter.  This is from a Linear Tech app note that shows the basic technique:

A: Here's a dumb booster using MOSFETs.

The circuit on the left is the opamp, because you can never trust an opamp Spice model to implement the power supply business as you expect, for example the model  could contain dependent voltage/current sources to GND, which means the current in or out of the supply pins will be bogus.
So, replace the mess with an opamp. Bottom pin of R4 goes to opamp's VCC, top pin of R3 to opamp VDD. R6 forces the opamp to output a current, which comes from its supply pins through its output transistors (Q7 Q6). This drives the gates of the FETs which make a rail to rail output current booster. R1/R2 are the feedback network. C2 is required for compensation, make sure to pick a value that makes the circuit stable. The FETs will get extremely slow as the output gets squeezed against the rails, so if it does oscillate, it will be when output voltage is close to the rails.
Note this is a very simple circuit which will have pretty bad transient response as the FET gates are not properly driven. If this is made to output AC, expect cross-conduction in the FETs.
EDIT:
If you can tolerate a bit of ripple in the output, a class D amp chip would be more efficient, for that more modern "no heat sinks" sleek feel.
If you go this route, I'd recommend IRS2092S. It's a simple chip. It does not include the output LC filter in the feedback loop, which means there are no stability issues if you overdo the filter. So you can use an output filter with a low cutoff frequency, which for only a few amps will cost a few bucks in inductors and caps. Since you don't care about harmonic distortion and output voltage is low, MLCCs would do nicely for the output filter caps. With a 4th order filter cutting off at around 5 kHz, the 200kHz switching frequency should represent just a tiny blip in the output. More conventional MOSFET drivers could also be used.
To have precision DC at the output, an opamp needs to be wrapped around this power stage. Since the power stage has a pretty low bandwidth due to the output filter, some compensation would be needed, and it wouldn't have the quickest transient response in the universe, but for a DC output, that's OK.
It is not rail to rail though, but this no longer matters since with a switching power stage, dissipation is no longer related to input-output voltage drop.


text:
Q: Rust / Egg (E-graphs): the size for values of type dyn cannot be known at compilation time I'm working with the documentation of egg (e-graphs good) to define a cost function that uses Analysis class. I copied their example.
I have defined the following:
#[derive(Default)]
struct CostData;
impl Analysis<MyLanguage> for CostData {
    type Data = (Option<u64>, Option<Symbol>, Option<(Symbol, u64)>, Option<Vec<(Option<Symbol>, Option<u64>)>>);

    fn merge(&mut self, to: &mut Self::Data, from: Self::Data) -> DidMerge {
        egg::merge_min(to, from)
    }

    fn make(egraph: &EGraph<MyLanguage, Self>, enode: &MyLanguage) -> Self::Data {
      // implementation
    }
}

struct EGraphCostFn<'a> {
    egraph: &'a EGraph<MyLanguage, Analysis<MyLanguage,
    Data = (Option<u64>, Option<Symbol>, Option<(Symbol, u64)>, Option<Vec<(Option<Symbol>, Option<u64>)>>)>>,
}

impl<'a> CostFunction<MyLanguage> for EGraphCostFn<'a> {
    type Cost = usize;
    fn cost<C>(&mut self, enode: &MyLanguage, mut costs: C) -> Self::Cost
    where
        C: FnMut(Id) -> Self::Cost
    {
       // implementation
    }
}

However, I get the following error:
error[E0782]: trait objects must include the `dyn` keyword
When I added dyn:
struct EGraphCostFn<'a> {
    egraph: &'a EGraph<MyLanguage, dyn Analysis<MyLanguage,
    Data = (Option<u64>, Option<Symbol>, Option<(Symbol, u64)>, Option<Vec<(Option<Symbol>, Option<u64>)>>)>>,
}

I get:
error[E0277]: the size for values of type `(dyn egg::Analysis<MyLanguage, Data = (Option<u64>, Option<egg::Symbol>, Option<(egg::Symbol, u64)>, Option<Vec<(Option<egg::Symbol>, Option<u64>)>>)> + 'static)` cannot be known at compilation time
error[E0038]: the trait `egg::Analysis` cannot be made into an object

Also tried to wrap it in Box:
struct EGraphCostFn<'a> {
    egraph: &'a EGraph<MyLanguage, Box<dyn Analysis<MyLanguage,
    Data = (Option<u64>, Option<Symbol>, Option<(Symbol, u64)>, Option<Vec<(Option<Symbol>, Option<u64>)>>)>>>,
}

But got:
error[E0277]: the trait bound `Box<(dyn egg::Analysis<MyLanguage, Data = (Option<u64>, Option<egg::Symbol>, Option<(egg::Symbol, u64)>, Option<Vec<(Option<egg::Symbol>, Option<u64>)>>)> + 'static)>: egg::Analysis<MyLanguage>` is not satisfied

Any ideas what I need to change to make it work?
Thanks

A: try substituting the second parameter in the generic list of EGraph there for a concrete type or generic parameter.
struct EGraphCostFn<'a> {
    egraph: &'a EGraph<MyLanguage, Analysis<MyLanguage,
    Data = (Option<u64>, Option<Symbol>, Option<(Symbol, u64)>, Option<Vec<(Option<Symbol>, Option<u64>)>>)>>,
}

should be
type MyLanguageAnalysisData = (Option<u64>, Option<Symbol>, Option<(Symbol, u64)>, Option<Vec<(Option<Symbol>, Option<u64>)>>);

struct EGraphCostFn<'a, C> {
    egraph: &'a EGraph<MyLanguage, C>
} where C: Analysis<MyLanguage, Data = MyLanguageAnalysisData>


text:
Q: How to find dropdown selected value with in div View code:

    for(i=1;i<3;i++)
    {

            @html.dropdownlistfor(m=>m.id,new selectlist((viewbag.country) as selectlist,"Value","Text"),new{@class="country"})
            @html.dropdownlistfor(m=>m.stateid,new selectlist((viewbag.state) as selectlist,"Value","Text"),new{@class="state"})
            <input type="button" value="remove" class="remove">

     }

Button click event:
$("#maindiv").on("click",".remove",function(e){
     alert($(".country")[0].selectedIndex);  // This jquery returns only zero
     $this.parent('div').remove();
});

I need to country dropdown selected Index

A: Use option:selected to get selected option
$('.country option:selected').index();

Code
$("#maindiv").on("click ", ".remove ", function (e) {
    alert($('.country option:selected').index());
    $this.parent('div').remove();
});

A: You need to use the closest() parent like,
$("#maindiv").on("click ", ".remove ", function (e) {
    var $parent =$(this).closest('div'); // cache parent
    alert($parent.find('.country')[0].selectedIndex);
    $parent.remove();
});

Snippet

$("#maindiv").on("click ", ".remove ", function (e) {
    var $parent =$(this).closest('div'); // cache parent
    alert($parent.find('.country')[0].selectedIndex);
    $parent.remove();
});

    <select class="country">
      <option>Select</option>
      <option value="1">India</option>
    </select>
    <input type="button" value="remove" class="remove">

    <select class="country">
      <option>Select</option>
      <option value="2">USA</option>
    </select>
    <input type="button" value="remove" class="remove">

    <select class="country">
      <option>Select</option>
      <option value="3">Australia</option>
    </select>
    <input type="button" value="remove" class="remove">

A: Try this:
function Selected(country){
    alert(country);
}

@html.dropdownlistfor(m=>m.id,new selectlist((viewbag.country) as selectlist,"Value","Text"),new{ @onchange="Selected(this.value)"})


text:
Q: unable to configure postgreSQL JDBC driver using apache drill 1.2 With apache drill 1.2, we can query over RDBMS data https://drill.apache.org/blog/2015/10/16/drill-1.2-released/
I downloaded the JDBC PostgreSQL driver here:
 https://jdbc.postgresql.org/download.html
I took the JDBC4 I didn't know which to take.
I put the jar file in this folder 'apache-drill-1.2.0\jars\3rdparty'
And now, I'm trying to add a plugin for postgres. I am doing it using the web console (http://127.0.0.1:8047). I created a plugin with name pgplugin and added following configurations:
{
  "type": "jdbc",
  "driver": "org.postgresql.Driver",
  "url": "jdbc:postgresql://IP:port/myschema",
  "username": "root",
  "password": "root",
  "enabled": true
}
It is showing error:
error(Unable to create / update storage)
Even with just the following it's not working (same error):
{
  "type": "jdbc"
}
I know that I should add the jar (jdbc postgres driver) to apache drill classpath somewhere in the configuration files but I can't figure it out...
I tried to add this: drill.exec.sys.store.provider.local.path = "/mypath"
to the drill-override.conf -> result is:
drill.exec: {
  cluster-id: "drillbits1",
  zk.connect: "localhost:2181",
  drill.exec.sys.store.provider.local.path = "/mypath"
}
But it's not working... any ideas ?
Thanks a lot !

A: I experienced this same issue.  The cause of my problem was using the "JDBC42 Postgresql Driver, Version 9.4-1205" JDBC driver.  I fixed this issue by using the "JDBC4 Postgresql Driver, Version 9.4-1205" driver.
For reference, the Postgres JDBC downloads page: https://jdbc.postgresql.org/download.html


text:
Q: Why would disposal of resources be delayed when using the "use" binding within an async computation expression? I've got an agent which I set up to do some database work in the background. The implementation looks something like this:
let myAgent = MailboxProcessor<AgentData>.Start(fun inbox ->
    let rec loop =
        async {
            let! data = inbox.Receive()
            use conn = new System.Data.SqlClient.SqlConnection("...")
            data |> List.map (fun e -> // Some transforms)
                 |> List.sortBy (fun (_,_,t,_,_) -> t)
                 |> List.iter (fun (a,b,c,d,e) ->
                    try
                       ... // Do the database work
                    with e -> Log.error "Yikes")
            return! loop
        }
    loop)

With this I discovered that if this was called several times in some amount of time I would start getting SqlConnection objects piling up and not being disposed, and eventually I would run out of connections in the connection pool (I don't have exact metrics on how many "several" is, but running an integration test suite twice in a row could always cause the connection pool to run dry).
If I change the use to a using then things are disposed properly and I don't have a problem:
let myAgent = MailboxProcessor<AgentData>.Start(fun inbox ->
    let rec loop =
        async {
            let! data = inbox.Receive()
            using (new System.Data.SqlClient.SqlConnection("...")) <| fun conn ->
              data |> List.map (fun e -> // Some transforms)
                   |> List.sortBy (fun (_,_,t,_,_) -> t)
                   |> List.iter (fun (a,b,c,d,e) ->
                      try
                         ... // Do the database work
                      with e -> Log.error "Yikes")
              return! loop
        }
    loop)

It seems that the Using method of the AsyncBuilder is not properly calling its finally function for some reason, but it's not clear why. Does this have something to do with how I've written my recursive async expression, or is this some obscure bug? And does this suggest that utilizing use within other computation expressions could produce the same sort of behavior?

A: This is actually the expected behavior - although not entirely obvious!
The use construct disposes of the resource when the execution of the asynchronous workflow leaves the current scope. This is the same as the behavior of use outside of asynchronous workflows. The problem is that recursive call (outside of async) or recursive call using return! (inside async) does not mean that you are leaving the scope. So in this case, the resource is disposed of only after the recursive call returns.
To test this, I'll use a helper that prints when disposed:
let tester () =
  { new System.IDisposable with
      member x.Dispose() = printfn "bye" }

The following function terminates the recursion after 10 iterations. This means that it keeps allocating the resources and disposes of all of them only after the entire workflow completes:
let rec loop(n) = async {
  if n < 10 then
    use t = tester()
    do! Async.Sleep(1000)
    return! loop(n+1) }

If you run this, it will run for 10 seconds and then print 10 times "bye" - this is because the allocated resources are still in scope during the recursive calls.
In your sample, the using function delimits the scope more explicitly. However, you can do the same using nested asynchronous workflow. The following only has the resource in scope when calling the Sleep method and so it disposes of it before the recursive call:
let rec loop(n) = async {
  if n < 10 then
    do! async {
      use t = tester()
      do! Async.Sleep(1000) }
    return! loop(n+1) }

Similarly, when you use for loop or other constructs that restrict the scope, the resource is disposed immediately:
let rec loop(n) = async {
  for i in 0 .. 10 do
    use t = tester()
    do! Async.Sleep(1000) }


text:
Q: How do I supply parameters to a constructor called by another constructor? In my project, I have four structs: Node, Ring, Disc, and Graph.

*

*a Ring contains two vectors of 12 Nodes each

*a Disc contains a vector of Rings (a parameter tells the constructor how many)

*a Graph contains a vector of Discs (again, the number is supplied by a parameter)

Everything works fine except Graphs. If I want to construct a Disc, I allow the number of Rings it contains in its std::vector<Ring> rings to be set via the constructor like so:
Disc::Disc(size_t r) : rings {r} {};

But if I want to construct a Graph, I somehow need to set both the number of Discs and the number of Rings in each Disc. So I guess what I need is a way to input parameters to the Ring constructors when they get called for each Disc that is being constructed. I am new to programming, and unfortunately I haven't been able to find any tutorials on how to tell the constructor what to do in a situation like this. But perhaps I am going about this in the completely wrong way.

A: Vectors are flexible, they can be constructed empty and filled afterwards.
In Your scenario, You would do something like this.
Graph::Graph(size_t nDiscs, size_t *nRingsPerDisc) : discs{}
{
    for(int i = 0; i < nDiscs; i++)
        discs.push_back(Disc(RingsPerDisc[i]));
}

A: I would make it possible to initialize each of your classes directly with a container of the same type that you store in the classes. That way you don't have to supply how many of each there are in them.
Here are some made up versions of your classes.
struct Node { int x; };

struct Ring {
    Ring(std::array<std::array<Node, 12>, 2> a) : nodes(std::move(a)) {}
    auto begin() { return nodes.begin(); }
    auto end() { return nodes.end(); }
private:
    std::array<std::array<Node, 12>, 2> nodes;
};

struct Disc {
    Disc(std::vector<Ring> in) : rings(std::move(in)) {}
    auto begin() { return rings.begin(); }
    auto end() { return rings.end(); }
private:
    std::vector<Ring> rings;
};

struct Graph {
    Graph(std::vector<Disc> in) : discs(std::move(in)) {}
    auto begin() { return discs.begin(); }
    auto end() { return discs.end(); }
private:
    std::vector<Disc> discs;
};

You could then create a whole Graph object in one go if you'd like
Graph graph(
    { // discs
        { // disc 0
            { // rings
                { // ring 0
                    { // array initialization
                        { // outer array
                            { 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12}, // nodes 0 (inner)
                            {13,14,15,16,17,18,19,20,21,22,23,24}  // nodes 1 (inner)
                        }
                    }
                },
                { // ring 1
                    {
                        {
                            {25,26,27,28,29,30,31,32,33,34,35,36},
                            {37,38,39,40,41,42,43,44,45,46,47,48}
                        }
                    }
                }
            }
        },
        { // disc 1
            { // rings
                { // ring 0
                    {
                        {
                            {49,50,51,52,53,54,55,56,57,58,59,60},
                            {61,62,63,64,65,66,67,68,69,70,71,72}
                        }
                   }
                }
            }
        }
    }
);

Demo

A: I've just figured out a solution that seems to work nicely. For the sake of documentation, here's the definition I've now given to the Graph constructor:
Graph::Graph(size_t d, size_t r) : discs (d, *new Disc {r}) {};


text:
Q: AM_CONDITIONAL testing size of type I would like to define PLATFORM64 if SIZEOF_VOIDP equals 8, the configure snippet below don't work but shows what I would like to achieve. Is there a way of doing this in my configure script?
# Get size of void*
AC_CHECK_SIZEOF(void*)

# Determine if this is a 32 or 64 bit system, this can also be set manually with "-DPLATFORM64"
AM_CONDITIONAL([PLATFORM64], [test SIZEOF_VOIDP = 8])

Update:
I've tried:
AM_CONDITIONAL([PLATFORM64], [test "$SIZEOF_VOIDP" -eq 8])

but I get "test: bad number" error message.

A: The problem is that AC_CHECK_SIZEOF is defining a preprocessor directive, not setting a shell variable. You could try testing $host_cpu after calling AC_CANONICAL_HOST.
Alternatively:
AC_PREPROC_IFELSE([AC_LANG_SOURCE([
#if SIZEOF_VOIDP != 8
#error
#endif
])], [platform64=true], [platform64=false])

AM_CONDITIONAL([PLATFORM64], [test "$platform64" = true])


text:
Q: Error with string extraction: unused argument I typed this looking for the word "rogers" in a data frame column. It returned "unused argument" Any ideas? Thank you!
library(dplyr)
library(stringr)
data4$County1 <- data4 %>%
                       str_extract(County, "^\\D{5}(?= \\D{6})")

A: Try
library(dplyr)
library(stringr)
data4 <- data4 %>% mutate(County1 = str_extract(County, "^\\D{5}(?= \\D{6})")

A: Piping with %>% pushes the preceding object (data4) into the first argument of the function following. str_extract only takes two arguments, so with this piping it gets three. Furthermore, it is not designed to work with data.frames - you should give it the string directly. That is,
data4$County1 <- data4$County1 %>%
                       str_extract("^\\D{5}(?= \\D{6})")


text:
Q: How to retrieve data from Firestore the right way I want to retrieve data from my Firestore backend, but I have a problem accessing the data. My files look like this:
data.service.ts
import { Injectable } from '@angular/core';

import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import { HttpClient } from '@angular/common/http';
import { Incident } from '../profile/profile.component';
import { User } from '../../model/user';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  user$: Observable<User>;

  constructor(private http: HttpClient, private angularFirestore: AngularFirestore) { }

  fetchIncidentsFromUser(uid: string) {
  }

  reportIncident(newIncident: Incident) {
  }

  fetchUserData(uId: string): void {
    const user: AngularFirestoreDocument<User> = this.angularFirestore.doc('users/' + uId);
    this.user$ = user.valueChanges();
  }

  getUserData(): Observable<User> {
    return this.user$;
  }

}

profile.component.ts
import { Component, OnInit } from '@angular/core';
import {DataService} from '../services/data.service';
import {User} from '../../model/user';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  user$: Observable<User>;

  constructor(private dataService: DataService) {

  }

  ngOnInit() {
    this.user$ = this.dataService.getUserData();
    console.log(this.user$)
  }

}

When the profile component is going to be initialized, I want to access the data from the observable user$, but I don't know how to do that...can anyone help me?


text:
Q: Two histograms with two variables in Ggplot2 This is my DF :
> head(xgb_1_plot)
   week PRICE id_item food_cat_id test_label xgb_1
2     5    18      60           7          2     2
7     5    21       9           6          5     8
12    5    14      31           4          4     6
21    5    15      25           7         12    12
31    5    14      76           3          4     2
36    5     7      48           8          2     4

Where test_label is the test value, "xgb_1" is the column with the predicted values and id_items are the items.
I want to plot graph in which I can see predicted values VS true values side by side for some id_items.
There are over 100, so I need just a subset for the plot (otherwise it'll be a mess).
Let me know!
P.S. the best thing would be transform the test_label and the xgb1 in rows and add a dummy variable "Predicted/True value", but I have no idea how to do it.

A: I would suggest this approach, reshaping data and then plotting. Having more data, it will look better:
library(tidyverse)
#Data
dfa <- structure(list(id_item = c(60L, 9L, 31L, 25L, 76L, 48L), test_label = c(2L,
5L, 4L, 12L, 4L, 2L), xgb_1 = c(2L, 8L, 6L, 12L, 2L, 4L)), class = "data.frame", row.names = c("2",
"7", "12", "21", "31", "36"))

Code:
#Reshape
dfa %>% pivot_longer(cols = -id_item) %>%
  ggplot(aes(x=value,fill=name))+
  geom_histogram(position = position_dodge())+
  facet_wrap(.~id_item)

Output:

A: Here's a differnt approach using geom_errorbar. Maybe the color thing is a little bit too much, but today is a rainy day ... so was in need of some variety
"%>%" <- magrittr::"%>%"

dat <- dplyr::tibble(id_item=c(69,9,31,25,76,48),
              test_label=c(2,5,4,12,4,2),
              xgb_1=c(2,8,6,21,2,4))

dat %>%
  dplyr::mutate(diff=abs(test_label-xgb_1)) %>%
  ggplot2::ggplot(ggplot2::aes(x=id_item,ymin=test_label,ymax=xgb_1,color=diff)) +
  ggplot2::geom_errorbar()


text:
Q: Knime Install Extensions fails: HTTP Proxy Authentication Required I am using Knime on a remote desktop location and run it there in my local workspace on the other computer, I needed ot change my password and afterwards I cannot install updates again. Now I get the following error:
Some sites could not be found.  See the error log for more detail.
HTTP Proxy Authentication Required: http://update.knime.com/community-contributions/trusted/3.7/content.xml
Proxy Authentication Required
HTTP Proxy Authentication Required: http://update.knime.com/analytics-platform/3.7/content.xml
Proxy Authentication Required

I followd this thread here: Eclipse Neon HTTP Proxy Authentication Required Error
But this does not work out for me, any other ideas?

A: I found the solution on my own, under Help--> Install Software I need to exclude every update path which was not refereing to my local zip file


text:
Q: plot moving and rotating polygon over the static map I have a following setup: a tkinter app has a static real-life map, which is plotted via plotting two geodataframes (for land and water), both with a uniformed shape:
def make_figure(self, map):
    land = map.land.to_crs(epsg=4326)
    water = map.water.to_crs(epsg=4326)
    xmin, ymin, xmax, ymax = map.contour.bounds

    fig, ax = plt.subplots(figsize=(8, 9), dpi=100)
    fig.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01)
    plt.axis('off')
    ax.set_xlim([xmin,xmax])
    ax.set_ylim([ymin,ymax])

    water.plot(ax=ax, facecolor='lightskyblue')
    land.plot(ax=ax, edgecolor='grey', facecolor='cornsilk', linewidth=1, alpha=1)
    return fig, ax

Then returned figure and axes are embedded into tkinter canvas in a standard way:
    self.canvas = FigureCanvasTkAgg(fig, draw_frame)
    self.canvas.draw()
    self.canvas.get_tk_widget().pack()
    self.toolbar = NavigationToolbar2Tk(self.canvas, draw_frame)

There is also some model inside this tkinter's app, which does all agent-based operations like moving and rotating and updates their shapes on each step. What I want to do is to have an as much as possible smooth dynamic agents' shapes updating. At the moment the only working solution for me looks like this (we receive list of Shapely shapes via self.model object, after it does step() method inside tkinter's loop):
    def update_agents_shapes(self):
        shapes = self.model.get_new_shapes()
        self.ax.patches = []
        for shape in shapes:
            patch = PolygonPatch(shape, fc="green", ec="green", alpha=0.5, zorder=2)
            self.ax.add_patch(patch)

What it does: it deletes all the patches (descartes PolygonPatches) from axes (in which there is also a static map drawn above) and adds them one more time, recreating with an updated shape.
This solution works, but notably freezes my tkinter app. I understand, that it should be possible easier with the matplotlib animation and basically my shapes are rectangles, which are rotating and moving each step. Basically I know the new coordinates of the centroid and a new heading angle, that's enough to rebuild the shape.
My questions are: 1) how to do the animation over the static map, if you receive updates of your dynamic object's shapes from the "outside" and receive preferably as Shapely object? and 2) how to embed this solution into the tkinter app with the best performance? My option is bad at performance, mainly it is very slow reacting to pan/zoom

A: I don't have enough reputation to add this as a comment, but assuming you send each of the agent based model timestep/s to completion, it will freeze the GUI until that process is finished.  You will need to thread the agent based side of things if you don't want the GUI to freeze.
Secondly, should you want the plot to update continuously at each timestep, I suggest you look into blitting for the plot (docs here).  This will capture the map elements of the plot, and then only updates the agents at each timestep (saving the time of replotting the base map).  Depending on how many agents etc you have, this may solve the speed issue.  A word of warning however, blitting and threading do not like each other - you'll have to figure out how to get the plot information from the thread to the main GUI thread.


text:
Q: CondaHTTPError - SSL error while installing NLTK I am trying to install NLTK in my tensorflow environment of Anaconda. I have used the command "conda install nltk" for my windows 7 pc. It gives the following error:
 CondaHTTPError: HTTP 000 CONNECTION FAILED for url
 <https://repo.continuum.io/pkgs/r/win-32/repodata.json.bz2>
 Elapsed: -

 An HTTP error occurred when trying to retrieve this URL.
 HTTP errors are often intermittent, and a simple retry will get you on   your way.

 SSLError(MaxRetryError('HTTPSConnectionPool(host=\'repo.continuum.io\', port=443): Max retries exceeded with url: /pkgs/r/win-32/repodata.json.bz2 (Caused by SSLError(SSLError("bad handshake: Error([(\'SSL routines\', \'ssl3_get_server_certificate\', \'certificate verify failed\')],)",),))',),)

I have an additional certificate in my system. So I added the certificate hash to cert.pem file of anaconda/ssl. It worked for Linux machine, but windows machine still throws error. What can I do to solve this?

A: I have found the solution. I have modified the .condarc file and set the ssl_verify attribute False. It looks like this:
 channels:
   - defaults
 ssl_verify: False

Now I can add those packaged without any problem.
An alternate way is to modify the configuration file from command line:
conda config --set ssl_verify False

This will edit the file for you, wherever it might be located.

A: You can still make use of ssl by exporting the CA Certificate from a browser on the windows machine.
http://docs.bvstools.com/home/ssl-documentation/exporting-certificate-authorities-cas-from-a-website
Save the certificate to a folder that you can access, and then simply set the ssl_verify value in your .condarc file to the location of the cert.
ssl_verify: C:\\conda_config\\certificates\\ca_cert.cer

This will allow you to benefit from ssl protection quite easily.


text:
Q: Use input$ within inputPanel in rmarkdown document I would like to create a input panel with two numericInputs (a & b). The maximum value of numericInput b needs to the value from numericInput a.
---
title: "test input"
runtime: shiny
output: html_document
---

```{r, echo = FALSE}
inputPanel(
  numericInput("a", "A", 80,
               min = 1, max = 100),

  numericInput("b", "B", 15,
               min = 1, max = input$a)
)
```

This gives the error:

Operation not allowed without an active reactive context.

A: Without the use of shinyApp:
```{r, echo=FALSE}
  inputPanel(
    numericInput("a", label="A", min = 1, max = 100, value = 80),
    uiOutput('a')
)

  output$a <- renderUI({
    numericInput("b", label= "B", min = 1, max = input$a, value = 15)
 }
)
```

A: Hi you can do like in a classic shiny app :
```{r, echo = FALSE}
shinyApp(

  ui = fluidPage(
    inputPanel(
      numericInput("a", "A", 80,
               min = 1, max = 100),
      uiOutput("numericInput_reactive")
      )
  ),

  server = function(input, output) {
    output$numericInput_reactive <- renderUI({
      numericInput("b", "B", 15,
               min = 1, max = input$a)
    })
  }
)
```


text:
Q: Can we hide some rows in MySQL? Say we retrieve table data from a php code.

1- Without delete and restore particular rows from the table and,
2- Without having a column "hidden" (values are 0 or 1) and using the query SELECT ..... WHERE....AND hidden=0

Is it possible to temporary "hide" some of the rows ?
Or else what is the best way to do it ?

A: An alternative would be to create a VIEW which does not include the unwanted rows; that might be better if the requirement is of a (semi-)permanent nature. See here for more.

A: How do you know which rows you want to remove? For example, if you know the id for each of the rows you could append an exclusion to your queries
AND id NOT IN (4,9,28)

A: You can use WHERE id NOT IN
SELECT * FROM talName WHERE id NOT IN (1, 3)

+----+---------+-----+
| id |  name   | age |
+----+---------+-----+
|  2 | John    |  23 |
|  4 | Mary    |  21 |
|  5 | Michael |  26 |
+----+---------+-----+

A: There is no way to hide without deleting, since the mark for hidden is already done (hidden = 1).
Although the correct way is to alter the first query, since you won't retrieve unwanted data, you can:

*

*Query on the query, adding the 'where hidden=0' part

*Filter the data inside the script that handles the table

*Add a view on the database that is pre-filtering (where hidden=0)

*Filter the data on the client (start as hidden everything and using jquery show what you want (not recommended as a solution though)


text:
Q: I/system_server: oneway function results will be dropped but finished with status OK and parcel size 4 I'm seeing this in logcat sometimes, but don't know what it means.

A: I solved by passing view on in function argument
My XML
<TextView
android:onClick="@{ (view) -> handler.showSectionSelectionDialog(view) }"

My fragment
fun showSectionSelectionDialog(view: View) {
    Log.d(TAG, "showSectionSelection: clicked")
}

A: Its a binder message from onTransact(). if the process calling the service does not have the appropriate selinux permissions.
http://selinuxproject.org/page/NB_SEforAndroid_1#Android_Classes_and_Permissions.
you can simulate/get the same error from this snippet.
public void Run(){
        try {
            Process process = Runtime.getRuntime().exec("/system/bin/cmd wifi");
            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream()));
            StringBuilder result=new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            TextView tv = (TextView)findViewById(R.id.sample_text);
            Log.d(TAG, "Run: "+result.toString());
            tv.setText(result.toString());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

returns the same logcat error.
(the cmd binary in adb sends a shellCommand binder transaction).
running adb shell wifi runs the command correctly though, since the shell selinux context has the appropriate permissions.


text:
Q: Corrupted PDF when attempting to download I am trying to allow my users to download a PDF from our website and I got most of it working but when I attmept to open the PDF I get an error that the document is corrupted.  Where am I going wrong?
Here's my view:
<% @client.signed_documents.executed.each do |doc| %>

            <%= link_to (doc.external_document&.name || doc.folder_id ), download_pdf_signed_document_path(doc.id), download: true %>
            <%= doc.signed_at.strftime("%-m/%-d/%y") %>

<% end -%>

Router:
resources :signed_documents, only: [:index] do
    get "download_pdf", on: :member
end

Module:
module EsignGenie
  def self.download_pdf(folder_id)
    url = "https://www.esigngenie.com/esign/api/folders/download?folderId=#{folder_id}"

    begin
      response = RestClient::Request.execute(method: :get, url: url, raw_response: true, headers: {Authorization: "Bearer #{ENV['ESIGNGENIE_AUTH']}"} )
    rescue => e
      Sentry.capture_exception(e)
    end

    data = Base64.strict_encode64(File.open(response.file).read)
  end
end

Controller:
class SignedDocumentsController < ApplicationController
  before_action :authenticate_user!
  before_action :authorize_manager

  def download_pdf
    doc = SignedDocument.find(params[:id])
    data = EsignGenie.download_pdf(doc.folder_id)

    send_data(data, type: "application/pdf", disposition: "attachment", filename: "#{doc.external_document&.name || doc.folder_id}.pdf")
  end
end

Not sure where I'm going wrong or if I need to specify it's Base64 somewhere?  I just want to user to be able to download the file when they click the link.

A: I was able to modify the module to return the file rather than the Base64 encoded raw data:
module EsignGenie
  def self.download_pdf(folder_id)
    url = "https://www.esigngenie.com/esign/api/folders/download?folderId=#{folder_id}"

    begin
      response = RestClient::Request.execute(method: :get, url: url, raw_response: true, headers: {Authorization: "Bearer #{ENV['ESIGNGENIE_AUTH']}"} )
    rescue => e
      Sentry.capture_exception(e)
    end

    data = response.file
  end
end

I then changed the controller to call send_file rather than send_data now that it's a file rather than raw data
class SignedDocumentsController < ApplicationController
  before_action :authenticate_user!
  before_action :authorize_manager

  def download_pdf
    doc = SignedDocument.find(params[:id])
    data = EsignGenie.download_pdf(doc.folder_id)

    send_file(data, type: "application/pdf", disposition: "attachment", filename: "#{doc.external_document&.name || doc.folder_id}.pdf")
  end

After these changes, the download succeeded and the file was viewable.


text:
Q: BrowserMob Proxy Questions Is anyone familiar with using BrowserMob Proxy? I need some help.

https://github.com/lightbody/browsermob-proxy/blob/master/README.md

My goal is to try to use BrowserMob Proxy to detect that certain events are fired in the Network Tab. Any idea how to do this?
The language is in Java and I am using the Selenium Grid framework.

A: With the following code you can get the HAR archive.
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.start(0);
HashSet<CaptureType> enable = new HashSet<CaptureType>();
enable.add(CaptureType.REQUEST_HEADERS);
enable.add(CaptureType.REQUEST_CONTENT);
enable.add(CaptureType.RESPONSE_HEADERS);
proxy.enableHarCaptureTypes(enable);
HashSet<CaptureType> disable = new HashSet<CaptureType>();
disable.add(CaptureType.REQUEST_COOKIES);
disable.add(CaptureType.RESPONSE_COOKIES);
proxy.disableHarCaptureTypes(disable);

//get the Selenium proxy object
Proxy selProxy = ClientUtil.createSeleniumProxy(proxy);

capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, selProxy);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS,true);

FirefoxProfile profile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(new FirefoxBinary(),profile,capabilities);

driver.get(url);

Har har = proxy.getHar();

Then explore the har object entries as you need

A: *

*Assuming you ran script and got output in HAR format, upload at http://pcapperf.appspot.com/

*You will see the output like http://pcapperf.appspot.com/harviewer/index.html?path=examples/en-wikipedia-org.har
Sample Code just for reference in Java (please change at your need)
package com.selenium.performancetest;

import java.io.FileOutputStream;
import org.browsermob.core.har.Har;
import org.browsermob.proxy.ProxyServer;
import org.openqa.selenium.By;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class PerfTest {

public static void main(String[] args) throws Exception {

String strFilePath = "";

// start the proxy
ProxyServer server = new ProxyServer(4444);
server.start();
//captures the moouse movements and navigations
server.setCaptureHeaders(true);
server.setCaptureContent(true);

// get the Selenium proxy object
Proxy proxy = server.seleniumProxy();

// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);

// start the browser up
WebDriver driver = new FirefoxDriver(capabilities);

// create a new HAR with the label "apple.com"
server.newHar("assertselenium.com");

// open yahoo.com
driver.get("http://assertselenium.com");

driver.get("http://assertselenium.com/2012/10/30/transformation-from-manual-tester-to-a-selenium-webdriver-automation-specialist/");

// get the HAR data
Har har = server.getHar();
FileOutputStream fos = new FileOutputStream(strFilePath);
har.writeTo(fos);
server.stop();
driver.quit();

}

}

Reference


text:
Q: Yii Default Scope with 2 possible Conditions based on if statement I'm kinda new with MVC and Yii, and I'm trying to have 2 roles for users. I use User and Rights modules. Students can view, edit, create records but only own records (where userId is their Id) and tutors should be able to view only the records assigned to them in another column tutorId for each record.
I am trying to use defaultScope but it ignores the if statement and goes directly to the first condition always.
This is my code:
public function defaultScope()
{
    if($userId=Yii::app()->user->id){
        return array(
            'condition'=>'userid='.Yii::app()->user->id, //Scope is limited to logged in user only
        );
    } else {
        echo "You have Read Only Access";
        return array(
            'condition'=>'tutorid='.Yii::app()->user->id, //Scope is limited to tutor Id for each record
        );
    }
}

A: It should be
public function defaultScope()
{
    if(Yii::app()->user->checkAccess('tutor') == false)
    {
        return array(
            'condition'=>'userid='.Yii::app()->user->id, //Scope is limited to logged in user only
        );
    } else {
        echo "You have Read Only Access";
        return array(
            'condition'=>'tutorid='.Yii::app()->user->id, //Scope is limited to tutor Id for each record
        );
    }
}


text:
Q: How do I center my logo in Android Studio? I am trying to center my logo. Please see my code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/Background"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@drawable/Logo"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/signin"
        android:text="Sign in"
        android:textColor="@color/black"
        android:textSize="35dp"
        android:textStyle="bold"
        android:layout_margin="150dp"
        android:gravity="center"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/username"
        androi/>

</RelativeLayout>

I am trying to center the logo image but it is not working despite me using the layout_gravity="center" tag. Please help!

A: Use center in parent.
    <ImageView
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:src="@drawable/Logo"
    android:layout_centerInParent="true"/>


text:
Q: Elastic search nest search query I am getting stuck getting while implementing search using elastic search nest.
I have to implement like query with elastic search.
for ex. select * from table where username like '%abc xyz%'
As you can see in above sql query I have applied like query with string "abc" space and another string "xyz". Similarly I want this query in elastic search. Can anyone help me to implement such query in elastic search nest?
Below is the query
Client.Search<Video>(s => s
    .Query(q => q
        .Match(m => m
            .OnField("video_parent")
            .Query("0")
        ) && q
        .Match(m => m
            .OnField("video_status")
            .Query(objVideosFilterCriteria.VideoStatus.ToString())
        ) && q
        .MatchPhrase(ff=>ff
            .OnField("video_title")
            .Query(objVideosFilterCriteria.SearchString)
        ) && q
        .Range(r => r
            .OnField(f => f.video_date)
            .GreaterOrEquals(fromDate)
            .LowerOrEquals(toDate)
        )
    )
    .From(objVideosFilterCriteria.PageIndex)
    .Size(objVideosFilterCriteria.PageSize)
);

Above is the query I am using. In this query I am using
q.MatchPhrase(ff=>ff
    .OnField("video_title")
    .Query(objVideosFilterCriteria.SearchString)
)

for like query. But it doesn't seem to work.
I am using below data set and want to filter data from below list.
"hits" : [
  {
    "_source" : {
      "video_id" : 265006,
      "video_title" : "nunchuk rockin roller II"
    }
  },

  {
    "_source" : {
      "video_id" : 265013,
      "video_title" : "?Shaggy?????Locks???7??????Alberto E. Interview {407} 967 ~ 8596?"
    }
  },
  {
    "_source" : {
      "video_id" : 265014,
      "video_title" : "Shakin' Stevens - Kalundborg Rocker"
    }
  },
  {
    "_source" : {
      "video_id" : 265019,
      "video_title" : "?Shaggy?????Locks? = 7??????Greg M. Interview {407} 967 ~ 8596?"
    }
  },
  {
    "_source" : {
      "video_id" : 265023,
      "video_title" : "?Shaggy?????Locks? = 7??????Jason M. Interview {407} 967 ~ 8596?"
    }
  }

]
For example I would like to search with the keyword "kin rol" in the "video_title" field so with the above data it should fetch one record which exists at first position in above list but in my current query I am getting. nothing.


text:
Q: Xcode 4 not outputting .app package when building OSX project My Xcode 4 project is not actually building the .app bundle that it is supposed to when it finishes building. What are some reasons why this might be happening? The build process is not giving any errors, but it simply isn't giving me an app bundle which I can execute. What might be causing this?

A: The build output directory changed in xcode4. Open the Organizer (projects tab):

The built .app is located in the Derived Data directory, in this case:
~/Library/Developer/Xcode/DerivedData/GKTapper-dbndueflsmkgokewelsloryzthni


text:
Q: Adding controls to dynamics crm 2011 dynamically I want to keep a list of records with multiple fields, and enter them via one form, that shows the existing records as a list made of different text boxes. And a "new" button on the same form that'll create a new row of textboxes for the new entry.
Is it possible to create controls like textboxes dynamically on a form, as a result of button click? With JS or plugins?

A: For this you are probably best making a custom web page and presenting it in an iFrame on your form.
I don't believe creating textboxes dynamically will work very well, I don't think it would be supported - you would have to change the DOM. Also you would have to implement some weird and overly complicated logic.

A: I've been given requirements like this in the past. Although not totally supported, it is possible and I've seen it done many times.
Your best bet is to read up on some documentation to get familiar with making requests through javascript to the CRM service. You'll need to add libraries to your solution and make sure the form that is utilizing them references them.
Here's where to start: http://msdn.microsoft.com/en-us/library/gg334279.aspx
jQuery and jQueryUI will also make your life a lot easier when making DOM changes with javascript.
Read up on knockoutjs. I've essentially done the same thing you're asking and utilizing knockout made the task of adding\removing\updating rows so much simpler.
The best way you can approach your task is to first create an html page web resource that has your basic structure. Also create a javascript web resource that the page references. This file will be what works to dynamically modifies the page. In your entity form, add a new side navigation link and point it at your web resource.
Now when that web page loads, have an event handler in the js file that requests the list of records for that entity and displays them. From here you can include event handlers and buttons that will allow you to capture events and then make the appropriate service calls to CRM.

A: Why not have the fields already on the form in a separate hidden tab?
Then use javascript to:
Show the tab
Show a submit button
(user inputs data)
Submit the values via ajax (http://msdn.microsoft.com/en-us/library/gg328025.aspx)
Clear the text boxes
Hide the tab


text:
Q: Bash command for 7zip to convert multiple files into single 7zip files Trying to convert multiple .odt files to individual  7zip files with password
eg aa.odt and bb.odt to aa.odt.7z and bb.odt.7z with a password of YYY.
Have tried
for i in *; do 7z a -pYYY "%i.7z" "%i"; done

but it doesn't seem to find any of the files.
Thanks for the help

A: Sudodus solution is great
for i in *; do 7z a -pYYY "$i.7z" "$i"; done


text:
Q: Class 'BaseController' not found in 'RouteController.php' I started writing a site and encountered this problem. I created RouteController, which serves for address bar parsing, and created an inherited class to have a binding:
protected $controller;
protected $inputMethod;
protected $outputMethod;
protected $parameters;

Well, generally speaking, the base class, which is inherited by RouteController. But when I just added "extends BaseController" to "class RouteController", it immediately started crashing and outputted the following error:

PHP Fatal error: Uncaught Error: Class 'Core\Base\Controllers\BaseController' not found in /var/www/Artemiys_Shop/Core/Base/Controllers/RouteController. php:10 Stack trace: #0 {main} thrown in /var/www/Artemiys_Shop/Core/Base/Controllers/RouteController.php on line 10

Does anyone know where I might have made a mistake or done something wrong? I've never had a problem with this before.
RouteController.php
<?php

namespace Core\Base\Controllers;

use Core\Base\Exceptions\RouteException;
use Core\Base\Settings\Settings;
use Core\Base\Settings\ShopSettings;

class RouteController extends BaseController
{

    static private $_instance;

    protected $routes;

    private function _clone()
    {
    }

    static public function getInstance()
    {
        if(self::$_instance instanceof self){
            return self::$_instance;
        }
        return self::$_instance = new self;
    }

    /**
     * @throws RouteException
     */

    private function _construct()
    {

        $address_str = $_SERVER['REQUEST_URI'];

        if(strpos($address_str, '/') === strlen($address_str) - 1 && strpos($address_str, '/') !== 0){
            $this->redirect(rtrim($address_str, '/'), 301);
        }

        $path = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], 'index.php'));

        if($path === PATH){
            $this->routes = Settings::get('routes');
            if(!$this->routes) throw new RouteException('Website is under maintenance');
            $url = explode('/', substr($address_str, strlen(PATH)));
            if($url[0] && $url[0] === $this->routes['admin']['alias']){
                array_shift($url);
                if($url[0] && is_dir($_SERVER['DOCUMENT_ROOT'] . PATH . $this->routes['plugins']['path'] . $url[0])){
                    $plugin = array_shift($url);
                    $pluginSettings = $this->routes['settings']['path'] . ucfirst($plugin . 'Settings');
                    if(file_exists($_SERVER['DOCUMENT_ROOT'] . PATH . $pluginSettings . '.php')){
                        $pluginSettings = str_replace('/', '\\', $pluginSettings);
                        $this->routes = $pluginSettings::get('routes');
                    }
                    $dir = $this->routes['plugins']['dir'] ? '/' . $this->routes['plugins']['dir'] . '/' : '/';
                    $dir = str_replace('//', '/', $dir);
                    $this->controller = $this->routes['plugins']['path'] . $plugin . $dir;
                    $hrUrl = $this->routes['plugins']['hrUrl'];
                    $route = 'plugins';
                }else{
                    $this->controller = $this->routes['admin']['path'];
                    $hrUrl = $this->routes['admin']['hrUrl'];
                    $route = 'admin';
                }
            }else{
                $hrUrl = $this->routes['user']['hrUrl'];
                $this->controller = $this->routes['user']['path'];
                $route = 'user';
            }
            $this->createRoute($route, $url);
            if($url[1]){
                $count = count($url);
                $key = '';
                if(!$hrUrl){
                   $i = 1;
                }else{
                    $this->parameters['alias'] = $url[1];
                    $i = 2;
                }
                for( ; $i < $count; $i++){
                    if(!$key){
                        $key = $url[$i];
                        $this->parameters[$key] = '';
                    }else{
                        $this->parameters[$key] = $url[$i];
                        $key = '';
                    }
                }
            }

            exit();
        }else{
            try{
                throw new \Exception('Incorrect directory');
            }
            catch (\Exception $e){
                exit($e->getMessage());
            }
        }

    }

    private function createRoute($var, $arr){
        $route = [];
        if(!empty($arr[0])){
            if($this->routes[$var]['routes'][$arr[0]]){
                $route = explode('/', $this->routes[$var]['routes'][$arr[0]]);
                $this->controller .= ucfirst($route[0]. 'Controller');
            }else{
                $this->controller .= ucfirst($arr[0]. 'Controller');
            }
        }else{
            $this->controller .= $this->routes['default']['controller'];
        }
        $this->inputMethod = $route[1] ? $route[1] : $this->routes['default']['inputMethod'];
        $this->outputMethod = $route[2] ? $route[2] : $this->routes['default']['outputMethod'];

        return;
    }

}

BaseController.php
<?php

namespace Core\Base\Controllers;

use Core\Base\Exceptions\RouteException;

abstract class BaseController
{

    protected $controller;
    protected $inputMethod;
    protected $outputMethod;
    protected $parameters;

    /**
     * @throws RouteException
     */

    public function route() {
        $controller = str_replace('/', '\\', $this->controller);
        try {
            $object = new \ReflectionMethod($controller, 'request');
            $args = [
                'parameters' => $this->parameters,
                'inputMethod' => $this->inputMethod,
                'outputMethod' => $this->outputMethod
            ];
            $object->invoke(new $controller, $args);
        }
        catch (\ReflectionException $e){
            throw new RouteException($e->getMessage());
        }
    }
    public function request($args){

    }

}

Index.php
<?php

define ('VG_ACCESS', true);

header('Content-Type:text/html;charset=utf-8');
session_start();

require_once 'config.php';
require_once 'Core/Base/Settings/internal_settings.php';

use Core\Base\Exceptions\RouteException;
use Core\Base\Controllers\RouteController;

try{
    RouteController::getInstance()->route();
}
catch (RouteException $e) {
    exit($e->getMessage());
}

Setting.php
<?php

namespace Core\Base\Settings;

class Settings
{

    static private $_instance;

    private array $routes = [
        'admin' => [
            'alias' => 'admin',
            'path' => 'Core/Admin/Controllers/',
            'hrUrl' => false
        ],
        'settings' => [
            'path' => 'Core/Base/Settings/'
        ],
        'plugins' => [
            'path' => 'Core/Plugins/',
            'hrUrl' => false,
            'dir' => false
        ],
        'user' => [
            'path' => 'Core/User/Controllers/',
            'hrUrl' => true,
            'routes' => [

            ]
        ],
        'default' => [
            'controller' => 'IndexController',
            'inputMethod' => 'inputData',
            'outputMethod' => 'outputData'
        ]
    ];

And i would like to know, why is this error showing up?


text:
Q: Picard's Theorem (Lipschitz) Problem. I have the following question:

Determine if the function $F(x,y) = xy^{1/3}$ satisfy a Lipschitz condition on the rectangle $\{ (x,y) : |x| \leq h, |y| \leq k \}$ where $h > 0$ and $k > 0$?
If $b>0$ determine the region $|x| < h, |y|<k$ which has the largest value of $h$ in which Picard's theorem can be used to show that the initial-value problem
$y' = xy^{1/3}$, $y(0) = b$
has a unique solution (you may assume Picard's theorem, but should prove that the assumptions are satisfied) and find the solution explicitly.
If $b=0$ show that for any $c > 0$ there is a solution $y$ which is identically zero on $[-c,c]$ and positive when $|x| > c$. Find these solutions explicitly and show that the resulting solutions satisfy the ODE for all values of $x$.

In trying to determine whether or not this satisfies the Lipschitz condition or not I've done the following:
$|F(x,u) - F(x,v)| = |xu^{1/3} - xv^{1/3}| = |x||u^{1/3} - v^{1/3}| \leq h|u^{1/3} - v^{1/3}|$
But get stuck at this point as $h|u^{1/3} - v^{1/3}| \leq h|u-v|$ if and only if $u,v \geq 1$ - so I'm thinking this doesn't satisfy the Lipschitz condition but can't really formulate it.
For the two conditions of Picard's theorem to be satisfied, we must have:
$F(x,y)$ is continuous in $R$, where $R$ is the rectangle: $|x|<h$, $|y-b|<k$ and that $F$ is bounded by $M$ so $|F(x,y)| \leq M$ and $Mh \leq k$
The second condition being that $F$ satisfies a Lipschitz condition in $R$.
Beyond this I'm unsure what to do, thanks.

EDIT: Sorry, to include the version of Picard's theorem I'm using:

The ODE $y' = f(x,y)$ with $y(a) = b$ has a solution in the rectangle $R: |x-a| \leq h, |y-b| \leq k$ provided:
(i) $f$ is continuous in $R$, bounded by $M$ (so $|f(x,y)| \leq M$) and $Mh \leq k$
(ii) $f$ satisfies a Lipschitz condition in $R$.
Furthermore, this solution is unique.

A: The function $f(x, y)=xy^{1/3}$ is not Lipschitz on any domain containing $y=0$, for if we assume it is Lipshitz then it must satisfies $|xy^{1/3}|=|f(x, y)-f(x, 0)|\leq L|y|$ for some $L>0$. But $\displaystyle\lim_{y\rightarrow 0^{+}}\frac{xy^{1/3}}{y}=\displaystyle\lim_{y\rightarrow 0^{+}}\frac{x}{y^{2/3}}=\infty$ for $x>0$.


text:
Q: $Expand does not work when i get one item I prepare Odata API for mobile application, and i have a problem with $Expand. When i use this query everything works ok.
Query:
.../odata/forms?$expand=FormFields($expand=FormFieldRadios)&$filter=FormId eq 1
But when i use this query:
.../odata/forms(1)?$expand=FormFields($expand=FormFieldRadios)
Expand does not work and items collection si empy.
My json results
Items coolection
One item
My nugets
ConfigureServices:
services.AddOData();
services.AddODataQueryFilter();
services.AddMvc(options =>
    {
        // https://blogs.msdn.microsoft.com/webdev/2018/08/27/asp-net-core-2-2-0-preview1-endpoint-routing/
        options.EnableEndpointRouting = false;
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Configure
app.UseMvc(routeBuilder =>
{
    routeBuilder.Select().Expand().Filter().Count().OrderBy().MaxTop(250).Expand(QueryOptionSetting.Allowed);
    routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel(app.ApplicationServices));
});

ModelBuilder
 builder.EntitySet<Form>("Forms").EntityType.Filter().Count().Expand(OdataDefaults.MaxExpansionDepth).OrderBy().Page().Select();

Form Entity
 public class Form
 {
     [Key, Required]
     public int FormId { get; set; }

     [Required]
     public int Order { get; set; }

     [Required]
     public bool Active { get; set; }

     [Required, MaxLength(255)]
     public string Name { get; set; }

     public int IsDeleted { get; set; }

     [MaxLength(255)]
     public string SuccessMessage { get; set; }

     public ICollection<FormField> FormFields { get; set; } = new List<FormField>();
 }

Odata Controller
public class FormsController : ODataController
{
    private VillageContext _db;

    public FormsController(VillageContext context)
    {
        _db = context;
    }

    [EnableQuery(AllowedFunctions = OdataDefaults.AllowedFunctions, MaxExpansionDepth = OdataDefaults.MaxExpansionDepth, PageSize = OdataDefaults.PageSize)]
    public IActionResult Get()
    {
        return Ok(_db.Forms);
    }

    [EnableQuery(AllowedFunctions = OdataDefaults.AllowedFunctions, MaxExpansionDepth = OdataDefaults.MaxExpansionDepth, PageSize = OdataDefaults.PageSize)]
    public IActionResult Get([FromODataUri] int key)
    {
        return Ok(_db.Forms.Find(key));
    }
}

A: EntityFramework's Find method does not return an IQueryable<TEntity> but rather TEntity itself. It is therefore logical that OData can no longer expand on it, since there is no expression tree anymore to "modify".
Change your function to this:
[EnableQuery(AllowedFunctions = OdataDefaults.AllowedFunctions, MaxExpansionDepth = OdataDefaults.MaxExpansionDepth, PageSize = OdataDefaults.PageSize)]
public IActionResult Get([FromODataUri] int key)
{
    return Ok(SingleResult.Create(_db.Forms.Where(form => form.FormId == key)));
}

A: Have you defined a key against your entity (forms)?
Look at the demo http://services.odata.org/V4/TripPinService/$metadata - you'll see a key is defined so you can reference entity members by the key you choose.
  Example:
  <EntityType Name="Person" OpenType="true">
   <Key>
       <PropertyRef Name="UserName" />
   </Key>

Then as per the OData examples you can use a query like:
GET serviceRoot/People('russellwhyte')


text:
Q: Host phantomjs as cloud service I m using phantom.js for simulating some steps and to generate few pdf/image. Now I'm trying to host as service so i can use it from any place.
Is there any way to host as service in azure cloud and use it across the glob.


text:
Q: Which technique for locating many similar Base Pointer Adresses (fast)? I try to catch some Base Pointer Adresses from a Windows Application which I want to Bot (Its not a game, Its an Online Broker). So, I know how to find Base Pointer Adresses, but I do this with Cheatengine (Find Adresses, set Breakpointes, search for the Output Adresses... and so on) - but this takes very much time for Base Pointers with 6+ Offsets. Maybe there is a much faster technique how to scrape them out of Memory?
And here is my presumption: In  This Pic  you can see, there are many similar Entrys (Forex Entrys), and they are all similar structured. They have a Adress for Ask-Value and Bid-Value - these are the Pointers I need! The Values are represented as Double. Maybe, I can find multiple Adresses at once, if I find the one from another. I thought on object oriented programing, where many Instances have Adresses nearby to the other. So, is there a way to find multiple at once, and fast?
I tried some stuff with OllyDbg, and didnt find some nearby (But my skills with OllyDbg are not insane, I still dont know all functions of it). Do you guys have a better solution, how I can find them faster? I dont really want to code some stuff in Assembler - but if nececary, I can do this. Would be great if you can help. There are 89 Entrys, and I will need per something like 20 - 30 minutes. Would be awful.
Cheers!

*

*Filthy Frank

A: Using pointers and offsets is not the correct way to go about this.  On the back end they're just using HTTP and an API.  You should either use that directly or hook the function that does it and then work with the data right after it is received by the client.


text:
Q: Php 7 error for a simple form getting Object of class mysqli could not be converted to int The code gets error saying  Object of class mysqli could not be converted to int. When i try to load the page i get this error,i checked other questions but it was not helpful
<?php
$conn = mysqli_connect("localhost", "root", "", "coinlion");
if ($conn == 0) {
    echo "could not connect";
} else {
    mysqli_select_db("coinlion");
    echo "connected";
}
?>
<form method="post">

                     Link URL:
                    <input type="text" name="linkurl" value="" required>

                     Link Description:
                    <textarea name="linkdesc" cols="50" rows="5" required></textarea>

        <input type="submit" name="submit1">
        <input type="reset" name="reset1">

php code
<?php
if (isset($_POST['submit1'])) {
    $linkurl = $_POST['linkurl'];
    $linkdesc = $_POST['linkdesc'];
    mysqli_query($conn, "insert into
      test(linkurl,linkdesc)values('$_POST[linkurl]','$_POST[linkdesc]')");
    echo "data inserted";
}
?>

A: Well the issue was with the line    if($conn==0) ,This value was taken as an integer so the error occured and an Connection variable to Mysqli_select_db was missing , after fixing it , the code ran successfully


text:
Q: In apache maven, how to solve [ERROR] Error fetching link: .../package-list. Ignored it? I have a multimodule scala project that requires scaladocs to be attached to each of them. So I configured maven-javadoc-plugin to generate java/scala doc automatically:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-javadoc-plugin</artifactId>
  <version>2.10.4</version>
  <configuration>
    <attach>true</attach>
  </configuration>
  <executions>
    <execution>
      <id>attach-javadoc</id>
      <goals>
        <goal>jar</goal>
      </goals>
    </execution>
  </executions>
</plugin>

However it turns out that this configuration doesn't automatically generate package-list, so I keep getting this error when a submodule is used by another:

[ERROR] Error fetching link: .../package-list. Ignored it.

Is there a way to configure javadoc/scaladoc plugins to generate an empty package-list file if the package definition is not defined? Or there are better ways to avoid throwing this error?

A: Upgrading the maven-javadoc-plugin to version 3.1.0 or higher gets rid of this error message.


text:
Q: WordPress Error showing in compat.php I am really new to wordpress environment.
 I have the site on https://www.thewebdebug.com which is showing an error  like
PHP Error Message

Fatal error: require() [function.require]: Failed opening required '/home/a9739613/public_html/wp-includes/random_compat/random.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/a9739613/public_html/wp-includes/compat.php on line 338

can anybody tell me what is going on and how should i fix it.? I had tried on the web but couldnot find a solution that fits my need. I have recently upgraded my wordpress and some plugins failed to do.


text:
Q: How to use PHP rexep or preg_match to extract letters and numbers from a string Working with a ficticuous string such as;
$string = 'Ford : LTD 1988 Ford Station Wagon with HP 351 H Engine and Performance Transmission';

How could I use rexexp or preg_match (I don't know which would be better either) to extract a sequence of letters and numbers ("HP 351 H") from that string to use in another variable (ie: $EngineSize)
The above is a fictious example, I'm just trying to make it clear that I'm trying to extract letters and numbers from a UI.
NOTE: Being that this is coming from a UI, the engine size may be positioned anywhere in the string and the format may be with or without spaces and may or may not have a letter at the end, as well as the model could be 2 or 3 letters (ie; LE, LT, LTD etc) as well as the engine size could be 2 - 3 digits possibly  followed by 2 or three letters).
If anyone wouldn't mind showing me how to write an expression to retrieve this data and explain to me which is better (regexp or preg_match) I'd be most appreciative and I thank you in advance.

A: The following regex matches exactly what you describe, but there is a good chance of false positives:
/(?<=\s|^)[a-zA-Z]{2,3} ?\d\d\d? ?[a-zA-Z]{1,3}?(?=\s|$)/


text:
Q: Access on host served Angular app in Hyper-v for testing purposes I want to access my Angular application -- served on port 4200 of my computer (Windows 10) -- inside my HyperV virtual computer (Windows 7).
If I enter http://<host-ip>:4200 in IE or Chrome, I get:
This page can't be displayed.
Through ping <host-ip> I can sucessfully address the port and
thanks to @Mick I did try: netstat -ano | find ":4200" on my host, telling me
127.0.0.1:4200   0.0.0.0:4200   LISTENING

I tried:

*

*different switches (Intern / Extern)

*disabled the firewall on virtual machine

without any success.
Any ideas?

A: May I ask more detailed information for this issue?
This Angular app is running on the Hyper-V host? And used the port 4200?
Did you run the command "netstat -ano | find ":4200" "to check if the port 4200 is listening on the host?
I observed a similar thread as yours. It may cause the port used by the app is already in use. please check the following link if it helps.
https://stackoverflow.com/questions/39091735/port-4200-is-already-in-use-when-running-the-ng-serve-command


text:
Q: How to write regex to enforce maximum of 255 characters? What regular expression would match any characters (including spaces), but have a maximum of 255 characters?  Is this it?
^[a-zA-Z0-9._]{1,255}$

A: Well, anything would be:
^.{1,255}$

. doesn't allow new lines. If that's a problem, you can use the dot-all flag (usually /s).
If you want to add spaces to your regex, try this (note the space):

*

*^[a-zA-Z0-9._ \t]{1,255}$ - Allow spaces and tabs.

*^[a-zA-Z0-9._\s]{1,255}$ - Allow all whitespaces.

*^[\s\w.]{1,255}$ - Same as the above (unless your flavor supports Unicode).

A: Well that would not allow anything, if you want anything, you're better off using ^.{1,255}$.
Or, if you want to allow nothing as well: ^.{0,255}$