text:
Q: command is not getting executed, if started by service I have a java programm with an update function. This function simply starts the jar and then stops itself. If i start the programm manually to test the update function, it works just fine. But if i start the programm with a service, it does not.
This is the service:
[Unit]
Description=Starts the Main Java Programm
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash /usr/sbin/start.sh
TimeoutStartSec=0
User=USERNAME

[Install]
WantedBy=default.target

This is start.sh (This way the programm does not restart itself):
#!/bin/bash

cd /home/USERNAME/bin/java

echo 'PASSWORD' | sudo -S java -jar variobox.jar > output.txt 2> error.txt

How i call the  programm manually (This is the way the programm restarts correctly):
echo 'PASSWORD' | sudo -S java -jar variobox.jar > output.txt 2> error.txt &

This is how the java programm updates itself:
ProcessBuilder builder = new ProcessBuilder("java", "-jar", "variobox.jar");
builder.redirectOutput(new File("output.txt"));
builder.redirectError(new File ("error.txt"));
builder.start();

The 2 txt files are completly empty after the programm should restart and i do not get any error message. It just does not restart. I think the problem is some kind of user/access restriction, with the service. But i am not far enough into linux to fully understand this. I thought by setting the user in the service and using sudo it should work.
EDIT: After changing Type=simple to Type=forking it works once. But after that it still does not restart.


text:
Q: pandas sort a column by values in another column I have a dataset that I want to sort and assign rank based on it.
Suppose it has two columns, one is year and the other is the column that I want to sort.
import pandas as pd
data = {'year': pd.Series([2006, 2006, 2007, 2007]),
        'value': pd.Series([5, 10, 4, 1])}
df = pd.DataFrame(data)

I want to sort the column 'value' by each year and then give rank to it. What I would like to have is
data2= {'year': pd.Series([2006, 2006, 2007, 2007]),
        'value': pd.Series([10, 5, 4, 1]),
        'rank': pd.Series([1, 2, 1, 2]}
df2=pd.DataFrame(data2)

>>> df2
   rank  value  year
0     1     10  2006
1     2      5  2006
2     1      4  2007
3     2      1  2007

A: You can use groupby and then use rank (with ascending=False to get the largest values first).  You don't need to sort in the groupby, as the result is indexed to the dataframe (slightly faster performance).
df['yearly_rank'] = df.groupby('year', sort=False)['value'].rank(ascending=False)

>>> df.sort_values(['year', 'yearly_rank'])
   value  year  yearly_rank
1     10  2006            1
0      5  2006            2
2      4  2007            1
3      1  2007            2

A: Consider a groupby apply function with sort:
def rankfct(row):
    row['rank'] = row['value'].rank(ascending=False)
    return row

df = df.groupby(['year']).apply(rankfct).sort(['year','value'], ascending=[1,0])

redpajama_set_name: RedPajamaStackExchange


text:
Q: call jquery function from window.open() I've got the problem. I need load template from file and write it to new window.document.
var newWindow = $window.open();
newWindow.document.write('<title></title>');
newWindow.document.write('');
newWindow.document.write('
test
');
newWindow.document.write('');
$(printWindow.document).load('template.html  #element')
newWindow.document.close();

And $(printWindow.document).load('template.html  #element') doesn't work.
How do I implement this?


text:
Q: Cannot POST /register I am building my first node.js app, and I am starting with the authentication. So far, so good, BUT I can't seem to get my form to post.
I have spent a significant amount of time today trying to figure out why it will not post. I guess i'm just not understanding what is wrong with my code, and I hope someone could take a look and point out what is wrong with it, so it goes as follows...
my app.js looks like this...
const express = require('express');
      http = require('http');
      path = require('path');
      session = require('express-session');
      app = express();
      mysql      = require('mysql');
      bodyParser = require('body-parser');
      db = require(__dirname, 'models/db')

var index = require('./routes/index');
var register = require('./routes/register');

app.use('/', index);
app.use('/register', register);

var engine = require('ejs-mate');
app.engine('ejs', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

var server = http.createServer(app);

var port = 8995;
server.listen(port);

module.exports = app;

my register.js looks like this...
var express = require('express');
var router = express.Router();
var db = require(__dirname, 'models/db');
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
   extended: false
}));

app.use(bodyParser.json());

router.get('/', function(req, res, next) {
  res.render('register', { title: 'Register for a free account' });
});

router.post('/register', function(req, res) {
  var input = JSON.parse(JSON.stringify(req.body));
  var today = new Date();
  var users = {
    "first_name":req.body.first_name,
    "last_name":req.body.last_name,
    "email":req.body.email,
    "password":req.body.password,
    "username": req.body.username,
    "created":today,
    "modified":today
  };
  db.getConnection(function(err, connection) {
    connection.query('INSERT INTO users SET ? ', users, function(err, result) {
    connection.release();
    if (err) { return console.error(err); }
    });
  });
  res.redirect('/index');
});
module.exports = router;

and lastly, my register.ejs looks like this...
<% layout("/layouts/default") -%>

    <form method="post" action="/register" class="form-horizontal">

Sign Up

            Username

                <input type="text" class="form-control" name="username" required="required">

            Email Address

                <input type="email" class="form-control" name="email" required="required">

            Password

                <input type="password" class="form-control" name="password" required="required">

            Confirm Password

                <input type="password" class="form-control" name="confirm_password" required="required">

                <button type="submit" class="btn btn-primary btn-lg">Sign Up</button>

    </form>

Already have an account? Login here

I don't see why the error CANNOT POST /register comes up when I try to submit my form because i'm specifying what route to post ('/register') in my app.post

A: You've added the register router to be bound to the '/register' link... so all links in route register will have to start with /register/...
if you try to post /register/register it will work
app.use('/', register)

Will work


text:
Q: What are the benefits of creating a configure method to pass in view model versus passing in view model through the init of a View? I have seen both patterns where you have a view model for a view and you can either pass the view model in through the init of the view or have a configure method that takes in the view model and configures the property. What are the pros and cons for those patterns?
i.e.
struct ViewModel {
    let titleLabel: String
    let subtitleLabel: String
}

init method:
class View: UIView {
    let viewModel: ViewModel
    init(viewModel: viewModel) {
        self.viewModel = viewModel
    }
}

configure method:
class View: UIView {
    init() {}

    configure(viewModel: ViewModel) {
        // configuring view properties
    }
}

A: Generally, if you can set properties of an object during from its initializer, it's preferable to do so, because you won't need the properties to be optional (or worse, have non-sense default values like 0 for ints, false for bools, etc.).
You also get the benefit of Swift's definite-initialization guarantees, which ensure that you can't forget to set any properties from the initializer. Contrast this with the configure(viewModel:) method, which you can forget to call.
However, there are times when this simply isn't possible, such as when using Storyboards (which initialize the views for you, without a chance for you to pass through any arguments to the initializer) or when you're building views that are meant to be recycled (such as cells in a table view).


text:
Q: Definition of curvature Kay (Fundamentals of Statistical Signal Processing) defines the curvature of a log-likelihood function to be the "negative of the second derivative of the logarithm of the likelihood function at its peak".
I haven't come across this definition before, and Google hasn't been particularly forthcoming; is this a standard definition, or something Kay has introduced himself?
This is in the context of a derivation of the CRLB.

A: The first derivative indicates the slope of the curve at a given point. If you take the derivative again (ie, you take the second derivative) you have the rate of change of that slope.
If the slope changes slowly (or does not change at all) you have something that seems straight, while if the slope changes abruptly, you have a curve that twists a lot.
At least, that's how I get an intuition of the relationship between curvature and second derivaitve. I hope this helped!


text:
Q: Get samples from numpy array based in samples of another array I have one matrix a and another vector b:
a = np.array([[0,1,2],
              [3,4,5],
              [6,7,8]]

b = np.array([0.5,0.3,0.2])

Is there any shorthand function that can extract rows from a based in values of b?
For instance, get samples from a where b >= 0.3 should return:
[[0,1,2],
 [3,4,5]]

What i've came up with:
a_idx = np.argwhere(b >= 0.3).flatten()
c = np.take(a, a_idx)

This works, but i'd like to know if there's a better solution (specifically to work with large arrays).
Thanks in advance.

A: a[b >= 0.3] is cleaner but your method seems to be faster (tested on 1M-entry arrays with 200 measurements and yous is ~33% faster).


text:
Q: Constraint animation doesnt animate y position change This code is to expand a label by disabling the constraint which is keeping it at a max height of 54 to a full size. It works as it should but it jumps to the new y position straight away (without animating) and changes frame height after which makes it look like it jumps before animating
@IBOutlet var descriptionHeightConstraint: NSLayoutConstraint!

    @IBAction func toggleFullDescription(_ sender: Any) {
        if descriptionHeightConstraint.isActive {
            self.layoutIfNeeded()
            descriptionHeightConstraint.isActive = false
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
                self.layoutIfNeeded()
            }, completion: nil)
            //seeMoreButton.setTitle("See less", for: .normal)
        } else {
            self.layoutIfNeeded()
            descriptionHeightConstraint.isActive = true
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
                self.layoutIfNeeded()
            }, completion: nil)
            //seeMoreButton.setTitle("See more", for: .normal)
        }
    }

Video of the issue


text:
Q: ios-mapkit, strange behavior with custom image annotations I've written some code for showing annotations with custom images in a mapview.
My mapview delegate implements this method to customize annotation when they are put in the map:
- (MKAnnotationView *) mapView:(MKMapView *) mapView viewForAnnotation:(id<MKAnnotation>) annotation {
if ([annotation isKindOfClass:[Station class]]) {
    Station *current = (Station *)annotation;
    MKPinAnnotationView *customPinview = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
    if([[current type] compare:FONTANELLA]==NSOrderedSame)
        customPinview.pinColor = MKPinAnnotationColorPurple;
    else{
        int test=current.bici;
        if(test==0)
            customPinview.image = [UIImage imageNamed:@"bicimir.png"];
        else if(test<4)
            customPinview.image = [UIImage imageNamed:@"bicimi.png"];
        else if(test>=4)
            customPinview.image = [UIImage imageNamed:@"bicimig.png"];
    }
    customPinview.animatesDrop = NO;
    customPinview.canShowCallout = YES;
    return customPinview;
}
else{
    NSString *identifier=@"MyLocation";
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    return annotationView;
}

}
The problem is a strange behavior when I long click on a custom annotation on the map:
The image change and the default red pin is shown.
Why this behavior? And How can I avoid it?

A: When you want to use a custom image for an annotation view, create a generic MKAnnotationView instead of an MKPinAnnotationView.
The MKPinAnnotationView really likes to display its default image which is a pin.
Rearrange the logic a bit so that for FONTANELLA, it creates an MKPinAnnotationView but for the rest an MKAnnotationView.
Also, you should really implement annotation view re-use for all cases (and the last else part doesn't make sense since nothing is done if the dequeue doesn't return anything--you could just do return nil; instead).

A: inside .h file
@interface AddressAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;
    NSString *mPinColor;

}

@property (nonatomic, retain) NSString *mPinColor;

@end

in .m file
@implementation AddressAnnotation

@synthesize coordinate mPinColor;

- (NSString *)pincolor{
    return mPinColor;
}

- (void) setpincolor:(NSString*) String1{
    mPinColor = String1;
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
    coordinate=c;
    NSLog(@"%f,%f",c.latitude,c.longitude);
    return self;
}
@end

inside .m class file
- (MKAnnotationView *) mapView:(MKMapView *)mapView1 viewForAnnotation:(AddressAnnotation *) annotation{

    UIImage *anImage=[[UIImage alloc] init];

MKAnnotationView *annView=(MKAnnotationView*)[mapView1 dequeueReusableAnnotationViewWithIdentifier:@"annotation"];

    if(annView==nil)
    {
        annView=[[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotation"] autorelease];

    }

    if([annotation.mPinColor isEqualToString:@"green"])
    {

        anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Google pin green.png" ofType:nil]];
    }
    else if([annotation.mPinColor isEqualToString:@"red"])
    {
        anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Google pin red.png" ofType:nil]];
    }
    else if([annotation.mPinColor isEqualToString:@"blue"])
    {
        anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Google pin blue.png" ofType:nil]];
    }

    annView.image = anImage;

    return annView;

}


text:
Q: nginx Restrict or Redirect requests to go through index.php in the root My project requirement is to launch an angular(v6)/ionic(v4) app(index.html) from Slim framework (index.php).
The root folder structure is attached in the image below:

'www' is the root directory where the Slim index.php lies. Inside 'www' is the app folder where the angular build files(index.php) are added.
The requirement is that all the requests should go through Slim index.php in the root folder and based on some session logic we have to route or launch the angular app (index.html).
Right now, 'https://domain/' goes through index.php. But,
'https://domain/app/' directly launches the angular app (index.html).
How can I configure nginx so that all requests are to be handled in the root directory by Slim index.php ?
server {
    server_name <domain>;

    root /var/www/<some name>/public/www/;
    index index.php index.html index.htm;

    access_log  /var/log/nginx/<some name>.log;
    error_log   /var/log/nginx/<some name>.log;

    sendfile off;

    location / {
        index index.php index.html index.htm;
        try_files $uri $uri/ index.php /index.php?$args;
    }
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_read_timeout 36000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Thanks

A: you can restrict access to your app directory like so
location /app {
    deny all;
    return 404; #show not found instead of 403
}

Or you can override the 403 handling by sending a redirect to https://example.com/
location /app{
     deny all;
     error_page 403 https:/domain.com/;  #redirect to your main directory
 }


text:
Q: Understanding With query operation I saw this example in postgresql guide:
WITH t AS (
DELETE FROM foo
)
DELETE FROM bar;

The manual says:

This example would remove all rows from tables foo and bar. The number
  of affected rows reported to the client would only include rows
  removed from bar.

Why would it delete from foo if I didn't "call" t?
Normaly with is used like:
WITH t AS (
    UPDATE products SET price = price * 1.05
    RETURNING *
)
SELECT * FROM t;

There is an actuall call to t which only then "summons" the with block.
Can someone explain this?

A: The quoted example shows that a query in with clause is executed regardless of whether it is used in the main query or not. With this principle you can perform several independent operations in a single query. It is a very convenient solution and greatly expands the flexibility of SQL.
Note that if you do not want the query t to be executed, just do not use it:
 DELETE FROM bar;

If you have used
 WITH t AS (
 DELETE FROM foo
 )
 DELETE FROM bar;

this means that your intention is to remove rows from both tables foo and bar in one query.
In the documentation you can find:

If a data-modifying statement in WITH lacks a RETURNING clause, then
  it forms no temporary table and cannot be referred to in the rest of
  the query. Such a statement will be executed nonetheless.


text:
Q: Python Count per hour log file I have a python script that displays the Date, hour and IP Address for an attack in a log file. My issue is that i need to be able to count how many attacks occur per hour per day but when i implement a count it just counts the total not what i want.
The log file looks like this:
Feb  3 08:50:39 j4-be02 sshd[620]: Failed password for bin from 211.167.103.172 port 39701 ssh2
Feb  3 08:50:45 j4-be02 sshd[622]: Failed password for invalid user virus from 211.167.103.172 port 41354 ssh2
Feb  3 08:50:49 j4-be02 sshd[624]: Failed password for invalid user virus from 211.167.103.172 port 42994 ssh2
Feb  3 13:34:00 j4-be02 sshd[666]: Failed password for root from 85.17.188.70 port 45481 ssh2
Feb  3 13:34:01 j4-be02 sshd[670]: Failed password for root from 85.17.188.70 port 46802 ssh2
Feb  3 13:34:03 j4-be02 sshd[672]: Failed password for root from 85.17.188.70 port 47613 ssh2
Feb  3 13:34:05 j4-be02 sshd[676]: Failed password for root from 85.17.188.70 port 48495 ssh2
Feb  3 21:45:18 j4-be02 sshd[746]: Failed password for invalid user test from 62.45.87.113 port 50636 ssh2
Feb  4 08:39:46 j4-be02 sshd[1078]: Failed password for root from 1.234.51.243 port 60740 ssh2
Feb  4 08:39:55 j4-be02 sshd[1082]: Failed password for root from 1.234.51.243 port 34124 ssh2

the code i have so far is:
import re

myAuthlog=open('auth.log', 'r') #open the auth.log for reading
for line in myAuthlog: #go through each line of the file and return it to the variable line
ip_addresses = re.findall(r'([A-Z][a-z]{2}\s\s\d\s\d\d).+Failed password for .+? from (\S+)', line)

print ip_addresses

the outcome is as shown
[('Feb  5 08', '5.199.133.223')]
[]
[('Feb  5 08', '5.199.133.223')]
[]
[('Feb  5 08', '5.199.133.223')]
[]
[('Feb  5 08', '5.199.133.223')]
[]
[('Feb  5 08', '5.199.133.223')]

A: The python function groupby() will group your items according to any criteria you specify.
This code will print the number of attacks per hour, per day:
from itertools import groupby

with open('auth.log') as myAuthlog:
    for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
        print "%d attacks in hour %s"%(len(list(group)), key)

Or, with an additional requirement from the comments:
from itertools import groupby

with open('auth.log') as myAuthlog:
    myAuthlog = (line for line in myAuthlog if "Failed password for" in line)
    for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
        print "%d attacks in hour %s"%(len(list(group)), key)

Or, with different formatting:
from itertools import groupby

with open('auth.log') as myAuthlog:
    myAuthlog = (line for line in myAuthlog if "Failed password for" in line)
    for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
        month, day, hour = key[0:3], key[4:6], key[7:9]
        print "%s:00 %s-%s: %d"%(hour, day, month, len(list(group)))

A: import collections
from datetime import datetime as dt

answer = collections.defaultdict(int)
with open('path/to/logfile') as infile:
    for line in infile:
        stamp = line[:9]
        t = dt.strptime(stamp, "%b\t%d\t%H")
        answer[t] += 1


text:
Q: Joining strings using separator in Java I have an object called MyDate and it return three methods String getDay(), String getYear(), String getMonth()
For example Sep 24 2013 will 2013, 24, 9 .. I want to join these three strings using a common separator which is DASH "-". How do I join without using StringBuilder or "+" operator ? What would be the most compact code form ?
For e.g I know I can do this  but is there a more compact form ? Because I know + operator is expensive.
MyDate myDate = new MyDate();
myDate.getYear()+"-"+myDate.getMonth()+"-"+myDate.getDay();

A: You could use String.format(...)
For example, if your getXXX() methods return a Strings:
String dateStr = String.format("%s-%s-%s",
      myDate.getYear(), myDate.getMonth(), myDate.gateDay());

Else if they return an int:
String dateStr = String.format("%4d-%02d-%02d",
      myDate.getYear(), myDate.getMonth(), myDate.gateDay());

For more on this, check out any tutorial on the printf(...) method or the Formatter object.

A: You can be cool and use Guava
public static void main(String[] args) {
    Date myDate = new Date();
    Object[] objects = new Object[] {
            myDate.getYear(), myDate.getMonth(), myDate.getDay()
    };
    String message = Joiner.on("-").join(objects);
    System.out.println(message);
}

A: If you're not opposed to using Apache commons.
StringUtils#join

A: If you can use apache commons then String concatenate(Object[] array) would be perfect.
You can give your strings in one go :
StringUtils.concatenate([myDate.getYear(), myDate.getMonth(), myDate.gateDay()])

More info here :
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html


text:
Q: Minikube not pull image from local docker container registry i am trying to deploy containers to local kubernetes, for now i have install docker deamon, minikube and minikube dashboard. this all are working fine. i had also setup local container repository on port 5000. i had also push 2 images of my application. i can see them on browser http://localhost:5000/v2/_catalog
now when i am trying to up pod using minikube.
kubectl apply -f ./docker-compose-k.yml --record

I am getting error on dashboard like this:-
Failed to pull image "localhost:5000/coremvc2": rpc error: code = Unknown desc = Error response from daemon: Get http://localhost:5000/v2/: dial tcp 127.0.0.1:5000: connect: connection refused

Here is my compose file:-
apiVersion: apps/v1
kind: Deployment
metadata:
  name: core23
  labels:
    app: codemvc
spec:
  replicas: 1
  selector:
    matchLabels:
      app: coremvc
  template:
    metadata:
      labels:
        app: coremvc
    spec:
      containers:
      - name: coremvc
        image: localhost:5000/coremvc2
        ports:
        - containerPort: 80
        imagePullPolicy: Always

i don't know why this images are not pulled as docker deamon and kubernetes both are on same machine. i have also try this with dockerhub image and it's working fine, but i want to do this using local images.
please give me hint or any guideline.
Thank you,

A: Based on the comment, you started minikube with minikube start (without specifying the driver).
That means that the minikube is running inside a Virtualbox VM. In order to make your use case work, you have two choices :

*

*The hard way Set-up the connection between you VM and your host and use your host IP

*The easy way Connect to your VM using minikube ssh and install your registry there. Then your deployment should work with your VM's IP.

If you don't want to use Virtual box, you should read the documentation about other existing drivers and how to use them.
Hope this helps !

A: localhost:5000 is pointing to the pod itself.
If the Docker registry is running on the same host where minikube is running:

*

*Get the IP address of the host (e.g. using ifconfig). Say, it is 10.0.2.15.

*Tag the image:
docker tag coremvc2:latest 10.0.2.15:5000/coremvc2:latest

*Push the so-tagged image to the local registry:
docker push 10.0.2.15:5000/coremvc2:latest

*Change in the Deployment:
image: localhost:5000/coremvc2

to
image: 10.0.2.15:5000/coremvc2:latest

EDIT: If getting "...http: server gave HTTP response to HTTPS client" error, you could configure the local Docker registry as insecure registry for the local Docker daemon by editing /etc/docker/daemon.json (create it if it doesn't exist):
{
... any other settings or remove this line ...
  "insecure-registries": ["10.0.2.15:5000"]
}

...then restart docker:
 sudo service docker restart

Not sure how you run the local Docker registry, but this is one way:
 docker run -d -p 5000:5000 --name registry registry:2

A: The issue is that you have setup docker registry on your host machine and minikube runs in virtualized environment (according to your example it is Virtualbox).
That is why you are receiving "connection refused" error upon attempt to fetch image on port 5000. The root cause is that there is no process "inside" minikube that listens on 5000. Your registry is deployed "outside" of minikube.
As Marc told, there are 2 ways to fix ita and I have reproduced both. The Hard way will get you to:
Failed to pull image "10.150.0.4:5000/my-alpine": rpc error: code = Unknown desc = Error response from daemon: Get https://10.150.0.4:5000/v2/: http: server gave HTTP response to HTTPS client

So you'll have to set-up secure Docker registry according to The Docker Documentation
The easy way is to set it up on top of your minikube.
my@linux-vm2:~$ minikube ssh
$ docker run -d -p 5000:5000 --restart=always --name registry registry:2
...
Status: Downloaded newer image for registry:2

$ docker pull nginx:latest
...
Status: Downloaded newer image for nginx:latest

$ docker tag alpine:latest localhost:5000/my-nginx
$ docker push localhost:5000/my-nginx
$ logout

my@linux-vm2:~$ kubectl apply -f ./docker-compose-k.yml --record
deployment.apps/core23 created

my@linux-vm2:~$ kubectl get  pods
NAME                     READY   STATUS    RESTARTS   AGE
core23-b44b794cb-vmhwl   1/1     Running   0          4s

my @linux-vm2:~$ kubectl describe pods
...
Events:
  Type    Reason     Age        From               Message
  ----    ------     ----       ----               -------
  Normal  Scheduled  <unknown>  default-scheduler  Successfully assigned default/core23-b44b794cb-vmhwl to minikube
  Normal  Pulling    9s         kubelet, minikube  Pulling image "localhost:5000/my-nginx"
  Normal  Pulled     9s         kubelet, minikube  Successfully pulled image "localhost:5000/my-nginx"
  Normal  Created    9s         kubelet, minikube  Created container coremvc
  Normal  Started    9s         kubelet, minikube  Started container coremvc

Please note that I've been using nginx instead of coremvc2 in this example (but still steps are the same).
To sum it up, it is possible to achieve the result you need in a few different ways.  Please try and let us know how it went. Cheers :)


text:
Q: Accidentally deleted git ignored file in Flutter project I accidentally deleted a file that was in .gitignore, let's call the file abc. Since the file was an important asset and was located in pubspec.yaml under the "asset" entry, every time the workflow starts it fails when it runs "flutter analyze". Any suggestions?

A: If the file is git-ignored, git does not track it (unless it was forcibly added, but then it's not really ignored even though it appears in the .gitignore file). Unless you have some other filesystem backup, I fear you're out of luck.


text:
Q: Displaying a Message I am working on a new security assessment webpage in which I am using HTML and Java Script. For some reason, the code is not working properly. The way the page supposed to work is by having the user answer Yes or No questions, and when the user is done they click submit. Then the page would display the number of questions answered yes, and a message if the user passed or failed the assessment. But when I click submit, I only see the result, not the message.
Any feedback would be appreciated.

function sumInputs() {
  var text;
  var score = document.getElementById("total").value;

  if (score < 60) {
    text = "You have failed the Assessment";
  } else(score > 60) {
    text = "You have passed the Assessment";
  }

  document.getElementById("demo").innerHTML = text;
}

function calcscore() {
  var score = 0;
  $(".calc:checked").each(function() {
    score += parseInt($(this).val(), 10);
  });
  $("input[name=sum]").val(score)
}

$().ready(function() {
  $(".calc").change(function() {
    calcscore()

  });
});

window.sumInputs = function() {
  var inputs = $('.calc:checked'),
    result = document.getElementById('total'),
    sum = 0;

  for (var i = 0; i < inputs.length; i++) {
    sum += parseInt(inputs[i].value);
  }

  $('#total').val(sum);
}

Security Assessment

      PERSONNEL SECURITY

      1. Does your staff wear ID badges?
        <form>
          Yes
          <input class="calc" type="radio" name="radio1" value="1" /> No
          <input class="calc" type="radio" name="radio1" value="0" />

      2. Is a current picture part of the ID badge? Yes
        <input class="calc" type="radio" name="radio2" value="1" /> No
        <input class="calc" type="radio" name="radio2" value="0" />

      3. Are authorized access levels and type (employee, contractor, visitor) identified on the Badge? Yes
        <input class="calc" type="radio" name="radio3" value="1" /> No
        <input class="calc" type="radio" name="radio3" value="0" />

        </form>

  Total : <input type="text" name="total" id="total" />

  <input type="Submit" value="Submit" onclick="sumInputs()">

A: Check if this works. Also check your variable type

function calcscore() {
     var score = 0;
     $(".calc:checked").each(function() {
         score += parseInt($(this).val(), 10);
     });
     $("input[name=sum]").val(score)
 }

 $().ready(function() {
     $(".calc").change(function() {
         calcscore()
     });
 });

 function sumInputs() {
     var inputs = $('.calc:checked'),
         result = document.getElementById('total'),
         sum = 0;

     for (var i = 0; i < inputs.length; i++) {
         sum += parseInt(inputs[i].value);
     }

     $('#total').val(sum);

     var text, score = document.getElementById("total").value;

     if (score < 60) {
         text = "You have failed the Assessment";
     } else if(score > 60) {
         text = "You have passed the Assessment";
     }

     document.getElementById("demo").innerHTML = text;
 }

<!DOCTYPE html>

Security Assessment

    PERSONNEL SECURITY

    1. Does your staff wear ID badges?

<form>
Yes
<input class="calc" type="radio" name="radio1" value="1" />
No
<input class="calc" type="radio" name="radio1" value="0" />

</form>

    2. Is a current picture part of the ID badge?

<form>
Yes
<input class="calc" type="radio" name="radio2" value="1" />
No
<input class="calc" type="radio" name="radio2" value="0" />

</form>

    3. Are authorized access levels and type (employee, contractor, visitor) identified
on the Badge?

<form>
 Yes
<input class="calc" type="radio" name="radio3" value="1" />
No
<input class="calc" type="radio" name="radio3" value="0" />

</form>

Total : <input type="text" name="total" id="total"/>

<input type="Submit" value="Submit" onclick="sumInputs()">

A: You have two functions named sumInputs; the second one (which filled the 'score' field) was overwriting the first one (which was supposed to output the message.)
Additionally the scoring was trying to be based on percentages, but never calculated a percentage, just a count of correct questions.
(There were also a couple of syntax errors here and there.)
Correcting all those by merging the two sumInputs functions results in:

function calcscore() {
  var score = 0;
  $(".calc:checked").each(function() {
    score += parseInt($(this).val(), 10);
  });
  $("input[name=sum]").val(score)
}

$().ready(function() {
  $(".calc").change(function() {
    calcscore()
  });
});

window.sumInputs = function() {
  var inputs = $('.calc:checked'),
    result = document.getElementById('total'),
    sum = 0;

  for (var i = 0; i < inputs.length; i++) {
    sum += parseInt(inputs[i].value);
  }

  $('#total').val(sum);

  var score = sum / 3 * 100; // calculate percentage

  if (score < 60) {
    text = "You have failed the Assessment";
  } else { // no need for else if (score > 60)... which would have failed if the score was exactly 60
    text = "You have passed the Assessment";
  }
  document.getElementById("demo").innerHTML = text;
}

Security Assessment

      PERSONNEL SECURITY

      1. Does your staff wear ID badges?
        <form>
          Yes
          <input class="calc" type="radio" name="radio1" value="1" /> No
          <input class="calc" type="radio" name="radio1" value="0" />

      2. Is a current picture part of the ID badge? Yes
        <input class="calc" type="radio" name="radio2" value="1" /> No
        <input class="calc" type="radio" name="radio2" value="0" />

      3. Are authorized access levels and type (employee, contractor, visitor) identified on the Badge? Yes
        <input class="calc" type="radio" name="radio3" value="1" /> No
        <input class="calc" type="radio" name="radio3" value="0" />

        </form>

  Total : <input type="text" name="total" id="total" />

  <input type="Submit" value="Submit" onclick="sumInputs()">

Incidentally, the calcscore() function is unnecessary -- it updates the displayed score while the user takes the quiz, but the sumInputs function used at the end of the quiz doesn't depend on it.  If you don't want to give the user immediate feedback on whether each question was correct or not, you can remove that function (and move $("input[name=sum]").val(score) into sumInputs().

A: I added some already done modifications, and changed the plain javascript to jquery.

$('.calc').change(function() {
    calcscore();
});

$('#submitted').click(function() {

    sumInputs();
    result();

});

function sumInputs() {

    var inputs = $('.calc:checked'),
        result = $('#total').val(),
        sum = 0;

    for (var i = 0; i < inputs.length; i++) {
        sum += parseInt(inputs[i].value);
    }

    $('#total').val(sum);

}

function result() {

    var text;
    var score = (( $('#total').val() ) / 3 ) * 100;
    var score = score.toFixed(2);

    if (score < 60) {
        text = "Total " + score + ": You have failed the Assessment";
    }
    else {
        text = "Total " + score + ": You have passed the Assessment";
    }

    $('#demo').text(text);
}

function calcscore() {

    var score = 0;

    $('.calc:checked').each(function () {
        score += parseInt($(this).val(), 10);
    });

    $('#total').val(score);

}

Security Assessment

    <form>

            PERSONNEL SECURITY

            1. Does your staff wear ID badges?
                Yes <input class="calc" type="radio" name="radio1" value="1" />
                No <input class="calc" type="radio" name="radio1" value="0" />

            2. Is a current picture part of the ID badge?
                Yes <input class="calc" type="radio" name="radio2" value="1" />
                No <input class="calc" type="radio" name="radio2" value="0" />

            3. Are authorized access levels and type (employee, contractor, visitor) identified on the Badge?
                Yes <input class="calc" type="radio" name="radio3" value="1" />
                No <input class="calc" type="radio" name="radio3" value="0" />

    </form>

    Total : <input type="text" name="total" id="total" />
    <input id="submitted" type="Submit" value="Submit">


text:
Q: Stop NSTimer in a UICollectionViewCell after leaving view I have a NSTimer set up in a UICollectionViewCell. It's running ok, except it keeps on going even after i change the view through a segue. How should i stop it? One solution that came in mind is NSNotificationCenter. Is there a better way? Thanks a lot!

A: How about creating a method for invalidate a timer for your cell and in viewWillDisappear()
call that method for all visible cells
let cells = self.tableView.visibleCells();
for cell in cells {
    // call invalidate
}

A: I'm not sure but when you give your timer a name, for example: let myTimer:NSTimer = ... then you can do in the prepareForSegue function: myTimer.invalidate() This function stops the timer.
So put all timers in an var myArray = [NSTimer]() and then in prepareForSegue:
for timer in myArray {
timer.invalidate()
}


text:
Q: RHEL 6.2 hangs at startup screen after forced reboot I had to force a hardware reboot due to some CPU hungry application. It now hangs at the start-up screen right after the progress circle completes.
I have no way to see what it is doing (checking the FS or something) but when I press ctrl+alt+del, a s/w reboot occurs in 5 seconds.
How can I see the regular Linux start-up log instead of the splash screen and at least understand what it is doing.

A: Boot your machine as you would normally and when prompted to, Press any key to enter the menu do so.
In the grub menu select the entry you want to boot then press e
Highlight the kernel line and press e
Navigate to the end of the line and remove rhgb quiet then press enter
Press b to boot your system.
You should now see the system messages as it boots.


text:
Q: 12 and 13-bit balanced Gray codes I am trying to find a transition sequence for both 12 and 13 bit balanced Gray codes. I know there are some excellent papers on the topic of deriving these sequences available on the internet, but I regret to say that it's been a while since I've been in a formal math class and I can't quite follow them to the end.  Any help would be greatly appreciated!
-Erik


text:
Q: Layout with two TextViews and ellipsis I want to create a layout with two TextViews in one row. I want the first TextView to be ellipsized if its text is too long. I want them to behave as if they had the width of wrap_content if they can both fit in the row. How do I do it?
Here's the result I want to get:
[Short text1][text2]
[Very long text1 that has to be ellipsized...][text2]

A: Create a horizontal chain of the two views, set max lines to one of the left view and set the constrained width of the left view to true to keep it in bounds:
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        app:layout_constrainedWidth="true"
        android:text="Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/textView"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Add these two lines in your xml layout to your TextView that may need ellipses.
android:ellipsize="end"
android:maxLines="1"


text:
Q: Creating background services for Bluetooth low energy on Android Background:
Ideally I would like my Android device to be scanning for Bluetooth Low Energy devices all the time an the ability to start an application whenever a new device with specific properties appears.
So the broadcast packet in BLE will for instance enumerate a set of services provided by the broadcasting device. An app would then be able to register an interest for certain services and automatically be started when a device with this services comes into range.
From what I understand this is not how the Android BLE API works? So how can I get something similar?
Simplest possible example:
I have a BLE sensor that logs ambient temperature over time. Whenever my Android phone is close enough I want to connect and download all the data, sending it to some cloud storage solution. This app would not need any GUI (at least not after configuration is done). But how should it run in the background without draining the battery, but still give me a fairly good chance of connecting the device quickly once it is in range?
Question:
Do I need to set a timer and wake the app every once in a while and then manually start scanning? What kind of intervals should I then choose. How long can I leave the scanner running without adversely affecting the battery?
Possible solution:
This is what I've come up with so far.

*

*A configuration activity to set the intervals and devices to scan for

*The configuration activity will set up an WakefulBroadcastReceiver similar to the Scheduler example

*When the receiver get's the onReceive event I start a BLE scan service (that I've written) as a wakeful service.

*The scan service starts scanning (with a registered callback).

*The service might get adv reports that it can act upon

*After a timeout the service will stop the scanner and end the wakeful service.

This works, but I'm not sure it's the best way. I also don't know how small intervals I can have and still avoid destroying the battery life. What I would want is to start scanning every two minutes, scanning for 10-20 seconds. But I'm afraid that would be rather frequently to wake up the device?

A: This functionality has all been moved to the open source Android Beacon Library which will:

*

*wake up/launch your app when iBeacons matching a desired pattern are detected

*perform beacon scanning in the background even if the user has not launched your app yet

*reduce the scan rate automatically in the background to 30 seconds every five minutes to save battery.  (Timing configurable.)
Code examples are show here
If your BLE device is not a beacon you could still use this library to accomplish this by having your sensor also transmit as a beacon then after it is detected connect to the main service.


text:
Q: Make java class Comparable to 2 different Classes I would like to implement the Comparable Interface "Twice"
public class Segment implements Comparable<Segment,Point>{
@Override
public int compareTo(Segment o) {
    return 0;
}
@Override
public int compareTo(Point p) {
    return 0;
}

Is it possible in some way? (Without using the generic interface compareTo(Object o) i think it's nasty...)

A: This is not a good idea, as a design pattern. And, by the way, it is impossible in Java, because Comparable and Comparable are the same binary interface due to type erasure.
Anyway, I'll try to explain why I think that's a bad idea. When you implement Comparable you are defining a so-called "natural sorting", which is a sorting intrinsic to the class itself, a natural ordering. This ordering should involve the class and elements of the same class. So, I think (and this is a purely personal opinion) that you should only implement Comparable with the same class as the one you're implementing.
If you want to compare segments with points, this is of course a perfectly legitimate thing, as long as you have a well-defined ordering. You can achieve that by implementing a so-called "external comparator", i.e. a class that implements Comparator<X>, where X is a common superclass of Point and Segment. Java standard classes and functions are prepared to always accept an optional external comparator, because, in general, you might want to have different sorting criteria for objects of the same class.
You seem not to have a common base class/interface. Maybe you should define one, they're both geometrical entities, after all. As of now, the only thing you can do is use Comparator<Object>, and then use the instanceof operator to check the types. Which is a lot of boilerplate code, and also, I think, bad design: since you're saying the points and segments are comparable, they should have some common property that you wish to compare. Then this property should become a method of a common base class or an interface they both implement (which, indeed, might lead you to use Comparable again, but in a cleaner way).
For instance, assume that you want to compare points and segments based on their coordinates, and you want the median of a segment to be considered in sorting. Then, you could do something as:
public abstract class GeometricEntity implements Comparable<GeometricEntity> {
  protected abstract Point getSortingPoint();
  @Override
  public int compareTo(GeometricEntity other) {
    //Compare by getSortingPoint
  }
}

public class Point implements GeometricEntity {
  @Override
  protected Point getSortingPoint() { return this; }
}

public class Segment implements GeometricEntity {
  private Point ptFrom;
  private Point ptTo;
  @Override
  protected Point getSortingPoint() { return meanPoint(ptFrom, ptTo); }
}

A: if you are doing it for Collection sorting  then use Comparator
/**
 * Comparator implementation which sorts Person objects on person_id field
 */
public class SortByPerson_ID implements Comparator{

    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o;
        Person p2 = (Person) o;
        return p1.getPersonId() - p2.getPersonId();
    }
}

To sort -
 Collections.sort(perSonlist, new SortByPerson_ID());

Read more: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html#ixzz3RKoKZpB5

A: If you Segment and Point both implements a same Interface or they are Parent and Child, you may do that.

A: You can implement Comparable only once, but you can use Comparator interface more than once --> http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html
It has int  compare(T o1, T o2) instead of Comparable's compareTo. If you want to sort your collection for example then you can use:
Collections.sort(Your list, Your new Comparator object)

A: Why dont you try this way
public class Segment implements Comparable<Object>{
     @Override
     public int compareTo(Object o) {
         if(o instanceof Segment)
         {
              return 0;
         }
         else if(o instanceof Point)
         {
             return 0;
         }

     }
}

Well if you really want to do it in your way, then you can just add another method using overloading (without adding the @Override annotation).
public class Segment implements Comparable<Segment>{
    @Override
    public int compareTo(Segment o) {
        return 0;
    }

    public int compareTo(Point p) {
       return 0;
    }
}

It will be useful if you call the compareTo method manually. I am not sure what will happen they called from some other library methods.


text:
Q: MakeFile: Implicit file declaration warnings in C i am new to creating Make File and im running into some error caused by dependencies, basically in each "*.c" file i only include it self for example: Main will only include Main.h. As a result of this, i am trying to create the dependencies on MakeFile, the dependencies are:
-Main.c uses functions/structs that are declared in memory.h, synchronization.h, client.h, server.h proxy.h and process.h
-memory.c uses functions/structs that are declared in synchronization.h
-process.c uses functions/structs that are declared in client.h, proxy.h and server.h
Some other dependencies are made by #include  in the header files.
Some of the errors i have got so far are:
gcc -c process.c
process.c: In function 'launch_process':
process.c:25:46: warning: implicit declaration of function 'execute_client' [-Wimplicit-function-declaration]
             data->client_stats[process_id] = execute_client(process_id, buffers, data, sems);

process.c:30:45: warning: implicit declaration of function 'execute_proxy' [-Wimplicit-function-declaration]
             data->proxy_stats[process_id] = execute_proxy(process_id, buffers, data, sems);

process.c:33:46: warning: implicit declaration of function 'execute_server' [-Wimplicit-function-declaration]
             data->server_stats[process_id] = execute_server(process_id, buffers, data, sems);

gcc -c main.c
main.c: In function 'launch_processes':
main.c:159:32: warning: implicit declaration of function 'launch_process'; did you mean 'launch_processes'? [-Wimplicit-function-declaration]
         data->client_pids[i] = launch_process(i, 0, buffers, data, sems);

main.c: In function 'wait_processes':
main.c:243:33: warning: implicit declaration of function 'wait_process'; did you mean 'wait_processes'? [-Wimplicit-function-declaration]
         data->client_stats[i] = wait_process(data->client_pids[i]); //o retorno dos processos client_pids etc ira returnar o return do execute_client sendo que sera o "exit" do processo

PS:I am not allowed to change header files and sorry for the long question by have spent more then 24 hours straight around this and this is not allowing me to test my finished project, Thank you.
Here is the makefile that i have created.
sovaccines: client.o proxy.o server.o process.o main.o memory.o  synchronization.o
            gcc client.o proxy.o server.o process.o main.o memory.o  synchronization.o  -o sovaccines -lrt -pthread -g

main.o: main.c ../include/memory.h ../include/synchronization.h ../include/client.h ../include/proxy.h ../include/server.h ../include/process.h
            gcc -c main.c

client.o: client.c
            gcc -c client.c

memory.o: memory.c ../include/synchronization.h
            gcc -c memory.c

process.o: process.c ../include/client.h ../include/proxy.h ../include/server.h
            gcc -c process.c

proxy.o: proxy.c
            gcc -c proxy.c

server.o: server.c
            gcc -c server.c

synchronization.o: synchronization.c
            gcc -c synchronization.c

A: Your warnings simply tell you that you forgot to include the correct header files in your C source files, or that you did not tell the compiler where to find these header files. Example: if in main.c you have something like:
#include "memory.h"
#include "synchronization.h"
#include "client.h"
#include "server.h"
#include "proxy.h"
#include "process.h"

you should pass the -I../include option to gcc. As you are using GNU make your Makefile could then look like this:
SRC     := $(wildcard *.c)
OBJ     := $(patsubst %.c,%.o,$(SRC))
INCLUDE := ../include
CFLAGS  := -g -I$(INCLUDE)
LDLIBS  := -lrt -pthread
VPATH   := $(INCLUDE)

sovaccines: $(OBJ)
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)

main.o: memory.h synchronization.h client.h proxy.h server.h process.h
memory.o: synchronization.h
process.o: client.h proxy.h server.h

%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

*

*wildcard and patsubst are make functions

*CC, CFLAGS, LDLIBS... are Variables Used by Implicit Rules

*VPATH defines a Search Path for All Prerequisites

*$@, $^, $<... are Automatic Variables

*%.o: %.c is a Pattern Rule
Note that there are ways to automatically generate the dependencies of source files on header files. If you are interested, have a look, for example, at this excellent guide: Auto-Dependency Generation.
Note also that make knows already how to compile and link C projects. It has Implicit Rules. This is another way to further simplify your Makefile. In the proposed Makefile above you could, for instance, omit the pattern rule completely and also the recipe of the sovaccines: $(OBJ) rule.


text:
Q: Nosuchelementfound exception in Selenium Webdriver As a new learner for Selenium, I am trying to identify a basic element on the Google page for the Google Search button. However I am getting a NoSuchElementException even though the element is perfectly visible on the page.
Code Snippet :
String driverPath = "C:\\Users\\nchaudhary006\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver",driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
InternetExplorerDriver  driver = new InternetExplorerDriver(capabilities);

driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("https://google.com");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

driver.findElement(By.name("btnK"));

Solutions Tried :

*

*Element until visible option

*Scroll down so that page is in view

*Identifying element by xpath, id , name, etc.

*All possible wait combinations.

What can I be possibly doing wrong?

A: I am not sure to which element you exactly referred by name as btnK but on https://google.com there is a Search field by name as q
Using Selenium 3.4.0, IEDriverServer 3.4.0 & IE 10.x (& above) the below code will put "Neha Chaudhary" in the Search field.
A few words about the Solution:

*

*Once you set ImplicitlyWait at the begining, it remains valid throughout your execution. So you don't have to mention again & again.

*Instead of InternetExplorerDriver implementation you must use the WebDriver interface.

*While you search for an element driver.findElement(By.name("btnK")); either store it as a WebElement for future use or perform some action by click() or sendKeys("Neha Chaudhary")

*Here is the working code snippet:
String driverPath = "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver",driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver  driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://google.com");
driver.findElement(By.name("q")).sendKeys("Neha Chaudhary");

Let me know if this Answers your Question.


text:
Q: How to tell a paradox from a "paradox"? Russell's paradox showed that naive set theory leads to a contradiction. This was something that was taken seriously and caused a lot of work.
Now, Banach–Tarski paradox is arises from a result that a ball can be decomposed into finite amount of pieces and the pieces can be used to built two identical copies of the decomposed ball. Banach-Tarski paradox is often treated as a "paradox", basicly meaning that, yes, it is counter intuitive but yet there is no problem - mathematics just occasionally is counter intuitive.
To be honest, I have never understood why Banach-Tarski is not a "real" paradox but not being expert of measure theory I chose to accept the common view.
Is there some high level explanation on how to tell a paradox from a "paradox"? What is it that makes a counter intuitive result to a "real mathematical paradox" that we should start worrying about?

A: Although I am not so good with philosophical subtleties, I have always found useful to make a distinction between an antinomy and a paradox.
The first leads to a formal contradiction, i.e., a logical inconsistency in your theory (you can prove both a formula and its negation).
The second `merely' defies human intuition, without being a (known) antinomy. Much less worrying (ask Frege :)).
Many just use `paradox' for both things, but I find this highly confusing.

A: I don't see how these two a so fundamentally different. Russell's paradox tells us that we have to think more carefully about what a set actually is, and Banach-Tarski tells us that we have to think more carefully about what the measure of a set is and which sets are measurable.
When arriving at a counterintuitive statement, there are two possible conclusions: First, the previous intuition was wrong, and in this case the result is genuinely counterintuitive, and the second possibility is that the definitions or the logic were wrong and need to be changed. Banach-Tarski falls into the second category, because one would not conclude that matter can be created by clever cuts and rearrangements, but rather that one needs a thorough definition of measure.

A: What you're describing as a "true paradox" is sometimes called an "antimony" and it means an actual logical inconsistency in the underlying theory.  The Burali-Forti paradox is another example and it means there can't be a set of all ordinals (the ordinals are a proper class).  By contrast, the Banach-Tarski theorem is consistent; it's just counterintuitive.  The reason we don't hear much about "true paradoxes" (antimonies) these days is that logicians in the 1920's got the earlier inconsistencies under control, and (in all likelihood) we're not dealing with any actual inconsistent systems today, at least in everyday mathematics.

A: Both the Russell paradox and the Banach-Tarski "paradox" show that certain ideas are contradictory.  It seems to me that the key difference between the two is that, in Russell's case, the ideas in question had been proposed (by Frege) as axioms for a foundation of mathematics, and they seemed sufficiently basic to be accepted, until the paradox appeared.  In the Banach-Tarski case, one of the ideas involved in the contradiction is the idea that one can meaningfully talk about the "volume" of arbitrary sets in $\mathbb R^3$.  (Here "meaningfully" is intended to include additivity and invariance under Euclidean motions.)   Although that is a very appealing idea intuitively, I'm not aware of anyone's proposing it as an axiom (or even as a conjecture).  The development of Lebesgue's measure theory had already shown that the intuition is not reliable and the measurability of general sets is a delicate issue.

A: Many paradoxes are first expressed in a semi-formal way, for example "the least number not describable by fewer than eleven words". They are warning signs that lead us to further analysis and can be resolved in different ways:

*

*We can just get used to a "paradox" and accept it as "truth", e.g., there are infinite sets of different sizes, or there is a real function which is continuous at irrational arguments and discontinuous at rational arguments. There are famous paradoxes in philosophy which would not be considered paradoxes today, such as Zeno's paradox ("How can an infinite sum of positive numbers be finite? No movemement is possible!") and various arguments from Prime Cause ("How could we have an infinite descending chain of causality? God must exist!").

*We find the paradox unacceptable and so we need to change something. We might change rules of logic, definitions, or axioms, everything is up in the air.
A paradox which actually proves falsehood, or a statement as well as its negation, is more properly called an inconsistency. An inconsistency is something we can never get used to and so we have to change something. A milder form of paradox is one which does not prove falsehood but just something very counter-intuitive, in which case we have to decide whether to accept it, or admit that our attempt to bring something into the realm of mathematics worked in unexpected ways.
I think this question is about how to tell whether a given "paradox" is of the first or second kind. When should we just "get used" to a paradox and when should we "change things"? In the case of Russell paradox we had no choice but to change something. In the case of Banach-Tarski paradox there is a choice. The accepted view is that we should just get used to it, but there are interesting alterantives which force us to rethink the notion of space. Even though these alternative notions of space are far better suited for probability, measure and randomness than the classical approach, mathematicians are unlikely to adopt them widely out of sheer inertia and historical coincidence. But mathematicians do not like to admit that mathematics is a human activity, and as such subject to sociological and historical trends.
So I suppose my answer is this: when faced with an unacceptable counter-intuitive statement which offers several mathematical resolutions, the choice will be made through social interaction which has some mathematical content, but not as much as we would like to think. Other factors, such as arguments from authority and social intertia will play an important role.


text:
Q: PHP Nested array Sum of branches I want to get the sum of "score" on root of all branches.My code manage to get it all correctly but not on the first level.
I've tried everything I know to get it worked - no luck.
I do have the following code:
query the database:
$db->query("SELECT * FROM EvalSections WHERE EvalKitID = ".CCGetFromGet('Kit'));
while($db->next_record()){
    $data[] = array ('id'          => $db->f("IDSection"),
                     'name'        => $db->f("SectionName"),
                     'parent'      => $db->f("SectionParentID"),
                     'depth'       => 0,
                     'score'       => 0,
                     'sort'        => $db->f("SectionSort")
                     );
}

build array:
function buildTree(array $elements, $parentId = 0,$depth = 1) {
$branch = array();
global $TotalGeneral;
foreach ($elements as $element) {
    if ($element['parent'] == $parentId) {
        $children = buildTree($elements, $element['id'],$depth+1);

        if ($children) {
            $TotalGeneral = 0;
            usort($children, function($a, $b) {
                return $a['sort'] - $b['sort'];
            });

            foreach($children as $c => $v){
                $Total = getScore($v['id']);
                $TotalGeneral += $Total;
                $children[$c]['depth'] = $depth+1;
                $children[$c]['score'] += $Total;
            }

            $Total = getScore($element['id']);
            $TotalGeneral += $Total;
            $element['depth'] = $depth;
            $element['score'] += $TotalGeneral;
            $element['children'] = $children;
        }else{
            $Total = getScore($element['id']);
            $TotalGeneral += $Total;
            //$element['score'] += $Total;
        }
        //$element['score'] = $TotalGeneral;
        $branch[] = $element;
    }
}
return $branch;}

on print_r I get:
    Array
(
    [0] => Array
        (
            [id] => 196
            [name] => Abilități spirituale
            [parent] => 0
            [depth] => 1
            [score] => 152 = WRONG VALUE
            [sort] =>

        [children] => Array
            (
                [0] => Array
                    (
                        [id] => 395
                        [name] => Date generale
                        [parent] => 196
                        [depth] => 2
                        [score] => 0
                        [sort] => 1
                    )

                [1] => Array
                    (
                        [id] => 197
                        [name] => Armonia cu sine
                        [parent] => 196
                        [depth] => 2
                        [score] => 145
                        [sort] => 2
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 201
                                        [name] => Gândirea pozitivă
                                        [parent] => 197
                                        [depth] => 3
                                        [score] => 57
                                        [sort] => 1
                                    )

                                [1] => Array
                                    (
                                        [id] => 202
                                        [name] => Satisfacția personală
                                        [parent] => 197
                                        [depth] => 3
                                        [score] => 38
                                        [sort] => 2
                                    )

                                [2] => Array
                                    (
                                        [id] => 203
                                        [name] => Concordanța cu sine
                                        [parent] => 197
                                        [depth] => 3
                                        [score] => 29
                                        [sort] => 3
                                    )

                                [3] => Array
                                    (
                                        [id] => 204
                                        [name] => Managementul calitativ al timpului liber
                                        [parent] => 197
                                        [depth] => 3
                                        [score] => 21
                                        [sort] => 4
                                    )

                            )

                    )

                [2] => Array
                    (
                        [id] => 198
                        [name] => Armonia cu ceilalți
                        [parent] => 196
                        [depth] => 2
                        [score] => 54
                        [sort] => 3
                    )

                [3] => Array
                    (
                        [id] => 199
                        [name] => Sensul vieții și misiunea personală
                        [parent] => 196
                        [depth] => 2
                        [score] => 49
                        [sort] => 4
                    )

                [4] => Array
                    (
                        [id] => 200
                        [name] => Perspectiva de ansamblu asupra realității
                        [parent] => 196
                        [depth] => 2
                        [score] => 49
                        [sort] => 5
                    )

            )

    )

)


text:
Q: How to notify duplicate value is posted in mongodb I am using mongodb(with monk api) and expressjs.
In my code I wrote
router.post("/",function(req, res) {
    var collection = db.get("details");
    collection.insert({ id: req.body.id, data: req.body.data },
                        function(err, details) {
                            if(err) throw err;
                            res.json(details);
                        })
});

'id' field is set to unique. If any duplicate 'id' is entered, then I want to notify it to the frontend. How to di it.
Thanks..

A: add this to the mongoose schema : unique true will give you the error on duplicate insertion.
 { require: true, unique: true },

A: you can use count to find if that id already exists:
collection.count({id : req.body.id},function(err,count){
    if(!err){
        if(count>0){
            //send the response that its duplicate.
        }
    }
});


text:
Q: Let scrollable Div Box take remaining height I'm tryining to implement a layout with a header and two div boxes with maximum height.

The Header is full width and has a fixed height.
The right box should take the remaining height and should'n be scroll-able.
The left box contains a headline and a list with a variable length. The box should also be the maximum height of the window. If the list is longer than the box, a scrollbar should appear.
I tried to add overflow: hidden to the left box and overflow-y: scroll to the inner list, but its not working.
Someone have a hint for me?

A:

        body {
            margin: 2vh
        }

        header {
            position:relative;
            background-color: aquamarine;
            padding: 5vh;
            box-sizing: border-box;
        }

        #scrollable, #fixed {
            margin: 2vh 0;
            box-sizing: border-box;
            height: 82vh;
            width: 50%;
            border: 1px solid #000;
            float: left;
            position: relative;
        }

        #list {
            /* Reset */
            padding: 0;
            margin: 0;

            /* Style */
            box-sizing: border-box;
            height: calc(100% - 10vh - 1px);
            overflow-y: scroll;
            padding: 25px;
            position: relative;
            width: 100%;
        }

        #list li{
            padding: 10px 20px;
        }
<!DOCTYPE html>

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum


text:
Q: TSQL- How to count number of instances I'm using SQL Server 2014 and I need to know which set of students have an action code used only once, and which students have an action code used more than once.

I'm trying to see if a student has more than one of 5 action codes.
e.g.
SELECT StudentID
FROM #T
WHERE ActionCode IN (51201,51206,51207,51208,51209)

How would I code this please?
Thank you for your help.

A: SELECT
   StudentID,
   ActionCode,
   ActionCodeCount = Count(*)
FROM
   dbo.StudentActionCodes
WHERE
   ActionCode IN (51201, 51206, 51207, 51208, 51209)
GROUP BY
   StudentID,
   ActionCode
ORDER BY
   StudentID DESC,
   ActionCode
;

See this working in a live demo at SqlFiddle
Given this set of values (including some unwanted ActionCodes):
StudentID   ActionCode
----------- -----------
987654      51201
987654      51206
987654      51207
987654      51208
987654      51209
987654      51210
987653      51201
987653      51208
987653      51208
987653      51211
987652      51201
987652      51206
987652      51206
987652      51207
987652      51208
987652      51209
987652      51212
987652      51213
987651      51201
987651      51206
987651      51209
987651      51209
987651      51214
987651      51215
987650      51201
987650      51201
987650      51201
987650      51201
987650      51208
987650      51208
987650      51216

Here are the results:
StudentID   ActionCode  ActionCodeCount
----------- ----------- ---------------
987654      51201       1
987654      51206       1
987654      51207       1
987654      51208       1
987654      51209       1
987653      51201       1
987653      51208       2
987652      51201       1
987652      51206       2
987652      51207       1
987652      51208       1
987652      51209       1
987651      51201       1
987651      51206       1
987651      51209       2
987650      51201       4
987650      51208       2

You might also enjoy this query:
SELECT
   *
FROM
   dbo.StudentActionCodes S
   PIVOT (
      Count(S.ActionCode) FOR S.ActionCode IN ([51201], [51206], [51207], [51208], [51209])
   ) P
;

Which gives this result:
StudentID   51201       51206       51207       51208       51209
----------- ----------- ----------- ----------- ----------- -----------
987650      4           0           0           2           0
987651      1           1           0           0           2
987652      1           2           1           1           1
987653      1           0           0           2           0
987654      1           1           1           1           1

A: Please try the below query:
SQL fiddle link: http://sqlfiddle.com/#!6/d1dc6/6
It gives sum of same type of actions per student as well as sum of all allowed actions per student
SELECT DISTINCT
    StudentID,
    Actioncode,
    COUNT(1) OVER (PARTITION BY StudentID,Actioncode  ) as [Count_of_this_action_instance],
    COUNT(1) OVER (PARTITION BY StudentID  ) as [Count_of_all_action_instance] FROM StudentActionCodes
WHERE ActionCode IN (51201,51206,51207,51208,51209)

A: count and group by
SELECT
   StudentID,
   Count(*) as 'count'
FROM
   dbo.StudentActionCodes
GROUP BY
   StudentID;


text:
Q: How to capture a image in Android OpenCV I am working in a project of Image processing and now I have one issue where I imported the OpenCV library I converted the RGB frame to binary frame. Now I dont know how to capture the binary image and store it in database. There is no tutorial available regarding the OpenCV library. So could any one please help me to solve the issue. My coding is below..
public class MainActivity extends AppCompatActivity implements View.OnTouchListener,CameraBridgeViewBase.CvCameraViewListener2 {

private static final String TAG = MainActivity.class.getCanonicalName();
private CameraBridgeViewBase mOpenCvCameraView;
private Mat mRgba;
private Scalar mBlobColorHsv;
private Scalar mBlobColorRgba;

private Mat mIntermediateMat;
private Mat mGray;
Mat hierarchy;

List<MatOfPoint> contours;

private BaseLoaderCallback mLoaderCallback=new BaseLoaderCallback(this) {
    @Override
    public void onManagerConnected(int status) {
        switch (status) {
            case LoaderCallbackInterface.SUCCESS: {
                Log.i(TAG, "OpenCV loaded successfully");
                mOpenCvCameraView.enableView();
                mOpenCvCameraView.setOnTouchListener(MainActivity.this);
            }
            break;
            default: {
                super.onManagerConnected(status);
            }
            break;

        }
    }

};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    mOpenCvCameraView=(CameraBridgeViewBase)findViewById(R.id.opencv_tutorial_activity_surface_view);
    mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    mOpenCvCameraView.setCvCameraViewListener(this);
}
@Override
public void onPause(){
    super.onPause();
    if(mOpenCvCameraView!=null)
        mOpenCvCameraView.disableView();
}
@Override
public void onResume(){
    {
        super.onResume();
        if(!OpenCVLoader.initDebug()) {
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mLoaderCallback);
        }
        else{
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }
}
@Override
public void onDestroy(){
    super.onPause();
    if(mOpenCvCameraView!=null)
        mOpenCvCameraView.disableView();
}

@Override
public boolean onTouch(View v, MotionEvent event) {

    return false;
}

@Override
public void onCameraViewStarted(int width, int height) {
    mRgba=new Mat();
    mBlobColorRgba=new Scalar(255);
    mBlobColorHsv=new Scalar(255);
    mRgba = new Mat(height, width, CvType.CV_8UC4);
    mIntermediateMat = new Mat(height, width, CvType.CV_8UC4);
    mGray = new Mat(height, width, CvType.CV_8UC1);
    hierarchy = new Mat();
}

So in short what I want to do is create a button and in onclick method I want to capture the image and preview of the image has to be displayed. Please someone help me to resolve this issue. Thanks in advance.

A: if you want to preview the image then you have to convert the mat to a bitmap and then display it in an ImageView. You can set a CvCameraViewListener to receive the bitmap. Like so
    private Mat mat;
    private boolean showPreviews;
        private BaseLoaderCallback mLoaderCallback=new BaseLoaderCallback(this) {
            @Override
            public void onManagerConnected(int status) {
                switch (status) {
                    case LoaderCallbackInterface.SUCCESS: {
                        Log.i(TAG, "OpenCV loaded successfully");
                      someButton.setOnclickListener(new View.OnclickListener(View v){
                               showPreviews = !showPreviews;
});
                        mOpenCvCameraView.enableView();
                        mOpenCvCameraView.setOnTouchListener(MainActivity.this);
        mOpenCvCameraView.setCvCameraViewListener(MainActivity.this);

                    }
                    break;
                    default: {
                        super.onManagerConnected(status);
                    }
                    break;

                }
            }

        };

        @Override
            public void onCameraViewStarted(int width, int height) {
                // TODO Auto-generated method stub

            }
            @Override
            public void onCameraViewStopped() {
                // TODO Auto-generated method stub

            }
            @Override
            public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
                // TODO Auto-generated method stub
               if(!showPreviews)
      mat = inputFrame.rgba();
           // you can return a modified mat if you want to display it in opencv
                return mat;
            }


text:
Q: Avoid saving commands with newlines to bash history I'm trying to filter certain commands from bash history. I've read about HISTIGNORE, but I would like to avoid saving commands that have new lines, or commands longer than N characters.
I frequently use very long commands, and when I navigate my history with CTRL+R, when the command is long enough to take all the screen space, my prompt disappears, so I would like to avoid saving these very long commands to my history.
I've tried to solve the prompt disappearing issue, but it happens in all the shells I've tried (xfce-terminal/rxvt) and with the default $PS1/.bashrc/.profile files that come with debian, so I suspect it is a bash related issue.


text:
Q: Android: Image set as button background is not being shrunk? I created a button with an image set as the background through a drawable. When I run the program the image is not being centered nor shrunk to fit the button. But when you click it, the pressed image is showing properly. This was working just the other day and I have no clue what happened to change it.
main.xml
<Button
            android:id="@+id/rightarrow"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:clickable="false" />

Activity.java
rightarrow = (Button) findViewById(R.id.rightarrow);
rightarrow.setBackgroundResource(R.drawable.rightarrow_drawable);

rightarrow_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/rightarrow_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/rightarrow" />
</selector>

A: Why not set the selector in XML? You do not have to set it by code.
Try Project->Clean in Eclipse - maybe your resources got mixed.

A: Just replace your Button with an ImageView


text:
Q: About prime ramification in cyclotomic fields. I got a question about lemma 2.2, in the appendix of Cyclotomic Fields I+II written by Karl Rubin.
Let me explain its situation:
a. $m$ and $M$ are fixed positive integers(especially, $M$ is odd).
b. $F$ is the maximal real subfield of $\mathbb Q(\mu _m)$
c. $r$ is a positive squarefree integer divisible only by primes $l$ which
      split completely in $F/ \mathbb Q$ and $l \equiv 1 \pmod M$.
He says, "a simple ramification argument shows that  $\mu _M \cap F(\mu _r) =1$."
I am eager to understand this...If you explain this, I would appreciate about it.


text:
Q: How to make the if statement be repeated to specific array not all the program The program works fine if all the data is entered correctly. but as you see below i made 2 if statements for the hours to be between 0 and 60 and rate to be between 0 and 50, when i make the hours or the rate outside their range the program simply exits the for loop and restarts from the while loop.
i made that program before without using the arrays and the program used to return to the specific if statement that have the wrong entered value and the older values for every thing was still saved and can be used in the final process without any mistake.
see here in the comments for the working code which i did not use arrays method
import java.util.Scanner;
public class homework3_Arrays
{
 public static void main(String[] args)
 {
  int emp_num, flag=0;
  Scanner kb = new Scanner(System.in);
  while(flag == 0)
  {
  System.out.printf("Please enter employees number\n");
   String[]emp1 = new String[emp_num];
   String[]emp2 = new String[emp_num];
   String[]emp3 = new String[emp_num];
   double[]hours = new double[emp_num];
   double[]rate = new double[emp_num];
   double[]gross = new double[emp_num];
   double[]overtime = new double[emp_num];
   double[]STtax = new double[emp_num];
   double[]FEDtax = new double[emp_num];
   double[]union = new double[emp_num];
   double[]net = new double[emp_num];
   double[]Tgross = new double[emp_num];
   double[]Agross = new double[emp_num];

   for(int i = 0; i < emp_num; i++)
  {

     System.out.printf("please enter the employee first name\n ");
     emp1[i] = kb.next();
     System.out.printf("please enter the employee middle initial\n ");
     emp2[i] = kb.next();
     System.out.printf("please enter the employee last name\n ");
     emp3[i] = kb.next();
     System.out.printf("please enter worked hours\n ");
     hours[i] = kb.nextDouble();
     if(hours[i] >= 0 && hours[i] <= 60)
     {
      System.out.printf("please enter the pay rate\n ");
      rate[i] = kb.nextDouble();
      if(rate[i] > 0 && rate[i] <= 50)
      {
       if(hours[i] <= 40)
        overtime[i] = 0;
        else
         overtime[i] = (hours[i] - 40) * rate[i] * 1.5;

        gross[i] = (rate[i] * 40) + overtime[i];
        STtax[i] = gross[i] * 0.06;
        FEDtax[i] = gross[i] * 0.12;
        union[i] = gross[i] * 0.01;
        net[i] = gross[i] - (STtax[i] + FEDtax[i] + union[i]);
        System.out.printf("hi %s%s%s\n", emp1[i], emp2[i], emp3[i]);
        System.out.printf("worked hours %6.2f\n", hours[i]);
        System.out.printf("your pay rate $%2.4f\n", rate[i]);
        System.out.printf("OverTime is %2.2f\n", overtime[i]);
        System.out.printf("Gross income $%6.2f\n", gross[i]);
        System.out.printf("State tax $%6.2f\n", STtax[i]);
        System.out.printf("Federal tax $%6.2f\n", FEDtax[i]);
        System.out.printf("Union fees $%6.2f\n", union[i]);
        System.out.printf("NET $%6.2f\n", net[i]);

      }
       else
        System.out.printf("Pay Rate can only be between 0 and 50\n");
      Tgross[i] = Tgross[i] + gross[i];
      Agross[i] = Tgross[i] / (i + 1);
      System.out.printf("Total gross for all entered employees is $%6.3f\n", Tgross[i]);
      System.out.printf("Average gross for all entered employees is $%6.4f\n", Agross[i]);
      System.out.printf("number of entered employees is %d\n\n", i + 1);
     }
      else
       System.out.printf("Hours can only be between 0 and 60\n");
   }
   System.out.printf("type 0 to repaeat\n");
   flag = kb.nextInt();
  }
 }
}


text:
Q: Color-coded timeline plot in R I am working on visualising user touch interactions within a mobile application. I would like to plot them in a one-dimensional timeline that is color-coded by action type.
i.e., my two variables are time (in ms, on the x-axis) and type of touch (used to color-code the line). Colors should be able to be repeated.
Ideally the plot would look like this, and I have found this previous question which delivers something similar, but I'm wondering if there isn't something better.
Is there any other methods using R which will allow me to do this?

A: Without a working example, I would suggest that you use ggplot2 package (along with ggfortify), which allows you to map variables (here: action type) to color. A frequent alternative is size (of points/dots) or thickness (of lines).
In addition, you may find time-series ts objects (see example/reference here) to be helpful. However, it is not a requirement for the type of data that you're interested in plotting. Best of luck!

A: I have the workings of a base R method. It's a bit hacky, but with some tweaking it should work nicely. I have removed the reliance on the data.table, timeline, and ggplot packages, opting for using the polygon function.
df <- data.frame(Set=c("x","y","z","x","y","z","x","y","z","x","y","z","x"),
       StartDate=c(1380708900,1402963200,1420070400,1421280000,1410912000,1396310400,1397520000,1418860800,1404172800,1405382400,1395100800,1412121600,1413331200),
       EndDate=  c(1395099900,1404171900,1421279100,1430985600,1412120700,1397519100,1402962300,1420069500,1405381500,1410911100,1396309500,1413330300,1418859900))

df$StartLabel <- as.POSIXct(df$StartDate,tz="UTC",origin="1970-01-01")
df$Set <- as.factor(df$Set)

Above sets up the data.frame object.
This sets up the plotting canvas
plot(c(df$StartDate[1], tail(df$EndDate,1)), c(0.4,0.65),
     type='n', xlab='Time', ylab='', axes=FALSE)

This clunk-ily loops through your values and draws a colored polygon for each period of time for each observation
for(i in 1:nrow(df)){
  polygon(x=c(rep(df$StartDate[i],2), rep(df$EndDate[i],2)),
          y=c(0.6,0.4,0.4,0.6), col=rainbow(3, alpha=0.75)[df$Set[i]],
          border=rainbow(3)[df$Set[i]])
}

Then I add in the axis (this could use some tweaking depending on how much of the date information you care to show.
axis(1, labels=df$StartLabel, at=df$StartDate)

Then this sets up the legend at the top of the plot.
legend('top', horiz=TRUE,
       c('Test set', 'Training set', 'Validation set'),
       pch=16, col=rainbow(3), bty='n', x.intersp=1.5, title='Group')

Hopefully this helps.


text:
Q: Можно ли как-то быстро включить / отключить xdebug? Без изменения php.ini и перезагрузки сервера? Страницы моего сайта без xdebug грузятя за несколько миллисекунд, а с xdebug за 5 секунд - минимум. А бывает и дольше.
Мне не всегда нужен xdebug. Я хочу иногда отключать его. И иногда включать. Но делать это без изменения php.ini и без перезагрузки сервера, а побыстрее. Как я могу это делать? Нажатием какой-нибудь кнопки, например. Или комментированием кода.
Я попробовал вот такой код:
if (function_exists('xdebug_disable')) {
   xdebug_disable();
}

Но сайт все равно тормозит.

A: Я использую скрипт, который редактирует php.ini и рестартует php-fpm. Включение / отключение занимает доли секунды.
Вот пример bash-файла, который позволяет включать и отключать xdebug, а также включать профайлер.
ini_file="/etc/php.d/xdebug.ini"

if [ -z $1 ]
then
    if grep -q '\;zend_extension' "$ini_file"
    then
        echo 'xdebug is OFF'
        exit 0
    fi
    if grep -q 'xdebug.profiler_enable=0' "$ini_file"
    then
        echo 'xdebug is ON'
        exit 0
    else
        echo 'xdebug is PROF'
        exit 0
    fi
fi

if [ 'on' = $1 ]
then
    sed -i s/^\;zend_extension/zend_extension/g $ini_file
    sed -i s/^\xdebug.profiler_enable=1/xdebug.profiler_enable=0/g $ini_file
    systemctl restart php-fpm
    exit 0
fi

if [ 'prof' = $1 ]
then
    sed -i s/^\;zend_extension/zend_extension/g $ini_file
    sed -i s/^\xdebug.profiler_enable=0/xdebug.profiler_enable=1/g $ini_file
    systemctl restart php-fpm
    exit 0
fi

if [ 'off' = $1 ]
then
    sed -i s/^zend_extension/\;zend_extension/g $ini_file
    sed -i s/^\xdebug.profiler_enable=1/xdebug.profiler_enable=0/g $ini_file
    systemctl restart php-fpm
    exit 0
fi

echo 'argument can be "on", "off" or "prof" only'
exit 1

Использование (если этот файл назван xdebug):

*

*xdebug on - включает xdebug

*xdebug prof - включает xdebug + профайлер

*xdebug off - выключает xdebug и профайлер

*xdebug - выводит информацию о текущем статусе

A: Включенный xDebug, не должен замедлять работу. Попробуйте следующее:
1) попробуйте в php.ini, оставить настройки по минимуму, только те, что вам нужны, например, если у вас включен профайлер, отключите его.
2) Пока вам не нужен дебаггер, отключайте прослушку в свой среде разработки.
3) Если вы отключили прослушку (п.2), а у вас все по-прежнему медленно, попробуйте убедится, что она действительно отключена. В php.ini узнайте порт, на который xdebug шлет запросы, далее проверьте, работает ли он telnet localhost {ВАШ_ПОРТ}. Если порт работает, то среда разработки не корректно завершает работу прослушки
Вроде как все просто, но возможно, что-то поможет.

A: Как по мне все волшебные скрипты которые то включают, то отключают xDebug весьма себе шаманство, однако имеют место быть.
Если бы мне у меня была крайняя необходимость дебажить на продакшене (ну вдруг) я бы использовал бы чуть другой подход.
Я могу ошибаться, однако даже "выключеный" xDebug замедляет работу. Под  выключеным я  понимаю xdebug.remote_enable=0 . Все дело в том что он загружен модулем и соответственно работает.
Что касается другого подхода. Ежели вы используете php-fpm, я бы создал две конфигурации в одной из которых модуль не подгружается, а в другой модуль подгружается. Запустил бы эти конфигуации на разных портах.
Далее то что мы называем продакшн - ваш веб сервер отсылает на тот демон, который без загруженого модуля, а вот для дебага - создаете дополнительный хост в веб сервере с другим DNS именем или попросту слушаете на другом порту и в этой конфигурации отправляете ваш запрос на второй демон php-fpm который как раз с загруженым модулем xdebug.
Получаете весьма прозрачную штуку без каких либо мегаскриптов.
Возникла надобность - подняли php-fpm с xDebug, пропала надобность - прибили. Ну и  конечно же дополнительными интсрументами можете ограничить доступ к дебажному варианту только на ваш ip, например.
Ну и само собой у вас нет ровным счетом ни какой надобность перегружать сервисы либо сервер (кто перегружает сервер ?).


text:
Q: Make an HTA file run as admin (elevated) In wsf, vbs and js files you can easily find out if they run elevated and if not you can easily make them.
The code I've written for that is this:
EnsureElevatedPrivileges();
WScript.Echo("Running elevated now!");

function EnsureElevatedPrivileges() {
    if (!WScript.Arguments.Named.Exists("elevate")) {
        new ActiveXObject("Shell.Application").ShellExecute(WScript.FullName, "\"" + WScript.ScriptFullName + "\" /elevate", "", "runas", 1);
        WScript.Quit();
    }
}

But this doesn't work in HTA files because the global WScript variable doesn't exist there.
So how can I force a specific HTA file run (itself) as admin?

A: You can take a look at this : Procedure to run HTA elevated
<html>
<head>
<title>HTA Helpomatic</title>

<HTA:APPLICATION
     ID="oHTA"
     APPLICATIONNAME="HTAHelpomatic"
     SCROLL="yes"
     SINGLEINSTANCE="yes"
>
<!-- ID="objHTAHelpomatic" -->
<!-- WINDOWSTATE="maximize" -->

</head>

<SCRIPT Language="VBScript">

If HTAElevate() = True Then
    CreateObject("WScript.Shell").Run "mmc.exe compmgmt.msc", , True
    Call Main()
End If

Sub Main()
    MsgBox "HTA-Ende", 4096
End Sub

'*** v13.3 *** www.dieseyer.de *****************************
Function HTAElevate()
'***********************************************************
' Unter Windows x64 laufen VBS' nach einem Doppelklick in der x64-Umgebung
' mit %WinDi%\System32\wscript.exe oder mit %WinDi%\System32\cscript.exe.
' In der x64-Umgebung laufen VBS aber nicht (richtig). Die Prozedur
' HTAElevate() erkennt dies und startet ggf. das VBS in der

  Const Elev = " /elevated"

' MsgBox oHTA.commandLine, , "5016 :: "

' Trace32Log "5018 :: oHTA.commandLine: ==" & oHTA.commandLine & "==", 1

  HTAElevate = True

' If InStr( LCase( oHTA.commandLine ), Elev) > 0 then MsgBox oHTA.commandLine, , "5022 :: "
  If InStr( LCase( oHTA.commandLine ), Elev) > 0 then Exit Function

  On Error Resume Next
    window.resizeto 750, 10 ' : window.moveto screen.width / 2, screen.height / 2
  On Error GoTo 0

' MsgBox oHTA.commandLine, , "5030 :: "

  createobject("Shell.Application").ShellExecute "mshta.exe", oHTA.commandLine & Elev, "", "runas", 1

  HTAElevate = False

  self.close

End Function ' HTAElevate()

</SCRIPT>
<body>

</body>
</html>

A: <html>
<head>
    <SCRIPT LANGUAGE="VBScript" use="to move window offscreen so that it should not flicker">
        X=top.screenleft
        Y=top.screentop
        window.moveTo -2000,-2000
    </SCRIPT>
    <hta:application
      ID="thisHta"
      ApplicationName="The Great ManojBhakarPCM"
      Border="thin"
      BorderStyle="Static"
      Caption="Yes"
      ContextMenu="No"
      MaximizeButton="No"
      MinimizeButton="No"
      Navigable="No"
      Scroll="yes"
      Selection="yes"
      ShowInTaskbar="Yes"
      SingleInstance="no"
      SysMenu="Yes"
      WindowState="normal"
    >
    <SCRIPT Language="VBScript" use="to Run As Administrator And window onload.">
        If InStr(LCase(thisHta.commandLine), " /elevated") = 0 Then
            createobject("Shell.Application").ShellExecute "mshta.exe", thisHta.commandLine & " /elevated", "", "runas", 4
            self.close
        else
            window.moveTo X,Y
        End If
        Sub Window_OnLoad 'On window loading elements compeleted. start work here.
          Document.body.innerHtml = "hello public, to kaise hai aap log? तो कैसे है आप लोग ?"
        End Sub
    </SCRIPT>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"  />
</head>

<style>
    /* Author: ManojBhakarPCM */
    body {
          font-family: Arial, Helvetica, sans-serif;
    }
    .tile{/* Tile: width:vary, height: content wrap, padding: 5px;*/
        height: auto !important;
        padding:10px;
        margin:3px;
        display:inline-block;
    }
    .tilehead{
        height: auto !important;
        padding-left:10px;
        padding-right:10px;
        padding-top:2px;
        padding-bottom:2px;
        margin:2px;
        font-size:10px;
        display:inline-block;
    }
    /*-----COLORS----*/
    .pink{background-color:#FF4081;color:white;}
    .red{background-color:#D32F2F;color:white;}
    .purple{background-color:#E040FB;color:white;}
    .deeppurple{background-color:#512DA8;color:white;}
    .indigo{background-color:#536DFE;color:white;}
    .blue{background-color:#1976D2;color:white;}
    .lightblue{background-color:#0288D1;color:white;}
    .cyan{background-color:#00BCD4;color:white;}
    .teal{background-color:#00796B;color:white;}
    .green{background-color:#388E3C;color:white;}
    .lime{background-color:#CDDC39;color:white;}
    .yellow{background-color:#FFEB3B;color:white;}
    .darkyellow{background-color:#FBC02D;color:white;}
    .orange{background-color:#FF5722;color:white;}
    .bluegray{background-color:#607D8B;color:white;}
    .gray{background-color:#333;color:white;}

    .roundcorner{border-radius:5px;}
    .bold{font-weight:bold;}
    .padmin{padding:5px;}
    .padmid{padding:10px;}
    .padfull{padding:15px;}
    .inline{display:inline-block;}
    /* --------CONTROLS---------*/
    /*NAVBAR*/

    .navbar {overflow: hidden;background-color: #333;padding:3px;text-decoration: none;}
    .navbar a{padding:5px;font-size: 10px;text-decoration: none;}
    .navbar a:hover{background-color:red;}

    table {
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 50%;
    }

    td, th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 8px;
    }

    tr:nth-child(even) {
      background-color: #dddddd;
    }
</style>
<body>

Hellow Worlds
</body>
</html>

I have created this hta templet and i use it very often. I belive that templets are best way to work with scripting etc. i usually keep uploaded these templets to websites so when working on any computer(which is not mine) can do work done just by downloading and start coding.
FEATURES:

*

*Run as administrator

*Does Not Flicker.

*Don't Even Show Before getting admin prev.

*Unicode support.

*All HTA tags.

*usefull classes of css for smooth UI


text:
Q: Can I find my own deleted answers which don't show up in the "Deleted Recent Answers" list I was going to make a post on my website on an answer I gave to a question once about doing a loop in in PHP but without using a loop (in which my answer was to use recursion). I went to my list of answers, sorted by newest but I can't find it. I do recall the question getting downvoted so I suspect that the OP might have deleted it as I was sure that another answer was selected as accepted. I checked my "Deleted Recent Answers" list yet it doesn't appear there so the question probably wasn't deleted recently.
Looking at this question which comes up in the similar questions list as I was typing this, the question is a feature request made years ago and the answers are just showing why or why not we should not have the list of our deleted posts and was made before we have "Deleted Recent Answers" list.
So I would like to know if I am able to find my own answers that were deleted which don't appear in the "Deleted Recent Answers".

A: If you have 10k on the site, you can use deleted:1 in a search to find your deleted posts (it will not show you others'). Otherwise, well, good luck finding it in a cache somewhere. There's no provision for finding older deleted posts without having at least moderator tools privileges.
If it's important, consider asking a ♦ mod to find it for you. (For example, this is sometimes done to help question-banned users.)

A: Google has aggressive caching, which sometimes isn't cleared when content is deleted.
You can use this for your advantage, e.g. using this search, I found two deleted answers of yours: one, two. I went only through first three pages, you can go over more and probably find what you're looking for. If you remember key words from your answer, it might help as well.