text:
Q: Retrieve Html datas between two div with same classes with jquery How could I retrieve HTML datas between two div having the same class but with no children like here:

 EXT.PARK.DAY

 He is walking fast.

JOHN

I have to hurry!

INT.WAITING ROOM.DAY

As an example the result of the query to retrieve everything between the div with scene class would be to retrieve all this:

 He is walking fast.

JOHN

I have to hurry!

How could get these elements with Jquery ?

A: You could use jQuery's nextUntil()

$(".scene")
  .nextUntil(".scene")
  .css("background-color", "red");

 EXT.PARK.DAY

 He is walking fast.

JOHN

I have to hurry!

INT.WAITING ROOM.DAY

A: If you want to apply some css to the element between scene class then see below soltion.

var childs = document.body.children;
for(var i = $('.scene').index() + 1; i < childs.length; i++) {
    if($(childs[i]).hasClass('scene')){
      break;
    }
    $(childs[i]).css('color', 'red');
}

 EXT.PARK.DAY

 He is walking fast.

JOHN

I have to hurry!

INT.WAITING ROOM.DAY

And if you want to get element between scene class div and put it in another div then you use below code.

function extract() {
  var childs = document.body.children;
  var extracted_elements = '';
  for (var i = $('.scene').index() + 1; i < childs.length; i++) {
    if ($(childs[i]).hasClass('scene')) {
      break;
    }

    extracted_elements += $(childs[i])[0].outerHTML;
  }
  $('.extracted_elements').html(extracted_elements);
}

 EXT.PARK.DAY

 He is walking fast.

JOHN

I have to hurry!

INT.WAITING ROOM.DAY

<button onclick="extract()">Extract</button>


text:
Q: Converting RGB to Grayscale manually tensorflow I wanted to convert an RGB image to grayscale manually without library usage in tensorflow. So I wrote the following...
import tensorflow as tf
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

# First, load the image again
filename = "MarshOrchid.jpg"
raw_image_data = mpimg.imread(filename)

image = tf.placeholder("float", [None, None, 3])
slice = tf.slice(image,[0,0,0],[-1,-1,1])

with tf.Session() as session:
    result = session.run(slice, feed_dict={image: raw_image_data})
    plt.imshow(result)
    plt.show()

I extracted the first channel of the image for the conversion. But this generates error while using imread saying
TypeError: Invalid dimensions for image data

What should I do?

A: From the doc of plt.imshow(X):

X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)

Here you have an input of shape [None, None, 1]. You just need to remove the last dimension like this:
result = np.squeeze(result, 2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: R - Base Line Chart - How to remove X and Y axes lines I am trying to get rid of the X and Y axes lines in R but it seems impossible. I am running the below code:
par(mar=c(5,5,5,5), cex.main = 1.5, col.main = "gray30", bg="white", cex =
0.8, family="Calibri", las=1)
plot(y1~x, col=blk_blue, type="l", lwd=2, ylim = y1_limits, xlab = x_label,
ylab = y1_label, las=1, axes=FALSE)

rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col =
"gray90", border=NA)
grid(nx = 5, ny = 5, col = "white", lty = "solid", lwd = 1)
grid(nx = 10, ny = 10, col = "white", lty = "dotted", lwd = 1)

par(new=TRUE, las=1, bty="n")
plot(y1~x, col=blk_blue, type="l", lwd=2, ylim = y1_limits, xlab = x_label,
ylab = y1_label)

axis(side=1, col = "white", labels = FALSE)
axis(side=2, col = "grey90", labels = FALSE, ylim = y1_limits)
axis(side=3, col = "grey90", labels = FALSE, tick = FALSE)
mtext(y2_label, side=4, line=3)

par(new=TRUE, bty="n", las=1, bty="n")
plot(y2~x, col=blk_red, type="l", lwd = 2, axes=FALSE, xlab = "", ylab="",
ylim=y2_limits, las=1, xaxt="n")
axis(side = 4,  ylim = y2_limits, col="grey90")

and the resulting chart looks like the below:

As you can see there are still some remainder black segments in the x-axis.
How can I remove those?

A: In your calls to plot(...), set axes=FALSE
In your calls to axis(...), set labels=TRUE
I believe this solves the issue, it prevents the black axis lines from being plotted in the first place but it still plots the numbers along the axes.


text:
Q: What kind of signals can a frequency synthesizer like this generate? Take this chip as an example: http://www.maxim-ic.com/datasheet/index.mvp/id/3491.
It says that the frequency range is 8.1kHz to 133MHz on the main output and 8.2MHz to 133MHz on the reference output. But, to my untrained eye it doesn't say much else.
The datasheet left me with a few questions:

*

*What kind of oscillator is it? Sine wave, triangle, saw tooth?

*It says it only needs a single +5v supply, but what if I wanted the sine wave to oscillate between, for example, -2.5 volts and 2.5 volts?

I know I can build an oscillator with an op-amp, but this question doesn't relate to that. I'm merely curious about the nature of chips like the one I posted.

A: The output is a square wave compatible with digital logic.  The "high" state is at least 2.4 volts and could be as high as the power supply.  The "low" state is between 0.0 and 0.4 volts.
Chips like this are used for generating clocks for digital logic and are not suitable for making sine waves.


text:
Q: Find current working revision number in bzr after revert -rN How can I tell which revision number I am currently compiling/linking (is there a "canonical" name for this revno?), in a bzr repo on which I have performed bzr revert -rN?
I remember some time ago finding a python script that obtained this info, but I cannot find it now.
Note:
http://doc.bazaar.canonical.com/development/en/user-reference/update-help.html is an old question, and the answer involves the use of bzr update.
I am not sure if it worked, and if it works now.
But the script I mention did not involve update (if so, it was under the hood).

A: "bzr log", "bzr revno" or "bzr revision-info" will tell you where your branch is at.
Unlike "bzr update", "bzr revert" only changes the specified files in the working tree to the specified revision. It does not affect history or the metadata for the working tree, and thus there is no way afterwards to find the revision those files came from.
In fact, it's possible to revert different files to different revisions in history.


text:
Q: How to implement role based permission in React.Js? I want to implement role-based permission in React. I have 3 different roles.

*

*Operator

*Supervisor

*Admin

Each role has certain permissions.
Example: Operator can view user form but can not edit user. The supervisor can edit the form but can not delete the user. This is just an example. I have different 20-25 permissions. (either canView / canEdit).
enum permission = {
   viewUser,
   editUser,
   viewReport,
   modifyReport,
   etc..
}

Post Data: { permissionType: permission.viewUser } // Backend will have already user role and id stored in service when user logged in, so no need to pass that.
Response may look like: { canView: true, canEdit: false }
My Question: Where and how can I create that enum and shared service (to make an API call at one place) so all the components can use that shared service to get the permissions and return results to component? I don't want to get all the permissions at once. As soon as I load the component, I want to make an API call and get specific permissions.

A: You can create a separate file for this (e.g permission.jsx) and import in any module needed
But I guess, this is not your question, more clarity will be better.
The other suggestion is to create an authorized component and wraps all the component that requires permission around it


text:
Q: android canvas.drawBitmap() paints whole bitmap in one color im doing a simple paint program.
I'm drawing to a custom Bitmap and then draw this bitmap to the canvas in the onDraw method.
custom bitmap and canvas creation:
bitmap = Bitmap.createBitmap(w - 150,h,Bitmap.Config.ALPHA_8);
canvasa  = new Canvas(bitmap);

when someone touches the screen a circle gets drawn:
canvasa.drawCircle(x, y, 10, paint);

which works fine, but every time the bitmap gets drawn on Screen, every circle has the same color (the paints current color):
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap,0,0, paint);
super.onDraw(canvas);
}

So if i have a red circle, change the color to blue and draw another circle, both circles in the bitmap are blue. Why is that? And how do I fix this?

A: For what you are doing, it does not make sense to pass the paint color at the time of drawing to the canvas. This is how the current color of paint is appearing on the canvas. If you check the documents you see this can be null.
Also as has been pointed out in comments, the config of the bitmap is incorrect for what you want to do. I suggest ARGB_8888 is more likely what you need here, so:
Bitmap.createBitmap(w - 150, h, Bitmap.Config.ARGB_8888);

and:
canvas.drawBitmap(bitmap, 0, 0, null);


text:
Q: JSON value search I'm getting below JSON result from a PHP page using ajax request. I tried a lot to get the desired result. I have done below approach but still unable to get as expected.
{
    "search": {
        "entry": [
            {
                "attribute": [
                    {
                        "name": "title",
                        "value": [
                            "Mr."
                        ]
                    },
                    {
                        "name": "mail",
                        "value": [
                            "kiran@gmail.com",
                            "Kiran@yahoo.com",
                            "kiran@hotmail.com"
                        ]
                    }

                ]
            }
        ]
    }
}

I have tried the following search to get the value using Defiant.js
success: function (data) {
var xx=JSON.stringify(data);
//                    var got = $.each(data.search.entry[0].attribute, function (i, v) {
//                        return v;
//
//                    });
           alert(xx);
     var z=JSON.search( xx, '//*[name="title"]/value[1]' );
                  alert(z);
                },

How would I can get results like title='Mr' or mail='kiran@gmail.com'.

A: Why you need regex solution if your json has proper structure. I have seen your code and json and it seems that you need first index value for title and mail. see following function which can search both title and mail.
var arrt = ' {"search": {"entry": [    {"attribute": [    {"name": "title","value": [    "Mr."]    },    {"name": "mail","value": [    "kiran@gmail.com",    "Kiran@yahoo.com",    "kiran@hotmail.com"]    }]    }]    }}';

    SearchMyWordTT(arrt,"title");
    //SearchMyWordTT(arrt,"mail");

    function SearchMyWordTT(arr,index){

        arr = JSON.parse(arr);

        for(var i=0;i< arr["search"]["entry"][0]['attribute'].length;i++){
            if(typeof (arr["search"]["entry"][0]['attribute'][i]['name']) !="undefined" && arr["search"]["entry"][0]['attribute'][i]['name'] == index)
                retIn = arr["search"]["entry"][0]['attribute'][i]['value'][0];
        }

        return retIn;
    }


text:
Q: Rails skip over/ignore data for links? So I am setting up previous post links in my Rails app and have the following in my show:
<% if @post.previous.blog_key == 'blog' && @post.previous.visible == true %>
 <%= link_to 'previous post', blog_post_path(@post.previous.url_name%>
<% else %>
 <%= link_to 'Home', '/blog/home' %>
<% end %>

Then in my model I have:
def previous
 SpudPost.where(["published_at < ?", published_at]).last
end

def next
 SpudPost.where(["published_at > ?", published_at]).first
end

What I'm trying to do is only have the previous links to go to those blog posts that are marked as having a blog_key that says blog AND marked to be visible. If it's not blog/false then ignore it and go to the next one that says blog and visible.
The problem is that it doesn't go to the next one that says blog/true. If the next one says blog_key == 'news' then it applies to 'Home'. Should it just be another filter within the previous/next methods instead?

A: Model works better.
def previous
 SpudPost.where(blog_key: 'blog').where(visible: true).where(['published_at < ?', published_at]).last
end

def next
 SpudPost.where(blog_key: 'blog').where(visible: true).find_by(['published_at > ?', published_at])
end


text:
Q: Crash : Convert dictionary to Json string in Swift 3 I'm trying to convert my swift dictionary to Json string but getting strange crash by saying
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
My code:
let jsonObject: [String: AnyObject] = [
            "firstname": "aaa",
            "lastname": "sss",
            "email": "my_email",
            "nickname": "ddd",
            "password": "123",
            "username": "qqq"
            ]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
    // here "decoded" is of type `Any`, decoded from JSON data

    // you can now cast it with the right type
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch {
    print(error.localizedDescription)
}

Please help me!
Regards.

A: String is not of type AnyObject.  Objects are reference types, but String in swift has value semantics.  A String however, can be of type Any, so the code below works.  I suggest you read up on reference types and value semantic types in Swift; its a subtle but important distinction and its also different from what you expect from most other languages, where String is often a reference type (including objective C).
    let jsonObject: [String: Any] = [
        "firstname": "aaa",
        "lastname": "sss",
        "email": "my_email",
        "nickname": "ddd",
        "password": "123",
        "username": "qqq"
    ]

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
        // here "jsonData" is the dictionary encoded in JSON data

        let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
        // here "decoded" is of type `Any`, decoded from JSON data

        // you can now cast it with the right type
        if let dictFromJSON = decoded as? [String:String] {
            print(dictFromJSON)
        }
    } catch {
        print(error.localizedDescription)
    }


text:
Q: Backbone localStorage and relations I'm having two RelationalModels, Student and School. School has many Students. All the data is to be stored in Backbone.localStorage
I need advice how the following should be done:

*

*I suppose I need two collections, one for each model, Student and School?

*I'm confused about how to store the data using localStorage. Should each collection store data in its own localStorage?

A: I understand you are using Backbone.localStorage to accomplish local storage with backbone.js.
As I see it, you would need two collections - SchoolsCollection and StudentsCollection. SchoolsCollection would implement the local-storage uplink:
var SchoolsCollection = Backbone.Collection.extend({

  localStorage: new Backbone.LocalStorage("schools")

});

Within SchoolsCollection you would save models of type SchoolModel. Instances of SchoolModel would carry an attribute named students, beeing an instance of StudentsCollection.
This would result in the localstorage look something similar like
key: schools
value: afe5a7bd,afe5a7bd

key: schools-afe5a7bd
value: {"name":"MIT","students":[{"name":"Joe"}],"id":"afe5a7bd"}

key: schools-afe5a7bd
value: {"name":"Eaton","students":[{"name":"Max"}],"id":"afe5a7bd"}

As you can see, StudentModel looses its type on serialization. You have to implement parse() in SchoolModel to complement this effect:
var SchoolModel = Backbone.Model.extend({
    parse: function(response) {
        return _.extend({}, response, {
            students: new StudentCollection(response.students)
        });
    }
});

A single school model gets restored by parse() with a custom treatment of it's attribute students. A new StudentsCollection is beeing created with the array of objects containing key-value-pairs describing each student's model.


text:
Q: Windows 10 iot Raspberry Pi 2 Tcp Connection c++ I have write server/client app. between raspberry pi2 and windows PC.(Raspi is server). If I placed both server and client program on raspberry pi2 then it works, but when client is run from windows pc then it I couldn't connect , got error timeout(10060). I am simply connecting pc and pi2 through a switch, firewall of my PC is disabled.
My sample code as same as windows https://msdn.microsoft.com/en-us/library/windows/desktop/ms737889(v=vs.85).aspx
Thank you for your time

A: I have found solution. We need to add a firewall rule to Windows 10 iot.
like:
netsh advfirewall firewall add rule name="Open Port 80" dir=in action=allow protocol=TCP localport=80


text:
Q: How to display multiple fetched data? I am using the following to fetch the latest articles from the database:
//Latest Article
$title_query1 = "SELECT title FROM articles ORDER BY id DESC LIMIT 1";
$description_query1 = "SELECT description FROM articles ORDER BY id DESC LIMIT 1";
$content_query1 = "SELECT content FROM articles ORDER BY id DESC LIMIT 1";
$image_query1 = "SELECT image FROM articles ORDER BY id DESC LIMIT 1";

$title_result1 = mysqli_query($con, $title_query1) or die(mysqli_error($con));
$description_result1 = mysqli_query($con, $description_query1) or die(mysqli_error($con));
$content_result1 = mysqli_query($con, $content_query1) or die(mysqli_error($con));
$image_result1 = mysqli_query($con, $image_query1) or die(mysqli_error($con));

//Second Latest Article
$title_query2 = "SELECT title FROM articles ORDER BY id DESC LIMIT 2,1";
$description_query2 = "SELECT description FROM articles ORDER BY id DESC LIMIT 2,1";
$content_query2 = "SELECT content FROM articles ORDER BY id DESC LIMIT 2,1";
$image_query2 = "SELECT image FROM articles ORDER BY id DESC LIMIT 2,1";

$title_result2 = mysqli_query($con, $title_query2) or die(mysqli_error($con));
$description_result2 = mysqli_query($con, $description_query2) or die(mysqli_error($con));
$content_result2 = mysqli_query($con, $content_query2) or die(mysqli_error($con));
$image_result2 = mysqli_query($con, $image_query2) or die(mysqli_error($con));

However, i'm not sure how I can then do something like this:

Here is the first article: <?php $title_result1 ?>

Here is the first article description: <?php $description_result1 ?>

Here is the second article: <?php $title_result2 ?>

Here is the second article description: <?php $description_result2 ?>

Also, is this method not good? If I am going to do this for 100+ articles, will it cause the web page to load slowly?
Thanks

A: You do not need to do a single query for each column. You can get all columns for a row by doing select * Also, as mentioned, you can fetch as many rows as you want, and loop through them.
I prefer the while method.. Example, show last 100 articles
// fetch latest 100
 $sql = "SELECT * FROM articles ORDER BY id DESC LIMIT 100";

if ($result = mysqli_query($con, $sql)){
// got results, convert result object to array called $row

while ($row = mysqli_fetch_array($result)) {

// echo out $row array elements with
//the column names from the database as array index

echo  '
'. $row['title'] .'
';  // example wrap results with HTML
echo '' .$row['description'] .'';
echo $row['content'];
echo ';
echo '
'; //so next result is on new line

}   // end of while loop

} else {
//no result,  error
}


text:
Q: Clarification on Central Limit Theorem (Sample Mean vs. Sample Distribution) I know the CLT says that as sample size (n) increases, the distribution of the sample mean has a mean that approaches the population mean and the variance of those means approaches (σ^2/n).  The way I have visualized this is that lets say you take 100 samples, each with 50 observations (n = 50), you will end up with 100 means.  You calculate the mean of the means and the variance of the means and the distribution of those means has mean = μ and variance = σ^2/50.
My question is, does this relationship also apply to the sample distribution itself, or only to the means of sample distributions.  For example, if I took only 1 sample, with an observation size of (n = 50).  I know the expected mean of that single sample is still μ, but is the expected variance of that sample also still σ^2/50?
I've been reading a bunch and may have confused two separate concepts.
Thanks!


text:
Q: Finding out which function, model or script created a variable in a workspace I'm using a simulationenvironment in matlab that's consisting of multiple scripts, functions and simulink models. Now I want to find out which of These created a specific variable in my Base-Workspace. Is there a way of finding this out?

A: One cannot trace back how a variable was created, but you may find the possible candidates that might create the variable.
If you know the name of the variable (let's say is 'my_var'), the use the 'Find files...' from the Edit menu (the usual key biding is [Ctrl]+[Shift]+[F]) to look into all files that containing the text my_var. Do not forget to configure the containing folder to include other paths than the current one, if you're calling some package/toolbox-level scripts.


text:
Q: Issue with DateTimeFormatter.ISO_INSTANT at millisecond I am using DateTimeFormatter but at end of milli seconds after 999 mill seconds its loosing the milliseconds field.Please let me know if this issue with java
public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            File file = new File("/users/test/filenamedate12.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedWriter bw= null;
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            bw = new BufferedWriter(fw);
            for(int i=0;i<=1000000;i++){
            ZonedDateTime zdt = ZonedDateTime.now();
            String  content =zdt.format(DateTimeFormatter.ISO_INSTANT);

                //String content = "This is the content to write into create file";

            bw.write(content);
             bw.newLine();

            }

            bw.flush();
            bw.close();
        }

output sample
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z

A: No, this is intentional. From the javadoc of DateTimeFormatter.ISO_INSTANT:

The nano-of-second outputs zero, three, six or nine digits digits as necessary.

In other words, redundant 0s after the . are being removed for brevity.
The source code shows:
ISO_INSTANT = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendInstant()
                .toFormatter(ResolverStyle.STRICT, null);

The appendInstant method is responsible for this behaviour. The docs for that method mention it as well.


text:
Q: Python, how trace operations over functions? In my project i would trace some operations achieved on my functions (like call number ecc ecc)
Which is the best solution for do it?
Thanks in advance

A: The best approach is using decorators.
The following
defines and applies a function decorator that counts the number of calls made to the decorated function and prints a trace message for each call:
class tracer:
 def __init__(self, func): # On @ decoration: save original func
  self.calls = 0
  self.func = func
 def __call__(self, *args): # On later calls: run original func
  self.calls += 1
  print('call %s to %s' % (self.calls, self.func.__name__))
  self.func(*args)

@tracer
def spam(a, b, c): # spam = tracer(spam)
 print(a + b + c) # Wraps spam in a decorator object

Notice how each function decorated with this class will create a new instance, with its own saved function object and calls counter. Also observe how the *args argument syntax is used to pack and unpack arbitrarily many passed-in arguments. This generality enables this decorator to be used to wrap any function with any number of positional arguments; this version doesn't yet work on keyword arguments or class-level methods, and doesn't return results but works for general concept.

A: You can use the trace functionality built into python. For example:
python -m trace -t your_program.py

this will list all functions as they are called
python -m trace -l paths.py

This will show a summary of all functions that were called
more information here:
https://docs.python.org/2/library/trace.html

A: Best solution is to use a Python magic: decorator, e.g., if you want to count the execution time of a function, you can define a decoration like this:
# This is in Python 3
ex_time = 0
def dec(func):
    def wrapper(*args, **kwargs):
        global ex_time
        ex_time += 1
        return func(*args, **kwargs)
    return wrapper

@dec
def your_func(a):
    # Define your function here
    print(a) # For example

# Let's test
your_func('hello')
your_func('world')
print(ex_time)

Check if the result is 2.


text:
Q: Convert the str to list of tuple I call the oxidation states of A and B in AB compounds from list1 ('CaFe', 'BaSi', 'SeOs', 'BaGeO', 'CdCe'):
dfA = pd.read_csv("oxi_state.csv",index_col=0, header =0)
A1 = []
A2 = []
final = []
for i in range(len(list1)):
   A1 = dfA['OS'][list1[i][0]]
   A2 = dfA['OS'][list1[i][1]]
   A = (A1, A2)
   final.append(A)
final

When I have called the data from DataFrame. The data is in the form:
[('2', '2,3,4'),
 ('2', '4'),
 ('-2,4,6', '4,5,6,7'),
 ('2', '2,4'),
 ('2', '3,4')]

Now I want to convert in the following form:
[([2], [2, 3, 4]),  ([2], [4]),  ([-2,4,6], [4,5,6,7]),  ([2], [2,4]),  ([2], [3,4])]

For post processing.
Thanks in advance

A: you may have to loop through all of the items. Using
list('2,3,4')

will return
['2',',','3',',','4']

You can then go through and remove the commas and convert the str to int

A: Use split method with , as a seperator.
   A1 = list(int(x) for x in dfA['OS'][list1[i][0]].split(","))
   A2 = list(int(x) for x in dfA['OS'][list1[i][1]].split(","))

A: Here a brute force solution :
a = [('2', '2,3,4'),
 ('2', '4'),
 ('-2,4,6', '4,5,6,7'),
 ('2', '2,4'),
 ('2', '3,4')]

fin = []
for i in range(len(a)):
  tup = []
  for j in a[i]:
    tmp = []
    for v in j.split(','):
      tmp.append(int(v))
    tup.append(tmp)
  fin.append(tuple(tup))

A: It's unclear how the list of tuples is being created. However, based on the sample shown then:-
lot = [('2', '2,3,4'),
 ('2', '4'),
 ('-2,4,6', '4,5,6,7'),
 ('2', '2,4'),
 ('2', '3,4')]

for i, e in enumerate(lot):
    lot[i] = [list(map(int, e_.split(','))) for e_ in e]

print(lot)

Output:
[[[2], [2, 3, 4]], [[2], [4]], [[-2, 4, 6], [4, 5, 6, 7]], [[2], [2, 4]], [[2], [3, 4]]]


text:
Q: Defining a method via constructor in JavaScript I have defined a JS class:
class Animation{

    constructor(name, el, func){
        this.name = name;
        this.target = el;
        this.animate = func.bind(this, this.target);
        this.running = true;

    }
// more methods here controlling animations
}

When creating an Animation object, I would like to have this behaviour:
... new Animation("animation", objToOperateOn, (target) => {
   doStuff();
   this.anAnimationMethod() // causes error because this is undefined
});

How can i get the anonymous function given as an argument to the constructor to have a refrence to the Animation object in the this keyword? The bind method that I'm using in the constructor doesn't seem to work, as logging this on the arrow function returns undefined.
PS. The target argument would be useless given we have a refrence to this, i just got it there for testing purposes.
Thanks for your time.


text:
Q: How to use HTTPPost without a new runnable thread I have the following code inside my MainAcitivity for logging to the application using username and password taken by a method jsnrqstr.sendRequest(username, password, URL);
loginButton.setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                username = userNameBox.getText().toString();
                password = passwordBox.getText().toString();
                login_state = jsnrqstr.sendRequest(username, password, URL);
                if(login_state.equals("ok")){
                    details.setUserName(username);
                    details.setPassword(password);
                    Toast.makeText(MainActivity.this, "User Verified", Toast.LENGTH_LONG).show();
                    passwordBox.setText("");
                    Intent myIntent = new Intent(MainActivity.this, DashBoardActivity.class);
                    MainActivity.this.startActivity(myIntent);
                }else
                    Toast.makeText(MainActivity.this, "Login Unsuccessful", Toast.LENGTH_LONG).show();
                    passwordBox.setText("");
            }
        });

This method uses the following code for receiving the response from an erlang server which responses with a JSON object and I could receive the login_state from it. Code for jsnrqstr.sendRequest(username, password, URL);
public class JSONRequester {

String state;

public String sendRequest(final String userName, final String password, final String URL){

    new Thread(new Runnable() {
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
            HttpResponse response;
            JSONObject json = new JSONObject();
            try{
                HttpPost post = new HttpPost(URL);
                post.setHeader("Content-type", "application/json");
                json.put("username", userName);
                json.put("password", password);
                StringEntity se = new StringEntity( json.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);
                /*Checking response */
                if(response!=null){
                    String temp = EntityUtils.toString(response.getEntity()); //Get the data in the entity
                    //Log.v("response", temp);
                    JsonObject o = new JsonParser().parse(temp).getAsJsonObject();
                    Log.v("response", o.get("state").toString());
                    state = o.get("state").toString();
            }}
            catch(Exception e){
                e.printStackTrace();
                //createDialog("Error", "Cannot Estabilish Connection");
            }
        }
      }).start();
          return state;
}

But I get the following Null-pointer Exception @
if(login_state.equals("ok")){

line which means that I have not returned the login_state value from the above method correctly. As I think This is because by the time the new runnable thread returns the value it is too late. What could I do for fixing this issue?

A: You should use a callback of some sorts that will begin executing your code when the thread has completed if you rely on the return value. Or you can start up the new thread and just wait for it to return before doing anything else.

A: The problem is between the lines :) - these two:
}).start();
<== HERE!!!
  return state;

The second one gets executed prematurely, while your thread is still running.  Concurrency is the solution.
One common Android-specific pattern is AsyncTask - http://developer.android.com/reference/android/os/AsyncTask.html - or its analogs (Thread/Handler etc.)
On click, initiate the process in onPreExecute (code before sendRequest): say, bring up a progress dialog and do the initializations.  Your thread's code goes into the doInBackground method and sets the state variable.  When done, in onPostExecute, dismiss the progress dialog, and proceed with your login logic: if(/*response*/ state!=null) ...


text:
Q: iOS UISwitch Action called twice I have UISwitch IBAction in my app, which is:
- (IBAction)nearMeSwitchAction:(UISwitch *)sender {

        if(nearMeSwitch.isOn)
            [self getLocation];

        [self myMethod];
}

- (void) getLocation
{
  my code...
 [nearMeSwitch setOn:NO animated:YES];
}

In my getLocation method I've used [nearMeSwitch setOn:NO animated:YES] which calls nearMeSwitchAction again when I click on my switch. Therefore myMethod gets called twice. I dont want that. I don't want to execute nearMeSwitchAction when I turn off my switch from getLocation. Is there other way to accomplish this?

A: You cannot stop nearMeSwitchAction to get called when you changed UISwitch value, but you can stop your myMethod to getting called. Create one Bool property like isFromGetLocation and if it is true don't call the method.
- (IBAction)nearMeSwitchAction:(UISwitch *)sender {

        if(nearMeSwitch.isOn)
            [self getLocation];
        if(isFromGetLocation)
           //For next time
           isFromGetLocation = NO;
        else
            [self myMethod];
}

- (void) getLocation
{
    //my code...
    isFromGetLocation = YES;
    [nearMeSwitch setOn:NO animated:YES];
}


text:
Q: In pdf.js how do I turn on handtool as the default setting? I am using  pdf.js to display a pdf. I would like the handtool to be on as the default setting, rather than people having to access it via clicking on the button.
This is the html button code:
  <button id="toggleHandTool" class="secondaryToolbarButton handTool" title="Enable hand tool" tabindex="27" data-l10n-id="hand_tool_enable">
              <span data-l10n-id="hand_tool_enable_label">Enable hand tool</span>
            </button>

This is the code on the .js document:
    var HandTool = {
  initialize: function handToolInitialize(options) {
    var toggleHandTool = options.toggleHandTool;
    this.handTool = new GrabToPan({
      element: options.container,
      onActiveChanged: function(isActive) {
        if (!toggleHandTool) {
          return;
        }
        if (isActive) {
          toggleHandTool.title =
            mozL10n.get('hand_tool_disable.title', null, 'Disable hand tool');
          toggleHandTool.firstElementChild.textContent =
            mozL10n.get('hand_tool_disable_label', null, 'Disable hand tool');
        } else {
          toggleHandTool.title =
            mozL10n.get('hand_tool_enable.title', null, 'Enable hand tool');
          toggleHandTool.firstElementChild.textContent =
            mozL10n.get('hand_tool_enable_label', null, 'Enable hand tool');
        }
      }
    });
    if (toggleHandTool) {
      toggleHandTool.addEventListener('click', this.toggle.bind(this), false);
    }

toggle: function handToolToggle() {
this.handTool.toggle();
SecondaryToolbar.close();
 },

Can I add something to my html to turn that on immediately after page load? Or can I change the .js file to do that?

A: I was just trying to achieve the same thing.
Apparently it's as simple as changing enableHandToolOnLoad: false to enableHandToolOnLoad: true in viewer.js.
Probably this wasn't possible at the time you've posted this question.

A: OK I worked it out.....
I added:
<body onLoad="HandTool.toggle()">

to the end of the html, just before
</body>

A: In viewer.js, turn cursorToolOnLoad to 1 in getDefaultPreferences.

A: You can do this call once the viewer page is initialized.
 PDFViewerApplication.pdfCursorTools.switchTool(1);

Select: 0, Hand: 1, Zoom: 2


text:
Q: How to represent data objects gradually getting augmented in a pipeline I'm working on a Scala data-processing program.  Essentially we start with a collection of many small data objects, say, (eventId: String, basicInfo: Basic) and gradually filter out some objects and add more information by joining the original collections with other data sources (typically on the eventId field), or by computing new fields as functions of existing fields.
Now, I'm having a certain amount of trouble designing this properly.  It's rather adhoc now - the original data item is modeled as case class FirstStage(eventId: String, basicInfo: Basic) and subsequent stages are modeled compositionally: case class SecondStage(first: FirstStage, someOtherId: Long), and so on.  This results in rather ugly chains of accessors (e.g third.second.first.basicInfo) and makes the code very difficult to modify.  For example, we might want to change some function persist:ThirdStage => to operate instead or additionally on SecondStage, but the lack of polymorphism in the design makes that pretty hard.
One idea might be to start out with the terminal stage, initially set all its fields to null, and gradually fill them out, but it seems as if it would be difficult to keep track of what happens when.  Or, we could ditch the case classes in order to have SecondStage extend FirstStage and so on, but I think it's probable that the program will lose its linearity in the next few months, which will make the inheritance approach rather clunky.

A: I think you need to use the State monad from scalaz -> http://eed3si9n.com/learning-scalaz/State.html
The data type would be State[Stage, Data] where Stage consists of your stages and data the value that accompanies the current stage.
case class Stage(id: String, someStateInfo: String)
case class Data(someData: String, anotherData: String)

Create a state:
State[Stage, Data] {
   case Stage(id, someStateInfo) =>

   // some function that inspects stateInfo and generates a newData
   val newData = if (someStateInfo == ...) Data("x", "y")
                 else Data("a", "b")
   val newState = State(generateNewId(), generateNewStateInfo())

   // return new state and new data
   (newState, newData)
}

The question is a bit vague and I am not sure if this is what you want, but hopefully it will get you to explore the link I provided and be willing to bend your mind with this functional programming pattern (Monad + State Monad).


text:
Q: Return function's nest level in postgresql? In MS SQL you have @@NESTLEVEL but what about in postgresql?
I check the docs, only found a function that returns the nest level of triggers.
Searched the docs several few times, lot of things there.
So, I'm not sure if I've missed something, thought I'd asked here to be sure.
Anyone knows what function that returns the nest level for functions (if there is any)?
I'd appreciate other workarounds.


text:
Q: "State of Maryland" or "state of Maryland"? When referring to a U.S. state in a formal document, is it correct to capitalize "State," or should it remain uncapitalized?
For example:
This school is accredited by the State of Maryland
OR
This school is accredited by the state of Maryland

A: If you wanted to follow the State of Maryland's lead, you should say State of Maryland. Also, I would say if you're using the phrase as an honorific symbolizing deference (as is the case in law), use "State of Maryland."
But really, unless this is to be used in financial, governmental, or official records, both are acceptable and used.

A: If it's a "formal document", OP should probably be accurate, and write...

This school is accredited by Maryland State Department of Education

...since they're presumably the relevant authority, and that's what they call themselves. The general principle being that the "referent" of any proper noun is the primary authority in such matters.

But in more general contexts where we don't know (or don't care) which particular "arm" of the state is involved, or what they call themselves, capitalisation is gradually falling out of favour...


text:
Q: Why Prometheus does not raise error on invisible metric? We have a custom metric that gets exported only upon some error condition in app
Alert rule use that custom metric that gets registered with rule manager of Prometheus
Why Prometheus does not raise error, when this metric name is queried? Despite the metric is not available in Prometheus yet...

A: It seems correct that the absence of a signal is not treated as an error.
However, it can cause problems with dashboards and alerting.
See this presentation by one of Prometheus' creators: Best Practices & Beastly Pitfalls


text:
Q: Android - Insert in DB if value is greater than the value in DB I am using Android studio and Firebase to develop an application. I want to store a score in the database if the value is greater than the score in database. How do I check for that?
            userData.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    userData.child("score").setValue(count);

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

A: You use the dataSnapshot to get the value from the reference.
Then, use that reference to update the data as you have, but add the conditional.
userData.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        final String scoreKey = "score";

        Long oldScore = dataSnapshot.child(scoreKey).getValue(Long.class);
        if (oldScore == null || count > oldScore) {
            userData.child(scoreKey).setValue(count);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});


text:
Q: How to prevent the style of the annotation point from appearing to be lost, it turns completely black? I am using the react-native-mapbox-gl library and I am showing some points on a map. Each has its own callout to display additional information when the respective point is pressed.
I have found the docs/Callout.md and Callout.js source and and example using it in example/src/examples/ShowPointAnnotation.js. This was a great help, thank you so much for the example... I might though doing something really wrong and I have spent days already on this...
My issue is that when I press one annotation, the styling of the annotations appears to be lost (they go all black). Similarity, the styling for the callouts don't seem to be applied. They all black, too. I have shared code and screenshots bellow.
<MapboxGL.PointAnnotation
    key={id}
    id={id}
    coordinate={coordinate}
    title={title}
    onSelected={feature => {
        debugger
        this.onAnnotationSelected(i, feature)
    }}
    onDeselected={this.onAnnotationDeselected}
>
    <View
        style={[
            styles.annotationContainer,
            {
                backgroundColor: bgColour,
                borderRadius: ANNOTATION_SIZE / 2,
                borderWidth: StyleSheet.hairlineWidth,
                borderColor: borderColor
            }
        ]}
    >
        <Text style={[styles.annotationFill, { color: borderColor }]}>
            {studio.id}
        </Text>
    </View>
    <MapboxGL.Callout
        style={[
            styles.calloutContainer,
            { backgroundColor: bgColour, borderColor: borderColor }
        ]}
        title={title}
    >
        <View
            style={[
                styles.calloutContent,
                {
                    backgroundColor: bgColour,
                    borderColor: borderColor
                }
            ]}
        >
            <Text style={[styles.annotationFill, { color: borderColor }]}>
                {title}
            </Text>
        </View>
        <View
            style={[
                styles.tip,
                styles.calloutContent,
                {
                    backgroundColor: bgColour,
                    borderColor: borderColor
                }
            ]}
        />
    </MapboxGL.Callout>
</MapboxGL.PointAnnotation>

And stylings
const ANNOTATION_SIZE = 32

const styles = StyleSheet.create({
    annotationContainer: {
        width: ANNOTATION_SIZE,
        height: ANNOTATION_SIZE,
        alignItems: 'center',
        justifyContent: 'center'
    },
    annotationFill: {
        color: 'black'
    },
    container: {
        flex: 1
    },
    calloutContainer: {
        alignItems: 'center',
        justifyContent: 'center',
        width: 180,
        zIndex: 9999999
    },
    calloutContent: {
        flex: 1,
        position: 'relative',
        padding: 8,
        borderRadius: 3,
        borderWidth: 1
    },
    calloutTitle: {
        width: ANNOTATION_SIZE,
        height: ANNOTATION_SIZE,
        color: 'black',
        textAlign: 'center'
    },
    calloutTip: {
        zIndex: 1000,
        marginTop: -2,
        elevation: 0,
        backgroundColor: 'transparent',
        borderTopWidth: 16,
        borderRightWidth: 8,
        borderBottomWidth: 0,
        borderLeftWidth: 8,
        borderTopColor: 'white',
        borderRightColor: 'transparent',
        borderBottomColor: 'transparent',
        borderLeftColor: 'transparent'
    }
})

I am concerned though as well that I should not be using PointAnnotation, as it is marked to be deprecated. Is there an alternative way to achieve the same? Could someone point me into right direction? I am happy to contribute too if needed.


text:
Q: How many Deus Ex Human Revolution Missions Have A Time Limit? I've just started playing Deus Ex: Human Revoution, and the very first non-opening mission that I got had a time limit for starting it proper, with major consequences for dallying too long.
I really don't want to get anybody in a tight spot in this game, so is this a one-off thing, or are there more missions that will punish me for leaving them to rust forever?  And if so, how many of these missions can I not leave on the backburner for too long?

A: There are two parts of the game that have a time limit of sorts - you won't "fail" a mission by taking too long but there are lasting effects if you take too long to complete the mission objectives. In order, these are as follows;
At Sarif HQ, after the prologue
After the prologue, once you've arrived back at Sarif HQ post augmentation, you will be told to meet David Sarif at the helipad to start the first mission, while commenting that you need to go and meet up with Pritchard to get your retinal prosthesis recalibrated.
If you spend more than 15 minutes looking around, the hostages in the next mission will be dead on arrival. David will warn you once you reach about half way through the available time limit.
Malik's crash
Later in the game upon returning to Hengsha for the second time, Malik's flight will be shot out of the sky (with you on board). You will start in a level under siege with multiple waves of enemies attacking consisting mainly of ground soldiers at first before escalating to security robots. If you take longer than 10 minutes to clear all of the hostiles (shortly after the security robots are activated), Malik's ship will be destroyed, along with Malik.


text:
Q: SSH Connection to a remote server using PHP I want to make a SSH connection to a remote server using php.
Im using php 5.3 on Linux/CEntOS.
What I have done so far :
$connection = ssh2_connect('192.168.1.22', 22);
ssh2_auth_password($connection, '_username', '_password');
$stream = ssh2_exec($connection, 'ls -l');

But I'm getting this error :
Fatal error: Call to undefined function ssh2_connect()
So, my questions are :

*

*Are ssh2_* functions not installed by default in php?

*Do I need an extension or library for using these functions?

*How can I solve this problem ?

A: You can configure your server (Ubuntu):
sudo apt-get install libssh2-php
sudo service apache2 restart

A: phpseclib

*

*Download it from here or  here ( direct link ) ,

*Include it to the project ,
And then :
   include('Net/SSH2.php');
   $ssh = new Net_SSH2('www.example.com');
   $ssh->login('username', 'password') or die("Login failed");
   echo $ssh->exec('command');

A: ssh_* function are not per default installed in php core.
You have to add them using pecl, see php manual for a good description: http://de1.php.net/manual/en/ssh2.installation.php


text:
Q: How to map get values by dynamic key from array of object? I want to fetch object values by dynamic key inside map() if possible.

const array = [
  { "ts": 1620988054, "KEY1": 14, "KEY2": 23, "KEY3": 58 },
  { "ts": 1620901654, "KEY1": 46, "KEY2": 34, "KEY3": 42 },
  { "ts": 1620898054, "KEY1": 16, "KEY2": 44, "KEY3": 24 }
];
let data = {};
const arrayOfKeys = [ "KEY1", "KEY2", "KEY3" ];
const keyObject = { "KEY1": "KEY1", "KEY2": "KEY2", "KEY3": "KEY3" };

for (let index = 0; index < arrayOfKeys.length; index++) {
  const key = Object.keys(keyObject)[index];
  data[key] = array.map(({ KEY1 }) => KEY1);
  data[key] = array.map(({ KEY2 }) => KEY2);
  data[key] = array.map(({ KEY3 }) => KEY3);
}

console.log(data);

A:

const array = [
      {"ts":1620988054, "KEY1":14, "KEY2":23, "KEY3":58},
      {"ts":1620901654, "KEY1":46, "KEY2":34, "KEY3":42},
      {"ts":1620898054, "KEY1":16, "KEY2":44, "KEY3":24}];

    const data = array.reduce((acc, cur) => { // loop through array
       const {ts, ...rest} = cur; // for each item, isolate ts from the rest
       Object.entries(rest).forEach(([k, v]) => { // loop through the rest
        if (k in acc) acc[k].push(v) // if we already have an array for the key, push the new value to it
        else acc[k] = [v]; // else create a new array with that key/value pair
       });
       return acc
    }, {});

    console.log(data);

A: If you want an object containing keys that correlate with your array of keys, you can reduce the items in the array by reducing over the array, and within the items, reducing the keys.

const array = [
  { "ts": 1620988054, "KEY1": 14, "KEY2": 23, "KEY3": 58 },
  { "ts": 1620901654, "KEY1": 46, "KEY2": 34, "KEY3": 42 },
  { "ts": 1620898054, "KEY1": 16, "KEY2": 44, "KEY3": 24 }
];
const arrayOfKeys = [ "KEY1", "KEY2", "KEY3" ];

const data = array.reduce(
  (accOuter, record) => arrayOfKeys
    .reduce((accInner, key) => ({
      ...accInner,
      [key]: record[key]
        ? [...accInner[key], record[key]]
        : accInner[key]
    }),
  accOuter),
  Object.fromEntries(arrayOfKeys.map(key => [ key, [] ])));

console.log(data);
.as-console-wrapper { top: 0; max-height: 100% !important; }


text:
Q: Measure the size of an object with camera I need to do an method which measure the object from a photo... I mean that I can compare the object with the size from a card to get the size from object, but I don't know how to compare this... Any idea?
Here is how I am taking the picture
- (IBAction)takePicture:(id)sender {
// Create image picker controller
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

// Set source to the camera
imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;

// Delegate is self
imagePicker.delegate = self;

// Allow editing of image ?
imagePicker.allowsImageEditing = NO;

// Show image picker
[self presentModalViewController:imagePicker animated:YES];

  }

       - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
     {
UIAlertView *alert;

// Unable to save the image
if (error)
    alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                       message:@"Unable to save image to Photo Album."
                                      delegate:self cancelButtonTitle:@"Ok"
                             otherButtonTitles:nil];
else // All is well
    alert = [[UIAlertView alloc] initWithTitle:@"Success"
                                       message:@"Image saved to Photo Album."
                                      delegate:self cancelButtonTitle:@"Ok"
                             otherButtonTitles:nil];
[alert show];
[alert release];
 }

A: Here's a site with some ios ported image processing algorithms.  If you can detect the outer edges of the image and some reference object (and know that they are at the same depth), you should be able to approximate size.
EDIT - Turns out there's no code at that link.  Here's an SO answer about using OpenCV to do edge detection.  Anyway, the point is, you need image processing to pull measurable features from the photo.


text:
Q: How to place different marker for each marker added to map? I would like to know if it is possible when placing a marker on the map, to then select from a list which marker to place. So for example, when the user wants to place a marker at a point of interest, like lets say a castle,  then the user can select from various marker icons from a list and select the marker (castle icon) and place it on the map.  Is this possible? and if so is there an example to follow or can someone point me in the right direction?
EDIT
Something like this:

A: MarkerOptions can be added at any particular latitude and longitude. Yon can set its title, alpha value, marker icon color etc. Snippet content will be shown in marker info window when marker is clicked. We need to ensure to moveCamera to your coordinates with required zoom level (9 in below example). You can check map tutorial.
GoogleMap object will be available from onMapReady() callback.
LatLng NYC = new LatLng(40.714, -74.00);
googleMap.addMarker(
      new MarkerOptions().position(NYC).alpha(0.8f).title("NYC")
            .snippet("AndroidSRC Map Demo")).setIcon(
      BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(NYC, 9));

A: See method addMarker and class MarkerOptions.
Marker mark = map.addMarker(
    new MarkerOptions()
        .position(latlng)
        .title(title)
        .icon(icon)
);

Using MarkerOptions you can define custom icon when adding your marker.
In my example, latlng is LatLng object with coordinates, title is a String containting the title and icon is BitmapDescriptor for a custom marker icon.
Also, it seems that Marker has its own method setIcon(BitmapDescriptor icon) which can be used after the marker is added to map I guess.


text:
Q: error when running python script: "AttributeError: 'EventObject' object has no attribute 'sentence'" when I run my code, I receive the following error message. I think the fault must lie in a short script that is called upon when I run the main script, because that is the only one in which there is an "EventObject". This is the error:
AttributeError: 'EventObject' object has no attribute 'sentence'

This is the code from the short script:
class AnnotationsObject:

def __init__(self):
    self.eventlist = []
    self.entitylist = []
    self.polaritytriggerslist = []

class EventObject:
    def __init__(self):
        self.eventtext = []
        self.polarity = None
        self.sameclause = False

class EntityObject:
    def __init__(self):
        self.entitytype = None
        self.entitytext = []
        self.polarity = []
        self.metonymy = False

class PolarityTriggersObject:
    def __init__(self):
        self.text = []
        self.polarity = []
        self.target = []
        self.id = None
        self.irony = []
        self.eventrelationpolarity = []
        self.span = []

Any ideas on what the problem might be?
Edit: This is the piece of code which calls on "EventObject" and the "sentence"-attribute
def write_annotations_eventpolarity(allAnnotationsDict, annotatornames, outfilefolder):
alleventsdict = get_all_events(allAnnotationsDict)
'''
Gets, for every unique event (alleventslist), its polarity given by each annotator
'''
with open(os.path.join(outfilefolder,'annotations_eventpolarity.csv'), 'w') as csvfile:
    outfilewriter = csv.writer(csvfile, delimiter='\t',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    outfilewriter.writerow(['Document', 'Event'] + [a for a in annotatornames] + ['Sentence', 'Sentence without event'])
    for documentname, annotatordict in allAnnotationsDict.items():
        #Get a list of all events per document, consider the first annotator in the dict, as the events are the same for each annotator.
        allevents = alleventsdict[documentname][annotatornames[0]]
        alleventstrings = ['+'.join(x.eventtext) for x in allevents] #Events can be stored as lists of two non-consecutive spans
        alleventsentences = [x.sentence for x in allevents]
        alleventsentenceswithoutevent = [x.sentencewithoutevent for x in allevents]
        seen = []
        for eventText, eventSent, eventSentWith in zip(alleventstrings, alleventsentences, alleventsentenceswithoutevent):
            rowelements = [] #Rowelements will be written to output file
            rowelements.append(documentname)
            rowelements.append(eventText)
            for a in annotatornames:
                pol = []
                eventobjectslist = alleventsdict[documentname][a]
                for eveobj in eventobjectslist:
                    found = False
                    if '+'.join(eveobj.eventtext) == eventText and eveobj.sentence == eventSent:
                        if eveobj.polarity == None:
                            pol.append('None')
                        else:
                            pol.append(eveobj.polarity)
                        found = True
                    else:
                        continue
                    if not found:
                        print('Warning: event\t{0}\t{1}\tfrom annotator {2} not found in alleventslist.'.format(eveobj.eventtext, documentname, a))
                        warnings.append('Write annotations for event polarities: event\t{0}\t{1}\tfrom annotator {2} not found in alleventslist.'.format(eveobj.eventtext, documentname, a))
                if len(pol) > 1 and 'None' in pol: #Event polarity can be 'None' if the event is part of a linked event span and its polarity was added to the other part
                    indx_none = pol.index('None') #Remove 'None' polarities
                    pol.pop(indx_none)
                rowelements.append(','.join(list(set(pol))))
            rowelements.append(eventSent)
            rowelements.append(eventSentWith)
            if not (eventText,eventSent) in seen: #Discard 100% duplicates (i.e. events that are annotated twice in the sentence)
                outfilewriter.writerow(rowelements)
            seen.append((eventText,eventSent))

The error seems to occur at alleventsentences = [x.sentence for x in allevents]

A: class EventObject:
def __init__(self):
    self.eventtext = []
    self.polarity = None
    self.sameclause = False

You are missing sentence here. Something like self.sentence = None

A: You are reading an uninitialized field from an object.
For example:
EventObject e = EventObject()

and then
print(e.sentence)

before
e.sentence = "..."

Another solution is to initialize the field in the constructor:
class EventObject:
    def __init__(self):
        self.eventtext = []
        self.polarity = None
        self.sameclause = False
        self.sentence = "..."


text:
Q: Functions to return Db values in c# I want to write three functions:

*

*that gets  list of all database

*gets the table name for the database name I  provide from 1

*gets the column name from the table name I provide from 2

I can get the  table  name of specific database I  want by writing a query to that database and getting  table names and column names. I'm looking for a way to achieve this  by specifying the parameters which a user can get values from any database and any table and column names. In short I want   my function to do act like a function which when  given the appropriate dbname, tablename and column name would work.


text:
Q: java.jdbc clojure execute! insert arity I'm working with a postgres database from clojure using java.jdbc.
[org.clojure/clojure "1.7.0"]
[org.clojure/java.jdbc "0.6.1"]
[org.postgresql/postgresql "9.4-1201-jdbc41"]

I want to do an 'upsert' operation on a database using some code like this:
 (if (-> updatesU count pos?) (sql/execute! spec ["insert into users(id, name) values (?, ?) on conflict(id) do update set name=EXCLUDED.name;"]  updatesU  {:multi? true} ))
 (if (-> updatesTE count pos?) (sql/execute! spec ["insert into time_entries(id, spent_date, hours, userid, project, task) values (?, ?, ?, ?, ?, ?) on conflict(id) do update set spent_date=EXCLUDED.spent_date, hours=EXCLUDED.hours;"] updatesTE {:multi? true} )))

The documentation seems to have no examples so I'm sort of lost for a solution.
I get this error:
Exception in thread "main" clojure.lang.ArityException: Wrong number of args (4) passed to: jdbc/execute!

Any help would be great.

A: The common case is that parameters to the statement go inside the vector as scalars:
(sql/execute!
  spec
  ["insert into users(id, name) values (?, ?) on conflict(id) do update set name=EXCLUDED.name;"  id name]
  {:multi? false} ))

The { :multi? true } is when you are executing the statement multiple times, not a single time with multiple parameters, for instance:
(sql/execute!
  spec
  ["insert into users(id, name) values (?, ?) on conflict(id) do update set name=EXCLUDED.name;"  [id1 name1] [id2 name2] [id3 name3]]
  {:multi? true} ))

Some additional examples are here:
http://clojure-doc.org/articles/ecosystem/java_jdbc/using_sql.html
The clojure.java.jdbc library currently has a great, active, helpful maintainer but a confusing legacy API that predates modern idiom. A perhaps slightly more intuitive API is available through a newer jdbc library, called clojure.jdbc (as opposed to clojure.java.jdbc):
http://funcool.github.io/clojure.jdbc/latest/


text:
Q: What is the relationship between the 2nd Fundamental Form and Gaussian Curvature? I am looking at the proof for this Lemma:

If $S \subset \mathbb{R}^3$ is a regular, compact orientable surface,
  then $S$ has an elliptic point.

The proof concludes with stating that since $II_p$ has a fixed sign, then that implies that the Gaussian Curvature of $p$ on $S$ is positive.
I am having trouble seeing why this is so. I know that both the 2nd fundamental form and Gaussian curvature involves $dN_p$, but one is an Inner product and the other is determinant. I also know that the prinicpal curvatures are the eigenvalues of $dN_p$, but I can't see how they are related more explicitly.
Would really appreciate some help is developing a better understanding of this. Thanks!

A: Gaussian curvature is $$K(p):={\rm det}\ dN_p $$
If $x(u,v)$ is a parametrization, and if $$ N_u= dN x_u ,\ N_v=dN
x_v
$$ then we have first and second fundament form :
 $$ (x_u,x_u)=E,\ (x_v,x_v)=G,\ (x_u,x_v)=F $$
$$ (N_u ,x_u)=e,\ (N_v,x_v)=g,\ (N_u,x_v)= f $$ and $$ {\rm det} dN
=\frac{eg-f^2}{EG-F^2} $$
Here recall a normal curvature : $$k_n(p)= -(dN c'(0),c'(0)) $$ for
a curve on $S$ passing through $p$. In further $dN$ is self adjoint
so that there exist eigenvalues $dN v_i=\lambda_i v_i $. That is,
$-\lambda_i$ are normal curvatures. That is sign of $K$ is equal to
$\lambda_1\lambda_2$.
If $S$ is a compact then we choose some inner point $o$ which is not in $S$.
 So the farthest point $x\in S$ from $o$ has
 normal curvatures of same sign. Hence we are done.

A: Only for elliptic points the sign is positive and for saddle/hyperbolic points it is negative.
By Euler relation in the fiber tangent bundle normal curvature sign passes from positive via zero to negative if anti-clastic type $ k_1k_2< 0 $ of surface and for syn-clastic $ k_1k_2> 0 $ both are on the positive side.
$$ k_n = k_1 \cos^{2}\psi +  k_2 \cos^{2}\psi $$
The second fundamental form determinant can be expressed in terms of the first fundamental form coefficients & derivatives thereby making scalar Gauss curvature entirely isometric mapping independent, demonstrated in the proof of Gauss Theorema Egregium.


text:
Q: Trignometric Equation Find the three smallest positive values of $ \theta $ such that $ 4\cos^2(2\theta-\pi) =3. $
I saw that $\cos{(2\theta-\pi)}$ equals $\frac{\sqrt{3}}{2}$, therefore, $2\theta-\pi=\frac{\pi}{6}+2x\pi$ or $2\theta-\pi=\frac{11\pi}{6}+2x\pi.$
This gives the three smallest values as $\frac{5\pi}{12}$, $\frac{7\pi}{12}$, and $\frac{17\pi}{12}$. However, these answers are not correct, so where did I go wrong?

A: Whenever we have squares of any Trigonometric ratio, we can convert it to respective double angle of cosine
See also : Writing answers to trigonometric equation
$\displaystyle 4\cos^2(2\theta-\pi) =3\implies\cos\{2(2\theta-\pi)\}=2\cos^2(2\theta-\pi)-1=\frac32-1=\frac12$
$\displaystyle\implies2(2\theta-\pi)=2n\pi\pm\frac\pi3$ where $n$ is any integer
$\displaystyle\implies\theta=\frac{n\pi}2+\pi\pm\frac\pi{12}$
Taking '+' sign, we need $\displaystyle 0<\frac{n\pi}2+\pi+\frac\pi{12}<2\pi$
Multiplying each by $\dfrac{12}\pi,$
$\displaystyle\implies 0<6n+12+1<24\iff -13<6n<11\iff -2\le n\le1$ as $n$ is any integer
Similarly, for the '-' sign

A: Your equation is
$$
4\cos^2(2\theta-\pi)=3.
$$
When taking the square root, do not forget to account for the nonpositive roots. More specifically, the solutions to the equation are
$$\cos(2\theta-\pi)=\frac{\sqrt{3}}{2},\text{ or }\cos(2\theta-\pi)=-\frac{\sqrt{3}}{2},$$
which proves that the following $\theta$ are the solutions of the equation:
$$\theta=\frac{7\pi}{12}+k\pi,\text{ or }\theta=\frac{5\pi}{12}+k\pi,\text{ or }\theta=\frac{\pi}{12}+k\pi,\text{ or }\theta=\frac{11\pi}{12}+k\pi,$$
where in these equations $k\in\mathbb{Z}$ is arbitrary.
Thus the smallest positive $\theta$ solving the equation are $\theta_1=\frac{\pi}{12}$, $\theta_2=\frac{5\pi}{12}$, $\theta_3=\frac{7\pi}{12}$.


text:
Q: Authentication with firebase and angular. How to navigate to other component after the user log in? I want to authenticate a site that is written in Angular, with the help of firebase.
I found a guide that describes in a detailed and clear way how to do it.
Website address: https://www.positronx.io/full-angular-7-firebase-authentication-system/
The github that the guide attached:https://github.com/SinghDigamber/angularfirebase-authentication
I followed the instructions but i didn't succeed to navigate to other component  after the user logs in (The user remains on the same page).
 when I ran the code from the github, I encountered the same problem.
Partial code from auth.service.ts:
  // Sign in with email/password
  SignIn(email, password) {
    alert(":)");
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['/dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

Why the user does not navigate to dashboard component after login?
What could be the cause of the problem? Thank you.
EDIT:
I'll add the code here that I think is relevant:
auth.service.ts:
import { Injectable, NgZone } from '@angular/core';
//import { User } from "../services/user";
//import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

export interface User {
  email: string;
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; // Save logged in user data
  authStateSubs: any;
  //authStateSubs: any;

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public auth: AngularFireAuth,
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {

    /* Saving user data in localstorage when
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));

      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        alert("after signInWithEmailAndPassword");
        this.ngZone.run(() => {
          alert("after ngZone.run");
          this.router.navigate(['/authorized-zone']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Returns true when user is looged in and email is verified
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  /* Setting up user data when sign in with username/password,
  sign up with username/password and sign in with social auth
  provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.email}`);
    const userData: User = {
      email: user.email,
    }
    return userRef.set(userData, {
      merge: true
    })
  }

  // Sign out
  SignOut() {
    return this.afAuth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['login']);
    })
  }
}

auth.guard.ts:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../services/auth.service";
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ){ }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.authService.isLoggedIn !== true) {
      this.router.navigate(['login'])
    }
    return true;
  }

}

A: If you would like to do something based on sign-in and sign-out, a simple and good way is use a subscription to authState. Do it in your service's constrictor.
You do not do any thing inside signInWithEmailAndPassword's then.
constructor(
    public auth: AngularFireAuth,
    private router: Router,
    //...
    ){
        this.authStateSubs=this.auth.authState.subscribe(fbUser=>{
           //this is a Sign in.
           if( fbUser && fbUser.uid){
                this.router.navigate(['/wherever_you_want']);
           }else{
            //Sign out. Go to sign-in page.
           }
        });
    }

A: you can try to wait navigation result with promise, maybe it never happens
    this.router.navigate(['dashboard']).then(succeeded => {
      this.SetUserData(result.user);
    });

you can use async/await to simplify promise code, in example
    async signIn(email, password) {
      alert(":)");
      const result = await this.afAuth.signInWithEmailAndPassword(email, password);

      const succeeded = await this.router.navigate(['dashboard']);

      if (succeeded) {
        this.SetUserData(result.user);
      }
    }

try to fork these example and replace environment.ts with your own settings and test how it work

A: I think have to saving user data in localStorage when before navigate.
        this.ngZone.run(() => {
          alert("after ngZone.run");
          localStorage.setItem('user', JSON.stringify(result.user));
          this.router.navigate(['/authorized-zone']);
        });

if not, the localStorage is null and guarded when navigating.


text:
Q: Renci.SshNet : "server response does not contain ssh protocol identification" I'm working with the Renci SSH.Net library on a WPF application and I'm having an issue with using the SFTP client.  When the user tries to connect to download some files from the SFTP server he gets the message shown below:

Server response does not contain ssh protocol identification

It doesn't appear to be something specific with the server as I'm able to connect and download the files just fine on my development desktop and a secondary laptop.  The same application is able to connect over SSH and run commands without issue, it's just the SFTP connection that appears to be the problem.  I'm looking for a little guidance as to where to begin troubleshooting this.
Code for SFTP shown below:
void DownloadPlogs()
    {
        try
        {
            SftpClient SFTP;
            if (GV.UseCustomPort && GV.CustomPort > 0 && GV.CustomPort < 65535)
            {
                SFTP = new SftpClient(GV.IpAddress, GV.CustomPort, GV.Username, GV.Password);
            }
            else
            {
                SFTP = new SftpClient(GV.IpAddress, 22, GV.Username, "");
            }
            SFTP.Connect();

            DownloadDirectory(SFTP, "/PLOG", Directory.GetCurrentDirectory() + @"\PLOG");
            ZipFile.CreateFromDirectory("PLOG", String.Format("{0} - {1} PLOGS.zip", GV.IpAddress, DateTime.Now.ToString("yyyyMMddHHmmss")));
            Directory.Delete(Directory.GetCurrentDirectory() + @"\PLOG", true);

            SFTP.Disconnect();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error Getting PLOGS");
        }
    }

    void DownloadDirectory(SftpClient Client, string Source, string Destination)
    {
        var Files = Client.ListDirectory(Source);
        foreach (var File in Files)
        {
            if (!File.IsDirectory && !File.IsSymbolicLink)
            {
                DownloadFile(Client, File, Destination);
            }
            else if (File.IsSymbolicLink)
            {
                //Ignore
            }
            else if (File.Name != "." && File.Name != "..")
            {
                var Dir = Directory.CreateDirectory(System.IO.Path.Combine(Destination, File.Name));
                DownloadDirectory(Client, File.FullName, Dir.FullName);
            }
        }
    }

    void DownloadFile(SftpClient Client, Renci.SshNet.Sftp.SftpFile File, string Directory)
    {
        using (Stream FileStream = System.IO.File.OpenWrite(System.IO.Path.Combine(Directory, File.Name)))
        {
            Client.DownloadFile(File.FullName, FileStream);
        }
    }

Code for SSH below:
public SshConnection(string Host, int Port, string Username, string Password)
    {
        myClient = new SshClient(Host, Port, Username, Password);
        myClient.KeepAliveInterval = new TimeSpan(0, 0, 5);
        myClient.HostKeyReceived += myClient_HostKeyReceived;
        myClient.ErrorOccurred += myClient_ErrorOccurred;
    }

void myClient_ErrorOccurred(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message, "SSH Error Occurred");
    }

    void myClient_HostKeyReceived(object sender, Renci.SshNet.Common.HostKeyEventArgs e)
    {
        e.CanTrust = true;
    }

    public async void Connect()
    {
        Task T = new Task(() =>
        {
            try
            {
                myClient.Connect();
            }
            catch (System.Net.Sockets.SocketException)
            {
                MessageBox.Show("Invalid IP Address or Hostname", "SSH Connection Error");
            }
            catch (Renci.SshNet.Common.SshAuthenticationException ex)
            {
                MessageBox.Show(ex.Message, "SSH Authentication Error");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
                MessageBox.Show(ex.GetType().ToString());
                OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
            }
        });

        T.Start();
        await T;
        if (T.IsCompleted)
        {
            OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
        }
    }

    public void Disconnect()
    {
        try
        {
            myClient.Disconnect();
            OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.StackTrace, ex.Message);
        }
    }

    public void SendData(string Data)
    {
        try
        {
            if (Data.EndsWith("\r\n"))
            {
                RunCommandAsync(Data, SshCommandRx);
            }
            else
            {
                RunCommandAsync(String.Format("{0}\r\n",Data), SshCommandRx);
            }
            //SshCommand Command = myClient.RunCommand(Data);
            //OnDataReceived(this, new DataEventArgs(Command.Result));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.StackTrace, ex.Message);
        }
    }

    private async void RunCommandAsync(String Data, SshCommandCallback Callback)
    {
        Task<SshCommand> T = new Task<SshCommand>(() =>
        {
            try
            {
                SshCommand Command = myClient.RunCommand(Data);
                return Command;
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().ToString());
                return null;
            }
        });

        T.Start();
        await T;
        if (T.IsCompleted)
        {
            Callback(this, T.Result);
        }
    }

    private void SshCommandRx(SshConnection C, SshCommand Command)
    {
        if (Command != null)
        {
            string Rx = Command.Result;
            //if (Rx.StartsWith(Command.CommandText))
            //{
            //    Rx = Rx.Remove(0, Command.CommandText.Length);
            //}
            while (Rx.EndsWith("\r\n\r\n") == false)
            {
                Rx += "\r\n";
            }
            OnDataReceived(this, new DataEventArgs(Rx));
        }
    }

A: I solve it for my self only with connections retrying attempts. Didn't find what exactly the issue is, but have this connection issue many times.
Example:
int attempts = 0;
            do
            {
                try
                {
                    client.Connect();
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    attempts++;
                }
            } while (attempts < _connectiontRetryAttempts && !client.IsConnected);

A: I experienced the same odd error message when attempting to connect to a SFTP server while using the SSH.NET library in a program on the server. The problem did not appear while testing from my development machine.
The solution was to have our server team add the IP address of the server into the hosts.allow file on the SFTP Linux server.


text:
Q: I upgraded to react 16.0 then I have to install npm install prop-types package separately. But some node modules even not updated What should I do? Because I have to check lot of dependency. When I upgraded after I changed my files but when it's running I gotta errors from some node modules files. It's error showing one by one. When one file fixed, then have to run again and then showed it again another node module Proptypes undefined.
[this is error , i have got from node modules ]1

A: Try updating all the the Packages by npm update or give a npm outdated and check whether if some of them are not updated yet. Let me know if its fixed

A: It depends on the node modules you are using some may still use the old PropTypes From react package, so you may need to fork it and update it yourself.


text:
Q: Return unique mongo document I have a collection. Below are the sample documents
{
"bannerUserSessionId" : "565269c7d52ece855050b3b7bd4ae8d6f52161871394e2d312c340a086f93314",
"bannerId" : "<String> kitchen-chimneys||1488286849020|HP|PromoBanner4",
"bannerEventLabel" : "<String> kitchen-chimneys",
"bannerPage" : "HP",
"bannerWidget" : "PromoBanner4",
"bannerClickTimestamp" : "Mar 04, 2017 15:05:56 PM"
}
{
"bannerUserSessionId" : "565269c7d52ece855050b3b7bd4ae8d6f52161871394e2d312c340a086f93314",
"bannerId" : "<String> kitchen-   chimneys||1488286849020|HP|PromoBanner4",
"bannerEventLabel" : "<String> kitchen-chimneys",
"bannerPage" : "HP",
"bannerWidget" : "PromoBanner4",
"bannerClickTimestamp" : "Mar 04, 2017 15:06:19 PM"
}

Is it possible to query mongodb in such a way that I'll get unique document as above two documents are same except different timestamp object?
So I want only one record.

A: You can $group by keys and pick the $first timestamp value.
db.collection.aggregate([{
    $group: {
        _id: {
            "bannerUserSessionId": "$bannerUserSessionId",
            "bannerId": "$bannerId",
            "bannerEventLabel": "$bannerEventLabel",
            "bannerPage": "$bannerPage"
        },
        "bannerClickTimestamp": {
            $first: "$bannerClickTimestamp"
        }
    }
}])


text:
Q: If $p:\tilde{X} \longrightarrow X$ is a covering map and $X$ locally path connected, then prove that $\tilde{X}$ is locally path connected. If $p:\widetilde{X} \longrightarrow X$ is a covering map and $X$ locally path connected, then prove that $\widetilde{X}$ is locally path connected. I try to prove it by these arguments.
Let $\widetilde{x} \in \widetilde{X}$ and $U$ be a open neighborhood of $\widetilde{x}$. Since $p$ is a covering map, $p$ is an open map and $f(U)$ is open. Since $X$ is locally path connected, there exists an open neighborhood $U'$ of $p(\widetilde{x})$ which is path connected. Then $p^{-1}(U') \subset U$ is open. We will show that $p^{-1}(U')$ is path connected.
Since $p$ is a covering map, there exists open neighborhood of $U"$ of $p(\tilde{x})$ that is evenly covered by $p$. Let $p^{-1}(U'')=\bigsqcup_{j \in J} V_j$. Hence, $U' \cap U" \subset U''$ is an open neighborhood of  $p(\widetilde{x})$ and $p^{-1}(U'' \cap U')$ is open.
Because $U' \cap U'' \subset U''$, $U' \cap U''$ is evenly covered by $p$ and $p^{-1}(U' \cap U'')=\bigsqcup_{j \in J} V_j$ with $p|_{V_j}:V_j \longrightarrow U' \cap U''$ is a homeomorphism.
Claim : $V= p^{-1}(U' \cap '')$ is path connected. Take $\widetilde{y} \in V$. Suppose that $\widetilde{x} \in V_1$ and $\widetilde{y} \in V_2$. We will find a path $\widetilde{f}$ in $V$ from $\widetilde{x}$ to $\widetilde{y}$. Since $p(\widetilde{x}), p(\widetilde{y}) \in U'$, there exists path  $f:I \longrightarrow U'$ with $f(0)=p(\widetilde{x})$ and $f(1)=p(\widetilde{y})$.
But I have a problem to find the $\widetilde{f}$. Am I on the right path? Can you give me some suggestions ? Thank you.

A: Let $p:\widetilde{X}\to X$ be a covering map and $x\in \widetilde{X}$. The crucial observation is that since $p$ is a covering map then there is some open neighbourhood $V\subseteq X$ of $p(x)$ and some open neighbourhood $U\subseteq\widetilde{X}$ of $x$ such that the restriction $p_{|U}:U\to V$ is a homeomorphism. The way we utilize this is that preimages of (path)connected subsets via homeomorphism are again (path)connected.
Now let $U'\subseteq\widetilde{X}$ be an arbitrary open neighbourhood of $x$. We want to show that $U'$ has an open path connected subneighbourhood. Consider $U''=U'\cap U$ and note that $p(U'')$ is an open neighbourhood of $p(x)$. Since $X$ is locally path connected, then $p(U'')$ has a path connected subneighbourhood $V'\subseteq p(U'')\subseteq V$ of $p(x)$. And since $p_{|U}:U\to V$ is a homeomorphism then $p_{|U}^{-1}(V')=p^{-1}(V')\cap U$ is an open path connected subneighbourhood of $U''$, and ergo of $U'$, which completes the proof.

A: If $y \in \widetilde{X}$ then we can find a path-connected evenly covered neighbourhood $U$ of $x=p(y)$ and let the component of $p^{-1}[U]$ that contains $y$ be called $O_y$. So $p$ is a homeomorphism between $O_y$ and $U$.
If now $O$ is any open neighbourhood of $y$, $O \cap O_y$ is also an open neighbourhood of $y$ and $p[O \cap O_y]$ is an open neighbourhood of $x$ and so contains a path-connected neighbourhood $P$ and then $p^{-1}[P]$ is a path-connected neighbourhood of $y$ inside $O$, as required.


text:
Q: File.open failes in chef recipe when read from json The below with hardcoded file path works
File.open('/cm/Chef/instnst.loc', 'w') do |f2|
  # use "\n" for two lines of text
  f2.puts "inventory_loc=#{orainsloc}\ninst_group=dbas"
end

But when I change it to read from a JSON parameter, it errors. What am I doing wrong?
File.open('#{node['installParams']['InstallFilesLocation']}/instnst.loc', 'w') do |f2|
  # use "\n" for two lines of text
  f2.puts "inventory_loc=#{orainsloc}\ninst_group=dbas"
end

A: #{} formatting has be inside double quotes like "#{node['installParams']['InstallFilesLocation']}/instnst.loc".


text:
Q: How to remove namespace in xslt using xslt I am trying to get xhtml o/p .I have used xmlns="http://www.w3.org/1999/xhtml" in
<xsl:stylesheet>

to get xhtml o/p.Every thing is fine but in the first div I am getting the same namespace. i.e.
 <div  xmlns="http://www.w3.org/1999/xhtml">

Now how to remove xmlns="http://www.w3.org/1999/xhtml"

A: As others have pointed out, you may not want to do this. If you want the output to be XHTML, you need to keep the XHTML namespace declaration.
That being said, if you really want to do it:
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- attributes, commments, processing instructions, text: copy as is -->
  <xsl:template match="@*|comment()|processing-instruction()|text()">
    <xsl:copy-of select="."/>
  </xsl:template>

  <!-- elements: create a new element with the same name, but no namespace -->
  <xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

A: Why would you want to remove the namespace? It's part of the XHTML specification, and you say you want XHTML output. So - where's the problem?
Apparently you start your output with <div>, otherwise you would have the namespace declaration on the <html> element.


text:
Q: How can I stop Firefox's autocomplete from overriding jQuery autocomplete? I am losing my mind over this.
I have an extremely simple form that uses jQuery autocomplete to query my database, and return a list of store/customer names as the user types. It looks like this:
<form action="/" name="myForm" id="myForm" autocomplete="off">
    <input type="text" name="my_autocomplete" autocomplete="off">
    <input type="submit" value="Submit">
</form>

I have 'autocomplete="off" set on both the form and the input field. However, after selecting anything and submitting the form, Firefox refuses to stop autofilling the field, overriding the jQuery autocomplete and rendering some values un-selectable:

I have been Googling and I can't seem to find anyone else having this issue.
What am I doing wrong? Could it be a Firefox bug in v51?

Update to add: Apparently, this is actually happening for all input fields that utilize autocomplete, not just my own application, including sites like Apple and Amazon:

This is happening both on Firefox 51 on Mac, and Firefox 38 on Linux, which I find extremely odd, given that I've been on v38 for quite some time and never remember this happening until the last few weeks. I'm so stumped.

A: Try adding style="display:none" to your input.
But, i suggest try reinstalling your firefox because the auto complete also appear on other website like amazon which is not normal. Also try reseting your firefox to factory setting
https://support.mozilla.org/en-US/kb/reset-preferences-fix-problems


text:
Q: Lennard-Jones / WCA Potential Simulation i am trying to implement a molecular dynamics simulation with the Lennard Jones potential.
I have the time evolution of the positions and velocities of the particles in multiple config files (n = 0,...,99) in steps of dt, such that t=n dt. So the actual simulation part is taken care of in that sense, for now i only have to calculate the potential energy and the force on each particle.
I already implemented a function to read in the config.dat files and put them in vectors, that part works as far as i know without an error. Then i wrote functions that calculate the force and the potential energy with a given distance r_ij between two particles (also used Newtown's  third law so that i don't have to calculate the forces multiple times for the same interaction).
I also (hopefully correctly) implemented the periodic boundary conditions so that the particles can interact with their own images in the image boxes.
To test if my code works, i wanted to plot the total potential energy for all t=n dt.
However that does not work as intended because for some reason the potential energy that is written into the output files is always zero (the function for the potential energy returns zero if r_ij > r_cut, r_cut is where the potential is set to zero).
#include <iostream>
#include <math.h>
#include <fstream>
#include <stdlib.h>
#include <vector>
#include <string>
#include <utility>
#include <stdexcept>
#include <sstream>

using namespace std;
// Python >> C/C++

// Reads the initial states from the files
// The whole simulation in Python would have been as long as the function in c++ that just reads in the input
void read_input(int num_file, vector<double>& n, vector<double>& x, vector<double>& y, vector<double>& vx, vector<double>& vy, double& lx, double& ly) {
    // Variable file name + opening it
    ifstream file("configurations/config_" + to_string(num_file) + ".dat");

    // Temp variables for reading in the file
    double num, temp_x, temp_y, temp_vx, temp_vy;

    // Looping over it
    if (file.is_open()) {
        string line;
        while (getline(file, line)) {
            // For the header; The header contains only the dimensions, e.g, 14 14, there are only 5 characters
            if (line.length() == 5) {
                stringstream dim_str(line);
                dim_str >> lx >> ly;
                continue;
            }
            // For the rest files
            stringstream temp_str(line);
            temp_str >> num >> temp_x >> temp_y >> temp_vx >> temp_vy;
            n.push_back(num);
            x.push_back(temp_x);
            y.push_back(temp_y);
            vx.push_back(temp_vx);
            vy.push_back(temp_vy);
        }
        file.close();
    }
}

// Calculates the potential for rij
double calc_pot(double r) {
    double sigma = 1.0;
    double epsilon = 1.0;
    if (r <= pow(2, (1.0 / 6)) * sigma) {
        double res = 4.0 * epsilon * (pow(sigma / r, 12) - pow(sigma / r, 6)) + epsilon;
        return res;
    }
    else {
        return 0;
    }
}

// Calculates the force for rij
double calc_force(double r) {
    double sigma = 1.0;
    // Replaced the sigma^n with 1 bcs sigma = 1
    double epsilon = 1.0;
    if (r <= pow(2, (1.0 / 6)) * sigma) {
        double res = (48.0 * epsilon / pow(r, 13)) - (24 * epsilon / pow(r, 7));
        return res;
    }
    else {
        return 0;
    }

}
// Calculates the distance of the
double dist(double rx, double ry) {
    return sqrt(rx * rx + ry * ry);
}

int main() {
    // Misc. parameters
    int N = 144;
    double mass = 1.0;
    double sigma = 1.0;
    double epsilon = 1.0;
    // Tau = sqrt(mass*sigma^2/epsilon) = (here) 1
    double tau = 1.0;
    double dt = 0.02;

    // Vectors for the read in values for i and i+1
    vector<double> n, x, y, vx, vy;
    double lx, ly;

    // Vector for the potential and two for the force, x and y
    vector<double> epot(N), f_x(N), f_y(N);
    for (int i = 0; i < N; i++) {
        epot[i], f_x[i], f_y[i] = 0;
    }

    // Outerloop for time steps (in this case the files n = {0,..,99})
    for (int k = 0; k <= 99; k++) {
        string fname = "output/epot_" + to_string(k) + ".txt";
        ofstream output(fname);
        read_input(k, n, x, y, vx, vy, lx, ly);
        // Inner two loops to accses every possible interaction without doing them twice
        for (int i = 0; i < N - 1; i++) {
            // Vecctor for particle i
            double rix = x[i];
            double riy = y[i];
            for (int j = i + 1; j < N; j++) {
                // Vector for particle i+1
                double rjx = x[j];
                double rjy = y[j];
                // Periodic boundary cond.
                if (rix > lx) {
                    rix -= lx;
                }
                if (riy > ly) {
                    riy -= ly;
                }
                if (rjx > lx) {
                    rjx -= lx;
                }
                if (rjy > ly) {
                    rjy -= ly;
                }
                if (rix < 0) {
                    rix += lx;
                }
                if (riy < 0) {
                    riy += ly;
                }
                if (rjx < 0) {
                    rjx += lx;
                }
                if (rjy < 0) {
                    rjy += ly;
                }
                // Component wise distance for the force
                double dist_x = rix - rjx;
                double dist_y = riy - rjy;

                // Minimum image convention
                if (abs(dist_x) > lx / 2) {
                    dist_x = (lx - abs(dist_x)) * (-dist_x) / abs(dist_x);
                }
                if (abs(dist_y) > ly / 2) {
                    dist_y = (ly - abs(dist_y)) * (-dist_y) / abs(dist_y);
                }

                // Normalized Force/R
                f_x[i] += calc_force(dist_x) * (1 / dist(dist_x, dist_y));
                f_y[i] += calc_force(dist_y) * (1 / dist(dist_x, dist_y));
                f_y[j] += -calc_force(dist_x) * (1 / dist(dist_x, dist_y));
                f_y[j] += -calc_force(dist_y) * (1 / dist(dist_x, dist_y));

                // Potential energy
                epot[i] += calc_pot(dist(dist_x, dist_y));
            }
            // Potential energy per particle
            output << fixed << std::setprecision(4) << epot[i] / (N) << endl;
        }
    }
}

A config file looks something like this
14 14
0 0 0 1.0292605474705 0.394157727758591
1 0 1.16666666666667 1.05721528014223 1.9850461002085
2 0 2.33333333333333 1.18385526103892 0.143930912297367
3 0 3.5 -0.938850340823852 1.71993225409788
4 0 4.66666666666667 1.99468650405917 0.952210892864475
5 0 5.83333333333333 -0.985361963654284 3.05201529674118
6 0 7 2.84071317501321 0.0689241023507716
7 0 8.16666666666667 3.56152464385237 2.88858201933488
8 0 9.33333333333333 0.147896423269195 1.40592679110988

The header contains the dimensions of the simulation box, here (14,14).
Then all the lines have the corresponding values of {#Particle, x, y, velocity x, Velocity y).
The file above shows this for the first 9 particles.
I am relatively new to c/c++ so have mercy with me .
Also i am aware that the code has still potential to be optimised but i will deal with that when i can calculate the force on each particle correctly.
Edit:
Here is the formula for the potential energy:

The force can be calculated via F= -d/dr U(r).


text:
Q: beta2 maxRotation set to 0 causes labels to overlap I'm using a Chart.js beta 2 line chart. I'd like my x axis labels not to rotate, because it messes up my layout. I'm setting the options to have the ticks.maxRotation property set to 0. When I do so the labels are not skipped properly, but overlap instead.
this.options = {
    scales: {
        xAxes: [{
            ticks: {
                maxRotation: 0
            }
        }]
    }
};

I also tried providing a ticks.userCallback to only show certain labels and skip myself, however I found doing this not only removes the label from the xAxis display, but also from the tooltip. I always want the tooltips to display the label.
So, what is the best way to keep labels oriented at 0 rotation and not have them overlap ?


text:
Q: Convert string to float in Python ' 0,3638412' Im trying to convert a string to a float
with the float function:

   pointsx = float(x)

got error:
>ValueError: could not convert string to float: ' 0,3638412'

Any ideas on how to fix this?

A: This should work:
pointsx = float(x.replace( ',', '.'))

Floating point numbers use dot . as a separator, not the comma.

A: you are applying the correct method but are you sure the value of x is '0,3638412'.
if it is wrong then you need to change the value of x.
x = '0.3638412'
pointsx = float(x)

if it is right then the code given below solves your value.
pointsx = float(x.replace(',','.'))


text:
Q: Restrictions on drop collections on mongodb Is there a way to add a restriction when deleting collections that are referenced by id in other collections using mongodb or mongoose?
I need something like "on delete restrict" from sql to use on mongodb.

A: References from one collection to another are not explicit. So Mongo has no way to know that an ObjectId property in a document refers to the id of another document, nor in which collection. So I believe it's not possible to have such restrictions.

A: MongoDB doesn't support this feature, you can implement in your own application.
Keep a refcount field in your document to track referenced count.
db.coll.remove({refcount: 0})


text:
Q: An exercise in fuzzy logics built from a t-norm (I also asked this in MathOverflow)
Consider the following t-norm:
$
a * b = \begin{cases}
       \text{$2ab,$} &\quad\text{if $a, b$}\le1/2\\
       \text{$min\{a, b\}$} &\quad\text{otherwise}\\
      \end{cases}
$
We build from it the $\langle [0, 1]_*, \{1\}\rangle$ matrix logic as usual. Thus, the resulting R-implication and associated negation are:
$
a \rightarrow b = \begin{cases}
       \text{1} &\quad\text{if $a \le b$}\\
       \text{$b/2a$} &\quad\text{if 1/2 $\ge a>b$}\\
        \text{$b$} &\quad\text{if a > b and a > 1/2}\\
      \end{cases}
$
$
¬ a = \begin{cases}
       \text{1} &\quad\text{if $a = 0$}\\
       \text{0} &\quad\text{otherwise}\\
      \end{cases}
$
As usual, $\wedge$ is the minimum and $\lor$ is the maximum.
For this logic, I need to prove the following implication, for any formulas $\phi$ and $\psi$:
$ \phi \rightarrow \phi * \phi, \phi \models \psi$ implies $ \phi \rightarrow \phi * \phi \models \phi \rightarrow \psi$
This is equivalent to showing the following:
if for any $[0, 1]_*$-interpretation I, we have $I(\phi) = 1 \Rightarrow I(\psi) = 1$
then for any $[0, 1]_*$-interpretation I, we have $I(\phi) \ge 1/2 \Rightarrow I(\psi) \geq I(\phi)$

A: My teacher has provided a solution:
Take a $[0, 1]_*$-interpretation with $I(\phi \rightarrow \phi * \phi ) = 1$, and say $a:=I(\phi)$.
Define the function \begin{align*}
h: [0, 1] & \rightarrow [0, 1]\\
x&\mapsto \begin{cases}
       1 &\quad\text{if $x \geq a$}\\
       x &\quad\text{if $x < a$}
      \end{cases}
\end{align*}
We can check this function preserves all of the connectives of the logic. So $h \circ I$ preserves connectives and is thus a $[0, 1]_*$-interpretation. And $h \circ I (\phi \rightarrow \phi * \phi) = h \circ I (\phi) = 1 $, so by our supposition $h \circ I (\psi) = 1$ and thus $I(\phi) \leq I(\psi)$.