text:
Q: RESTful API design and load select options Let's have a form, where I have a couple of selects. I need to fill them with options provided from server.
But a RESTful API should only have methods for

*

*Get

*Post

*Put

*Delete

There's no place for retrieving some other data. I guess I should create these 4 method for each select options, but that seems to me like a overkill.

A: Your form data lists can be orthogonal to each other but your form must obviously put them together in a business context. The object that you would GET or PUT or POST or DELETE would be your business object that only has a property for each of the selects. You can GET the lists populating your selects separately.
You can have the 4 methods for each of those lists only if you wish to provide those services via REST as opposed to maintaining them directly (using SQL). Otherwise, only GET would suffice.


text:
Q: How to use wx.Slider as scroller for a simple wx.Panel? I am creating a simple wx.Dialog box for my wxPython application.
I have a panel inside that dialog box with many widgets and the size of the panel is larger than the dialog box. I want to scroll that panel using a wx.Slider. I don't want to use ScrolledPanel which is there by default in the library because the default windows scroller that appears for that looks dirty.
Can anyone guide me how to do such a thing. I mean how to scroll a panel. I am ready for using wx.PaintDc if needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add animtion in Horizonal Pager in Jetpack Compose? I have a HorizonalPager but there is no animation means it goes to second page suddenly i want that it animates to go softly or little bit slow and How to get rid of those stretch animation or whatever they are called
Here is a gif

A: I faced same issue when I used old version of library:
implementation "com.google.accompanist:accompanist-pager:0.20.0"

But when I updated it to
implementation "com.google.accompanist:accompanist-pager:0.23.0"

all went good. Try it.


text:
Q: pandas: exact match does not work in an if AND condition I have two dataframes as follows:
data = {'First':  [['First', 'value'],['second','value'],['third','value','is'],['fourth','value','is']],
'Second': ['noun','not noun','noun', 'not noun']}

df = pd.DataFrame (data, columns = ['First','Second'])

and
data2 = {'example':  ['First value is important', 'second value is important too','it us good to know',
                  'Firstap is also good', 'aplsecond is very good']}

df2 = pd.DataFrame (data2, columns = ['example'])

and I have written the following code that would filter out the sentences from df2 if there is a match in df for the first word of the sentence, only if in the second column we have a match for the word 'noun'. so basically there are two conditions.
def checker():
    result =[]
    for l in df2.example:
        df['first_unlist'] = [','.join(map(str, l)) for l in df.First]
        if df.first_unlist.str.match(pat=l.split(' ', 1)[0]).any() and df.Second.str.match('noun').any():
            result.append(l)
    return result

however, i realized that i get ['First value is important', 'second value is important too'] as the output when I run the function, which shows that the second condition for 'noun' filter only does not work. so my desired output would be ['First value is important'].
I have also tried .str.contains() and .eq() but I still got the same output

A: I would suggest filtering out df before trying to match:
def checker():
    result = []
    for l in df2.example:
        first_unlist = [x[0] for x in df.loc[df.Second == 'noun', 'First']
        if l.split(' ')[0] in first_unlist:
            result.append(l)
    return result

checker()
['First value is important']


text: Q: making Subscription in android studio with kotlin I'm Working on app that let you subscribe to get exclusive thing and i don't know how to show the lock on icon and after their subscribe, the lock remove


text:
Q: Running out of RAM when writing to a file line by line [Python] I have a data processing task on some large data. I run the script on EC2 using Python that looks something like the following:
with open(LARGE_FILE, 'r') as f:
    with open(OUTPUT_FILE, 'w') as out:
        for line in f:
            results = some_computation(line)
            out.write(json.dumps(results))
            out.write('\n')

I loop over the data line by line and write the results to another file line by line.
After running it for a few hours, I can't log in to the server. I would have to restart the instance to continue.
$ ssh ubuntu@$IP_ADDRESS
ssh_exchange_identification: read: Connection reset by peer

It's likely the server is running out of RAM. When writing to the file, RAM slowly creeps up. I am not sure why memory would be a problem when reading and writing line by line.
I have ample hard drive space.
I think closest to this issue: Does the Python "open" function save its content in memory or in a temp file?

A: I was using SpaCy to do some preprocessing of text. Looks like using the tokenizer causes steady memory growth.
https://github.com/spacy-io/spaCy/issues/285


text:
Q: Framer Motion: change color animation direction In Framer Motion, I'm trying to get two colors to animate smoothly.  The colors are red 'hsl(0, 100, 50)' and blue 'hsl(240, 100, 50)'.  Unfortunately, the animation is going through the color wheel, making pit stops at orange, yellow, green, cyan, etc.  How do I get it to switch "direction" and transition smoothly from red, then violet, then blue?

A: Although this is surprisingly simple to do, it is not at all initially obvious to do this.
This is wrong: animate={{ backgroundColor: ['hsl(0, 100, 50)', 'hsl(240, 100, 50)] }},
while this is right: animate={{ backgroundColor: ['hsl(0, 100, 50)', 'hsl(-120, 100, 50)'] }}.
(Just in case anybody is confused about where this code goes, "animate" is a prop within the motion.div element.  For more examples, please looks at these examples from the docs: https://www.framer.com/api/motion/examples/)


text:
Q: CakePHP 3.0 - Post Link - adding a class removes alert confirmation functionality How do can you add a class to this code?
$this->Form->postLink(
    __('Delete'),
    ['action' => 'delete', $user->id],
    ['confirm' => __('Are you sure you want to delete # {0}?', $user->id)]
)

When i add a class the "confirm functionality" disappears.
$this->Form->postLink(
    __('Delete'),
    ['action' => 'delete', $user->id],
    ['class' => 'btn btn-danger'],
    ['confirm' => __('Are you sure you want to delete # {0}?', $user->id)]
)

A: confirm and class should be in same array
$this->Form->postLink(
    __('Delete'),
    ['action' => 'delete', $user->id],
    ['confirm' => __('Are you sure you want to delete # {0}?', $user->id),'class'=>'btn btn-danger']
)

A: Set class before confirm
['class' => 'btn btn-danger','confirm' => __('Are you sure you want to delete # {0}?', $user->id)]


text:
Q: Validation in namespaces? I am wondering what the best practice for error validation is using the javascript pattern for namespacing ? Should it be done on a per page basis or rather as a global one ?
By this I mean:
myPage = {
    validation: function() {

    },
    open: function() {

    },
    init: function() {

    }
};

or move validation to a higher namespace such as:
myValidation = {
    myPage: function() {

    //perform validation

    }
};

and return it as myValidation.myPage() ?


text:
Q: RxJs looping over returned array Is there a better way using RxJS operators to loop over an array returned from an observable than this to emit a new individual ListingItem?
onGetItemData(){
this.dataService.getItemData().subscribe((itemData) =>
{
  this.itemDataJSON = itemData;
  this.itemDataJSON.forEach(function (value) {
    let new_listing = new ListingItem(value.label,value.market,value.name);
    console.log(new_listing);
  });
 });
}

The API returns a single array containing the items, so I am unable to use .map to access itemData.name
//-- DataService --//
getItemData(){
 return this.http.get(this._URL, { headers })
        .pipe(map((res: Listings) => res.items))
}

A: I'm still learning Observables myself, but I think you can create an Observable from an Array like I did in this StackBlitz: https://stackblitz.com/edit/angular-tbtvux
In a nutshell (in Angular 6):
import { from, pipe } from 'rxjs';
...
let observable = from([10, 20, 30])
  .subscribe(v => console.log(v));

So maybe you can pipe the switchMap operator on your observable which returns an array, something like this:
import { switchMap } from 'rxjs/operators';
...
yourArrayObservable$.pipe(
  switchMap(val => from(val))
);

... and then you could use map after that like so:
import { switchMap, map } from 'rxjs/operators';
...
yourArrayObservable$.pipe(
  switchMap(val => from(val)),
  map(val => val * 42)
);

... at least that seems to work in my aforementioned StackBlitz.

Update: I think the flatMap operator also works similarly, with a single operator:
yourArrayObservable$.pipe(
  flatMap(val => val * 42)
);

A: Why don't just pipe a map() ?
this.dataService.getItemData()
    .pipe(
        map(itemData => {
            return itemData.map(value => {
                return new ListingItem(value.label, value.market, value.name);
            })
        })
    )
    .subscribe((listingItem) => {
        console.log(listingItem) // gives an array of listingItem
    });

Note that .map() is a JavaScript's native array function, you will use it to transform the data, by looping over each item of the array
Just for a one-liner:
.pipe(
    map(itemData => itemData.map(value => new ListingItem(value.label, value.market, value.name)))
)


text:
Q: On Galois groups and $\int_{-\infty}^{\infty} \frac{x^2}{x^{10} - x^9 + 5x^8 - 2x^7 + 16x^6 - 7x^5 + 20x^4 + x^3 + 12x^2 - 3x + 1}\,dx$ Given the solvable decic (among many in this database),
$$P(x) := x^{10} - x^9 + 5x^8 - 2x^7 + 16x^6 - 7x^5 + 20x^4 + x^3 + 12x^2 - 3x + 1$$
we have,
$$\int_{-\infty}^{\infty} \frac{x^2}{P(x)}\,dx = 2\pi\sqrt{\frac{y}{33}}$$
where $y\approx 0.005498$ is a root of the solvable $5$-real root quintic,
$$P(y):=410651^2 - 297369569963257 y + 64437688060325415 y^2 - 3213663132678906688 y^3 + 59485209442439490149 y^4 - (11^3\cdot67^2\cdot199^6) y^5 = 0$$
(Added later): A relation between the roots $x,y$ such that $P(x)=P(y)=0$ is,
$$12675353 + 84680609 x^3 + 55168143 x^6 - 6841070 x^9 - 1801451 x^{12} = (11\cdot67^2\cdot199^2) y$$

Q: In general, if,
  $$\int_{-\infty}^{\infty} \frac{x^2}{ P(x)}\,dx= 2\pi \sqrt{y}$$
  and $P(x)$ has a solvable Galois group, is it true that $P(y)$ also has a solvable Galois group?

A: Not an answer - just listing some obvious facts that seem to be relevant to get the ball rolling.

*

*The polynomials from that database surely only have simple roots, because they were selected with a suitable splitting field in mind.

*For the integral $\int_{-\infty}^\infty\dfrac{x^2}{P(x)}\,dx$ to converge it is necessary that $P(x)$ has no real roots.

*With $P(x)$ of high enough degree the usual business with sophomore level complex path integrals gives $$I=\int_{-\infty}^\infty\dfrac{x^2}{P(x)}\,dx=2\pi i\sum_{P(z)=0,z\in H}\operatorname{Res}(\frac{z^2}{P(z)},z),$$
where the summation ranges over the zeros of $P(x)$ in the upper half plane $H$.

*Those zeros are simple, so a single application of l'Hospital shows that at a zero $z_i\in H$ the residue is
$$
\operatorname{Res}(\frac{z^2}{P(z)},z_i)=\frac{z_i^2}{P'(z_i)}.
$$

*So if we write $I=2\pi U$, then
$$U^2=-\left(\sum_i \frac{z_i^2}{P'(z_i)}\right)^2.$$

*If $K$ is the splitting field of $P(x)$ (inside $\Bbb{C}$), then $U^2\in K$. Furthermore, because $U^2$ is real, it belongs to the real subfield $L=K\cap \Bbb{R}$. So the minimal polynomial of $U^2$ is solvable, iff $Gal(K/\Bbb{Q})$ is. The number $U\in K(i)$, so it, too, has a solvable minimal polynomial.


text:
Q: Populating Columns headings from JSON in bootstrap-table? I can how to populate the data from the JSON file on my server (url: file.json), but then I still need to declare the columns themselves manually as I initiate the bootstrap table.
I would like to populate the entire table according to the JSON information. Is the possible?
Current code:
function create_table_from_json() {
$('#table').bootstrapTable({
        url: 'data.json',
        columns: [{
            field: 'firstname',
            title: 'First Name',
            sortable: 'true'

            }, {
            field: 'lastname',
            title: 'Last Name',
            sortable: 'true'
            }, {
            field: 'desc',
            title: 'Description'
            }, {
            field: 'donotcall',
            title: 'Do Not Call'
            }],

        sortName:   'lastname',
        striped:    'true',
        search:     'true',
        showColumns: 'true'

    });
}

sidenote:
If anyone has experience with other table enhancement tools or plugins and wants to recommend them that would be great.

A: Long story short will be in the next release as fix.
Confirmed it seems to be accepting the JSON via JS and populating the columns and data properly now.
Primitive example in case someone stumbles on this. Keep in mind the JSON has values needed for the column filter control which you might not need.
$table.bootstrapTable({
    height: getHeight(),
    data: fromAJAXJSON.data,
    columns: fromAJAXJSON.columns
});

In a perfect world you would most likely want to combine the data and columns into one JSON call for timing reasons rootObject.data/rootObject.columns but you get the point.
Example data JSON: https://api.myjson.com/bins/r8nya
Example columns JSON: https://api.myjson.com/bins/zkqf6
https://github.com/wenzhixin/bootstrap-table/issues/3895


text:
Q: How do I turn preprocessed data from pipelines into dataframes? I have a piece of code that is a preprocessing file for my data. Everything is kosher until I have to feed that preprocessed data into a fit function that takes pandas dataframes and arrays. How can I turn this training data into a dataframe for feeding? As of the pipeline.fit() function, the datatype is a column transformer and not a pandas df.
Code:
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split

# generate the data
data = pd.DataFrame({
    'y':  [1, 2, 3, 4, 5],
    'x1': [6, 7, 8, np.nan, np.nan],
    'x2': [9, 10, 11, np.nan, np.nan],
    'x3': ['a', 'b', 'c', np.nan, np.nan],
    'x4': [np.nan, np.nan, 'd', 'e', 'f']
})

# extract the features and target
x = data.drop(labels=['y'], axis=1)
y = data['y']

# split the data
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)

# map the features to the corresponding types (numerical or categorical)
numerical_features = x_train.select_dtypes(include=['int64', 'float64']).columns.tolist()
categorical_features = x_train.select_dtypes(include=['object']).columns.tolist()

# define the numerical features pipeline
numerical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

# define the categorical features pipeline
categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

# define the overall pipeline
preprocessor_pipeline = ColumnTransformer(transformers=[
    ('num', numerical_transformer, numerical_features),
    ('cat', categorical_transformer, categorical_features)
])

# fit the pipeline to the training data
preprocessor_pipeline.fit(x_train)

# apply the pipeline to the training and test data
x_train_ = preprocessor_pipeline.transform(x_train)
x_test_ = preprocessor_pipeline.transform(x_test)

Bonus: Do I need to preprocess my labels (y_train) as well?

A: to transform your pipeline results into dataframes you would just need this:
x_train_df = pd.DataFrame(data=x_train_)
x_test_df = pd.DataFrame(data=x_test_)

As your labels y are already numeric in most cases there is no further preprocessing needed. But it also depends on the ML model you want to use in the next step.


text:
Q: Python package import not taken into function I have a very basic script that takes a piece of data as a CSV file, and converts the timestamps to whole hours. Part of this time conversion involves the package datetime, but the import of the package is not taken into the function that does the reformatting, and I have no idea why.
My code:
from datetime import datetime, timedelta
from dateutil import parser
import sys

def whole_hours(datafileloc, outfileloc):
    whole_hour_data = {}
    f = open(datafileloc, "r")
    data = f.readlines()
    f.close()

    for line in data[1:]:
        time = parser.parse(line.split(",")[0])
        values = line.split(",")[1:]

        if time.minute >= 30:
            newtime = datetime(year=time.year, month=time.month, day=time.day, hour=time.hour, minute=0) + timedelta(hours=1)
        else:
            newtime = datetime(time.year, time.month, time.day, time.hour, 0)

        if newtime not in whole_hour_data.keys():
            whole_hour_data[newtime] = {"oldtime": time, "values": values}
        else:
            oldtime = whole_hour_data[newtime]["oldtime"]
            if abs((time - newtime).total_seconds()) < abs((oldtime - newtime).total_seconds()):
                whole_hour_data[newtime] = {"oldtime": time, "values": values}

    with open(outfileloc, "w") as outfile:
        outfile.write(data[0])
        for datetime in sorted(whole_hour_data.keys()):
            outfile.write("{datetime},{values}".format(datetime=datetime, values=",".join(whole_hour_data[datetime]["values"])))

whole_hours("C:/Users/<user>/Documents/test.csv", "C:/Users/<user>/Documents/output.csv")

When executing this script, I get the following error:
Traceback (most recent call last):
  File "C:/Users/<user>/test.py", line 73, in <module>
    whole_hours("C:/Users/<user>/Documents/test.csv", "C:/Users/<user>/Documents/output.csv")
  File "C:/Users/<user>/test.py", line 54, in whole_hours
    newtime = datetime(year=time.year, month=time.month, day=time.day, hour=time.hour, minute=0) + timedelta(hours=1)
UnboundLocalError: local variable 'datetime' referenced before assignment

Note I've masked my username :)
I've figured out I can work around this error by using from datetime import datetime inside the function, or give the datetime package as a parameter for the function, but I am wondering why this needs to be done when the package is already imported at the start of the script. I've made several similar scripts that do not need this extra import.

A: There is a section of code where you iterate values over a for loop here:
for datetime in sorted(whole_hour_data.keys()):

When you do this, I think that Python now sees datetime as a local variable and not a global import statement.  You should change this variable name.


text:
Q: gcj error when trying to compile hadoop mapreduce examples I am trying to use gcj on hadoop-mapreduce-examples-2.7.1.jar to generate native machine code from the jar file. I need this for my research. But I am getting error: expected type 'java.lang.Throwable' but stack contains 'java.io.IOException'
I have gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04) and the command I used is to do this is:
gcj --classpath={hadoop-mapreduce-client-core-2.7.1.jar:hadoop-common-2.7.1.jar:commons-cli-1.2.jar:commons-logging-1.1.3.jar:guava-11.0.2.jar:hsqldb-2.0.0.jar} -d {destination} hadoop-mapreduce-examples-2.7.1.jar

Since I am beginner with java, I am not sure if I am on the right path or not. I am not even sure if this is possible. Please suggest.

A: Does adding -findirect-dispatch flag works for you?
Notice you can also add -O1, -O2 or -O3 optimization flag. In my case, -O1 actually works best, but you have to test for yourself.


text:
Q: Flask-SQLAlchemy association table I make a tuition payment app using Flask and using Flask-SQLAlchemy for ORM.
I have a User table, and this table I'm using to log in for school account and parent account. While the student data I store it in table Student and the student don't have a login account.
What I want to ask for, how to make relationship for the Student table to SCOOL_ID and PARENT_ID..? while the parent account and the school account is in the same table, which is User table.
One student have one parent and one student have one school.
Did I must separate the table between the school and the parent..?
So far, I have made it with Flask-SQLAlchemy like this, but I'm not sure this good.
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200))
    email = db.Column(db.String(120), index=True, unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    created_at = db.Column(db.DateTime, default=datetime.utcnow())
    updated_at = db.Column(db.DateTime, default=datetime.utcnow())

association_roles = db.Table('association_roles',
    db.Column('parent_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('school_id', db.Integer, db.ForeignKey('user.id'))
)

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    student_registration_number = db.Column(db.String(120), index=True, unique=True)
    name = db.Column(db.String(100))
    major = db.Column(db.String(50))
    created_at = db.Column(db.DateTime, default=datetime.utcnow())
    updated_at = db.Column(db.DateTime, default=datetime.utcnow())

    association_roles = db.relationship(
        'Student', secondary=association_roles,
        primaryjoin=(association_roles.c.parent_id == id),
        secondaryjoin=(association_roles.c.school_id == id),
        backref=db.backref('student', lazy='dynamic'), lazy='dynamic')

So, how to do that..?, any help will be much appreciated.

A: I already know the concept for my question, I must make a table School and Parent and inherit it from the table User, here is snippet of the code:
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200))
    roles = db.relationship('Role', secondary=roles_users,
                            default='parent',
                            backref=db.backref('users', lazy='dynamic'))

    __mapper_args__ = {
        'polymorphic_identity': 'user',
        'with_polymorphic': '*'
    }

class Parent(User):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    school_id = db.Column(db.Integer, db.ForeignKey('school.id'))

    __mapper_args__ = {
        'polymorphic_identity': 'parent',
        'with_polymorphic': '*'
    }

class School(User):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    __mapper_args__ = {
        'polymorphic_identity': 'school',
        'with_polymorphic': '*'
    }

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    school_id = db.Column(db.Integer, db.ForeignKey('school.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
    parent = db.relationship('Parent', backref=db.backref('Student', lazy='dynamic'))


text:
Q: Add regular JavaFX Node into FXML So I have a regular component extending from BorderPane and I want to add it into some FXML code. I am getting java.lang.IllegalArgumentException: Unable to coerce SettingsTab to class javafx.scene.Node. SettingsTab extends BorderPane:
public class SettingsTab extends BorderPane { ...

I am trying to include it like this:
<Tab fx:id="settingsTab" text="%ui.gui.settings.title" content="SettingsTab"/>

The FXML code and the class are in the same package/directory.
I am relatively new to FXML and not very familiar with the syntax, so I am not sure how to do this.
I can include FXML files like this, but I want to include a class file:
 <Tab fx:id="scheduleTab" text="%ui.gui.schedule.title">
      <fx:include source="ScheduleTab.fxml"/>
 </Tab>

A: The Tab needs a content tag like this and not as an attribute value.
<TabPane>
  <Tab fx:id="settingsTab" text="%ui.gui.settings.title">
    <content>
      <BorderPane></BorderPane>
    </content>
  </Tab>
</TabPane>

And in your case:
<TabPane>
  <Tab fx:id="settingsTab" text="%ui.gui.settings.title">
    <content>
      <SettingsTab></SettingsTab>
    </content>
  </Tab>
</TabPane>

And you need an import in your fxml for your custom component:
<?import my.custom.package.SettingsTab ?>


text:
Q: ¿Cómo cambio el valor de una variable? Quiero hacer una página en la cual se te muestre la hora, pasa que al mostrarse la hora, no sale con un cero a la izquierda. Imagino que cambiando algún valor en el new Date() es posible, pero en el ejercicio se me pide que añada un cero a la izquierda a través de un If. He probado ya de todo, principalmente, cambiar el valor de las variables a través de condicionales, pero no me funciona. Quisiera que en el caso de que el valor fuera menor que 10, tanto en los segundos, como en los minutos, como en las horas, aparezca un cero a la izquierda. Os dejo aquí el código, muchas gracias.
<!DOCTYPE html>

<head

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ejercicio 402</title>

        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sapiente odio sequi explicabo quo, labore architecto soluta quisquam nesciunt dolorum deserunt reprehenderit totam aspernatur eum, perferendis provident voluptatibus vero ut nobis!

Time

A: Lo que pasa que estas cambiando el valor de la variable pero no la estas volviendo a pintar en tu html
     function hora(){
        var areaHora = new Date();

        var horas = areaHora.getHours();

        var minutos = areaHora.getMinutes();

        var segundos = areaHora.getSeconds();
        if (seconds < 10) seconds = "0" + segundos;

        caja = document.getElementById('tiempo');

        caja.innerHTML = horas+":"+minutos+":"+segundos;
    }

Con eso deberia funcionar :D!


text:
Q: RDLC report from MySQL formating issue I need to create a RDLC report from a MySQL db that needs to show timecard info per user, per day between 2 dates (user choice) Like this eg:
UserFirstName UserLastName
2019-01-11 InTimeStamp OutTimeStamp TimeSpan
2019-01-12 InTimeStamp OutTimeStamp TimeSpan
2019-01-13 InTimeStamp OutTimeStamp TimeSpan
2019-01-14 InTimeStamp OutTimeStamp TimeSpan
Total: totalTimeForThePeriod
I need this for every user within the dates provided by the user.
I have already setup the HR report page and the date choice (works perfectly) but I can`t seem to be able to format my RDLC report to show the info as requested. How can I seperate the data to acheive this? My dataset gets all the data from the db (query works great). All I need to do now is to show it properly in the report. Any ideas on how I can acheive this?
I've tried using a simple table but that does'nt work.
I also tried a matrix, but I can't seem to show the data as requested.

A: You'll want to go one by one creating your rows. Also have your Grouping window open, so you can see your grouping. First right click where you want your first row and click Add Group -> Parent Group. In the Group by: drop down select a UserFirstName. Then it should add UserFirstName to your grid. To the right of it add UserLastName. Next in your grouping window under Row Groups click the drop down arrow on (UserFirstName) and click Add Group->Child Group. This time group by [TimeStampDate]. This will create a new row under your original row that is a sub group of UserFirstName. Add in the addition data in this new row. Lastly in the grouping window under Row Groups click the drop down on TimeStampDate then click Add Total->After. This should add a total row under the TimeStampDate row. You can change the [Sum(TimeStampDate )] to [totalTimeForThePeriod]. This should get you what you need.
[UserFirstName]     [UserLastName]
[TimeStampDate] [InTimeStamp]   [OutTimeStamp]  [TimeSpan]
Total:  [totalTimeForThePeriod]

I struggled with the same issue for hours, so I hope this helps!


text:
Q: Prevent UNDOTBS to abort import I have a dumpfile that I want to import in an Oracle 10g database in a virtual machine (with limited disk space). The dump file is about 3.5GB.
When I try to import the dump, the size of the UNDOTBS01.DBF file explodes (up to 12GB – stopped because the disk was full).
I tried the following with no luck:

*

*lower the undo_retention value

*switch undo_management to MANUAL

*switch the AUTORESIZE property of the UNDOTBS01 tablespace to OFF
I read that the undo tablespace was used for flashbacks and rollbacks, I don't need any of these, I just want the data of the dump into the database.
What can I do?

A: Undo function is to provide oracle with "past" versions of the data.
Don't switch undo management to manual, it will make things worse, as you will have to manage the rollback segments by hand.
What should work is to remove autoextend from the undo datafiles. Set the undo total space higher that is normal usage. The undo will fill 100% and will oracle will begin reusing it.
That can have consequences, like transactions failing with snapshot too old errors, so be careful in a production enviroment.


text:
Q: Lucene SpanNearQuery partial matching Given a document {'foo', 'bar', 'baz'}, I want to match using SpanNearQuery with the tokens {'baz', 'extra'}
But this fails.
How do I go around this?
Sample test (using lucene 2.9.1) with the following results:

*

*givenSingleMatch - PASS

*givenTwoMatches - PASS

*givenThreeMatches - PASS

*givenSingleMatch_andExtraTerm - FAIL

...
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class SpanNearQueryTest {

    private RAMDirectory directory = null;

    private static final String BAZ = "baz";
    private static final String BAR = "bar";
    private static final String FOO = "foo";
    private static final String TERM_FIELD = "text";

    @Before
    public void given() throws IOException {
        directory = new RAMDirectory();
        IndexWriter writer = new IndexWriter(
                directory,
                new StandardAnalyzer(Version.LUCENE_29),
                IndexWriter.MaxFieldLength.UNLIMITED);

        Document doc = new Document();
        doc.add(new Field(TERM_FIELD, FOO, Field.Store.NO, Field.Index.ANALYZED));
        doc.add(new Field(TERM_FIELD, BAR, Field.Store.NO, Field.Index.ANALYZED));
        doc.add(new Field(TERM_FIELD, BAZ, Field.Store.NO, Field.Index.ANALYZED));

        writer.addDocument(doc);
        writer.commit();
        writer.optimize();
        writer.close();
    }

    @After
    public void cleanup() {
        directory.close();
    }

    @Test
    public void givenSingleMatch() throws IOException {

        SpanNearQuery spanNearQuery = new SpanNearQuery(
                new SpanQuery[] {
                        new SpanTermQuery(new Term(TERM_FIELD, FOO))
                }, Integer.MAX_VALUE, false);

        TopDocs topDocs = new IndexSearcher(IndexReader.open(directory)).search(spanNearQuery, 100);

        Assert.assertEquals("Should have made a match.", 1, topDocs.scoreDocs.length);
    }

    @Test
    public void givenTwoMatches() throws IOException {

        SpanNearQuery spanNearQuery = new SpanNearQuery(
                new SpanQuery[] {
                        new SpanTermQuery(new Term(TERM_FIELD, FOO)),
                        new SpanTermQuery(new Term(TERM_FIELD, BAR))
                }, Integer.MAX_VALUE, false);

        TopDocs topDocs = new IndexSearcher(IndexReader.open(directory)).search(spanNearQuery, 100);

        Assert.assertEquals("Should have made a match.", 1, topDocs.scoreDocs.length);
    }

    @Test
    public void givenThreeMatches() throws IOException {

        SpanNearQuery spanNearQuery = new SpanNearQuery(
                new SpanQuery[] {
                        new SpanTermQuery(new Term(TERM_FIELD, FOO)),
                        new SpanTermQuery(new Term(TERM_FIELD, BAR)),
                        new SpanTermQuery(new Term(TERM_FIELD, BAZ))
                }, Integer.MAX_VALUE, false);

        TopDocs topDocs = new IndexSearcher(IndexReader.open(directory)).search(spanNearQuery, 100);

        Assert.assertEquals("Should have made a match.", 1, topDocs.scoreDocs.length);
    }

    @Test
    public void givenSingleMatch_andExtraTerm() throws IOException {

        SpanNearQuery spanNearQuery = new SpanNearQuery(
                new SpanQuery[] {
                        new SpanTermQuery(new Term(TERM_FIELD, BAZ)),
                        new SpanTermQuery(new Term(TERM_FIELD, "EXTRA"))
                },
                Integer.MAX_VALUE, false);

        TopDocs topDocs = new IndexSearcher(IndexReader.open(directory)).search(spanNearQuery, 100);

        Assert.assertEquals("Should have made a match.", 1, topDocs.scoreDocs.length);
    }
}

A: SpanNearQuery lets you find terms that are within a certain distance of each other.
Example (from http://www.lucidimagination.com/blog/2009/07/18/the-spanquery/):

Say we want to find lucene within 5
positions of doug, with doug following
lucene (order matters) – you could use
the following SpanQuery:

new SpanNearQuery(new SpanQuery[] {
  new SpanTermQuery(new Term(FIELD, "lucene")),
  new SpanTermQuery(new Term(FIELD, "doug"))},
  5,
  true);

(source: lucidimagination.com)

In this sample text, Lucene is within
3 of Doug

But for your example, the only match I can see is that both your query and the target document have "cd" (and I am making the assumption that all of those terms are in a single field).  In that case, you don't need to use any special query type.  Using the standard mechanisms, you will get some non-zero weighting based on the fact that they both contain the same term in the same field.
Edit 3 - in response to latest comment, the answer is that you cannot use SpanNearQuery to do anything other than that which it is intended for, which is to find out whether multiple terms in a document occur within a certain number of places of each other.  I can't tell what your specific use case / expected results are (feel free to post it), but in the last case if you only want to find out whether one or more of ("BAZ", "EXTRA") is in the document, a BooleanQuery will work just fine.
Edit 4 - now that you have posted your use case, I understand what it is you want to do.  Here is how you can do it:  use a BooleanQuery as mentioned above to combine the individual terms you want as well as the SpanNearQuery, and set a boost on the SpanNearQuery.
So, the query in text form would look like:
BAZ OR EXTRA OR "BAZ EXTRA"~100^5

(as an example - this would match all documents containing either "BAZ" or "EXTRA", but assign a higher score to documents where the terms "BAZ" and "EXTRA occur within 100 places of each other; adjust the position and boost as you like.  This example is from the Solr cookbook so it may not parse in Lucene, or may give undesirable results.  That's ok, because in the next section I show you how to build this using the API).
Programmatically, you would construct this as follows:
Query top = new BooleanQuery();

// Construct the terms since they will be used more than once
Term bazTerm = new Term("Field", "BAZ");
Term extraTerm = new Term("Field", "EXTRA");

// Add each term as "should" since we want a partial match
top.add(new TermQuery(bazTerm), BooleanClause.Occur.SHOULD);
top.add(new TermQuery(extraTerm), BooleanClause.Occur.SHOULD);

// Construct the SpanNearQuery, with slop 100 - a document will get a boost only
// if BAZ and EXTRA occur within 100 places of each other.  The final parameter means
// that BAZ must occur before EXTRA.
SpanNearQuery spanQuery = new SpanNearQuery(
                              new SpanQuery[] { new SpanTermQuery(bazTerm),
                                                new SpanTermQuery(extraTerm) },
                              100, true);

// Give it a boost of 5 since it is more important that the words are together
spanQuery.setBoost(5f);

// Add it as "should" since we want a match even when we don't have proximity
top.add(spanQuery, BooleanClause.Occur.SHOULD);

Hope that helps!  In the future, try to start off by posting exactly what results you are expecting - even if it is obvious to you, it may not be to the reader, and being explicit can avoid having to go back and forth so many times.


text:
Q: Simplify Boolean Expression Given Truth Table Truth Table
I have the truth table above which gives the minterm expression
$$F = (\neg a \land \neg b \land c) \lor (\neg a \land b \land \neg c) \lor (a \land \neg b \land \neg c) \lor (a \land b \land c)$$
but I'm unsure how to simplify it using boolean algebra to prove it is the XOR of a, b, and c.

A: We know that $x \veebar y = (\neg x \land y) \lor (x \land \neg y)$.
Note that, by combining terms with $a$ and combining terms with $\neg a$:
$$\begin{align*}
F &= (\neg a \land \neg b \land c) \lor (\neg a \land b \land \neg c) \lor (a \land \neg b \land \neg c) \lor (a \land b \land c) \\
&= (\neg a \land (\neg b \land c)) \lor (\neg a \land (b \land \neg c)) \lor (a \land (\neg b \land \neg c)) \lor (a \land (b \land c)) \\
&= (\neg a \land ((\neg b \land c) \lor (b \land \neg c))) \lor (a \land ((\neg b \land \neg c) \lor (b \land c))) \\
&= (\neg a \land (b\veebar c)) \lor (a \land \neg((\neg b \land c) \lor (b \land \neg c))) \\
&= (\neg a \land (b\veebar c)) \lor (a \land \neg(b\veebar c)) \\
&= a \veebar (b \veebar c) = a \veebar b \veebar c
\end{align*}$$


text:
Q: AWS s3api 'get-object' costs I need to download this 60 milions tweets dataset (https://github.com/compsocial/CREDBANK-data) for my thesis work.
So I signed up for an AWS account and configured it with the correct parameters in my Mac terminal, then I signed in also into the S3 page, BUT when I try the following command:
aws s3api get-object --request-payer requester --bucket credbank --key stream_tweets_byTimestamp.data stream_tweets_byTimestamp.data
I get this error message:
An error occurred (NotSignedUp) when calling the GetObject operation: Your account is not signed up for the S3 service. You must sign up before you can use S3.
So, from what I understand, the problem is that my prepaid card wasn't accepted as a valid payment method and therefore my account isn't fully activated yet.
So, my question is, if I only need to run the get-object command above to download the data, could I be charged for some money if I use a real credit card, even if with my new account I'm in the 12-months free tier period?
Please let me know if you need further details to understand my question!
Thank you very much!

A: No. Your card will not be charged a single penny unless one of these happens:
a) You use >5 GB of Standard Storage. This one is really important in your case so ensure the data size you will be downloading
b) You make >20,000 Get Requests
c) You make >2,000 Put Requests
I've signed up for AWS free tier and used their S3 and EC2 services for a year without bearing any cost.

A: If the file you want to download is smaller than 15GB, then the download will cost you nothing, even if you use a real credit card.
You'll only use 1 GET request (you have 20,000 free) and a portion of the 15 GB of free download transfer per month.
Source:

As part of the AWS Free Usage Tier, you can get started with Amazon S3
  for free. Upon sign-up, new AWS customers receive 5 GB of Amazon S3
  storage in the Standard Storage class, 20,000 Get Requests, 2,000 Put
  Requests, and 15 GB of data transfer out each month for one year.


text:
Q: Well-Ordering and Induction on the Natural Numbers I apologize in advance if this question seems overly pedantic.
On a high level, I am confused about the relationships between the principle of recursive definition, induction, and well-ordering on the natural numbers.
First, suppose that we represent the natural numbers with their set theoretic construction. Of course, this is a recursive definition; is this allowed? In other words, how are we guaranteed that this definition covers all of the natural numbers? My impression was that recursion is a property of the natural numbers, but my confusion arises from the fact that it's also necessary in their set theoretic construction.
Second, if we assume that the natural numbers are well-ordered, then we can easily prove induction on the naturals. Conversely, if we assume that the natural numbers are inductive, then we can prove that they are well-ordered. All of the proofs of well-ordering that I've seen on here rely on that. So, how do we prove that these properties are indeed true of the natural numbers? It seems like we have to assume one to generate the other. Are there any texts out there that address this issue?
I would love to find out if there's any deeper approach that answers these three problems, recursion, induction, and well-ordering, from the ground up.
Sorry again if this is diving too deep into formality. We all know how natural numbers should behave, and perhaps the questions I'm asking are more-so related to their specific representation by sets. Any help is greatly appreciated.

A: In set theory, natural numbers are typically defined in the following way:

*

*The successor of a set $x$ is defined as $x^+=x\cup \{x\}$.

*We say that $A$ is a successor set if $0\in A$ and for all $x$, if $x\in A$ then $x^+\in A$.

*The natural numbers $\mathbb N$ are defined as the minimal successor set: they are the unique successor set with the property that if $A$ is a successor set, then $\mathbb N\subset A$.

This definition makes sense on an intuitive level, but it raises the question: how do we know a successor set exists? If we try to appeal to recursion, then we do indeed land in trouble. There is a theorem, known as the recursion theorem, which basically amounts to saying that recursive definitions make sense. However, the proof of this theorem relies heavily on the properties of natural numbers, and so trying to appeal to the recursion theorem would be circular.
Instead, we appeal to the axiom of infinity, which is the very assertion that a successor set exists. In other words, the axiom of infinity states that there exists a set containing $0$ and containing the successor of each of its elements. Note that the set $A$ postulated to exist by the axiom of infinity is not necessarily $\mathbb N$; it might be that $A$ consists all of the elements of $\mathbb N$, plus some other elements. Nevertheless, we can use the axiom of infinity, along with the other axioms of set theory, to prove that there is a set $\mathbb N$ satisfying the properties set out above. For a description of how one can do this, see Paul Halmos' Naive Set Theory, chapter 11.
It is baked into the definition of $\mathbb N$ that induction works on it. The fact that they can be well-ordered is also provable by induction. Suppose $A\subset \mathbb N$ has no least member. Let $B$ equal the set of natural numbers not in $A$. One can prove by induction that $B=\mathbb N$, and so $A=\varnothing$. Thus, the only subset of $\mathbb N$ which does not have a least member is the empty set.


text:
Q: Rhapsody java api - How to add an Object Model Diagram to a Class? I am using the Rhapsody Java API to create some plugins in order to get automations features. I am trying to create an Object Model Diagram from a Class, but there is no functions in order to do it.
Basically I would like to do something like :
IRPClass cla = prj.addClass("Class");
IRPObjectModelDiagram omd = cla.addObjectModelDiagram("My OMD");

However, the addObjectModelDiagram() function is unavailable to a class.
I tryied to use ChangeTo() to the class to turn it into a Pkg then turn it back to a class without success, and to do the same with the OMD by creating an other type of diagram supported by IRPClass and then by turning it into an OMD. It didn't worked neither.
Does anyone have a solution in order to help me ?
Thomas

A: Thomas,
IRPModelElement has a generic "add" method called addNewAggr (see javadoc below).
In general, because of its open nature, I would only use this method in cases where you don't have a dedicated method. (Not every type of element can be added to every other type of element, so you have to be careful when using this. But in this case, you're talking about something that can be done in the UI - adding an OMD to a class, so there shouldn't be any problems.)
javadoc for addNewAggr

A: Assuming that you already created a class,
1. Determine IRPModelElements that you want to use in OMD. I.e classes, objects, link, associations, etc.
2. You can collect them using
implPackage.getNestedElementsByMetaClass("Class", 1); // 1 means one level, you can increase it if you have to go deeper nests.
IRPModelElement implClass = null;
for(int i = 1; i < numberOfClasses+1 ; i++) {
    elementInCollection = (IRPModelElement)classesOfImplPack.getItem(i);
    if( elementInCollection.getMetaClass().equals("Class") && elementInCollection.getDisplayName().equals(componentName+"_Class") )
    {
        implClass = elementInCollection;
        break;
    }
 }

*Create a collection to collect them. (I just added a class as an example.)
IRPCollection packages = app.createNewCollection();
packages.setSize(3);
packages.setModelElement(1, implObject);
packages.setModelElement(2, association);
packages.setModelElement(3, link);
//Assuming that you have collected them before.

*Determine what to be drawn in OMD:
IRPCollection relTypes = app.createNewCollection();
relTypes.setSize(2);
relTypes.setString(1, "Link");
relTypes.setString(2, "Association");

*Create OMD
IRPObjectModelDiagram testerOMD = testerPackage.addObjectModelDiagram(componentName+"_Tester_OMD");

*Populate Diagram
testerOMD.populateDiagram(packages, relTypes, "fromto");


text:
Q: Json cascading dropdown I'm trying to set up a cascading dropdown using JSON data. I have it working somewhat but need some assistance getting the 2nd tier to work as intended. Currently it seems to be grabbing the number in the array.
Ideally for my 2nd tier I want to show the text in the dropdown as the option text, and I'd like to use the id field in the json as the value of the option.
var data = {
            "Crime":[
                {"id":"1","text":"Number of police"},
                { "id":"2","text":"Number of crimes"}
                    ],
            "Health":[
                {"id":"3","text":"Number of doctors"},
                {"id":"4","text":"Number of hospital visits"},
                {"id":"5","text":"Number of nurses"}
                    ],
                }

I have a jsfiddle showing what I have so far.
Happy to use whatever combination of javascript/jquery works best.

A: The way you have used for..in seems to be incorrect. The question variable will not contain the entire value if the pointed collection (data[this.value], in this case) is not a simple array. Rather, it would contain the index of the first row, the second row and so on. I request you to read this for a more in-depth understanding :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
This line here
questionSel.options[questionSel.options.length] = new Option(question, question);

Must read this way
questionSel.options[questionSel.options.length] = new Option(
                                      data[this.value][question].text,
                                      data[this.value][question].id);

Here's an updated fiddle after this change has been made:
http://jsfiddle.net/tc1f3kup/2/

A: please try this
 var data = {
        "Crime":[
            {"id":"1","text":"Number of police"},
            { "id":"2","text":"Number of crimes"}
                ],

        "Health":[
            {"id":"3","text":"Number of doctors"},
            {"id":"4","text":"Number of hospital visits"},
            {"id":"5","text":"Number of nurses"}

                ],

            }
 window.onload = function () {
        var themeSel = document.getElementById("theme"),
        questionSel = document.getElementById("questions");
        for (var theme in data) {
            themeSel.options[themeSel.options.length] = new Option(theme, theme);
        }
        themeSel.onchange = function () {
            questionSel.length = 1; // remove all options bar first
            if (this.selectedIndex < 1) return; // done
                for(var i=0;i<data[this.value].length;i++)
                {
                    questionSel.options[questionSel.options.length] = new Option(data[this.value][i].text, data[this.value][i].id);
                }

        }
}

working fiddle
http://jsfiddle.net/tc1f3kup/3/


text:
Q: MFC how to dock fill control? How do I force listctrl into tabctrl and from tabctrl into dialog?
Also is there a way to align the checkbox to the center of first column or only justify text to the center?


text:
Q: How scope of variable defined/flows in SQL statements compared to LINQ Here in this video at 11th minute, while explaining about strange structure (compared to SQL) of LINQ query, Anders Hejlsberg says that "Scope of variables in SQL flows backward in SQL", What does he mean by that? I'm totally confused... :(

A: Consider this simple SQL statement:-
 SELECT FirstName, LastName FROM People

Lexically we establish what fields we want (FirstName, LastName) from whatever before we define where we are getting them from (People).  Whereas:-
var query = from People select new {FirstName, LastName}

Lexically we establish from where we are getting data (People) before we define which specific bits of that data we want (FirstName, LastName).  The SQL approach is backward.


text:
Q: How to use AND logic operator using MongoDB\Driver\Manager class in PHP Mongodb I want to login a user if user name and password exist in the database. I have done so far is
<?php
    try {
        $name  = 'john';
        $password = 12345;

        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        $filter = [ 'name' => $name ];
        $query = new MongoDB\Driver\Query($filter);

        $res = $manager->executeQuery("DBName.Col", $query);

        $data = current($res->toArray());
        if (!empty($data)) {

        } else {
            echo 0;
        }
    } catch (MongoDB\Driver\Exception\Exception $e) {

        $filename = basename(__FILE__);
        echo "The $filename script has experienced an error.\n";
        echo "It failed with the following exception:\n";
        echo "Exception:", $e->getMessage(), "\n";
        echo "In file:", $e->getFile(), "\n";
        echo "On line:", $e->getLine(), "\n";
    }
?>

The line successfully filters the data if exists in the database $filter = [ 'name' => $name ]; But how can I confirm the password too? Will it not be odd if I get the password using username and then compare the passwords?


text:
Q: How to use an operator in where clause with an include? I have the following Model:
AuthorModel.hasMany(BookModel);
BookModel.belongsTo(AuthorModel);

I want to select an author whose name or the title of one of his books matches the search string.
Something like:
            Author.findOne({
                where: {
                    [Op.or]: [
                        { name: 'test'},
                        {'books.title':'test'}
                    ]
                },
                include: [{
                    model: Book
                }]
            })

Whatever I try, I always end up with: Unknown column 'books.title' in 'where clause'

A: You just need to move the where clause inside your include.
Author.findOne({
  include: [{
    model: Book,
    where: {
      [Op.or]: [
        { '$author.name$': 'test'},
        { title: 'test'}
      ]
    },
  }]
})


text:
Q: Getting dates with android facebook sdk v4.0 I have successfully installed the android sdk v4.0 in my studio.
I get to login correctly using LoginButton.
So far everything ok.
I want to have a string for each user data collecting interests me, for example:
String name = USER_NAME
String = USER_MAIL mail.
With the 3.0 sdk had it properly.
With the new SDK can not I do this, I followed the instructions in this thread:
Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User
I read in the documentation and in various threads about "Using the Graph API" but I can not get the data I'm looking for and assign them to each string.
this is my code (just as it is now):
LoginButton loginButton;
private CallbackManager mCallbackManager;
//...

loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
        mCallbackManager = CallbackManager.Factory.create();

//...

        loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                Toast.makeText(Ready.this, "Connected!", Toast.LENGTH_SHORT).show();

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(
                                    JSONObject object,
                                    GraphResponse response) {
                                // Application code
                                Log.v("LoginActivity", response.toString());
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender, birthday");
                request.setParameters(parameters);
                request.executeAsync();

            }
            @Override
            public void onCancel() {
                // App code
                Log.v("LoginActivity", "cancel");
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Log.v("LoginActivity", exception.getCause().toString());
            }
        });

As I said before, I connect with facebook perfectly, but do not know how to assign, for example, email to a string and name to another string.
Thank you very much in advance.

A: If you meant how to get name and email from the GraphRequest, it's simply this:
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(
                                JSONObject object,
                                GraphResponse response) {
                            // Application code
                            try {
                                String id=object.getString("id");
                                String name=object.getString("name");
                                String email=object.getString("email");
                                String gender=object.getString("gender");
                                String birthday=object.getString("birthday");
                                //do something with the data here
                            } catch (JSONException e) {
                                e.printStackTrace(); //something's seriously wrong here
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender, birthday");
            request.setParameters(parameters);
            request.executeAsync();

GraphResponse contains things like the HTTPConnect used, any error encountered, etc. Assuming everything goes as expected, only JSONObject object is needed to retrieve the data requested.

A: My working code for getting the profile information
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    profile = Profile.getCurrentProfile();
                    if(profile != null){
                            fbUserId = profile.getId();
                            editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
                            editor.putString("FbId",profile.getId());
                            editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
                            editor.commit();
                    }
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onError(FacebookException e) {

                }

            });

And you can track the profile changes here:
    profileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

            if(currentProfile != null){
                fbUserId = currentProfile.getId();

                if(!sharedPreferences.contains("UserName")){
                    editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
                }
                if(!sharedPreferences.contains("FbId")){
                    editor.putString("FbId",currentProfile.getId());
                }
                if(!sharedPreferences.contains("ProfilePicture")){
                    editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
                }

                editor.commit();
            }
        }
    };


text:
Q: Hibernate, JPA - example manytomany with two tables I try to use with many to many collection mapping, I hae two tables :
TASK and TASKRELATED, every task can has many related tasks and every related task can be in many parent tasks. here is my sql diagram:

Here is my entity :
@Entity
public class Task {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long taskId;

    @ManyToMany
    @JoinTable(name = "taskRelated", joinColumns = { @JoinColumn(name = "relatedTaskId") }, inverseJoinColumns = { @JoinColumn(name = "taskId") })
    private Set<Task> relatedTasks = new HashSet<Task>(0);

}

Here is my ropository :
public interface ITaskRepository extends JpaRepository<Task, Long>,
    QueryDslPredicateExecutor<Task>{
}

This is my code :
Task t = repository.findOne(1L);

This is my data in mysql:
task table

taskrelated table

When I do read of task object, there is en error:
    failed to lazily initialize a collection of role: org.Task.relatedTasks, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.Task.relatedTasks, no session or session was closed
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
    at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122)
    at org.hibernate.collection.PersistentSet.size(PersistentSet.java:162)
    at com.github.springtestdbunit.sample.service.UsersServiceTest.testTask(UsersServiceTest.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)

Please help !
in case of @ManyToMany(fetch=FetchType.EAGER) there is error like this :
 illegal access to loading collection
org.hibernate.LazyInitializationException: illegal access to loading collection
    at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:366)
    at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
    at org.hibernate.collection.PersistentSet.hashCode(PersistentSet.java:434)
    at org.Task.hashCode(Task.java:36)
    at java.util.HashMap.hash(HashMap.java:351)
    at java.util.HashMap.put(HashMap.java:471)
    at java.util.HashSet.add(HashSet.java:217)
    at java.util.AbstractCollection.addAll(AbstractCollection.java:334)
    at org.hibernate.collection.PersistentSet.endRead(PersistentSet.java:352)
    at org.hibernate.engine.loading.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:261)
    at org.hibernate.engine.loading.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:246)
    at org.hibernate.engine.loading.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:219)
    at org.hibernate.loader.Loader.endCollectionLoad(Loader.java:1005)
    at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:993)

A: It cannot initialize the collection, have you tried adding the set without initializing it?:
@ManyToMany
@JoinTable(name = "taskRelated", joinColumns = { @JoinColumn(name = "relatedTaskId") }, inverseJoinColumns = { @JoinColumn(name = "taskId") })
private Set<Task> relatedTasks;

A: As the exception says you are trying to access the collection elements - relatedTasks after closing the session and Hibernate lazily loads the collection elements by default.
So you need to access the elements within the session or alternatively you can add the fetch type to EAGER
 @ManyToMany(fetch = FetchType.EAGER)

Update:
As per stacktrace for exception - LazyInitializationException: illegal access to loading collection it has:
at org.hibernate.collection.PersistentSet.hashCode(PersistentSet.java:434)
at org.nli.seoweb.domain.Task.hashCode(Task.java:36)

Based on this I am assuming you have overridden the hashCode method in Task entity and this method is trying to access the Set. As Hibernate provides a wrapper class for the Set which is PersistentSet in this case, calling hashCode() internally has a validation that checks if the Set is fully initialized or not and then throw the exception.
So try modifying your Task.hashCode() method and make sure you are not using the Set in it, and see if it fixes the issue.
You can also refer to this post for similar exception.


text:
Q: What is the background of allowAllProperties, why is it necessary here? I have a form with a parameter that is mapped to an object storage. In a template I have form that sets this parameter with a list of checkboxes. Heres an overview of the action in the controller and the template.
Controller
/**
 * action list
 * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Redacted\Productfinder\Domain\Model\Category> $categories
 * @return void
 */
public function searchAction($categories=NULL) {
    \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump(func_get_args());
    ...
}

Template
<f:for each="{categories}" as="option">

            <f:form.checkbox name="categories" multiple="true" id="checkbox-category-{option.uid}" value="{option.uid}" checked="{x:condition.iterator.contains(haystack:'{filter.categories}', needle:'{option}', then:'checked')}" />
            {option.title}

</f:for>

This, so far, works like a charm. I'm now trying to set the $categories parameter with a link, but that doesn't work. I have a f:for loop with the categories.
If I set the Parameter to the single object like so, it is ignored. No error message, Extbase just ignores the value.
<f:link.action action="list" arguments="{categories:category}">{category.title}</f:link.action>

If I set the parameter to an array with that value, like so
<f:link.action action="list" arguments="{categories:{0:'{category}'}}">{category.title}</f:link.action>

Extbase tells me, that the Parameter cannot be mapped.
#1297759968: Exception while property mapping at property path "": It is not allowed to map property "0"

I've managed to figure out, that I can tell Extbase to allow the property mappging, and then resolve the raw uids into extbase objects, like so
        $propertyMappingConfiguration = $this->arguments->getArgument($property)->getPropertyMappingConfiguration();
        $propertyMappingConfiguration->allowAllProperties();

I'd like to understand the background of this, why is this necessary to allow this for GET parameters, when it just works for POST? Am I doing something wrong, or is this by design?

A: This is indeed by design. If you use <f:form.textfield..... it isn't needed to set it expliciet like you do.
This is to prevent that unwanted items are past/persisted because someone changed the form manually.
So it's a security thing


text:
Q: Finding Joint Probability Using Marginal Density Functions?
I was asked to represent $\Pr(X>x, Y>y)$ using the marginal distribution functions. The question didn't mention anything about independence. How would one do this?

A: It's easy to find examples of different joint distributions with the same marginal distributions.
Just take any continuous joint distribution with a density that has its support in a rectangular domain (or an unbounded equivalent of a rectangle), say $$f_{XY}(x,y)=k\,(x+y)\,\chi_{[0,1]}(x)\, \chi_{[0,1]}(y),$$ where $\chi_A$ is the characteristic function of set $A$ and $k\in (0,+\infty)$ is a such that the $f_{XY}$ integrates up to $1$ (that is, such that it actually be a density).
Then you can find a marginal density function for $X$ and for $Y$ as
$$f_X(x)=\int_{\mathbb R} f_{XY}(x,y) dy$$
and
$$f_Y(y)=\int_{\mathbb R} f_{XY}(x,y) dx.$$
Now if you define $g(x,y)=f_X(x)f_Y(y)$ this is also a joint density function, but not for the same distribution since any two variables with that distribution are independent (or just because $g$ and $f_{XY}$ are essentially different functions—as you'll see if do the calculations.)


text:
Q: Phrase meaning: fall as much as 90% Does the following quote mean the native population dropped to 90% of the original numbers or by 90%, that is to 10% of the original value?

[...] the native population of New Spain fell as much as 90% from its original numbers in the 16th century.

A: This phrase means that the native population fell to 10% of its original numbers in the 16th century. It fell by 90%. Hope this helps. Also see:
http://idioms.thefreedictionary.com/fall+by

A: "Fell as much as 90%" means that afterward, only 10% of the population may have remained. For example, if a population of 100 fell by 85%, the population is now 15.


text:
Q: how to exec a pod via WebSocket written in csharp I want use a websocket client to exec commands in a Kubernetes pod,Develop a web terminal using xterm.js, i wrote websocket for the backend via asp.net core 3.1,
         websocket                                                  websocket
xterm.js -----------------> websocketServer ----------------> k8s
          cmd:ls                                                       cmd:ls

here is my websocketServer code:(asp.net core 3.1)
[HttpGet("/ws"), AllowAnonymous]
public async Task Terminal()
{
   var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(Environment.GetEnvironmentVariable("KUBECONFIG"));

   var client = new Kubernetes(config);
   var namespaces = client.ListNamespace();

   if (!HttpContext.WebSockets.IsWebSocketRequest)
   {
      HttpContext.Response.StatusCode = 400;
   }

   //web websocketServer
   using var websocketServer = await
   HttpContext.WebSockets.AcceptWebSocketAsync();
   await Echo(websocketServer);

   //k8s websocket
   var k8sWebSocket = await client.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, "winter", "ls",pod.Spec.Containers[0].Name).ConfigureAwait(false);

   //receive user input
   async Task Echo(WebSocket webSocket)
   {
     var buffer = new byte[1024 * 4];
     var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

     while (!result.CloseStatus.HasValue)
     {
        var serverMsg = Encoding.UTF8.GetBytes($"{Encoding.UTF8.GetString(buffer)}");
        await webSocket.SendAsync(new ArraySegment<byte>(serverMsg, 0, serverMsg.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
        //todo:
        //how to transfer user input to k8sWebsocket...
        //...

        result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        //todo:
        //how to transfer k8sWebsocket stdout to websocket...
        //...

      }
      await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
   }

when run the project, execute the command as blow:

let webSocket = new WebSocket('ws://localhost:29126/ws');

an error occured: WebSocket connection to 'ws://localhost:29126/ws' failed:

and the error detail is Unable to read data from the transport connection: Software in your host aborted an established connection. .


text:
Q: Pure Python in Xcode Is there a way to program using pure python in Xcode? I want something like the c++ command line utility except for python, I found a tutorial that did not work for me: (after playing around with which active architecture finally decided on i386) when trying to print "Hello, World!" I get the following error "Data Formatters temporarily unavailable, will re-try after a 'continue'. (Cannot call into the loader at present, it is locked.)" (Using an intel Mac OS 10.6.4 and Xcode 3.2.3)
Here is how I followed the steps:
    1) Opened Xcode went to File -> New Project
    2) Selected from 'Other', 'Empty Project'
    3) Named it 'PyProject' in a local directory on my computer
    4) Went to File -> New File
    5) From 'Pure Python' I selected 'Python tool', named it main.py then clicked finish
    6) Added print ('Hello, World!') to the file, and saved the file
    7) Went to Project -> New Custom Executable
    8) Named it PyExecutable, gave it path" /Library/Frameworks/Python.framework/Versions/2.6/bin/python" and added it to project PyProject, then clicked Finish
    9) Double-clicked PyExecutable in PyProject window
    10) Went to Arguments and added the path of my main.py file "/Users/jordan/PyProject/main.py"
    11) Switched Active Architecture from the pull down menu at the top of the PyProject window to i386 (Now is in Debug, No Active Target, PyExecutable Is Active Executable and Architecture is i386)(If I don't switch the architecture and leave it on default x86_64 I get this error as a pop-up "The active architecture x86_64 is not present in the executable 'PyExecutable' which contains ppc/i386")
    12) Clicked Run -> Run and then I get the error listed above in the console
Before anyone suggests it: I know Xcode is not the best option for pure python please do not suggest that I use another text editor.
Edit: details of what was not working when following the tutorial
Edit: my system details were added, and the steps I followed to get the error
Update: I wrapped the path of main.py in double quotes "" and now when I press continue after the error the console prints hello world, but I get the same error originally.

A: /Library/Frameworks/Python.framework/Versions/2.6/bin/python is typically the path to the python.org installer Python (or possibly other non-Apple Python) which, indeed, includes only 32-bit architectures (ppc and i386).  It also is built using the OS X 10.4u SDK (an optional install with Xcode on 10.6).  The Apple-supplied Python 2.6 in 10.6 is built using a 10.6 SDK and includes 32-bit and 64-bit archs (i386, x86_64, and ppc for compatibility).
$ /usr/local/bin/python2.6 -c 'import sys;print(sys.executable)'  # python.org Python
/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
$ /usr/bin/python2.6 -c 'import sys;print(sys.executable)'  # Apple-supplied Python
/usr/bin/python2.6

Decide which Python you want to use and change your Xcode project accordingly.


text:
Q: Presto configuration As I set up a cluster of Presto and try to do some performance tuning, I wonder if there's a more comprehensive configuration guide of Presto, e.g. how can I control how many CPU cores a Presto worker can use. And is it good practice if I start multiple presto workers on a single server (in which case I don't need a dedicated server to run the coordinator)?
Besides, I don't quite understand the task.max-memory argument. Will the presto worker start multiple tasks for a single query? If yes, maybe I can use task.max-memory together with the -Xmx JVM argument to control the level of parallelism?
Thanks in advance.

A: Presto is a multithreaded Java program and works hard to use all available CPU resources when processing a query (assuming the input table is large enough to warrant such parallelism). You can artificially constrain the amount of CPU resources that Presto uses at the operating system level using cgroups, CPU affinity, etc.
There is no reason or benefit to starting multiple Presto workers on a single machine. You should not do this because they will needlessly compete with each other for resources and likely perform worse than a single process would.
We use a dedicated coordinator in our deployments that have 50+ machines because we found that having the coordinator process queries would slow it down while it performs the query coordination work, which has a negative impact on overall query performance. For small clusters, dedicating a machine to coordination is likely a waste of resources. You'll need to run some experiments with your own cluster setup and workload to determine which way is best for your environment.
You can have a single Presto process act as both a coordinator and worker, which can be useful for tiny clusters or testing purposes. To do so, add this to the etc/config.properties file:
coordinator=true
node-scheduler.include-coordinator=true

Your idea of starting a dedicated coordinator process on a machine shared with a worker process is interesting. For example, on a machine with 16 processors, you could use cgroups or CPU affinity to dedicate 2 cores to the coordinator process and restrict the worker process to 14 cores. We have never tried this, but it could be a good option for small clusters.
A task is a stage in a query plan that runs on a worker (the CLI shows the list of stages while the query is running). For a query like SELECT COUNT(*) FROM t, there will be a task on every work that performs the table scan and partial aggregation, and another task on a single worker for the final aggregation. More complex queries that have joins, subqueries, etc., can result in multiple tasks on every worker node for a single query.

A: -Xmx must be higher than task.max-memory, or at least equal.
otherwise you will be likely to see OOM issue as I have experienced that before.
and also, since Presto-0.113 they have changed the way Presto manages the query memory and according configurations.
please refer to this link:
https://prestodb.io/docs/current/installation/deployment.html

A: For your question regarding "many CPU cores a Presto worker can use", I think it's controlled by the parameter task.concurrency, which by default is 16


text:
Q: How do I allocate more space for my array of C structs? I'm trying to add 10 more elements to my struct that has been already malloc with a fixed sized of 20. This is the way I have my struct defined:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct st_temp {
   char *prod;
};

int main ()
{
   struct st_temp **temp_struct;

   size_t j;
   temp_struct = malloc (sizeof *temp_struct * 20);
   for (j = 0; j < 20; j++) {
      temp_struct[j] = malloc (sizeof *temp_struct[j]);
      temp_struct[j]->prod = "foo";
   }

   return 0;
}

So what I had in mind was to realloc as (however, not sure how to):
temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));

and then add the extra 10 elements,
   for (j = 0; j < 10; j++)
      temp_struct[j]->prod = "some extra values";

How could I achieve this? Any help is appreciated!

A: When you use realloc(), you must give the new size instead of the number of bytes to add. So:
temp_struct = (struct st_temp **) realloc (temp_struct, 30 * sizeof(struct st_temp*));

30 is, of course, your original 20 plus 10 more. The realloc() function takes care of copying the original data to a new location if it needs to move the memory block.
Then, adding the extra 10 elements would be something like (starting at index 20, not 0):
for (j = 20; j < 30; j++) {
    temp_struct[j]->prod = "some extra values";
}

A: To avoid memory leaks, we need to handle reallocating with care (more on that later). The realloc function:
void *realloc(void *ptr, size_t size), where
ptr = the pointer to the original (malloc'ed) memory block, and
size =  the new size of the memory block (in bytes).
realloc returns the new location of the dynamically allocated memory block (which may have changed) - or NULL if the re-allocation failed! If it returns NULL, the original memory stays unchanged, so you must always use a temporary variable for the return value of realloc.
An example will clarify this a bit (points of interest: realloc syntax is similar to malloc's (no need for extra casts etc.) and, after realloc, you need to produce the same steps for the new objects as you did after malloc):
struct st_temp **temp_struct;
temp_struct = malloc(20 * sizeof *temp_struct);
if (temp_struct == NULL) { /* handle failed malloc */ }
for (int i = 0; i < 20; ++i) {
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "foo";
}

// We need more space ... remember to use a temporary variable
struct st_temp **tmp;
tmp = realloc(temp_struct, 30 * sizeof *temp_struct);
if (tmp == NULL) {
    // handle failed realloc, temp_struct is unchanged
} else {
    // everything went ok, update the original pointer (temp_struct)
    temp_struct = tmp;
}
for (int i = 20; i < 30; ++i) { // notice the indexing, [20..30)
    // NOTICE: the realloc allocated more space for pointers
    // we still need to allocate space for each new object
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "bar";
}
// temp_struct now "holds" 30 temp_struct objects
// ...
// and always do remember, in the end
for (int i = 0; i < 30; ++i)
    free(temp_struct[i]);
free(temp_struct);

Do note, that this is not really an array of structs, but more an array of pointers to structs - or even an array of arrays of struct if you wish. In the last case, each sub-array would be of length 1 (since we only allocate space for one struct).


text:
Q: What's the right approach to generate multiple CSS bundles and import only the necessary ones on runtime? My team and I are currently working on a multi template / multi skin app. This means there is a base style and multiple style overwrites or custom styles. We use Sass.
There's basically a new template every month, this means that the styles files grow in size and in number.
What we currently do is to generate a single CSS bundle using Webpack. The app (React) imports that bundle. Only some styles are applied depending on which template we are using. It is not possible to switch from one template to the other during run time. The template to be used is determined server side using an identifier. We just basically use that identifier as the class of the root element so only the necessary styles are applied to it and its children.
The approach has worked for us so far cause there are still just a few templates. But we know this will impact the load times potentially if more and more styles are created.
We've thought about generating multiple bundles during build time but we will still need to get only THE ONE we need during run time. This way we would avoid bringing a big bundle from the server.
I would like to hear some suggestions and what would be a good approach to accomplish this.
Thanks for your time.


text:
Q: Move a table in the article before its declaration Hello I wrote 3 macros for creating a table of content I add within the article. \startMyTable, \inMyTable, \createMyTable their names suggests what they do.
So when I write:
Hello
\startMyTable
Hello2

\inMyTable{FIRST}
\inMyTable{SECOND}

Hello3
\createMyTable
Hello4

It creates something like this:
Hello
Hello2
Hello3
 --------
|  FIRST |
 --------
| SECOND |
 --------
Hello4

Is there I way to move the table at a certain point of the article (e.g. at the beginning of it)? I see this requires like a pre-compilation of the latex syntax but I have no clue about how to do it and what to search. Do you have any tip?
I post the code I was suggested to use for creating tables like these:
\newcommand\startMyTable{\def\MyTable{\begin{tabular}{|l|}}}

\newcommand\inMyTable[1]{%
   \edef\MyTable{%
   \expandafter\unexpanded\expandafter{\MyTable#1\\}}}

\newcommand\createMyTable{\begin{center}\MyTable\end{tabular}\end{center}}

A:
\documentclass{article}

\makeatletter

\newcommand\startMyTable{%
\immediate\write\@auxout{\unexpanded{%
  \gdef\MyTable{}}}}

\newcommand\inMyTable[1]{%
\immediate\write\@auxout{\unexpanded{%
   \xdef\MyTable{%
   \expandafter\unexpanded\expandafter{\MyTable#1\\}}}}}

\newcommand\createMyTable{%
  \begin{center}
\begin{tabular}{|l|}\ifx\MyTable\@undefined \ldots\else\MyTable\fi\end{tabular}
\end{center}}

\makeatother

\begin{document}

\createMyTable

\section{zzz}

Hello
\startMyTable
Hello2

\inMyTable{FIRST}
\inMyTable{SECOND}

Hello3

Hello4

\end{document}

Like all such things, takes two runs (you get ... in the first run)


text:
Q: Issue running shutdown hook in java I am trying to get a shutdown hook to run in java. The purpose of this hook is to write into a log file that the program was terminated. The java application is compiled into a jar file and executed using a batch file, which means that the output of the application goes to a cmd.exe window. When this cmd window is closed, i want the application to log that it was closed.
The application is intended to run indefinitely and do certain tasks at a certain time. Therefore, the program is executing a series of checks within a "While true" loop. I do not understand why this hook will not log that the application is closing!
In the main method we have:
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
{
    @Override
    public void run()
    {
        try { mainThread.join(); }
        catch (InterruptedException e) { }
        mission.log("Program Closed.", true);
    }
}
));

All "mission" is, is an instance of a custom class of mine that does data logging. When you call the method "log", it has a BufferedWriter and it calls its .write(), .newLine(), and .flush() methods.
I can't seem to get the "Program Closed" line in my logfile when i kill the batch window. What am I doing wrong?

A: Forcibly killing the application, i.e. not gracefully, so the JVM doesn't know that the application is exiting, therefore the shutdown hooks are not invoked.
Unfortunately, there is no way (in Windows, at least) to provide a mechanism that ensures that the hook is always invoked. It's just something that may be invoked, but there is no guarantee.

A: There is no way to always execute something before your process exits. E.g. if you pull the plug out of the wall outlet, your computer shuts down immediately. Or if the process is killed by the operating system by removing it from the scheduler for CPU time, it also has no chance.
However, if you remove the code
    try { mainThread.join(); }
    catch (InterruptedException e) { }

Then it will at least be executed for certain cases, e.g. a normal termination of the process. Checking for the main thread here doesn't make sense, because either the shutdown hook is executed as a result of the main thread having finished its work (it exited the main() method), or the main thread will continue to run until the JVM decides to terminate (in case of termination from outside).
Compare the accepted answer of How to gracefully handle the SIGKILL signal in Java, which contains another example of what you're trying to do.

A: Closing the window kills the process so a shutdown hook won't work.
It sounds like you would rather not have this process killed at all.  You should consider using something other than a batch script.  You can run an executable jar from the windows task scheduler and have it running in the background all the time - unless someone intentionally kills java or an error occurs.  In which case you should be trying to catch exceptions and log them that way.

A: Everyone here is correct - you can't log a forcible stop on your program. However, you might consider using another program to 'watch' your program and wait for it to exit. The 'watcher' program can then log the termination of the original program and then exit itself.


text:
Q: После падения сервера не включается mysql После падения сервера не видит сокет файл /var/lib/mysqld/mysqld.sock
При попытке запуска БД пишет следующее
Can't connect to local MySQL server through socket '/var/lib/mysqld/mysqld.sock' (2)
В статусе пишет следующее
# systemctl status mysql.service
● mysqld.service - MySQL Server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
   Active: activating (start-pre) since Fri 2022-08-19 15:44:51 UTC; 361ms ago
     Docs: man:mysqld(8)
           http://dev.mysql.com/doc/refman/en/using-systemd.html
  Process: 7008 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/m                                                                                ysqld.pid $MYSQLD_OPTS (code=exited, status=1/FAILURE)
  Control: 7035 (mysqld_pre_syst)
   CGroup: /system.slice/mysqld.service
           └─control
             ├─7035 /bin/bash /usr/bin/mysqld_pre_systemd
             └─7060 /usr/bin/python -Es /usr/sbin/semanage fcontext -a -e /var/l...

Aug 19 15:44:51  systemd[1]: Starting MySQL Server...


text:
Q: Scala Play2.4 / Sbt multi-project build not working I'm trying to fragment my sbt scala Play project into several buildable modules. I read the official sbt multi-project guide, Play 2.4.x multi-project guide, and these examples: playing-microservices and the example from the Scala Cookbook, Another good example. They all subtly diverge and I've had no luck so far.
I keep getting the following:
$ sbt (or ./activator)

> project myPlay
> compile
... OK
> start
...
(Starting server. Type Ctrl+D to exit logs, the server will remain in background)

Error: Could not find or load main class play.core.server.ProdServerStart

How do I get past this?
Here's what I did:
My first step was to create two toplevel dirs: my-common-lib and my-play-proj. I moved /app /conf /public /test into /my-play-project, and created a /src/main/scala/fooPackage/.. dir in my-common-lib, s.t.:
/my-common-lib
- /src
/my-play-project
- /app
- /conf
  - /application.conf
  - /routes
  - /evolutions
  ...
- /test
- /public
/build.sbt
/project
- /build.properties
- /plugins.sbt

Then I changed my build.sbt as follows:
import sbt.Keys._

lazy val root = (project in file (".")) settings (
    name := "root-overlord",
    version := "1.0.0"
  ) aggregate (common, myPlay)

lazy val common = (project in file ("my-common-lib")) settings (commonSettings: _*) settings (
    name := "some-common-lib",
    version := "1.0.0"
  )

lazy val myPlay = (project in file ("my-play-project")).
  enablePlugins(PlayScala).
  settings(commonSettings: _*).
  settings (
    name := """my-play""",
    version := "1.8.2",
    // Play provides two styles of routers, one expects its actions to be injected, the
    // other, legacy style, accesses its actions statically.
    routesGenerator := InjectedRoutesGenerator,
    javaOptions in run += "-javaagent:" + System.getProperty("user.home") + "/.ivy2/cache/org.aspectj/aspectjweaver/jars/aspectjweaver-1.8.8.jar -Xmx2G",
    fork in run := true,
    connectInput in run := true,
    javaOptions in Test += "-Dconfig.resource=test.application.conf",
    parallelExecution in Test := false,
    packageName in Universal := "myPlayProj"
  ).
  dependsOn(common % "compile->compile;test->test")

lazy val commonSettings = Seq (
  organization := "the-great-empire",
  scalaVersion := "2.11.8",
  libraryDependencies := Seq(
       ...
  ),
  resolvers := Seq(
    ...
  ),
  javaOptions in Test += "-Dconfig.resource=test.application.conf",
  parallelExecution in Test := false
)

Any ideas?
Many thanks.


text:
Q: How to append first and last element in each vector (of a different length) of a list in R, without making the code slow? I am new to R and StackOverFlow. So if there's something I am missing, please let me know. I am working on simulating nonhomogeneous processes to understand the neural behavior better. My code works in a way that I have, say 20 trials lasting 2 seconds each (each trial representing a spike train). Then the list SpikeTimes gives me a list of 20 vectors where each vector corresponds to the time stamps of where the spikes occurred in that particular trial. [Eg.SpikeTimes[1] which looks like this, 0.002250802 0.053934034...1.971574170 2.023090384 means that in the first Spike Train, spikes occurred at 0.002250802, 0.053934034 and so on. I don't know why it also brings up a time stamps beyond my time limit of 2 seconds, but I will work on that later]. My code looks like this--
nTrials=20
t_max=2.0000000

LambdaInv<- function(x){ifelse( x< 15, x/30,
                    ifelse(x >= 15 & x < 38, ((x-15)/46)+0.5,
                           ifelse(x >= 38 & x <53, ((x-38)/30)+1.0,
                                  ifelse(x >= 53 & x< 67.4, ((x-53)/72)+1.5,
                                         ((x-67.4)/30)+1.7))))}

 t = 0
 s = 0
 X = numeric(0)

 NonHomoSpikes <- function(t_max){
  while(t <= t_max){
    u <- runif(1)
    s <- s-log(u)
    t <- LambdaInv(s)
    X <- c(X,t)
       }
    return(X)
   }

SpikeTimes <- lapply(1:nTrials, function(x) NonHomoSpikes(2))

My problem is that, for each of the vector in the list SpikeTimes; which gives time stamps of spikes, I also want to include the beginning (that is 0) and the end (that is 2) of the spike train. So I want to append this list to have each vector include the first entry as 0 and the last entry as 2.
My SpikeTimes[1] would then look like 0 0.002250802 0.053934034...1.971574170 2 and other SpikeTimes[i] would look similar. I tried SpikeTimes <- c(0, SpikeTimes) for entering 0 in the beginning but it only made the list have 21 vectors instead of 20 with the vector 0 as the first element (I mean I get why that happened). How can I do it in a way that doesn't make my code slow? I am newbie in R and reading up on the internet hasn't help with this particular problem. I would appreciate any sort of input.

A: Solution: change NonHomoSpikes return statement to return(c(0, X, 2)).
To 'manually' stop if t < 2 (as described in comments):
NonHomoSpikes <- function(t_max){
  while(t <= t_max){
    u <- runif(1)
    s <- s-log(u)
    t <- LambdaInv(s)
    if(t > 2) break
    X <- c(X,t)
       }
    return(c(0,X,0))
   }


text:
Q: JAXB not generating field for redefined attribute I have an xsd that redefines a complex type to add a sequence:
<xs:redefine>
  <xs:complexType name="data-extension.type">
    <xs:complexContent mixed="true">
      <xs:extension base="data-extension.type">
        <xs:sequence>
          <xs:any minOccurs="0" maxOccurs="unbounded" processContents="strict"/>
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>
</xs:redefine>

However when I generate the code for my xsd using JAXB, the DataExtensionType class does not has a field for the sequence.
Am I missing something in the xsd or the JAXB generation parameters?
Edit:
This is the generated Java:
/**
*
Java class for data-extension.type complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="data-extension.type">
 *   <complexContent>
 *     <extension base="{http://graphml.graphdrawing.org/xmlns}data-extension.type">
 *       <redefine>
 *         <complexType name="data-extension.type">
 *           <complexContent>
 *             <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *             </restriction>
 *           </complexContent>
 *         </complexType>
 *       </redefine>
 *       <sequence>
 *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "data-extension.type", namespace = "http://graphml.graphdrawing.org/xmlns")
@XmlSeeAlso({
    DefaultType.class,
    DataType.class
})
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-03-02T02:29:07+00:00", comments = "JAXB RI v2.2.8-b130911.1802")
public class DataExtensionType
    extends OriginalDataExtensionType
{

}

The comment suggest the sequence was found during parsing.
I was expecting to see a List<Object> any (or similar) and its getter to be generated. The supper class has a contents field, but its type is String.
Edit 2:
The OriginalData class:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "content"
})
@XmlSeeAlso({
    DataExtensionType.class
})
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-03-02T02:29:07+00:00", comments = "JAXB RI v2.2.8-b130911.1802")
public class OriginalDataExtensionType {

    @XmlValue
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-03-02T02:29:07+00:00", comments = "JAXB RI v2.2.8-b130911.1802")
    protected String content;

    /**
     *
     *       Extension mechanism for the content of <data> and <default>.
     *       The complex type data-extension.type is empty per default.
     *       Users may redefine this type in order to add content to
     *       the complex types data.type and default.type which are
     *       extensions of data-extension.type.
     *
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-03-02T02:29:07+00:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public String getContent() {
        return content;
    }

    /**
     * Sets the value of the content property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2018-03-02T02:29:07+00:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public void setContent(String value) {
        this.content = value;
    }

}

At first I also expected that the contents field would be the sequence.


text:
Q: ServletContext getContextPath() I checked the javadocs of the Tomcat library I have included under my Netbeans project, and when I deploy the code works fine, but when I do a clean-build of my web project I get a "cannot find symbol" on the getContextPath() method of the ServletContext interface
It's driving me completely insane because in order to run my tests and so on I have to first deploy, then test, if I clean and build, or clean and run tests I get this error...
Anyone have any clue what could be causing this issue?  Is there a library I have to update or something?

A: I suspect it's not in the version of ServletContext you're building against, but it is in the version you're deploying against. According to the docs of version 2.5 it was introduced in 2.5. So basically change the servlet.jar you're building against to be the 2.5 one, and it should be fine.