text:
Q: Merging two dataframes without losing data I have two dataframes:
df_1 =
Material    TypeOf
4100          N200
4101          M200
4200          M200
4500          N200
...

df_2=
Material       Ms      Number1      Number2 ...
4000          PAK            1            1
4100          PAK            1            2
4101          PIE            2            2
4101          BOX            3            2
4102          BOX            2            2
4200          PAK            1            1
4200          BOX            2            3
...

I want to add to the second table the TypeOf, which can obviously achieved by just merging the two on Material. But there are lots of Materials that cannot be found in the second table, and I do not want to end up with half of the second dataframe. Is there any way of still adding the desired column, merging the two, but putting something like NaN for the records whose TypeOf cannot be found?

A: In the join documentation, there's a how parameter :
how{'left', 'right', 'outer', 'inner'}, default 'left'
How to handle the operation of the two objects.

left: use calling frame's index (or column if on is specified)

right: use other's index.

outer: form union of calling frame's index (or column if on is specified) with other's index, and sort it. lexicographically.

inner: form intersection of calling frame's index (or column if on is specified) with other's index, preserving the order of the calling's one.

cross: creates the cartesian product from both frames, preserves the order of the left keys.

What pandas does on default is the left join, .
Meaning that it matches the left dataframe's column elements but discards when there are no matches.
In your case, you might want an outer join. Matches in the columns will be next to each other but you'll discard no rows from either dataframe.


text:
Q: How to run kafka rest proxy on windows How to run kafka rest proxy on windows.
I downloaded confluent-2.0.1-2.11.7.tar.gz
in windows folder i cannot see kafka-rest-start.

A: Windows isn't currently a supported platform. However, it should work fine if you adapt the script. Even just running java io.confluent.kafkarest.KafkaRestMain with the appropriate classpath should work.

A: Here's the example of the command they are actually executing in the end of the bash script:
java -Xmx256M -server -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:+DisableExplicitGC -Djava.awt.headless=true -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dlog4j.configuration=file:C:/Dev/kafka/confluent-4.0.0/etc/kafka-rest/log4j.properties -cp .;C:/Dev/kafka/confluent-4.0.0/target/kafka-rest-*-development/share/java/kafka-rest/*;C:/Dev/kafka/confluent-4.0.0/share/java/confluent-common/*;C:/Dev/kafka/confluent-4.0.0/share/java/rest-utils/*;C:/Dev/kafka/confluent-4.0.0/share/java/kafka-rest/* io.confluent.kafkarest.KafkaRestMain C:/Dev/kafka/confluent-4.0.0/etc/kafka-rest/kafka-rest.properties

Make sure you change paths to yours if you want to try it out.

A: Perhaps, this answer will help anybody who is new to Kafka and stumble upon this situation, like me :).
I was looking for an answer to the very same question a week ago, came across the official suggestion to run jar files(in this path confluent-x.x.x\share\java\kafka-rest) in windows and was NOT successful in doing so.
Always ran into this error no main attribute found with or without specifying the proper classpath and io.confluent.kafkarest.KafkaRestMain.
I even tried running the shell scripts packaged for Linux distribution using [babun]: http://babun.github.io/, but that resulted in the error like Error: Could not find or load main class io.confluent.kafkarest.KafkaRestMain .
Eventually, docker image built with zookeeper, kafka, schema-registry, kafka-rest worked like a charm.
Here is the official page with info about the image name, further reference to it's doc: https://hub.docker.com/r/confluentinc/cp-kafka-rest/
Upon pulling this image, a new virtual machine gets created with four more images inside it(one for each service like zookeeper, Kafka, schem-registry and Kafka-rest). Running the images runs a separate Docker container.
This guide should get you started quickly:
http://docs.confluent.io/current/cp-docker-images/docs/quickstart.html
And finally, if you would like to expose the kafka REST proxy server running as a Docker container to outside network(like windows machine which is part of the separate network than these containers) just mention the Docker host IP(find it by hitting docker-machine ip <hostname>) in KAFKA_REST_LISTENERS and expose the port with -p option.
Like this:
docker run -d \
  --net=host \
  --name=kafka-rest \
  -p 8082:8082 \
  -e KAFKA_REST_ZOOKEEPER_CONNECT=localhost:32181 \
  -e KAFKA_REST_LISTENERS=http://192.168.99.100:8082 \
  -e KAFKA_REST_SCHEMA_REGISTRY_URL=http://localhost:8081 \
  -e KAFKA_REST_HOST_NAME=localhost \
  confluentinc/cp-kafka-rest:3.2.1

If everything is OK, you will be able to access REST proxy at this url http://<Docker_host_IP>:8082 from the windows machine.

A: I was able to run the command that @lexler mentioned above, but outside of cygwin. (directly with the windows command prompt.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load content into div, and resize the div using jQuery
Possible Duplicate:
jQuery Animation - Smooth Size Transition

I have a div #infoMenu, whose content is being replaced with the following code:
function infoMenu(worldID) {
    $('#infoMenu').load('main.php?worldID='+worldID+'&menu #infoMenu').html('Loading...');
}

I wonder if I can animate the div's height instead of it just "jumping" into diffrent heights depending on the new content´s space.
Thanks!

A: Try adding a callback function:
function infoMenu(worldID) {
    $('#infoMenu')
        .load('main.php?worldID='+worldID+'&menu #infoMenu', function(data){
          $('#infoMenu').animate({ height: '500px' }, 1000);
        })
        .html('Loading...');
}

But make sure the css has a set height and overflow: hidden;

Edit: Better yet, set the overflow:scroll then animate to the scrollHeight:
$('#infoMenu').animate({ height: $('#infoMenu')[0].scrollHeight }, 1000);


text:
Q: Does touching something cause quantum entanglement? Disclosure: I'm pretty uneducated when it comes to quantum entanglement.
I was aware that there are a few ways for particles to become entangled. Is physical interaction one of them?
I read this question and answer: Quantum entanglement question
Then I thought when I touch something, does that mean that trillion trillions of particles in my fingers have become partially or maximally entangled with the particles in the thing?
Say I touch a wall, is my hand partially quantumly entangled with the wall?

A:
Say I touch a wall, is my hand partially quantumly entangled with the wall?

In principle yes, though in practice there is a process called decoherence that removes the entanglement of massive objects so fast that it could never be observed. So your hand is not entangled with the wall in any physically meaningful sense.
The Schrodinger equation for any system (including your hand is):
$$ -\frac{\hbar^2}{2m}\nabla^2\Psi + V\Psi = -i\hbar\frac{d}{dt}\Psi \tag{1}$$
and to understand entanglement the key parameter is the potential term $V$. Suppose we have $n$ particles at positions $r_1$, $r_2$ etc up to $r_n$. If the particles do not interact with other we can write this potential as a sum of a separate potential for each particle:
$$ V = V_1(r_1) + V_2(r_2) + \ldots + V_n(r_n) \tag{2} $$
In this case the Schrodinger equation can be separated into  sum of separate equations for each particle, and the total wavefunction can be written as a product:
$$ \Psi = \psi_1(r_1)\psi_2(r_2) \ldots \psi_n(r_n) \tag{3} $$
This is what we mean by an unentangled system. Each particle is described by a wavefunction that does not depend on the positions of any other particle.
But suppose the particles do interact. Then the potential will contain terms that depend on the relative positions of the particles i.e. it will contain terms that depend on $r_i - r_j$. In that case the potential cannot be written in a form like equation (2), and the wavefunction will not have a form like equation (3). This is an entangled system. It's entangled because the position of one particle affects all the other particles.
This makes it clear what we mean by the term interaction. It is anything that causes the potential to depend on the relative positions of the particles. In the case of physically touching a wall the interaction obviously depends on the relative position of your hand and the wall, so your hand and the wall will (in principle) become entangled.


text:
Q: HTTP 500 error with Simple.OData.Client when authenticating I keep getting a 500 error when trying to create the ODataClient and passing in ODataSettings with new NetworkCredentials(username, password). Anyone have any examples of creating this service with Basic Authentication?

A: I enabled basic authentication for a sample OData Web site, and then I was able to access it using Simple.OData.Client and the following code:
var settings = new ODataClientSettings();
settings.UrlBase = "http://localhost/ProductService/odata";
settings.Credentials = new NetworkCredential("Tester", "tester123");
var client = new ODataClient(settings);

If it doesn't work for you I suggest you check if it works when you disable basic authentication and open the site for anonymous access. If it still doesn't work, then the problem is with something else. Otherwise let me know what platform and Simple.OData.Client version you are using (I tested on .NET 4.0, .NET 4.5 and Simple.OData.Client v.2.0.0).


text:
Q: Is there a Dropdown on extend event? I want to run a function that is always triggered when I open a certain Dropdown(Select). The first thing I tried was an onclick event in the select tag, but the problem is that the function is also triggered when I click any option inside the Dropdown.
The function should go through all input fields with a certain class-Name and take their values to build the options of the dropdown, which is working all right. The thing is, i can't choose one of the options as the fillDropdownReq()-function is always triggered after i try to choose something.
Is there any way to just trigger the event when i open the dropdown?

function fillDropdownReq(DD){
    let dropdown = $('#'+DD.id);

    dropdown.empty();

    dropdown.append('<option disabled>choose Prerequisite</option>');
    dropdown.prop('selectedIndex', 0);

    $(".fieldName_checkbox").each(function (){
        dropdown.append($('<option></option>').attr('value', $(this).val()).text($(this).val()));
    })
}
.fieldName_checkbox{
  float: left;
  margin: 5px;
}

.select_div{
  float: right;
  margin: 25px;

}

<input class="fieldName_checkbox" id="fieldName_checkbox1" value="testvalue1">
<input class="fieldName_checkbox" id="fieldName_checkbox2" value="testvalue2">

<select id="fieldPrerequisitesSelect" onclick="fillDropdownReq(this)">
  <option selected="true" disabled>choose Prerequisite</option>
</select>

A: There is no 'extended' or 'opened' event available for select elements.
One workaround for this case would be to invert your logic; populate the option elements in the select whenever the user interacts with any of the input fields used to create their values, something like this:

let $select = $('#fieldPrerequisitesSelect');
let updateOptions = () => {
  let options = $fields.map((i, el) => `<option value="${el.value}">${el.value}</option>`).get();
  options.unshift('<option selected="true" disabled>choose Prerequisite</option>');
  $select.html(options);
}

let $fields = $('.fieldName_checkbox').on('input', updateOptions);
updateOptions();
.fieldName_checkbox {
  float: left;
  margin: 5px;
}

.select_div {
  float: right;
  margin: 25px;
}

<input class="fieldName_checkbox" id="fieldName_checkbox1" value="testvalue1" />
<input class="fieldName_checkbox" id="fieldName_checkbox2" value="testvalue2" />

  <select id="fieldPrerequisitesSelect">
    <option selected="true" disabled>choose Prerequisite</option>
  </select>

Update...
Based on your comment under the question:

I would have to do that... when a new 'select' element is created fill that with options as well

Then you can just use clone() to create a new select as required, and convert the id to a class so that you can update the options within all select elements at the same time. The code for that would look like this:

let updateOptions = () => {
  let options = $fields.map((i, el) => `<option value="${el.value}">${el.value}</option>`).get();
  options.unshift('<option selected="true" disabled>choose Prerequisite</option>');
  $('.fieldPrerequisitesSelect').html(options);
}

let $fields = $('.fieldName_checkbox').on('input', updateOptions);
updateOptions();

$('.duplicate-select').on('click', e => {
  let $clone = $('.select_div:first').clone().insertAfter('.select_div:last');
  $clone.find('select').prop('selectedIndex', 0);
});
input,
button,
.select_div {
  margin: 0 0 10px;
}

<input class="fieldName_checkbox" id="fieldName_checkbox1" value="testvalue1" />

<input class="fieldName_checkbox" id="fieldName_checkbox2" value="testvalue2" />

<button type="button" class="duplicate-select">Duplicate select</button>

  <select class="fieldPrerequisitesSelect">
    <option selected="true" disabled>choose Prerequisite</option>
  </select>


text:
Q: Database is locking but all statements are followed by commit? I'm working on an IRC bot, forked from a modular bot called Skybot.
There are two other modules that make use of the sqlite3 database by default; they have both been removed and their tables dropped, so I know that the issue is somewhere in what I'm doing.
I only call 3 db.execute() statements in the whole thing and they're all immediately committed. This thing isn't getting hammered with queries either, but the lock remains.
Relevant code:
def db_init(db):
    db.execute("create table if not exists searches"
               "(search_string UNIQUE PRIMARY KEY,link)")
    db.commit()

    return db

def get_link(db, inp):
        row = db.execute("select link from searches where"
                         " search_string=lower(?) limit 1",
                         (inp.lower(),)).fetchone()
    db.commit()
    return row

def store_link(db, stub, search):
    db.execute("insert into searches (search_string, link) VALUES (?, ?)", (search.lower(), stub))
    db.commit()
    return stub

If the script only has to touch db_init() and get_link() it breezes through, but if it needs to call store_link() while the database is unlocked it will do the insert, but doesn't seem to be committing it in a way that future calls to get_link() can read it until the bot restarts.
The bot's db.py:
import os
import sqlite3

def get_db_connection(conn, name=''):
"returns an sqlite3 connection to a persistent database"

if not name:
    name = '%s.%s.db' % (conn.nick, conn.server)

filename = os.path.join(bot.persist_dir, name)
return sqlite3.connect(filename, isolation_level=None)

bot.get_db_connection = get_db_connection

I did adjust the isolation_level myself, that was originally timeout=10. I am fairly stumped.
EDIT: The usages of get_db_connection():
main.py (main loop):
def run(func, input):
args = func._args

if 'inp' not in input:
    input.inp = input.paraml

if args:
    if 'db' in args and 'db' not in input:
        input.db = get_db_connection(input.conn)
    if 'input' in args:
        input.input = input
    if 0 in args:
        out = func(input.inp, **input)
    else:
        kw = dict((key, input[key]) for key in args if key in input)
        out = func(input.inp, **kw)
else:
    out = func(input.inp)
if out is not None:
    input.reply(unicode(out))

...
def start(self):
    uses_db = 'db' in self.func._args
    db_conns = {}
    while True:
        input = self.input_queue.get()

        if input == StopIteration:
            break

        if uses_db:
            db = db_conns.get(input.conn)
            if db is None:
                db = bot.get_db_connection(input.conn)
                db_conns[input.conn] = db
            input.db = db

        try:
            run(self.func, input)
        except:
            traceback.print_exc()

A: Send conn in your functions, along with db, as mentioned. If you wrote the code yourself, you'll know where the database actually is. Conventionally you would do something like:
db      = sqlite3.connect('database.db')
conn    = db.cursor()

Then for general usage:
    db.execute("...")
    conn.commit()

Hence, in your case:
def db_init(conn,db):
    db.execute("create table if not exists searches"
               "(search_string UNIQUE PRIMARY KEY,link)")
    conn.commit()

    return db

def get_link(conn,db, inp):
        row = db.execute("select link from searches where"
                         " search_string=lower(?) limit 1",
                         (inp.lower(),)).fetchone()
    conn.commit()
    return row

def store_link(conn,db, stub, search):
    db.execute("insert into searches (search_string, link) VALUES (?, ?)", (search.lower(), stub))
    conn.commit()
    return stub

A: On the basis that you have set the isolation_level to automatic updates:
sqlite3.connect(filename, isolation_level=None)

There is no need whatsoever for the commit statements in your code
Edit:
Wrap your execute statements in try statements, so that you at least have a chance of finding out what is going on i.e.
import sqlite3
def get_db(name=""):
    if not name:
        name = "db1.db"
    return sqlite3.connect(name, isolation_level=None)
connection = get_db()
cur = connection.cursor()
try:
    cur.execute("create table if not exists searches"
               "(search_string UNIQUE PRIMARY KEY,link)")
except sqlite3.Error as e:
    print 'Searches create Error '+str(e)
try:
    cur.execute("insert into searches (search_string, link) VALUES (?, ?)", ("my search", "other"))
except sqlite3.Error as e:
    print 'Searches insert Error '+str(e)
cur.execute("select link from searches where search_string=? limit 1", ["my search"])
s_data = cur.fetchone()
print 'Result:', s_data


text:
Q: how to make responsive table with bootstrap need help to make table responsive.
On this size everything is ok:

but when screen size is reduced im getting smth like this:

table is displayed on col-md-7:

Turnyrinė lentelė

                                        Vieta
                                        Komanda
                                        Sužaista
                                        Perg.
                                        Lyg.
                                        Laim.
                                        Įm.
                                        Pr.
                                        +/-
                                        Taškai

                                        01
                                        Banani FC
                                        60
                                        35
                                        08
                                        16
                                        02
                                        04
                                        11
                                        95

EDITED:
If i trying to add max and min width, marked place is reducing too much:

A: I've had a look into your second example.
the troubling part is obviously your title bar, whose elements are inside the class ritekhela-fancy-title-two
And you have a wrapping div around this class, named row, this div needs to get set to adapt its width to the nested content.
Since fit-content is experimental and not available at all browsers, you'll need set width to auto and make it behave as an inline block
Then you must set the width of your ritekhela-fancy-title-two class to auto and remove the float:left, or set it to float:none and it will neither overflow on larger screens or not expand to the width of table on smaller screens.
that's it, check the fiddle with above changes implemented
these are the two css styles which were changed/added:
.row {
    width: fit-content; /*works with Chrome, but not with FF*/
    width: auto;
    display: inline-block;
}

.ritekhela-fancy-title-two {
    float: none;
    width: auto;
    padding: 12px 20px 12px 60px;
    border-top: 7px solid;
    background: url(/css/images/transparent-pattren.png);
    position: relative;
    margin-top: 30px;
    background-color: #6c757d;
}

edit: as above changes also affect the lower title bars, which is easy to correct, adding some height to the second row:
.ec-nextmatch {
    border: 1px solid #f3f3f3;
    border-top: none;
    background-color: #fff;
    margin-bottom: 60px;
    float:none;
    height:90px;
    width:auto;
}

also remove .ec-nextmatch from this css, so it looks now:
.ec-team-matches, .ec-match-countdown, .ec-match-countdown .countdown-row, .ec-ticket-button {
    float: left;
    width: 100%;
}

A: If you want to avoid the hassle of reducing font sizes, table cells widths, etc. I would recommend using the Bootstrap responsive table utility, basically makes the table scroll horizontally. Can be achieved like so...
...

        ...

...


text:
Q: React-admin, how to properly handle auth error on dataProvider? I am trying to integrate an authenticated data provider into React-Admin but I am having trouble when the data provider does not yet have a valid auth token from the auth provider.
I am using https://github.com/des-des/ra-postgraphile-client
My code to instantiate the data provider looks like this:
const dataProvider = buildPostgraphileProvider({
  apolloHttpLinkOptions: {
    uri: `http://localhost:5433/graphql`,
    fetch: (url, options) => {
      // You can add custom auth logic with a wrapper around fetch
      const token = localStorage.getItem("token");

      if (!token) {
        return;
      }
      if (jwt.decode(token).exp < Date.now()) {
        localStorage.removeItem("token");
        return;
      }

      const headers = {
        ...options.headers,
        authorization: `bearer ${token}`
      };
      return fetch(url, { ...options, headers });
    }
  }
});
console.log(dataProvider);

I expected when React-Admin received an error from the data provider, it would redirect back to the homepage. But instead it throws an unhandled rejection.
Unhandled Rejection (Error): Network error: Cannot read property 'then' of undefined
new ApolloError
src/errors/ApolloError.ts:46
  43 | // Constructs an instance of ApolloError given a GraphQLError
  44 | // or a network error. Note that one of these has to be a valid
  45 | // value or the constructed error will be meaningless.
> 46 | constructor({
     | ^  47 |   graphQLErrors,
  48 |   networkError,
  49 |   errorMessage,

I also tried to return a HTTPError when no token is present:
return new HttpError("denied", 403, { status: 403 });

And got a different result:
Unhandled Rejection (Error): Network error: fetcher(...).then is not a function


text:
Q: "maven.compiler.release" as an replacement for source and target? I have two questions about maven.compiler.release-tag
I want to replace
<properties>
    <maven.compiler.source>12</maven.compiler.source>
    <maven.compiler.target>12</maven.compiler.target>
</properties>

to
<properties>
     <maven.compiler.release>12</maven.compiler.release>
</properties>

If I use <maven.compiler.release>-property, do I have to set the release tag also in the plugin?
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <!-- do I need that ? -->
        <release>12</release>
    </configuration>
</plugin>

According to https://www.baeldung.com/maven-java-version, it is set to both.
If I use maven.compiler.release instead of maven.compiler.source and maven.compiler.target, then -bootclasspath is also set and will do a cross-compile. What does this mean? Will the compilation file sizes with set -bootclasspath be bigger or will the compilation need more time?

A: Simply the property <maven.compiler.release>12</maven.compiler.release> is sufficient. And you don't need to set also the configuration for maven-compiler-plugin. The configuration for release tag is automatically picked up.
The bootclasspath part is automatically done by using the --release option. The size of files is not related to that...
So simple suggestions use release part for JDK9+ otherwise source/target...

A: The "simple suggestion" in the other answer won't work correctly because unfortunately the situation is not simple. The compiler options mean slightly different things. The maven.compiler.source and maven.compiler.target options refer to the source code format and the format of the generated class files, respectively. But they do not take into account API changes as maven.compiler.release does.
So if you blindly just use <maven.compiler.source>8</maven.compiler.source> and <maven.compiler.target>8</maven.compiler.target>, if you build using Java 11 for example the generated class files will support Java 8 but the API may still rely on Java 11 changes and break when run on Java 8. See How should javac 11 link methods overridden in later versions with a Java 8 target? for more discussion.
The solution is not so simple if you want to designate Java 8 but build on Java 9+. You'll need to specify the source and target as you are doing, using compiler options supported by Java 8:
<properties>
  <maven.compiler.source>8</maven.compiler.source>
  <maven.compiler.target>8</maven.compiler.target>
</properties>

Then you'll need to set up a separate profile in the <profiles> section that is only activated in Java 9+ to turn on the maven.compiler.release option:
<profile>
  <id>java-8-api</id>
  <activation>
    <jdk>[9,)</jdk>
  </activation>
  <properties>
    <maven.compiler.release>8</maven.compiler.release>
  </properties>
</profile>

That way if you build on Java 9+, maven.compiler.release will come into effect and restrict the API to be compatible with Java 8. If you build on Java 8, the other two options will set the source code and class file format to Java 8, and the API will be Java 8 compatible by definition.
The better option for everyone involved of course is just to move to Java 11 as soon as possible.


text:
Q: Rudin's Dowker space is collectionwise normal I am trying to follow K.P. Hart's course Set-theoretic methods in general topology. In Chapter 6, Rudin's Dowker space $X$ is defined as follows. Let $P=\prod_{n=1}^\infty(\omega_n+1)$ be the box product of the successors of the first $\omega$-many uncountable ordinals, let $X'=\{x\in P:(\forall n)\,\operatorname{cf} x_n>\omega\}$, and let $X=\{x\in X':(\exists i)(\forall n)\ \operatorname{cf}x_n<\omega_i\}$. Exercise 2.8 asks to show that $X$ is collectionwise normal, using the following hint: prove that if $\mathcal{F}$ is a discrete family of closed subsets of $X$ then $\mathcal{F}'=\{\operatorname{cl}_{X'}F:F\in\mathcal{F}\}$ is a discrete family of closed subsets of $X'$.
It was already proved that disjoint closed sets in $X$ have disjoint closures in $X'$. I can prove that the space $X'$ is collectionwise normal, and using the statement of the hint I can also show that $X$ is collectionwise normal. But somehow I am not able to prove the hint.
Question: Is it true that if $Y\subseteq Y'$ are topological spaces, disjoint closed subsets of $Y$ have disjoint closures in $Y'$, and $\mathcal{F}$ is a discrete family of closed subsets of $Y$, then $\mathcal{F}'=\{\operatorname{cl}_{Y'}F:F\in\mathcal{F}\}$ is a discrete family of closed subsets of $Y'$? We can also assume that $Y$ and $Y'$ are normal. Or is that a special property of the above spaces $X$, $X'$?

A: The hint is a classical fact. No need for any assumptions on $X$. So suppose $\mathcal{F}$ is a discrete family. To see that $\{\overline{F}: F \in \mathcal{F}\}$ is also discrete, let $x \in X$ . Then $x$ has an open neighbourhood $O_x$ such that $\left|\{ F \in \mathcal{F}: O_x \cap F \neq \emptyset\}\right| \le 1$. But $O_x \cap F = \emptyset$ implies $O_x \cap \overline{F} = \emptyset$ (as for any $p \in O_x$, $O_x$ is a witnessing neighbourhood that $p \notin \overline{F}$), and this means that $O_x \cap F \neq \emptyset$ iff $O_x \cap \overline{F} \neq \emptyset$, so $O_x$ also intersects at most one set of the form $\overline{F}$, $F \in \mathcal{F}$, i.e.the family of closures is discrete.

A: I think that I finally got it. No assumptions on the spaces are needed.
Spaces $X$, $Y$ are not related to the spaces mentioned in the question.
Lemma 1.
Let $\mathcal{F}$ be a discrete family of closed subsets
of a topological space $X$.
Then $\bigcup\mathcal{F}$ is closed.
Proof.
If $x$ belongs to the closure of $\bigcup\mathcal{F}$
then every neighborhood of $x$ intersects at least one
set $F\in\mathcal{F}$.
Since $\mathcal{F}$ is a discrete family,
there exists an open neighbourhood $U$ of $x$
and a set $F\in\mathcal{F}$ such that $U\cap G=\emptyset$
for every $G\in\mathcal{F}\setminus\{F\}$.
It follows that $U\cap V\cap F\neq\emptyset$ for any open
neighbourhood $V$ of $x$, hence $x$ belongs to the closure
of $F$.
Since $F$ is closed, we have
$x\in F\subseteq \bigcup\mathcal{F}$.
Lemma 2.
Let $X$ be a subspace of a topological space $Y$
such that any two closed disjoint subsets of $X$ have
disjoint closures in $Y$.
Let $\mathcal{F}$ be a discrete family of closed subsets
of $X$.
Then $\mathcal{F}'=\{\operatorname{cl}_Y(F)\!:F\in\mathcal{F}\}$ is a discrete family of closed subsets of $Y$.
Proof.
Let $y\in Y$.
We have to find an open neighbourhood of $y$ that
intersects at most one member of $\mathcal{F}'$.
If $y\in\bigcup\mathcal{F}'$ then there exists
$F\in\mathcal{F}$ such that $y\in\operatorname{cl}_Y(F)$.
Let us denote $\mathcal{G}=\mathcal{F}\setminus\{F\}$.
Then $\mathcal{G}$ is a discrete family of closed subsets
of $X$.
By the above lemma, $\bigcup\mathcal{G}$ is closed in $X$.
Since $F$ and $\bigcup\mathcal{G}$ are disjoint closed
subsets of $X$, their closures in $Y$ are disjoint,
hence $y\notin\operatorname{cl}_Y(\bigcup\mathcal{G})$.
The set
$U=Y\setminus\operatorname{cl}_Y(\bigcup\mathcal{G})$
is an open neighbourhood of $y$ that is disjoint to
every set $\operatorname{cl}_Y(G)$ for $G\in\mathcal{G}$,
hence $U$ intersects at most one member of $\mathcal{F}'$.
If $y\notin\bigcup\mathcal{F}'$ then
$Y\setminus\bigcup\mathcal{F}'$ is an open neighborhood
of $y$ that is disjoint to any member of $\mathcal{F}'$.


text:
Q: Jenkins plugin - environment variables I am using Jenkins with Testswarm and this plugin (forked sources).
I want to get a "job name" for Testswarm containing the Jenkins job name, build number and svn revision number.
Putting JOB_NAME in the configuration field does not help, the variable is not replaced by its value.
So I modified the plugin source code to get the Jenkins environment variables but all I get are "null"s.
Here is the culprit code. (in src/main/java/com/javaclimber/jenkins/testswarmplugin/TestSwarmBuilder.java from line 205)
I researched a lot concerning this functionnality and I did not find a working example for getting a variable.
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    ...
EnvVars envVars = build.getEnvironment(listener);
    ...
    envVars.get("JOB_NAME")
}

I am not at ease in Java and I am stuck at this point.
Any idea anyone, please ?
Update: java used version
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.5) (6b24-1.11.5-0ubuntu1~10.04.2)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)

A: Replacing
EnvVars envVars = build.getEnvironment(listener);

By
EnvVars envVars = new EnvVars();
envVars = build.getEnvironment(listener);

did the trick...

A: What version of Java are you using?
According to this, to get an environment variable, you need to add the following:
String job_name = System.getenv("JOB_NAME");

Have you tried this instead?
Also, I'm not sure what the configuration field looks like, but did you try using $JOB_NAME instead of JOB_NAME ?

A: Jenkins pipelines appear to execute on the server, so the original post may be missing a variable defined for the agent (either via the server's agent definition or via the agent's OS).
I don't know the Jenkins pipeline way of obtaining the agent's environment.

A: I stumbled over this and searched a while for a solution, so for the next user the answer: If you need the environment variables, overwrite
public void perform(Run<?, ?> run, FilePath workspace, EnvVars env, Launcher launcher, TaskListener listener)
instead of
public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener)
and use the EnvVars from the parameters. (See also https://issues.jenkins.io/browse/JENKINS-29144)


text:
Q: Relativizing with respect to $P$ and $\neg P$ In this and this questions, relativization occurs with respect to new unary preicates $P$ and $Q$. For example, if the sets $X$ and $Y$ are spectra, say of the $L$-sentence $\varphi$ and the $K$-sentence $\psi$, respectively (where $L$ and $K$ are disjoint relational first order languages). Then the set
$$X+Y=\{\mbox{$m+n$ : $m\in X$ and $n\in Y$}\}$$
is the spectrum of the $L\cup K\cup\{P,Q\}$-sentence
$$\varphi^{P}\wedge\psi^{Q}\wedge (\forall x\,(Px\Leftrightarrow\neg Qx)),$$
were $P$ and $Q$ are new unary predicates, and $\varphi^{P}$ and $\psi^{Q}$ are the relativizations of $\varphi$ and $\psi$ to $P$ and $Q$, respectively.
Question: Could we simply relativize with respect to $P$ and $\neg P$. That is, $Q$ is simply $\neg P$? The sentence would become $\varphi^{P}\wedge\psi^{\neg P}$. But it seems there may be circumstances when this is not satisfiable, as we have the predicate $P$ in common. Or, where else is the pitfall?


text:
Q: Custom :hover animation from Javascript Im currently filling an element with data that contins spritesheet animations. this animations have custom dimensions so i cant really use any static css. using css3 i managed to define the keyframes like this:
@-webkit-keyframes play {
    from { background-position: 0px; }
    to { background-position: calc(-100% + 32px + 1px); }
}

now i want to only play the animation on hover like this
.emoticon:hover {
    -webkit-animation: play 1000ms steps(10) infinite;
}

but this only works when the spritesheet got 10 frames. what is a good way to do this without creating 100 different classes?


text:
Q: laravel controller redirect just shows in console, doesn't actually redirect the page I have a simple controller that redirects upon completion, but when it completes it just shows me the URL and page in my console but the actual page doesn't redirect at all, just stays static
Controller.php
function saveImages(Request $request) {

    $data = $this->service->save(
        $request->type,
        $request->image,
    );

    return Redirect::to(route('images.show', $data))->send();
}

My console shows 302 found and then shows the correct url of 'site.com/images/show/45' and 45 is indeed the returned value.
Why isn't the actual page redirecting?

A: Try
return response()->redirectToRoute('images.show')->with($data);

A: I'm new on coding but i use redirect like this,
Did you try;
 return redirect(route('images.show', $data))->send();


text:
Q: How To detect a specific Extension that communicate with my webpage In my webpage i want to make a script to detect a specific extension that manipulate my code
I've already tried the following in my webpage
async function tst(){
    debugger;
    window.addEventListener("PassToBackground", function(evt) {
        var blockedExID="bjnkkhimoaclnddigpphpgkfgeggokam";
    if (!chrome.runtime) {
        // Chrome 20-21
        chrome.runtime = chrome.extension;
    } else if(!chrome.runtime.onMessage) {
        // Chrome 22-25
        chrome.runtime.onMessage = chrome.extension.onMessage;
        chrome.runtime.sendMessage = chrome.extension.sendMessage;
        chrome.runtime.onConnect = chrome.extension.onConnect;
        chrome.runtime.connect = chrome.extension.connect;
    }
    var runtimeOrExtension = chrome.runtime && chrome.runtime.sendMessage ?
                         'runtime' : 'extension';

   var reponse= chrome[runtimeOrExtension].sendMessage(blockedExID,{ message: "version" },{
        function (reply) {
            if (reply) {
            alert(reply);
            }
    }

});
chrome[runtimeOrExtension].sendMessage({greeting: 'hello'});

        }, false);
}

but chrome.runtime is undefiled


text:
Q: How to convert values of a matrix into percentage without changing the format in R I have a matrix which is res
 > res
                     [,1]         [,2]       [,3]       [,4]       [,5]
        [1,]  0.025431667  0.024636307 0.02812685 0.02733088 0.02807624
        [2,] -0.005383589  0.000000000 0.02807624 0.02258878 0.02322090
        [3,] -0.002674251 -0.002674251 0.05502400 0.00000000 0.01385476
        [4,]  0.055024000  0.061028259 0.05932779 0.05956794 0.05839394
        [5,]  0.059327790  0.059567938 0.05839394 0.06048811 0.05944368

I want to have the results as percentage and keep the data structure unchanged.
When I try something like percent(res) from scales I get a vector instead of a matrix
> percent(res)
 [1] "2.54%"  "-0.54%" "-0.27%" "5.50%"  "5.93%"  "2.46%"  "0.00%"  "-0.27%"
 [9] "6.10%"  "5.96%"  "2.81%"  "2.81%"  "5.50%"  "5.93%"  "5.84%"  "2.73%"
[17] "2.26%"  "0.00%"  "5.96%"  "6.05%"  "2.81%"  "2.32%"  "1.39%"  "5.84%"
[25] "5.94%"

Any suggestions?

A: You could do:
require(scales)
set.seed(1) # Just for reproducibility
res <- matrix(data = rnorm(20), nrow = 5, ncol = 4)

 > res
           [,1]       [,2]       [,3]        [,4]
[1,] -0.6264538 -0.8204684  1.5117812 -0.04493361
[2,]  0.1836433  0.4874291  0.3898432 -0.01619026
[3,] -0.8356286  0.7383247 -0.6212406  0.94383621
[4,]  1.5952808  0.5757814 -2.2146999  0.82122120
[5,]  0.3295078 -0.3053884  1.1249309  0.59390132

res[] <- percent(res)

> res
     [,1]   [,2]   [,3]    [,4]
[1,] "-63%" "-82%" "151%"  "-4%"
[2,] "18%"  "49%"  "39%"   "-2%"
[3,] "-84%" "74%"  "-62%"  "94%"
[4,] "160%" "58%"  "-221%" "82%"
[5,] "33%"  "-31%" "112%"  "59%"

A: the function percent of formmattable package work fine with matrix :
library(formattable)
    percent(res)

and this is the result :
     X..1.  X..2.  X..3. X..4. X..5.
[1,] 2.54%  2.46%  2.81% 2.73% 2.81%
[2,] -0.54% 0.00%  2.81% 2.26% 2.32%
[3,] -0.27% -0.27% 5.50% 0.00% 1.39%
[4,] 5.50%  6.10%  5.93% 5.96% 5.84%
[5,] 5.93%  5.96%  5.84% 6.05% 5.94%

A: And also:
require(scales)
mat <- matrix(rexp(200, rate=.1), ncol=5, nrow=5)
> mat
           [,1]     [,2]      [,3]       [,4]      [,5]
[1,]  0.8633327  0.59608  4.255264  4.9075876 14.690223
[2,] 13.3531120 33.97510  9.292887  9.2030803  8.963202
[3,] 10.9540116 13.00999  3.345536 12.0012241 16.985236
[4,]  8.7139062 40.25450 22.578629  0.7283414  1.389453
[5,] 15.0364007 11.74895  8.764188 13.8024305  9.303271
> res <- apply(mat, 2, function(x) percent(x/100))
> res
     [,1]    [,2]    [,3]    [,4]    [,5]
[1,] "0.9%"  "0.6%"  "4.3%"  "4.9%"  "14.7%"
[2,] "13.4%" "34.0%" "9.3%"  "9.2%"  "9.0%"
[3,] "11.0%" "13.0%" "3.3%"  "12.0%" "17.0%"
[4,] "8.7%"  "40.3%" "22.6%" "0.7%"  "1.4%"
[5,] "15.0%" "11.7%" "8.8%"  "13.8%" "9.3%"
> res <- apply(mat, 2, function(x) percent(x)) #or without '/100' if you want 9% instead of 0.9%


text:
Q: Export Excel Chart To Word Using PasteFormat is Returning Error 4605 Command Not Available So I'm trying to understand what is wrong with my code. All I'm doing is taking some charts in my Excel workbook and exporting them to a Word document but I keep getting an error if I try to paste them a certain way. Here's my code:
Sub ExportingToWord_MultiplePages2()

    'Declare Word Variables
    Dim WrdApp As Word.Application
    Dim WrdDoc As Word.Document

    'Declare Excel Variables
    Dim ChrtObj As ChartObject

    'Create a new instance of Word
    Set WrdApp = New Word.Application
        WrdApp.Visible = True

    'Create a new word document
    Set WrdDoc = WrdApp.Documents.Add

    'Loop through the charts on the active sheet
    For Each ChrtObj In ActiveSheet.ChartObjects

        'Copy the chart
        ChrtObj.Chart.ChartArea.Copy

        **'THIS WON'T RETURN AN ERROR**
        With WrdApp.Selection
            .PasteAndFormat Type:=wdChartPicture
        End With

        '**THIS WILL RETURN THE ERROR**
        With WrdApp.Selection
            .PasteAndFormat Type:=wdChartLinked
        End With

        'Clear the Clipboard.
        Application.CutCopyMode = False

    Next ChrtObj

End Sub

This is the weird part because I've provided two different ways to paste, the first one I paste it as a chart picture and that works fine. However, if I try wdChart or wdChartLinked it won't work! I get Error 4605 "Command Not Avaiable".
Any thoughts as to why this would be the case?

A: So I found a workaround to the problem, but I'm still not sure why PasteFormat will not work with a linked chart.
If I replace:
'**THIS WILL RETURN THE ERROR**
With WrdApp.Selection
    .PasteAndFormat Type:=wdChartLinked
End With

With the following, I no longer get an error:
'**THIS WILL NOT RETURN AN ERROR**
With WrdApp.Selection
    .PasteSpecial Link:=True, DataType:=wdPasteOLEObject
End With

I guess it has to do something with the format of the chart or something, but I still find it strange that I can paste it as a picture using PasteFormat but not as a linked chart.


text:
Q: Unable to click button using ng-click for AngularJS application I am automating AngularJS application and need help for ng-click.
Here is the HTML code:
Create Project

I tried the code below:
.//a[ng-click='openProjectModal($event)']

Using xpath is working, but i don't want to use xpath.

A: since it is a link 1st think is you have to javascriptvoid(); to stop it redirection.
and in your controller you should have to write openProjectModal function
i.e
Create Project

$scope.openProjectModal = function(event){
  .............
  .............
 }

it will might help you


text:
Q: which repository will maven choose inside settings.xml If I define two repositories in my settings.xml, which repositories will maven choose during build?
Like below, codehausSnapshots1 or codehausSnapshots2 ?
<profiles>
  <profile>
    <repositories>
      <repository>
        <id>codehausSnapshots1</id>
        ......
      <repository/>
      <repository>
        <id>codehausSnapshots2</id>
        ......
      <repository/>
    </repositories>
  </profile>
</profiles>

A: It is using both of them. There is a certain order which repository maven looks first, what next and so on. If Maven fails to download artifact from the first repo, it will try download it from the next repo. Maven looks repositories first from settings.xml, then project's pom.xml and lastly parent pom's repositories. Also, order of declared repositories matter. In this example, maven looks codehausSnapshots1 repository first as it is declared before codehausSnapshots2.


text:
Q: В чём ошибка? argv Учу Python по книге. И не понимаю, в чём ошибка. В книге указано, что если выдаёт ошибку, как в моём случае, то я дал 3 значения, а не 4, но, я дал 4.
Код:
from sys import argv

script, first, second, third = argv
print("1:", script)
print("2:", first)
print("3:", second)
print("4:", third)

Вывод консоли:

A: Первым аргументом передаётся название скрипта, поэтому пользовательских аргументов ожидается всего 3.
Консоль:
python test.py spam bacon eggs

stdout:
1: test.py
2: spam
3: bacon
4: eggs


text:
Q: Factorial will not multiply When I run the code it doesn't multiply my number it just outputs in a loop until it reaches 1
I have tried multiple different ways and this one is the closest i've gotten
    ......................................
    var BR="
"; //html line break

    function factorial(Num) {

   document.write("The factorial of your number is" +Num +BR);

   if (Num == 1 ) return 1;

   else return (Num * factorial(Num-1));

    }
.....................................................

   .......................................
        var Num; //users number
        var Numfactorial;
        var ES="";
               var factorial
        Num=prompt("Enter a number between 1-20" +ES);
        Numfactorial=factorial(Num);
     .........................................

It's supposed to take the number and multiply it down, so say you put in 20 it should go 19*18*17... down until it multiplies 1 and then outputs the product.

A: Place the document.write outside your function, and just print the result (Numfactorial) to the page. You also need to parse Num to a number, and remove var factorial:
var BR = "
";
function factorial(Num) {
    if (Num == 1) return 1;
    else return Num * factorial(Num - 1);
}
var Num;
var Numfactorial;
var ES = "";
Num = parseInt(prompt("Enter a number between 1-20" + ES));
Numfactorial = factorial(Num);
document.write("The factorial of your number is " + Numfactorial + BR);

A: Well, that is the expected output of your code. Your function factorial is returning your value which you aren't using to display the value. You should instead write it like this:
....................................................
var BR="
"; //html line break
function factorial(Num) {
   if (Num == 1 ) return 1;
   else return (Num * factorial(Num-1));
}
.....................................................

.......................................
    var Num; //users number
    var Numfactorial;
    var ES="";
           var factorial
    Num=prompt("Enter a number between 1-20" +ES);
    Numfactorial=factorial(Num);
    document.write("The factorial of your number is" +Numfactorial +BR);
 .........................................


text:
Q: Complicated bar graph for measurements in z dimension and time I am writing code to analyze data that for each data point there is a value, a vertical z dimension height associated with it, and the time at which it was taken.  I would like to have a bar graph that contains all this information.  The measurements are taken for a large interval of time at one height, then move down to the next height, then the next, then back up again.  So I want the bar graph to reflect the height change by plotting the measurement displayed in time at three different levels on the y axis.  I have stored the heights, time, and measurements in a structured array.
I don't have the reputation yet to post pictures, but here is a sketch:
.....|....||||...||........................|||||||.................................................................................................................
.....|....|||||||||........................|||||||.................................................................................................................
.....|....|||||||||........................|||||||.................................................................................................................
.....|................||..||.......................................................................................................................................
.....|................|||||||.......................................................................................................................................
.....|............................|||||||...........................................................................................................................
     _________________________________________________

This is what I've tried:
for i = 11:numel(MARbckDATA.averageDepth)
    y = -1*MARbckDATA.averageDepth(i)

    figure(3);

bar(MARbckDATA.seconds(i), (-1*MARbckDATA.averageDepth(i)) + (MARbckDATA.area(i)), 'BaseValue',y);

 hold on

end

However, the x axis only has the last time in it. Why is this, and what's the proper way to do it?


text:
Q: Iphone SDK: move image around with the accelerometer Im trying to move an image around with the accelerometer by doing that:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    image.center = CGPointMake(acceleration.x, acceleration.y);

}

When i test the app, the image that is supposed to move around just sits in the x0 y0 position.
I declared the accelerometer, called the .h UIAccelerometerDelegate and so on...
What am i doing wrong?
Thanks in advance! -DD

A: You do realize that the accelerometer returns, as the name would suggest, measures of acceleration not points on the display? Anyway, what you need to do, is alter the center (not replace it completely), which will allow you to move the image.
Something along these lines:
image.center = CGPointMake(image.center.x + acceleration.x,
                           image.center.y - acceleration.y);

It is also important to note that the acceleration usually stays between -1 and 1 (unless the user shakes the device), which is due to the gravity being 1G. Therefore you should probably multiply the acceleration.x and .y values with some constant to make the image move a bit faster than about 1 point at a time.
There are additional things you should think about, what if the image is at the edge of the screen? What if the user wants to use the app in some other position than flat on a surface (needs calibration of the accelerometer)?

A: -(void)moveImage:(id)sender
{
    [operationView bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];

    [[[(UIPanGestureRecognizer*)sender view] layer] removeAllAnimations];

    CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];

    if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan)
    {
    firstX = [[sender view] center].x;
    firstY = [[sender view] center].y;
        [imgDeleteView setHidden:FALSE];
    }
    else if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded)
    {
        [imgDeleteView setHidden:TRUE];
    }

    translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
    [[(UIPanGestureRecognizer *)sender view] setCenter:translatedPoint];
 }


text:
Q: APK installation from Android studio 3 to Samsung with Android 9 gets stuck I'm using Android Studio 3.4 on Linux Debian 9 x64 and phone Samsung SM-A10 with Android 9 Pie.
Phone is completely new and clean with latest security patch.
Every time I'm installing apk directly from Android Studio to the phone, I have to re-plug USB cable, otherwise installation stucks with "Installing..." message in status bar of the Studio. No any error messages.
What is weird - my other phones with Android 7, 8 works well - Android Studio installs the same project well, every time I click "Run" icon.
But with Samsung A10 (Android 9), the situation always looks like:

*

*The phone connected with a USB cable

*I click the "Run" icon in the Studio

*Installation gets stuck with "Install..." status

*I re-plug USB cable and click "Run" again.

*Apk installs well.

...

*

*I click "Run" again (does not matter if the previous app removed from the phone or not)

*Installation gets stuck

*I have to re-plug cable again

Also, when I download big (>100mb) file from this phone (with "adb pull ...") it gets stuck too and was solved with cable reconnect for few attempts.
What I've tried:

*

*reboot phone

*reboot PC

*re-enable USB debugging in Android developer menu

*enable "Instant Run" (usually I'm not using it)

*run other apps

*run debugging in Android Studio - does not start at all, gets stuck on different steps (loading some library, mostly); No error messages too


text:
Q: How to set solver for control loop simulation? I have been developing a simulation of the field oriented control of the three
phase squirrel cage induction motor (control is oriented by the rotor flux).
I have been using the Xcos which is an equivalent of the Simulink software.
The simulation block diagram looks in this manner

Basically there are three main blocks

*

*IM model
-state space model of the induction motor in the continuous time domain

*Observer
-discrete block which calculates the unmeasurable components of the rotor
flux space vector

*Vector control
-discrete block which calculates reference values of the components of the
stator voltage based on given reference value of the flux and torque
components of the stator current
I used the default setting of the Xcos solver i.e.

As soon as I start the simulation I receive following error message:
Simulation problem: CVode: At t=0.78087, mxstep steps taken before reaching tout
comming from the IM model block

and the simulation ends. I have attempted to find some information about this error and I have found that it is caused by an algebraic loop detected by the solver and it can be solved by reducing solver tolerances in the simulation setup. I thought that the algebraic loop is broken by the first order low pass filters at the inputs of the S/H blocks. Nevertheless I tried to reduce the solver tolerances

and I run the simulation again. This resulted into another error message -
Simulation problem: singularity in a block again comming form the IM model block. This time from different place

Can anybody give me an advice how to resolve this issue or tell me what is going
on in my simulation? Thank you in advance for any ideas.

A: This problem solved by change to RK45 - Runge-Kutta 4(5) solver. Scilab 6.1.1


text:
Q: Android: Paging on custom class created from HorizontalScrollView is not smooth I am trying to create an infinite pager from a HorizontalScrollView.
It does infinitely scroll by continuously rearranging the children views as needed, but once it has to start moving the views (adding to the left or the right) it is no longer scrolling smoothly. I am trying to figure out how to get it to scroll to the next page smoothly even after it changes the child position.
Here is the class as I have it so far:
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

public class PagerInfinite extends HorizontalScrollView {
    private LinearLayout contents;
    private Map<Integer, Integer> childWidths =  new HashMap<Integer, Integer>();
    private int childSpacing = 0;
    private int activePageIndex = 1;
    private float oldX = 0f;
    private float oldY = 0f;
    private boolean firstScroll = true;

public PagerInfinite(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.contents = new LinearLayout(context);
    this.contents.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
    this.addView(this.contents);
    setVerticalScrollBarEnabled(false);
    setHorizontalScrollBarEnabled(false);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    for (int i = 0; i < this.contents.getChildCount(); i++) {
        View child = this.contents.getChildAt(i);
        int width = child.getWidth();
        if(width != 0) {
            this.childWidths.put(i, width);
        }
    }
    if(this.childWidths.size() > 0 && this.firstScroll) {
        this.smoothScrollTo(this.getActivePageOffset(), 0);
        this.firstScroll = false;
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected float getLeftFadingEdgeStrength() {
    return 0.0f;
}

@Override
protected float getRightFadingEdgeStrength() {
    return 0.0f;
}

public void addPage(View child) {
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.setMargins(0, 0, this.childSpacing, 0);
    child.setLayoutParams(params);
    if(this.contents.getChildCount() <= 1) {
        this.contents.addView(child);
    } else if(this.contents.getChildCount() <= 2) {
        this.contents.addView(child, 0);
    } else {
        View last = this.contents.getChildAt(0);
        this.contents.removeView(last);
        this.contents.addView(last);
        this.contents.addView(child, 0);
    }
    this.contents.requestLayout();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    boolean result = super.onTouchEvent(event);

    switch(event.getAction()) {
        case(MotionEvent.ACTION_DOWN):
            this.oldX = event.getX();
            this.oldY = event.getY();
            break;
        case(MotionEvent.ACTION_UP):
            float newX = event.getX();
            float newY = event.getY();
            float deltaX = newX - this.oldX;
            float deltaY = newY - this.oldY;

            // Use deltaX and deltaY to determine the direction
            if(Math.abs(deltaX) > Math.abs(deltaY)) {
                if(deltaX > 0) {
                    // right
                    if(this.activePageIndex <= 1) {
                        this.buildLeft();
                    } else {
                        this.activePageIndex -= 1;
                    }
                } else {
                    // left
                    if(this.activePageIndex >= this.contents.getChildCount() - 2) {
                        this.buildRight();
                    } else {
                        this.activePageIndex += 1;
                    }
                }
            }
            this.smoothScrollTo(this.getActivePageOffset(), 0);
            break;
    }

    return result;
}

private void buildLeft() {
    View view = this.contents.getChildAt(this.contents.getChildCount() - 1);
    this.contents.removeView(view);
    this.contents.addView(view, 0);
}

private void buildRight() {
    View view = this.contents.getChildAt(0);
    this.contents.removeView(view);
    this.contents.addView(view);
}

private int getActivePageOffset() {
    Log.d(LCHApplication.TAG, "ActiveIndex = " + this.activePageIndex);
    if(this.activePageIndex == 0) {
        return 0;
    }
    if(this.activePageIndex == this.contents.getChildCount() - 1) {
        return this.contents.getWidth();
    }
    int offset = 0;
    for(Map.Entry<Integer, Integer> entry : this.childWidths.entrySet()) {
        if(entry.getKey() < this.activePageIndex) {
            offset += entry.getValue() + this.childSpacing;
        } else {
            break;
        }
    }
    offset += (this.childWidths.get(this.activePageIndex) / 2);
    offset -= (LCHApplication.instance.width / 2);
    return offset;
}

public boolean hasPage(View v) {
    return this.contents.indexOfChild(v) != -1;
}

public void removePage(View v) {
    int index = this.contents.indexOfChild(v);
    this.contents.removeView(v);
    this.childWidths.remove(index);
}

public int getCurrentPageIndex() {
    return this.activePageIndex;
}

public int getPageCount() {
    return this.contents.getChildCount();
}

public void removeAllPages() {
    this.contents.removeAllViews();
    this.childWidths = new HashMap<Integer, Integer>();
}

public void cycle() {
    if(this.activePageIndex < this.contents.getChildCount() - 1) {
        this.activePageIndex += 1;
    } else {
        this.activePageIndex = 0;
    }
    this.smoothScrollTo(this.getActivePageOffset(), 0);
}

public int getChildSpacing() {
    return this.childSpacing;
}

public void setChildSpacing(int spacing) {
    this.childSpacing = spacing;
}
}

A: Its too late but I believe my answer may helpful to somebody else who has same issue.
Sample project with infinite pages - with page swipe effect
https://github.com/UdaySravanK/USK_APIs


text:
Q: Using stripe connect with react native I'm currently looking to use the Stripe connect feature in my react native application and was wondering if there were any libraries I could use to use stripe connect. I've looked at react native stripe libraries like tipsi react native but it didn't seem like they support stripe connect. Is there a reference for api I could use to incorporate stripe connect in my application?

A: The best course of action when using Stripe in react native is to just use the native Stripe libraries.
This is due to the security vulnerabilities that exist when not using a Stripe approved library, and due to the lack of support for things like Stripe Connect and other services.
--UPDATE--
While I stand by the above for not using unapproved 3rd party libraries, I will say that Stripe does have an API that can also be used securely. In react native, that would be the way I would go about using stripe if I was not in need of the full Stripe libaries.


text:
Q: Div scrolling issues while zoomed in on mobile device I have a chat log div on my webpage that will scroll fine while on the computer, and it will also scroll fine on mobile while the screen is at the default (zoomed out) position; however, when I zoom in and try to scroll the div, the div will scroll slightly, but unfortunately the entire screen will also scroll (more so than the div)...
Is there a way to prevent this from happening while zoomed?
CSS:
.a
{
    border:1px solid black;
    width:30vw;
    height:30vw;
    position:relative;
    display:inline-block;
    overflow-y:auto;
    overflow:scroll;
    font-size:1.1vw;
    text-align:left;
background-color:white;
}

HTML:

A: If the following doesn't work, and if you're ok with it, share your project source with me through a repo or something.
I was able to seemingly fix the issue (on FF and Chrome emulating an IPhone X) by changing the structure of the message nodes.

.a {
  border: 1px solid black;
  width: 30vw;
  height: 30vw;
  position: relative;
  display: inline-block;
  overflow-y: auto;
  overflow: scroll;
  font-size: 1.1vw;
  text-align: left;
  background-color: white;
}

.msg {
  width: 100%;
  font-size: 1.1vw;
  text-align: left;
}

.name {
  color: blue
}

.msgContent {
  color: black
}

      Name:
      This is a message.

I did not test on an actual phone, so results may vary.


text:
Q: How can I implement a gmail-style label chooser? What's the easiest way to implement (something like) Gmail's interface for labeling messages? Does any javascript library have a widget like this?
http://img294.imageshack.us/img294/7097/36698396.png
Behavior:

*

*Click a label in the dropdown to immediately label the message.

*Check multiple labels and then "Apply" to add multiple labels (not sure I like the "Apply" requirement...)

*Type in the box to narrow down your list of labels. If you narrow it down to 1, pressing enter applies that label.

*Trigger the widget with the shortcut key "L".

A: Horace - you want something really complicated, and you should take into account that even with a lot of pre-made component, it will take some time to get something like this working (not to mention - being pretty :-) ).
Anyway, pre-made components are nice but I often like to hack it myself, free-style like. So here is something I cooked up to get you going: My simple label demo (warning - I only tested this on Firefox 3 and I'm pretty sure that it won't work in anything else).
It is far from being pretty, but the code is pretty straight forward and should be easy to understand.

A: I doubt there is a precooked solution out there that does exactly what you want, but you should be able to put something together yourself with a decent JavaScript library. Something like Ext JS would be ideal for this.
A few API pages of potential interest:

*

*Ext.Panel

*Ext.form.TextArea

*Ext.menu.CheckItem

*Ext.KeyNav

A: I was looking for a similar label implementation, and stumbled on this thread.
I can't add to the JS part of the question, but in terms of the "prettiness" of the labels, you might find the following article/code useful:
CSS Gmail-Like Labels
All the best!


text:
Q: how do I know the data type of database field using PHP,.? I want to know how I can get the datatype of each field in a SQL database using PHP;
I want use this datatype for creating some docs in SOLR.
For Example:
if (datatype == int) then "[field_name] + _i".

So, if I have field bedrooms and the datatype is integer, in SOLR I'll save this field to be bedrooms_i.

A: You can use mysql_fetch_field() to retrieve metadata about fields.
mysql_connect('localhost','user','password');
mysql_select_db('database');

$sql = "SELECT * FROM  your_table";
$result = mysql_query($sql);

$i = 0;
while ($i < mysql_num_fields($result))
{
    $meta = mysql_fetch_field($result, $i);
    echo "<pre>".print_r($meta,TRUE)."</pre>";
    $i++;
}

Here $meta->type will give you the field type.

A: In MySQL you can use the SHOW COLUMNS to get the name, data type, etc. of all fields/columns in a table.

A: For the sake of argument, I'll assume MySQL.
SELECT COLUMN_NAME, DATA_TYPE, {ETC...}
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'your_database' AND
    TABLE_NAME = 'your_table'


text:
Q: How can I fail a TestNG test within a listener Is there a way to, from within an ITestListener implementation, actually fail a test that has already "passed" successfully?
My use case is this: I run all of the tests in my suite and then, at the end of the suite, perform some additional actions. As a result of these actions, I would like for tests that previously "passed" to now be marked as failures.
From within my listener (which is extends TestListenerAdapter), I am calling:
result.setStatus(ITestResult.FAILURE);
result.setThrowable(t);

on some ITestResult objects. Elsewhere in the listener, I have overridden onFinish like so:
@Override
public void onTestFailure(final ITestResult result) {
    super.onTestFailure(result);

    // TODO: This is updating the state of the test, but NOT causing it to fail
    Reporter.setCurrentTestResult(result);
}

When I fail the test, the callback is being executed. The Throwable is added to the test result. Everything happens as I expected it to.
However, both the generated report and the build output are incorrect:
[testng] ===============================================
[testng] <redacted>Tests
[testng] Total tests run: 51, Failures: 0, Skips: 0
[testng] ===============================================

Despite the fact that 3 of these test results are being updated as failures:

Any ideas?

A: I had success with changing the status from FAILURE to SKIP with this approach using IInvokedMethodListener.
The afterInvocation method, where the status can be changed, will not be invoked after the whole test suite completes but after each test method.


text:
Q: had you done something, something else would happen or would have happened? Example with a context (an excerpt from "The Art & Science of Java: An Introduction to Computer Science" by Eric Roberts):

For example, executing the line
println("Top student " + topStudent)
  would produce the following output:
Top student = John Doe (#20456)
Had you left out the implementation of the toString method, Java would instead use the default definition of the toString method from the Object class. The result in that case would be something like this
Top student = John Doe@154865
  which is rather less informative.

I don't really understand what actually made the author choose to use Java would instead use over Java would have instead used in that sentence. To me personally, would have instead used sounds like a better choice because it makes total sense that if you had done something in the past, something different would have happened, but since you didn't do that, it didn't happen either. What gives?

A: *

*Executing this line would produce the following output.

I regard "would produce" as employing the present (or possibly future) tense, indefinite aspect, and subjunctive mode.   The subjunctive "would" is more appropriate than the indicative "will" because this is a conditional result of a hypothetical action.   The conditional proposition is suggested by the gerund "executing", and we can't examine the mode of a gerund.

*

*Had you left that out, Java would instead use the default.

I regard "had left out" as employing the present tense, perfect aspect, and subjunctive mode.   This subordinate clause presents the conditional proposition.   I regard "would use" exactly the same as I regard "would produce" -- present indefinite subjunctive.
Both "would use" and "would produce" are doing the same job and using the same form.
The conditional proposition in both cases could be purely hypothetical.  You need never have executed such a line, and perhaps never will.   You need not have neglected that method, and perhaps never would.
Had you left the class's method out yesterday (and not fixed it since), Java would instead use the default when it runs your code tomorrow.

The "would produce" and "would use" both describe the present (and, because of the meaning of "will", future) behavior depending on the program's condition.   The passage in its entirety is consistent with a present-tense narrative describing hypothetical situations.
I suspect the author wants you to understand that, if you did something different in the past, something would be different in the present.   Your phrasing only suggests that one difference in the past would have caused another difference in the past.


text:
Q: MySQL union query, order by 2 variables Each table (table1 & table2) has its own DATETIME field.
I'm trying to catch id's of the two tables and order them by their DATETIME field.
Example:
Table 1                        Table 2
------------                 -------------
id |  datetime1               id | table1id  | datetime2
------------------------      -----------------------
1  |  2014-09-21 20:31:26     1  | 2         | 2014-09-21 20:31:29
2  |  2014-09-21 20:31:27     2  | 3         | 2014-09-21 20:31:30
3  |  2014-09-21 20:31:28

Table 3
------------
id |  user
------------------------
2  |  phil
3  |  nathalie

My output isn't ordered properly with this query:
SELECT *
FROM (
    SELECT
    1 AS selection,
    table1.id, table1.datetime1,
    table2.datetime2
    table3.user
    FROM Table1
    LEFT OUTER JOIN table2
    ON table1.id = table2.table1id
    LEFT OUTER JOIN table3
    ON table1.id = table3.id

    UNION ALL

    SELECT
    2 AS selection,
    table1.id, table1.datetime1,
    table2.datetime2
    table3.user
    FROM Table1
    INNER JOIN table2
    ON table1.id = table2.table1id
    INNER JOIN table3
    ON table1.id = table3.id
) AS query
ORDER BY table1.datetime1 DESC, table2.datetime2 DESC

Desired data:
from table 2 id: 2, 1,
from table 1 id: 3, 2, 1
So: 2, 1, 3, 2, 1
////EDIT
To people who could be struggling with long and complex MySQL request, please try it in PhpmyAdmin! It will tell you the error!
////EDIT

A: What you really need to do is to consider your schema more carefully. Consider naming the date time columns the same and then running a query like this - http://sqlfiddle.com/#!2/a3b4c/7/0
SELECT selection, id, datetimefoo, user FROM (
  SELECT
    1 AS selection,
    table1.id, table1.datetimefoo,
    table3.user
    FROM table1
    LEFT OUTER JOIN table2
    ON table1.id = table2.table1id
    LEFT OUTER JOIN table3
    ON table1.id = table3.id

  UNION

  SELECT
    2 AS selection,
    table1.id, table1.datetimefoo,
    table3.user
    FROM table1
    INNER JOIN table2
    ON table1.id = table2.table1id
    INNER JOIN table3
    ON table1.id = table3.id

  ) AS T2
ORDER BY datetimefoo DESC

In the SQL fiddle this produces the results closer to what you're looking for. I am still not sure why you need the INNER JOINS on the second query though - there is nothing that you're doing here whcih requires them.
Here is another method that does not require a changing of the column names, but requires an alias for the sortable columns - http://sqlfiddle.com/#!2/ec4bc/3/0
SELECT * FROM (
  SELECT
    1 AS selection,
    table1.id, table1.datetimefoo AS sort_date, -- alias on first table's date
    table2.datetimebar,
    table3.user
    FROM table1
    LEFT OUTER JOIN table2
    ON table1.id = table2.table1id
    LEFT OUTER JOIN table3
    ON table1.id = table3.id

  UNION

  SELECT
    2 AS selection,
    table1.id, table1.datetimefoo,
    table2.datetimebar AS sort_date, -- alias on second table's date
    table3.user
    FROM table1
    INNER JOIN table2
    ON table1.id = table2.table1id
    INNER JOIN table3
    ON table1.id = table3.id

  ) AS T2
ORDER BY sort_date DESC

A: I believe you are over-complicating a rather straight-forward task:
SELECT *
FROM (
    SELECT 1 AS selection, table1.id as id, table1.datetime1 as date FROM Table1
    UNION ALL
    SELECT 2 AS selection, table2.id as id, table2.datetime2 as date FROM Table2
) AS query
ORDER BY date DESC


text:
Q: OfficeJs - How to display modal dialog I am using OfficeJs to create word add-in. In that i want to show modal dialog on click on ribbon button. I have used below API
Office.context.ui.displayDialogAsync(url, {height: 30, width: 20}); to display dialog but it is non-modal dialog. Is there any API to display modal dialog using officeJS.

A: Office.js doesn't provide any other method for displaying dialogs. From MSDN:
The following design considerations apply to dialog boxes:

*

*An Office Add-in task pane can have only one dialog box open at any time. Multiple dialogs can be open at the same time from Add-in Commands (custom ribbon buttons or menu items).

*Every dialog box can be moved and resized by the user.

*Every dialog box is centered on the screen when opened.

*Dialog boxes appear on top of the host application and in the order in which they were created.

Use a dialog box to:

*

*Display authentication pages to collect user credentials.

*Display an error/progress/input screen from a ShowTaskpane or ExecuteAction command.

*Temporarily increase the surface area that a user has available to complete a task.

A: Custom application will load inside side loaded panel or we can say inside iFrame
You can write some restrict code inside your dailog window using check if loaded application running inside sidepanel
function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}


text:
Q: Are the global sections of a vector bundle a projective module?  Given a scheme $X$ with structure sheaf $\mathcal{O}_X$, we can associate to each $\mathcal{O}_X$-module $\mathcal{F}$ its global sections $\Gamma(\mathcal{F})$, which gets the structure of a $\Gamma(\mathcal{O}_X)$-module.

Suppose $\mathcal{F}$ is a vector bundle on $X$. Is then $\Gamma(\mathcal{F})$ a projective $\Gamma(\mathcal{O}_X)$-module of finite rank?

Here are two examples, where it works:

*

*If $X$ is an affine scheme, then a quasi-coherent sheaf is a vector bundle iff its global sections are a projective $\Gamma(\mathcal{O}_X)$-module [of finite rank, as Fred Rohrer pointed out].

*If $X$ is a projective scheme over some field $K$ and $\mathcal{F}$ an arbitrary coherent sheaf on $X$, then $\Gamma(\mathcal{F})$ is a free module of finite rank over the ring of global sections $\Gamma(\mathcal{O}_X) \cong K$. Under some restrictions, we can here also replace the field $K$ by a more general ring.

I would guess that it works in general if the natural map $X \to Spec \Gamma(\mathcal{O}_X)$ is locally free of finite rank [edit: and surjective] or something like this. Probably this fails in general, but I have not yet a (reasonable) counter-example. I am mainly interested here in the case of a quasi-projective scheme over a (not-necessarily algebraically closed) field of characteristic zero, so I would not only be interested in counter-examples but also positive answers to my question for a reasonable subclass of schemes.

A: This is not always a projective module.  Here is the simplest counterexample I can think of, but there are plenty of others.  Let $Y$ be $\text{Spec} k[x,y,z]$, where $k$ is a field.  Let $X$ be the complement of the closed point $\langle x,y,z \rangle$.  Then $\Gamma(X,\mathcal{O}_X)$ equals $k[x,y,z]$ since $k[x,y,z]$ is $S_2$.
Let $M$ be the $k[x,y,z]$-module that is the kernel of the homomorphism of finite free modules $k[x,y,z]^{\oplus 3} \to k[x,y,z]$ with matrix $[x,y,z]$.  Using the Koszul complex, $M$ is also the cokernel of the transpose of this matrix.  This is not a locally free module since the rank of $M/\langle x,y,z \rangle$ is $3$, whereas the rank of $M\otimes_{k[x,y,z]} k(x,y,z)$ equals $2$.  The coherent sheaf $\widetilde{M}$ on $Y$ is not locally free.  However, its restriction to the open subset $X$ is locally free.  Moreover, $\Gamma(X,\widetilde{M}|_X)$ is just $M$ since $M$ is $S_2$.

A: Here is another example that wont work (another variant of Jason Starr's example): consider a local ring $(R,\mathfrak{m})$ and let $U=\mathrm{Spec}\:R-\{\mathfrak{m}\}$ be its punctured spectrum. Assume that $\mathrm{depth}\:R\geq2$ and $\mathrm{Pic}(U)\neq0$. Now $U\hookrightarrow\mathrm{Spec}\:\Gamma(\mathcal{O}_U)$ is locally an isomorphism (the depth condition implies $\Gamma(\mathcal{O}_U)=R$). Now take a nontrivial line bundle $\mathcal{L}$ on $U$. To say that $\Gamma(\mathcal{L})$ is a projective $\Gamma(\mathcal{O}_U)$-module means $\Gamma(\mathcal{L})$ is a free $R$-module (over local rings projective = free). But this is not true because we assumed $\mathcal{L}$ to be a nontrivial line bundle.

A: Obviously, "locally free of finite rank" and surjective doesn't work. Compose Jason Star's morphism with the map $(x,y,z) \to ( (x+1)^2,y,z)$. It is still locally free of finite rank, but is now surjective.


text:
Q: Epilog: Only one point appears in graph I'm trying to graph something for a paper and I want to highlight two points in two function. I am using this code:
    Show[
 Plot[f[x, 50, .5, 1, .8, 3], {x, -3, 3}, PlotRange -> All,
  Epilog -> {Red, PointSize[Large],
    Point[{x[0, 50, .5, 1, .8, 3],
      f[x[0, 50, .5, 1, .8, 3], 50, .5, 1, .8, 3]}]}],
 Plot[f[x, 50, .5, .7, .8, 3], {x, -3, 3}, PlotRange -> All,
  Epilog -> {Green, PointSize[Large],
    Point[{x[0, 50, .5, .7, .8, 3],
      f[x[0, 50, .5, .7, .8, 3], 50, .5, .7, .8, 3]}]}]]

Where
x[cost_, t_, teta_, qa_, qv_, b_] :=
 2 Log[((3/2)*cost +
      Sqrt[(cost^2)*(9/4) + 4 (((t - b) t)^1.5) (1 + teta) qa*qv])] -
  2 Log[2 (1 + teta) qa (t - b)^1.5]

f[x_, t_, teta_, qa_, qv_,
   b_] := ((t - b)^1.5)*
    qa*(1 + teta) E^(-1/8) (1 - Erf[(2 x - 1)/Sqrt[8]]) + (t^1.5)*qv*
    E^(-1/8)*(1 + Erf[(2 x + 1)/Sqrt[8]])

My output however only shows one of the points...Am I doing anything wrong or is it just the programme?

Thank you in advance.

A: The value of Epilog option for Show is taken from the first plot, so the one from the second plot is ignored. As alternative, simply specify the Epilog directly in Show.
epi1 = {Red, PointSize[Large],
   Point[{x[0, 50, .5, 1, .8, 3],
     f[x[0, 50, .5, 1, .8, 3], 50, .5, 1, .8, 3]}]};
epi2 = {Green, PointSize[Large],
   Point[{x[0, 50, .5, .7, .8, 3],
     f[x[0, 50, .5, .7, .8, 3], 50, .5, .7, .8, 3]}]};
Show[
 Plot[f[x, 50, .5, .7, .8, 3], {x, -3, 3}],
 Plot[f[x, 50, .5, 1, .8, 3], {x, -3, 3}],
 Epilog -> {epi1, epi2},
 PlotRange -> All
 ]

Btw., this has the same effect and is somewhat more transparent to me:
Show[
 Plot[f[x, 50, .5, .7, .8, 3], {x, -3, 3}],
 Plot[f[x, 50, .5, 1, .8, 3], {x, -3, 3}],
 Graphics[{epi1, epi2}],
 PlotRange -> All
 ]


text: Q: What is the difference between "fold" and "unfold"? I'm doing an exercise using Isabelle recently and don't know the difference between fold and unfold. What I know is to apply the rules which contain inference symbol, we should use rule and those without inference symbol, we should use unfold. But when should we use fold? Some examples will be much appreciated.


text:
Q: Unable to understand error "SparkListenerBus has already stopped! Dropping event ..." The issue
I'd like to know if anyone has a magic method to avoid such messages in Spark logs:
2015-08-30 19:30:44 ERROR LiveListenerBus:75 - SparkListenerBus has already
stopped! Dropping event SparkListenerExecutorMetricsUpdate(41,WrappedArray())

After further investigations, I understand that LiveListenerBus extends AsynchronousListenerBus. And thus, at some point, .stop() method is called. Then, messages that might be sent/received will be dropped and remain unprocessed. Basically, some SparkListenerExecutorMetricsUpdate messages are unfortunately not received yet, and once they are, they become dropped to nowhere.
This doesn't look critical since SparkListenerExecutorMetricsUpdate just correspond to Periodic updates from executors.
What is embarrassing is that I absolutely don't understand why this happens and nothings refers to this issue. Note that this is totally non-deterministic and I can't reproduce this, probably due to the asynchronous nature and my lack of understand on how/when stop() is supposed to be called.
About the running code
A tight sample:
val sc = new SparkContext(sparkConf)
val metricsMap = Metrics.values.toSeq.map(
    v => v -> sc.accumulator(0, v.toString)
).toMap
val outFiles = sc.textFile(outPaths)

And there's no other reference to sc or a SparkContent instance.

A: This ticket might be related.
https://issues.apache.org/jira/browse/SPARK-12009
The message seems to indicate yarn allocation failure after sparkcontext stop.

Sorry for unclear comment.
The main reason seems that there is some interval between AM's shutdown event and executors stop all.
So, AM tries to reallocate after executors stop.
As Saisai said below,

A interesting thing is that AM is shutting down at time 2015-11-26,03:05:16, but YarnAllocator still request 13 executors after 11 seconds. Looks like AM is not exited so fast, that's why YarnAllocator is still requesting new containers. Normally if AM is exited as fast as it receive disconnected message, there will be not time for container requesting for YarnAllocator.

I have come across similar logs near finishing spark context sometimes.
In my case, this ticket seems to be answer.


text:
Q: Printing non ASCII glyphs in python In HTML-CSS, we put non-ascii glyphs like middle dots, copyright symbol etc, by using their numeric conventions. In order to use non-ASCII characters, Python requires explicit encoding and decoding of strings into Unicode.
I have tried using unidecode lib (from reference here), but I am having trouble printing these characters.
I have tried different conventions for the symbol:
U+25CF ,    ● [&#9679 with ';'] , and so on... (depending on variation of these glyphs)n For example sake, help me print same dot(above) in python
I want to know how to print these in python, for I have such requirement in a GUI project, made with kivy/kivymd in python.

A: print(chr(9679))

Just use the decimal part of the entity.
Using a special escape sequence you can embed the character in a string using the hex.
print('\u25cf')


text:
Q: How can I convert a Daisy-formatted ebook to epub? I own a Kobo Touch, and there are some books available online in the Daisy format that I'd like to read on my Kobo.
The book is also available in PDF format, but I'd much rather have it in epub form.
What can I do about that?

A: calibre is a free and open source e-book library management application developed by users of e-books for users of e-books. It has a cornucopia of features divided into the following main categories:

*

*Library Management

*E-book conversion

*Syncing to e-book reader devices

*Downloading news from the web and converting it into e-book form

*Comprehensive e-book viewer

*Content server for online access to your book collection

(For Windows, OSX and linux)


text:
Q: Electron with serialport native module Hello I am trying to use the serialport module in electron, but when running this tries to find the module anywhere the only place it does not look is in the node_modules folder, already run electron-rebuild and electron-builder install-app-deps but nothing .
Uncaught Error: Could not locate the bindings file. Tried:
 → /home/myusername/my-projects/yuumi-cnc/build/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/build/Debug/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/build/Release/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/out/Debug/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/Debug/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/out/Release/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/Release/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/build/default/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/compiled/12.4.0/linux/x64/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/addon-build/release/install-root/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/addon-build/debug/install-root/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/addon-build/default/install-root/bindings.node
 → /home/myusername/my-projects/yuumi-cnc/lib/binding/node-v73-linux-x64/bindings.node
    at bindings (bindings.js:126)
    at Object../node_modules/@serialport/bindings/lib/linux.js (linux.js:1)
    at __webpack_require__ (bootstrap:726)
    at fn (bootstrap:100)
    at Object../node_modules/@serialport/bindings/lib/index.js (index.js:14)
    at __webpack_require__ (bootstrap:726)
    at fn (bootstrap:100)
    at Object../node_modules/serialport/lib/index.js (index.js:2)
    at __webpack_require__ (bootstrap:726)
    at fn (bootstrap:100)

I have no idea how to solve this


text:
Q: What is the best way to find popular posts that are over a month old? Maybe it's in tabs? Or maybe something else?

A: This sort of depends on how you define "popular", but you can search for all posts with a particular tag (or combination of tags) and then sort them in various ways.
For example, you can search for all the questions with the c# tag just by clicking on the tag wherever you see it on the site.
And from the results page (which shows, at the time of this writing, nearly 200,000 questions with that tag), you can choose to sort those questions any of 6 different ways: newest, featured, faq, votes, active, and unanswered. These are the tabs at the top of the page. Click on one to change the sort order.
I'd say that the most popular questions are probably those with the highest number of votes, so you can click the "votes" tab to sort by the number of votes.

And if you really want to get high-tech, you can visit our advanced search page and search by whatever parameters you like. All of the available options are detailed on that page.

Warning: Be careful with this type of search, though! You're likely to find a lot of old questions that, while popular, no longer fit our guidelines for acceptable questions. Our rules have changed and evolved a lot since the early days of the site, when dinosaurs roamed Stack Overflow.
Since people find these questions useful, we haven't been able to bring ourselves to delete them from the site. But please be aware that they exist only as a historical curiosity; their presence does not provide sufficient justification to ask such types of questions yourself.
You can think of them as being effectively "grandfathered in".
For more information, see this question: Why do some off-topic questions get closed, and some don't?


text:
Q: How to get server IP variable in Apache config I want to do an action in Apache 2.4 config based on request matching Server IP (SERVER_ADDR environment variable). What is the best way to do this?

A: SetEnvIf is the answer.
SetEnvIf Host "^123.*" IPADDR=local
<If reqenv('IPADDR') != 'local'>
  Redirect "/" "https://example.net/"
</If>


text:
Q: How can I pass instance attributes as arguments automatically when running a function stored as an instance attribute? I am building out a class A to ultimately perform a particular statistical operation. I can set both a function and the arguments for that function as instance attributes, using class methods I have written. I would then like to be able to run the function, with the arguments being sourced from the instance attributes automatically. It is unclear to me if there is nimble way to do this as I am conceiving it or if another implementation is necessary.
A toy version of the relevant code so far, with run_function stopping short of what I ultimately want it to do:
import pandas as pd

df = pd.DataFrame(
    [[1,2.,"a"],[0,8.,"q"],[1,3.5,"a"],[1,9.5,"g"]],
    columns=["binary","float","letters"]
    )

c = "binary"
v = 1

def test_fn(df,c:str,v:list):
    if not isinstance(v,list):
        v = [v]

    return (df[c].isin(v)).sum()

class A():
    def __init__(self,df):
        self.df = df

    def _set_fn_args(self,**kwargs):
        self.__dict__.update(kwargs)

    def set_function(self,function,**kwargs):
        self.fn = function
        self._set_fn_args(**kwargs)

    def run_function(self,df=None,**kwargs):
        if df is None:
            df = self.df
        return self.fn(df,**kwargs)

a = A(df)
a.set_function(test_fn,c=c,v=v)

a.__dict__.keys()
# dict_keys(['df', 'fn', 'c', 'v'])

a.fn
# <function __main__.test_fn(df, c: str, v: list)>

a.run_function(c=a.c,v=a.v)
# 3

The method set_function stores any input function as a class attribute fn, so that the statistical operation can be run over any function. **kwargs can be passed to the function, that through the child method _set_fn_arguments stores these variables as class attributes. Another function, run_function, runs the function stored as fn.
Currently, I have to write in each argument for run_function, which pretty much defeats the purpose of storing these as class attributes. I would also like to be able to source the function arguments from A according to their names. In this example, I'd like to write run_function such that run_function() will source all necessary arguments (c and v) from within a when self.c and self.v are defined.
Is there a straightforward way to do this? Is there another way you would write the class to accomplish the same outcome?


text:
Q: Change path to different versions on an executable for currenct session in linux BASH I need to easy change path to an executable in bash without changing the name of the binary (e.g. there might be some other script/process that assumes a binary exists on PATH called exactly the name of the binary). For the sake of the example below lets say the executable is called: EXECUTABLE.
Right now I have:
~/.bashrc
e11() {
  export EXECUTABLE="/home/user/tools/EXECUTABLE-1.1.0/"
  export PATH=$EXECUTABLE:$PATH
}
export -f e11

e19() {
  export EXECUTABLE="/home/user/tools/EXECUTABLE-1.9.0/"
  export PATH=$EXECUTABLE:$PATH
}
export -f e19

The above works. Meaning in a terminal I can just type e11 or e19 so switch between the different version of the EXECUTABLE. But if I need a few more versions the list starts to grow. Are there better ways to do this?

A: Yes just pass the $var instead e.g.
myapp() {
  export EXECUTABLE="/home/user/tools/EXECUTABLE-${1}/"
}

myapp "$1"
echo $EXECUTABLE

output:
$ bash 1.sh 1.1
/home/user/tools/EXECUTABLE-1.1/
$ bash 1.sh 1.2
/home/user/tools/EXECUTABLE-1.2/
$ bash 1.sh whatevervalueiput
/home/user/tools/EXECUTABLE-whatevervalueiput/

edit: I'd be careful about always appending to $PATH though - that's a different problem for you to tackle


text:
Q: Python convert list of tuples to json I have list of tuples like :
[('a', '76', '20190208011713-0500'),
 ('b', '14', '20190208011713-0500'),
 ('c', '99', '20190208011713-0500'),
 ('d', '62', '20190208011713-0500'),
 ('e', '112', '20190208011713-0500'),
 ('f', '78', '20190208011713-0500'),
 ('g', '20', '20190208011713-0500'),
 ('h', '14', '20190208011713-0500'),
 ('i', '23', '20190208011713-0500'),
 ('a', '45', '20190208011803-0500'),
 ('b', '36', '20190208011803-0500'),
 ('c', '22', '20190208011803-0500'),
 ('d', '69', '20190208011803-0500'),
 ('e', '11', '20190208011803-0500'),
 ('f', '118', '20190208011803-0500'),
 ('g', '29', '20190208011803-0500'),
 ('h', '34', '20190208011803-0500'),
 ('i', '63', '20190208011803-0500')]

The third element of all the tuples are the same. I am trying to convert this list into a dictionary in the following way:
{timestamp: 20190208011713-0500,
  'a' : 76,
  'b' : 14,
  'c' : 99,
  'd' : 62,
  'e' : 112,
  'f' : 78,
  'g' : 20,
  'h' : 14,
  'i' : 23}

UPDATE:
As of now I am doing it manually but I have around 1000's of tuples in a list with the same timestamp, but sometimes I do also have different timestamps. I am trying to automate this process by writing a function as I need to re-use the code again and again for multiple list of tuples to create list of dictionaries but I'm not sure how to approach this problem. Any help would be appreciated?
[{'timestamp': '20190208011713-0500',
  'a' : 76,
  'b' : 14,
  'c' : 99,
  'd' : 62,
  'e' : 112,
  'f' : 78,
  'g' : 20,
  'h' : 14,
  'i' : 23},
  {'timestamp': '20190208011803-0500',
  'a' : 45,
  'b' : 36,
  'c' : 22,
  'd' : 69,
  'e' : 11,
  'f' : 118,
  'g' : 29,
  'h' : 34,
  'i' : 63}]

A: If the timestamp is guaranteed to be the same, or otherwise you don't care if it isn't, then just use:
result = {'timestamp': your_list[0][-1]}
result.update(tup[:2] for tup in your_list)

The second line takes the first two elements of each tuple, and passes those directly to the dict.update() method. Like the dict() constructor, that method accepts an iterable of (key, value) tuples, and with slicing, that's what you have already.
Demo:
>>> result = {'timestamp': your_list[0][-1]}
>>> result.update(tup[:2] for tup in your_list)
>>> from pprint import pprint
>>> pprint(result)
{'a': '76',
 'b': '14',
 'c': '99',
 'd': '62',
 'e': '112',
 'f': '78',
 'g': '20',
 'h': '14',
 'i': '23',
 'timestamp': '20190208011713-0500'}

If speed is of the essence, you can use operator.itemgetter() to do the fetching, and use the Python 3 version of map() to apply it when updating:
from operator import itemgetter
try:
    # forward compatibility with Python 3
    from future_builtins import map
except ImportError:
    pass

result = {'timestamp': your_list[0][-1]}
result.update(map(itemgetter(0, 1), your_list))

With those changes the whole result.update() loop is executed in native C code.
If your timestamps are not guaranteed to be the same and you need to produce a list, you need to split out (group) your tuples by timestamp. If your input is at least grouped (all entries with the same timestamp appear consecutively), then you can use itertools.groupby() to do the grouping. The way you then build each dictionary remains the same; we can use the itemgetter() calleble here too to produce the grouping key:
from itertools import groupby
from operator import itemgetter
try:
    # forward compatibility with Python 3
    from future_builtins import map
except ImportError:
    pass

def group_timestamp(timestamp, group):
    d = {'timestamp': timestamp}
    d.update(map(itemgetter(0, 1), group))
    return d

result = [group_timestamp(ts, group) for ts, group in groupby(your_list, itemgetter(2))]

If they are not grouped, then I'd not sort the input. You want to shunt them into each timestamp group linearly, using a dictionary to do the grouping, then just sort the values of that dictionary when producing the output:
groups = {}
for key, value, ts in your_list:
    if ts not in groups:
        groups[ts] = {'timestamp': ts}
    groups[ts][key] = value

result = sorted(groups.values(), key=itemgetter('timestamp'))

This gives you the grouped dicitonaries in timestamp order. If output order doesn't matter, just use result = list(groups.values()).

A: Accounting for changing timestamps:
lst = [('a', '76', '20190208011713-0500'),
    ('b', '14', '20190208011713-0500'),
    ('c', '99', '20190208011713-0500'),
    ('d', '62', '20190208011713-0500'),
    ('e', '112', '20190208011713-0500'),
    ('f', '78', '20190208011713-0500'),
    ('g', '20', '20190208011713-0500'),
    ('h', '14', '20190208011713-0500'),
    ('i', '23', '20190208011713-0500')]

dict = {}

for tuple in lst:
    if tuple[2] in dict:
        dict[tuple[2]][tuple[0]] = tuple[1]
    else:
        dict[tuple[2]] = {}
        dict[tuple[2]][tuple[0]] = tuple[1]

OUTPUT:
{'20190208011713-0500': {'a': '76',
  'b': '14',
  'c': '99',
  'd': '62',
  'e': '112',
  'f': '78',
  'g': '20',
  'h': '14',
  'i': '23'}}

A: tups = [('a', '76', '20190208011713-0500'),
 ('b', '14', '20190208011713-0500'),
 ('c', '99', '20190208011713-0500'),
 ('d', '62', '20190208011713-0500'),
 ('e', '112', '20190208011713-0500'),
 ('f', '78', '20190208011713-0500'),
 ('g', '20', '20190208011713-0500'),
 ('h', '14', '20190208011713-0500'),
 ('i', '23', '20190208011713-0500')]

def to_dict(tups):
    my_dict = {element[0]: element[1] for element in tups}
    my_dict['timestamp'] = tups[-1][2]
    return my_dict

m_d = to_dict(tups)
print(m_d)

A: I think the simplest way is the following:
return_dict = dict([item[:2] for item in your_list])
return_dict["timestamp"] = your_list[0][2]


text:
Q: How do I download a PPTX file in Reactjs I need to download a pptx file
  const download = (blob, filename) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  fetch("export-pptx", {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    })
      .then((response) => {
        response.blob().then(blob => download(blob, 'test.pptx'))
      })
      .catch(err => console.error(err));

The response I receive.
body: ReadableStream { locked: true }
bodyUsed: true
headers: Headers {  }
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "https://localhost:3030/export-pptx"

The file that is downloaded can not be opened as a Power Point.
How do I parse the response so I get a working file?


text:
Q: How to get authenticated in Microsoft teams tab in python The login page is displaying in the team's tab on the browser. Now the issue is on the login prompt it tries to open iframe which is not allowed in the one another iframe in the team's tab. It works fine on a normal browser page but having an issue only in the team's tab on the browser.
The error which we are getting is like: Refused to display 'https://login.microsoftonline.com/' in a frame because it set 'X-Frame-Options' to 'deny'.
Details of Code:
Language: Python
Architecture: Flask Apis for rendering pages
Issue: iframe not working in team's browser tab.
Authentication: MSGraph.Authorization
Could you please help with this?

A: I presume you're using MSAL 2.0 (recommended). If so, there are two auth flows - redirect and popup. In Teams, it's a little different because Teams itself is actually launching the popup for the auth flow. As a result, even though it involves a popup, this popup will launch to your own auth page, and you end up doing redirect flow from inside there.
Here's a sample I put together for Tab SSO that should help (it's not python, but hopefully the node/Dotnet examples will be good enough guidance): https://github.com/pnp/teams-dev-samples/tree/master/samples/tab-sso