text:
Q: Best way to initialise fields in a Class without boilerplate code I have a PivotModel class which I will initialise using the new keyword.
PivotModel pivotModel = new PivotModel()

When pivotModel gets initialised, all the dependant fields(model1, model2,cell1,cell2) should get initialised with new object but not to null.
I wanted to initialise all the fields and the fields of dependant classes without using new constructor. I don't want to have boilerplate code.
If you have any standard practice of way doing it, post it here. I am also using lombok in my project.
public class PivotModel {
    @Getter
    @Setter
    private Model1 model1;

    @Getter
    @Setter
    private Model2 model2;

    private Model3 model3 = new Model3() -----> Dont want to initialise this way for these fields
}

public class Model1 {
    private Map<String,Cell> cell1;
    private Map<String,Cell> cell2;
    private Map<String,Cell> cell3;
    ------ will have some 10 fields here
}

A: It seems that you are using Lombok project in your java project you can add @Getter @Setter above your class Scope, Lombok also provides Constructor Annotation, so Just type above your class Scope @AllArgsConstructor
so you class Should be like this
@Getter
@Setter
@AllArgsConstructor
public class PivotModel {
    private Model1 model1;
    private Model2 model2;
}

@Getter
@Setter
@AllArgsConstructor
public class Model1 {
    private Map<String,Cell> cell1;
    private Map<String,Cell> cell2;
    private Map<String,Cell> cell3;
}

A: For initialization, I would recommended Builder Pattern.
//keep your initialization logic in builder class and use build()/create() wherever required. Let's say:
Class Pivot{
 // Note: this have only getters for members

 //inner builder class
 PivotModelBuilder{

   //Note: all setter will be part of builder class

   /**
     * method which return instantiated required object.
    */
   public PivotModel build(){
        return new PivotModel(this);
    }
  }
}
//access initilization code as:
PivotModel pivot = new Pivot.PivotModelBuilder().build()

Adding referral link: https://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html
(You can search more about builder pattern and it's implementation online)
Limitations:

*

*However, it's good way to initialize/create bean, but, you might find duplication of member fields in both Parent and builder class.


text:
Q: Node-RED not able to access to array member I'm trying to access to a JSON array returned by a OpenWeatherMap request.
The JSON data is:
{ "city":
  { "id": 3171457, "name": "New York", "coord": { "lon": 0.32898, "lat": 4.802662 }, "country": "US", "population": 0, "sys": { "population": 0 } },
  "cod": "200", "message": 0.0317, "cnt": 40,
  "list": [ { "dt": 1483552800, "main": { "temp": 277.28, "temp_min": 275.705, "temp_max": 277.28, "pressure": 1013.85, "sea_level": 1021.42, "grnd_level": 1013.85, "humidity": 93, "temp_kf": 1.57 }, "weather": [ { "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" } ], "clouds": { "all": 0 }, "wind": { "speed": 4.74, "deg": 269.002 }, "sys": { "pod": "n" }, "dt_txt": "2017-01-04 18:00:00" },
...

If i use in a template {{payload.list}} I see a list of [object Object]s.
But if I use {{payload.list[0]}}, or {{payload.list[0].main}}, I see nothing - my guess was a single [object Object].
How can i access to the first member and inner members?

A: The template node uses the mustache format, documented here: https://mustache.github.io/mustache.5.html
To access array values, you should use the following syntax:
{{ payload.list.0 }}

and
{{ payload.list.0.main }}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vuejs how to trigger external script event In my vue-app I want to include an external script from a shop, so that when I click on a product, the script gets fired and opens the overlay with the buying process...
I tried to to this:
<template>

{{ product.title }}

           // then the code, the shop requires for its overlay to work
           Buy now 99$
           // product id = {{product.id}}

 </template>

then I included the script tag which is also provided by the shop ( for security reasons I cannot provide all of it...)
export default {
  head() {
    return {
      script: [
       {
         id: "fsc-api",
         src: "https://d1f8f9xcsvx3ha.cloudfront.net/...",
         type: "text/javascript",
         "data-storefront": "...",
         "data-popup-closed": "...",
         async: true,
       },
     ],
   };
 },
}

but this triggers nothing and I don't know how to solve this
can someone help me out?


text:
Q: My Login script automatically logs out I made myself a login script, but now when I sign in, It goes to the home page and when i click on a other page it signs me out. When i sign back in. It does work.
This is my login script:
if(isset($_POST['login'])){
if($sQuery = $db->query("SELECT salt, id FROM users WHERE email='".$db- >real_escape_string($_POST['email'])."'")){
    $sFetch = $sQuery->fetch_assoc();
    if($lQuery = $db->query("SELECT id FROM users WHERE email='".$db->real_escape_string($_POST['email'])."' AND password='".crypt($_POST['password'], $sFetch['salt'])."'")){
        if($lQuery->num_rows > 0){
            $_SESSION['email'] = $_POST['email'];
            $_SESSION['id'] = $sFetch['id'];
            header('Location: home');
            exit();
        }else{
            $errorlogin = "Je email of wachtwoord klopt niet.";
        }
    }else{
        $errorlogin = "Er is iets misgegaan. Foutmelding: ".$db->error;
    }
}else{
    $errorlogin = "Er is iets misgegaan. Foutmelding: ".$db->error;
}
}

And this is my index:
<?php
session_start();
include_once("includes/class.database.php");

if(isset($_SESSION['id'])){
    include("ingelogd.php"); //When signed in
}else{
    include("inloggen.php"); //when not signed in
}
?>

I hope someone can help me

A: Is the space intentional in the first .$db- >real_escape_string ?

A: also check if the session variable is available for the script..use empty() test instead of isset
if(!empty($_SESSION['id'])){
    include("ingelogd.php"); //When signed in
}else{
    include("inloggen.php"); //when not signed in
}


text:
Q: Group By Date Timestamp MySQL I've got the following query on a timestamp(specified by INT(10), which kind of does what I want, but not exactly:
SELECT count(entry_date) as theCount, FROM_UNIXTIME(entry_date, '%Y-%m-%d') AS dd
FROM exp_weblog_titles
WHERE entry_date < UNIX_TIMESTAMP(NOW())
GROUP BY dd
ORDER BY dd DESC
LIMIT 7

That spits out the last 7 dates and the # of entries on those dates that are before today's date.  The problem with the query I've created is, it only spits out the date if it actually has an entry on it.  When in actuality, I still want that date included even if there are zero entries.  Is that possible?

A: You will need to have a list of dates from somewhere. A lot of people create a calendar table just for this purpose with every date (or every value) that they need so that this calendar table and your data table can be joined to provide this kind of query.
You will find in the long run this is far simpler than any other solution, just takes a moment to set up.
See this article for an example of how to generate such a table.


text:
Q: Oracle - Unique values from a single column, but returning other columns I'm trying to figure out how pull select values from a table column, but return other results as well.  For example say I have the following table
person  ..........
------------------
bob     ..........
mary    ..........
bob     ..........
sue     ..........

What I want to return back is
bob     ..........
mary    ..........
sue     ..........

In this case I don't care what values I am actually receiving back for bob from the other columns how would I do that?

Follow up question, what if I did care though?  What if I had this table
person  type    color   ..........
----------------------------------
bob     0       blue    ..........
mary    1       green   ..........
bob     1       red     ..........
sue     0       yellow  ..........

And this time I again want unique people, but I want the results back for bob when his type is 0, so for him I would see
bob     0   blue    ..........
mary    1   green   ..........
sue     0   yellow  ..........

Thanks!

A: You can use analytic functions like RANK to describe the algorithm for which row you want to keep and then do something like
SELECT *
  FROM (SELECT person,
               type,
               color,
               RANK() OVER( PARTITION BY person
                                ORDER BY type asc ) rnk
          FROM <<person_table>>)
 WHERE rnk = 1

This returns the "first" row for each person where "first" is determined by the row with the lowest TYPE value.
One thing to be aware of when you start looking at ranking rows is that there are three different analytic functions-- RANK, DENSE_RANK, and ROW_NUMBER-- that all do basically the same thing but handle ties differently.  RANK is the standard athletics ranking function-- if there are two rows that tie for first place (i.e. two rows where PERSON='bob' and TYPE=0), they would both get a rank of 1 while the next row would get a rank of 3 so there would be no "second place" row.  In the same situation, DENSE_RANK would also give both tied rows a rank of 1 but would give the next row a rank of 2.  ROW_NUMBER would arbitrarily give one of the tied rows a rank of 1, give the other one a rank of 2, and give the third row a rank of 3.  Of course, you can break ties by adding additional columns to the ORDER BY clause.

A: Alternative syntax using Generic SQL for DBs that don't have RANK
SELECT
       person,
       type,
       color

FROM

   <<person_table>> p
   inner join
  (SELECT person,
         min(type) type
    FROM <<person_table>>
    GROUP BY
         person) minType
    on p.Person = minType.Person
       and p.type = minType.type


text:
Q: error when i integrate my flutter app with firebase i run my app and its worked correctly but when i tried to integrate it with firebase it shows an error
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:mergeDexDebug'.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
  Failed to transform artifact 'play-services-base.aar (com.google.android.gms:play-services-base:17.0.0)' to match attributes {artifactType=android-dex, dexing-enable-desugaring=true, dexing-is-debuggable=true, dexing-min-sdk=16}.
  Execution failed for DexingWithClasspathTransform: C:\Users\lenovo.gradle\caches\transforms-2\files-2.1\4c0b774c09d5393feb013f0dbe753af3\play-services-base-17.0.0\jars\classes.jar.
  Cannot parse result path string:

A: Inside build.gradle, do the following:
Change the minSdkVersion from:
minSdkVersion 16

Into the following:
minSdkVersion 21


text:
Q: Site assets not loading from a subdomain When I visit the site here > http://stammer.in/blog/ it loads perfectly but when I load it from here > http://blog.stammer.in/ no asset is loaded.
I have set up a subdomain which points blog.stammer.in to stammer.in/blog
After researching a bit, I found out that for some reason, blog.stammer.in is not loading the theme related html and I have absolutely no idea why it's happening.
The site and Home url are set to http://stammer.in/blog/.
Changing site url to http://blog.stammer.in does not do anything except it makes http://stammer.in/blog/ render a blank theme page when an Admin is logged in.

It renders fine for a visitor though.
EDIT: The problem is because of W3 Total Cache plugin. Anyone have any idea why it could have happened?


text:
Q: все привет !помогите)не работает импорт Beautifulsoup в питоне .не высвечивается и поэтому мой код видимо не работает     import requests
    from bs4 import BeautifulSoup as BS:

    def get_response(url):
        response = requests.get()
        if response.status_code == 200:
            return response.text
        else:
            return "Не успешный запрос "

    my_url = "сюда написала сайт который мне нужен"
    print(get_response(my_url))

A: Во второй строчке не должно быть двоеточия
    import requests
    from bs4 import BeautifulSoup as BS

    def get_response(url):
        response = requests.get()
        if response.status_code == 200:
            return response.text
        else:
            return "Не успешный запрос "

    my_url = "сюда написала сайт который мне нужен"
    print(get_response(my_url))


text:
Q: What is the $S^1$-equivariant cup product on $S^2$? Consider the sphere $S^2 = \mathbb{CP}^1$ with the $S^1 = \{ \tau \in \mathbb{C} \mid |\tau| = 1 \}$ action given by
$$ \tau \cdot [z_1, z_2] = [\tau ^ k \cdot z_1, z_2] $$
The corresponding $S^1$-equivariant cohomology is $H_{S^1}^\ast(\mathbb{P}^1) = \mathbb{Z}[u] \cdot 1 \oplus \mathbb{Z}[u]\cdot y$, where $1$ and $y$ correspond to the generators of the ordinary cohomology of $\mathbb{P}^1$ in degrees 0 and 2 respectively, and $\mathbb{Z}[u] = H^\ast (\mathbb{CP}^\infty)$ is the $S^1$-equivariant cohomology of a point, with $u$ in degree 2.
My question is, "what is the equivariant cup product in this case?"
My progress: since the cup product will make $H_{S^1}^\ast(\mathbb{P}^1)$ a unital $\mathbb{Z}[u]$-algebra, the product is determined by the value of $y \smile y$, which for degree reasons will be a linear combination of $u \cdot y$ and $u^2 \cdot 1$. Using Morse theory, with the $S^1$-invariant Morse function $f : [z_1, z_2] \mapsto |z_1|^2$, we can deduce that the $u^2 \cdot 1$ component vanishes. I expect the coefficient of the $u \cdot y$ component to be nonzero (when $k \ne 0$) and to depend on $k$. I would be grateful for any assistance.

A: The coefficient is $k$, so $y \smile y = kuy$.
A result on page 536 of [1] states the $k=1$ case, and the proof provided in the references of [1] uses Chern character theory.
From the $k=1$ case, we can deduce all further cases as follows.
Given a map $f : G \to H$, there is a natural map $f_\ast$ from $G$-equivariant cohomology to $H$-equivariant cohomology of any space $X$ with a $H$-action, where the $G$ action on $X$ is induced by the map $f$.
We will use the map $f: S^1 \to S^1 / (\mathbb{Z}/k) \cong S^1$, and look at the induced map $f_\ast$.
We are able to calculate the map for the action of rotation of a sphere, and we can use this to deduce what the cup product will be on the codomain of $f_\ast$.
First, $f_\ast(y) = y$.
This follows becaues the induced map $f_\ast$ will be an isomorphism on the non-equivariant part of the equivariant cohomologies (which is found by setting $u=0$), as can be seen by looking at the fibre of the bundle
$$ES^1 \times_{S^1} X \to ES^1 / S^1 = \mathbb{CP}^\infty,$$
which will be isomorphic to $X$.
Next, $f_\ast(u) = ku$. We set $X$ equal to a point, since by the functoriality of $f_\ast$ with respect to the space $X$, this case is sufficient to deduce the result for all $X$.
On the fundamental groups, $f_\ast : \pi_1(S^1) \to \pi_1(S^1)$ is multiplication by $k$. The map $f$ yields a natural map between the long exact sequences of homotopy groups associated to the principal bundle $S^1 \to ES^1 \to BS^1$. Since $ES^1$ has trivial homotopy groups, this long exact sequence has isomorphisms $\pi_2(BS^1) \to \pi_1(S^1)$. Thus the naturality of the map between the long exact sequences and our knowledge of the maps behaviour on the fibres force the induced map $f_\ast : \pi_2(BS^1) \to \pi_2(BS^1)$ to also be multiplication by $k$. Since, for $BS^1$, the Hurwitz homomorphism $\pi_2 \to H_2$ is an isomorphism, we deduce that the corresponding map in degree 2 on both homology and cohomology is multiplication by $k$, as desired.
Finally, the cup product is calculated using the fact that we know that the map $f_\ast$ on equivariant cohomology is a ring homomorphism which takes $y \mapsto y$ and $u \mapsto ku$. In particular,
$$y \smile_k y = f_\ast(y) \smile_k f_\ast(y) = f_\ast(y \smile y) = f_\ast(uy) = kuy.$$
[1] Hori, Kentaro; Katz, Sheldon; Klemm, Albrecht; Pandharipande, Rahul; Thomas, Richard; Vafa, Cumrun; Vakil, Ravi; Zaslow, Eric, Mirror symmetry, Clay Mathematics Monographs 1. Providence, RI: American Mathematical Society (AMS) (ISBN 0-8218-2955-6/hbk). xx, 929 p. (2003). ZBL1044.14018.


text:
Q: Glut in Dev C++ error "redeclaration of C++ built-in type `short'" I have this simple triangle drawing code and it produces an error "redeclaration of C++ built-in type short ". But When I put #include<iostream.h> before #include<glut.h>, it compiles and runs.
Can anyone explain the logic behind that?
#include<glut.h>
void renderScene(void) {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,0.0);
        glVertex3f(0.5,0.0,0.0);
        glVertex3f(0.0,0.5,0.0);
    glEnd();

        glutSwapBuffers();
}

int main(int argc, char **argv) {

    // init GLUT and create Window
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(320,320);
    glutCreateWindow("My first program");

    // register callbacks
    glutDisplayFunc(renderScene);

    // enter GLUT event processing cycle
    glutMainLoop();

    return 1;
}

A: Hard to say without seeing your exact glut.h and library versions, but I see roundabout line 45 of glut.h:
   /* XXX This is from Win32's <ctype.h> */
#  ifndef _WCHAR_T_DEFINED
typedef unsigned short wchar_t;
#   define _WCHAR_T_DEFINED
#  endif

If wchar_t is already defined (to short for example), but the _WCHAR_T_DEFINED macro is not, the line will then be treated as:
typedef unsigned short short;

Which is a redeclaration of the built-in type. <iostream> (don't use the .h btw, it's not used anymore per standard) is adding defines such that the typedef is not executed, or undef'ing wchar_t if it is a macro such that the typedef is legal.

A: I faced error redeclaration of c++ built-in type 'wchar_t' at the time of my car racing project. I searched in Google, but didn't find any solution to solve my problem :-(
But later, I solved this problem by including "windows.h" by myself :-)
#include<windows.h>
#include<bits/stdc++.h>
#include<GL/glut.h>

#include<windows.h> has to be added at the top. If it's added under glut.h there will be an error.
#include<bits/stdc++.h> just added for safety :-p
Use #include<GL/glut.h> or #include<glut.h> depending on the folder where glut.h has been placed.

A: I have faced the same problem and change the wchar_t variable name to wchar_tt in the "glut.h" file and it works fine.
#  ifndef _WCHAR_T_DEFINED
typedef unsigned short wchar_tt;
#   define _WCHAR_T_DEFINED
#  endif
# endif


text:
Q: Injecting configuration object into library I am building an angular library and consuming it in an angular app.
(Both the angular library and app are built in angular v.13)
The angular library holds a service that needs a configuration object to get some parameters.
This setup seems to work when I don't use a certain configuration, just 'ng serve'.
But, when using a configuration like 'ng serve -c dev', it gives me this error :
Error: NG0204: Can't resolve all parameters for AzureWebmetricsService: (?).
    at getUndecoratedInjectableFactory (core.mjs:11506:1)
    at injectableDefOrInjectorDefFactory (core.mjs:11496:1)
    at providerToFactory (core.mjs:11539:1)
    at providerToRecord (core.mjs:11526:1)
    at R3Injector.processProvider (core.mjs:11429:1)
    at core.mjs:11402:1
    at core.mjs:4162:1
    at Array.forEach (<anonymous>)
    at deepForEach (core.mjs:4162:1)
    at R3Injector.processInjectorType (core.mjs:11402:1)

Here is the code :
App.module.ts
@NgModule({
  imports: [
    ...
    WebmetricsModule.forRoot({ instrumentationKey : "bla"})
 ],
 ...

Configuration.model.ts
export class Configuration {
  public instrumentationKey: string;

  constructor() {
    this.instrumentationKey = '';
  }

}

dependencyinjection.ts
export const AZURE_WEB_METRICS_CONFIG = new InjectionToken<Configuration>('azure.web_metrics.config');

Webmetrics.module.ts
@NgModule({
  declarations: [
  ],
  imports: [
  ],
  exports: [
  ],
  providers: [
  ]
})
export class WebmetricsModule {

  static forRoot(configuration : Configuration): ModuleWithProviders<WebmetricsModule> {
    return {
      ngModule: WebmetricsModule,
      providers: [
        AzureWebmetricsService,
        {provide: AZURE_WEB_METRICS_CONFIG, useValue: configuration}
      ]
    };
  }
}

Azurewebmetrics.service.ts

export class AzureWebmetricsService {

  appInsights : ApplicationInsights;

  constructor(@Inject(AZURE_WEB_METRICS_CONFIG) private readonly config : Configuration) {
    this.appInsights = new ApplicationInsights({
      config: {
        instrumentationKey: config.instrumentationKey,
        enableAutoRouteTracking: true // option to log all route changes
      }
    });
    this.appInsights.loadAppInsights();
  }
}

A: You should be using an injection token.
export const AZURE_WEB_METRICS_CONFIG = new InjectionToken<Configuration>('azure.web_metrics.config');

Use it to declare the provider in your module definition
@NgModule({
  declarations: [
  ],
  imports: [
  ],
  exports: [
  ],
  providers: [
  ]
})
export class WebmetricsModule {

  static forRoot(configuration : Configuration): ModuleWithProviders<WebmetricsModule> {
    return {
      ngModule: WebmetricsModule,
      providers: [
        AzureWebmetricsService,
        {provide: , useValue: configuration}
      ]
    };
  }
}

Then use it in the dependency.
export class AzureWebmetricsService {

  appInsights : ApplicationInsights;

  constructor(@Inject(AZURE_WEB_METRICS_CONFIG) config : Configuration) {
    this.appInsights = new ApplicationInsights({
      config: {
        instrumentationKey: config.instrumentationKey,
        enableAutoRouteTracking: true // option to log all route changes
      }
    });
    this.appInsights.loadAppInsights();
  }
}

A: After implementing the InjectionToken, I needed to adjust the "lib" version in the tsconfig.json of my app. The library I built had the setting on "es2020" and my app "es2018". Changing that in the app to "es2020" made it work.. which I think is kind of strange.


text:
Q: What do i do to make alert dialog pop up when the app opens?
  late StreamSubscription<ConnectivityResult> subscription;

  @override
  void initState()  {
    super.initState();

    subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.none) {
        testAlert(context);
      }
    });
  }

  @override
  dispose() {
    super.dispose();

    subscription.cancel();
  }

Even with no internet the alert box does'nt trigger
Do i need a builder for this to work?
Full Code
https://github.com/swojas/plasma-donation

A: It might be too early to have the context, maybe better do sth like this in the build method
If (subscription == null) subscription = ...

Another reason this could happen is if this widget is disposed by the time the stream has a value.. in this case move it to your home page since it will never be closed

A: I think that your alert is not triggering because you are subscribing to network changes. And within the milliseconds of staring the application, nothing changes.
Could you try this and let me know if it works?
result = await _connectivity.checkConnectivity();


text:
Q: How to get the total duration of media being played in PyQt4? I am trying to write a small audio player in PyQt4. This is a part of the code I've written:
class Player(QMainWindow):

    def __init__(self, fileLoc, parent = None):
        super(QMainWindow, self).__init__()
        self.totTime = 0
        self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
        self.mediaObject = Phonon.MediaObject(self)

        self.mediaObject.setTickInterval(1000)

        self.mediaObject.tick.connect(self.tick)
        self.mediaObject.stateChanged.connect(self.stateChanged)

        Phonon.createPath(self.mediaObject, self.audioOutput)

        #Define Play, Pause and Stop actions
        self.playAction = QAction(self.style().standardIcon(QStyle.SP_MediaPlay),
                            "Play", self, enabled = False, triggered = self.mediaObject.play)

        self.pauseAction = QAction(self.style().standardIcon(QStyle.SP_MediaPause),
                            "Pause", self, enabled = False, triggered = self.mediaObject.pause)

        self.stopAction = QAction(self.style().standardIcon(QStyle.SP_MediaStop),
                            "Stop", self, enabled = False, triggered = self.mediaObject.stop)

        #Initiate User Interface
        self.userInterface()
        self.timeDisp.display('00:00')

        self.mediaObject.setCurrentSource(Phonon.MediaSource(fileLoc))
        self.mediaObject.play()

    def tick(self, time):
        self.displayTime = QTime(0, (time / 60000) % 60, (time / 1000) % 60)
        self.timeDisp.display(self.displayTime.toString('mm:ss'))

My problem is, I am unable to figure out how to get the total duration of the file being currently played. I have tried printing the output of mediObject.totalTime() at the end of init(). But it returned -1 for all the videos.  mediObject.totalTime() inside tick() is returning incorrect duration (10 - 15 seconds longer than the actual duration).
Also, I may have to access the value of total duration from outside the class. How can I do this?
Thanks in advance.

A: You could connect the pause, play, and stop actions with other functions:
in the class __init__:
     self.total_time = 0
self.playing = False
self.play_action = QAction(self.style().standardIcon((QStyle.SP_MediaPlay),"play",self)
self.play_action.triggered.connect(self.play_triggered_event)

and define the rest of the actions in a similar manner, connecting the triggered field of each QAction to a function
def play_triggered_event(self):
    if not self.playing:
        self.mediaObject.play
        self.playing = True
        self.start_time = time.clock()

def pause_triggered_event(self):
    if self.playing:
        self.mediaObject.pause
        self.playing = False
        self.total_time += (time.clock() - self.start_time)

def stop_triggered_event(self):
    if self.playing:
       self.mediaObject.stop
       self.playing = False
       print "Total time elapsed: " + str(self.total_time)

Basically, it's about saving some program state when the actions that affect the time elapsed are triggered.
To get the total time outside of the class, write an accessor for the class:
def get_total_time(self):
    return self.total_time


text:
Q: Synergy with a Macbook Laptop with Sony laptop Can you connect synergy with a Macbook with a Sony laptop with synergy and have the macbook be the server computer and the Sony be the client?

A: Yes,
just be sure to tell synergy (on each computer) whether it's a server or a client.


text:
Q: IntelliJ IDEA Plugin - cannot import package com.jetbrains.python I am writing a plug-in for ItelliJ IDEA Community Edition 2018.1.5. I set up an Executor class and a GenericProgramRunner class.
I am trying to import the class com.jetbrains.python.run.PythonRunConfiguration to use in the doExecute method of the runner, but it cannot seem to find the package come.jetbrains.python. Says symbol 'python' cannot be resolved.
This is the code of my runner class.
public class CheckerRunner extends GenericProgramRunner {
    @NotNull
    @Override
    public String getRunnerId() {
        return "CheckerRunner";
    }

    @Override
    public boolean canRun(@NotNull String executorId, @NotNull RunProfile runProfile) {
        boolean result = executorId.equals(CheckerExecutor.EXECUTOR_ID) ;
        result = result && runProfile.getClass().toString().contains("PythonRunConfiguration");
        return result;
    }

    @Override
    protected RunContentDescriptor doExecute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment env) throws ExecutionException {

        RunProfile profile = env.getRunProfile();
        if (profile != null) {
            System.out.println(profile.getClass().toString());
        }
        return null;
    }

}

The condition runProfile.getClass().toString().contains("PythonRunConfiguration") in the canRun method evaluates to true.
 The doExecute method prints class com.jetbrains.python.run.PythonRunConfiguration
 to the console. Why can't I import the class then?


text:
Q: problem with binarysearch(calculate the first,last,mid with the new values) The code below belongs to a binary search algorithm. The user enters numbers in textbox1 and enters the number that he want to find with binarysearch in textbox2.
now i have a problem with  it,i want when the value of mid,first,last changes it again begin the function.i mean that for example:when last=mid-1; the function begin again and calculate with the new value of last(i commented in codes for more explanation)
thanks
 private void button1_Click(object sender, EventArgs e)
    {
        string strsearchnums = textBox2.Text;
        int result = binarysearch(strsearchnums);
        textBox14.Text = result.ToString();
    }
    public int binarysearch(string strsearchnum)
    {
        string[] source = textBox1.Text.Split(',');
        int[] nums = new int[source.Length];
        for (int i = 0; i < source.Length; i++)
        {
            nums[i] = Convert.ToInt32(source[i]);
        }

        int searchnum = Convert.ToInt32(strsearchnum);
        int first = nums.First();

        int last = nums.Last();

        while (1 <= nums.Length - 1)
        {
            int mid = (int)Math.Floor(nums.Length / 2.0) - 1;

            if (nums[0]> nums[nums.Length-1])
            {
                break;
           }

            if (searchnum < nums[mid])
            {
                last = mid - 1;

         binarysearch(strsearchnum);       ///i thought i should do like this but this isnt correct it becomes stackoverflow
            }
            if (searchnum > nums[mid])
            {
                first = mid + 1;
      binarysearch(strsearchnum);      ///i thought i should do like this but this isnt correct it becomes stackoverflow
            }
            if (searchnum == nums[mid])
            {

              return nums[mid];

            }

        }

        return -1;
    }

A: 1st of all when user enter the numbers in the textbox then those numbers may not be sorted so you need to first sort the array because Binary Search algo works with the sorted sequences.
   1- Splitt the string with ',' and store in the int[] array.

  string[] strArray = textBox1.Text.split(new string[]{","}, StringSplitOptions.RemoveEmptyEntries);

    List<int> lstInts = new List<int>();
   foreach(string str in strArray)
   {
      int j;
      int k=0;

      if(int.TryParse(str,out j))
        {
           lstInts.Add(j);
        }
    }
     int[] bsArray = lstInts.ToArray();

   2- Now Sort the Array.
      Array.Sort(bsArray);

   3- Now use Array.Binaryearch() , if you wanna use  framework implementation which is optimized also

      Array.BinarySearch(bsArray, valueToBeSearched)

     if you don't wanna use Framework implementation than follow below algorithm

   public int DoBinarySearchNoNRecursively(int[] array, int value)
    {
        int high = array.Length - 1;

        int low = 0;

        while (low < high)
        {
            int mid = low + (high - low) / 2;

            if (value == array[mid])
                return mid;
            else if (value > array[mid])
                low = mid + 1;
            else if (value < array[mid])
                high = mid;

        }

        return -1;
    }

A: First problem is that you're never changing the value of strsearchnum - so you will always get a Stackoverflow exception since its an infinite recursion. In general for a recursive binary search you want your binarySearch method to pass the number you are looking for, the min and the max and modify min and max according to the binary search algorithm. Method signature should be something like
int binarySearch(int min, int max, int num)
{

}

This should help you get started.

A: i corrected the code like below and it corrected:
 public int binarysearch(int searchnum)
    {
        string[] source = textBox1.Text.Split(',');
        int[] nums = new int[source.Length];
        for (int i = 0; i < source.Length; i++)
        {
            nums[i] = Convert.ToInt32(source[i]);
        }
        int first = 0;
        int last = nums.Length - 1;

        while (1 <= nums.Length)
        {
            int mid = (int)Math.Floor((first + last) / 2.0);
            if (first > last)
            {
                break;
            }
            if (searchnum < nums[mid])
            {
                last = mid - 1;
            }
            if (searchnum > nums[mid])
            {
                first = mid + 1;
            }
            if (searchnum == nums[mid])
            {
                return nums[mid];
            }
        }
        return -1;

    }

A: This is how the BinarySearch work...

The binary search algorithm is more
  efficient than the linear search
  algorithm, but it requires that the
  array be sorted.

    // perform a binary search on the data
     public int binarysearch(string strsearchnum)
{

    string[] source = textBox1.Text.Split(',');
    int[] data = new int[source.Length];
    for (int i = 0; i < source.Length; i++)
    {
        data[i] = Convert.ToInt32(source[i]);
    }

  int low = 0 ; // low end of the search area
  int high = data.length - 1 ; // high end of the search area
  int middle = ( low + high + 1 ) / 2 ; // middle element
  int location = -1; // return value; -1 if not found

  do // loop to search for element
     {

    // if the element is found at the middle
     if ( searchElement == data[ middle ] )
    location = middle; // location is the current middle

    // middle element is too high
    else if ( searchElement < data[ middle ] )
    high = middle - 1 ; // eliminate the higher half
    else // middle element is too low
    low = middle + 1 ; // eliminate the lower half

    middle = ( low + high + 1 ) / 2 ; // recalculate the middle
    } while ( ( low <= high ) && ( location == -1 ) );

    return location; // return location of search key
   } // end method binarySearch


text:
Q: php variable not being filled correctly I have been looking for an explanation for this, but couldn't find one.
I'm using a Mysql database.
In my table I have a column called unitPrice. It's type: decimal(10,2) - unsigned
Now as for my php page:
    $price = mysql_result($rows, $tel, "unitPrice");
    if(is_null($price ) || $price = ""){
           echo " niet ingevuld ";
    }else{
           echo $price ;
    }

The if-tag is completed perfectly. Which lets me believe the value is correctly stored into the variable when it comes to NULL and empty values.
Now as for the else-tag, it goes wrong. Normally it should collect the value and store it into $price. Like it did with every single other value I collected previously (but stored in the database with other types)
But when I went to check my website page, there was no value!
When I placed:
$price = mysql_result($rows, $tel, "unitPrice");
    if(is_null($price) || $price = ""){
           echo " niet ingevuld ";
    }else{
           echo mysql_result($rows, $tel, "unitPrice") ;
    }

It showed the result correctly.
It wouldn't be a big problem if it wasn't for the fact that I need the variable somewhere else again and don't wish to keep writing the mysql_result phrase over and over again...
Could anyone please explain why it won't work properly with a variable? And perhaps give me a solution as to how to make it work with a variable?
My apologies if this has been answered before. I've looked around for a while, but couldn't find any answers.

A: Looking at the code.
if(is_null($EHprijs) || $EHprijs = ""){

Will always evaluate to true. You are assigning "" to $EHprijs instead of doing a comparison

A: This happens because the value is stored in a different variable then the one you are checking.
Change $price to $EHprijs
$EHprijs = mysql_result($rows, $tel, "EHprijs");


text:
Q: Maps Intents don't show specified location
I have a problem with my application. I want to open Google Maps with defined in code location, so I set the data to the intent, but maps open on my location  all the time (not the specified in code one).
Here is the code:
String addressString = "1600 Amphitheatre Parkway, CA";

Uri locationUri = new Uri.Builder();
        .scheme("geo")
        .path("0,0")
        .query(addressString);
        .build();

Intent mapIntent = new Intent(Intent.ACTION_VIEW, locationUri);
mapIntent.setPackage("com.google.android.apps.maps");

if(intent.resolveActivity(getPackageManager()) != null)
    startActivity(mapIntent);

Does anyone know how to handle this situation? I tried on my phone and on the virtual device and it's not working on both.

A: Use it this way to open with latitude and longitude:
double lat = YOUR_LATITUDE;
double lng = YOUR_LONGITUDE;
String placeLabel = YOUR_PLACE_LABEL;
String uri = String.format(Locale.ENGLISH, "geo:%f,%f?q=%f,%f(%s)", lat, lng, lat, lng, placeLabel);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

If you want to open the map with an address, replace de uri with:
geo:0,0?q=my+street+address

A: Change query(addressString) to                 appendQueryParameter("q", addressString) and you will rich what you want:
Uri locationUri = new Uri.Builder()
        .scheme("geo")
        .path("0,0")
        .appendQueryParameter("q", addressString)
        .build();


text:
Q: How can print my variables summary outputs with for loop in R I use summary() function to see which variables get what value. For example I have 10 variables in my data. ( v1, v2, v3,...,v10) This is the output I want it to write for each variables in for loop.
First variable is "v1", "3" is minimum, "9" is maximum and "5.6" is mean for "v1".
Second variable is "v2", "6.2" is minimum, "15.3" is maximum and "8.9" is mean for "v1".
.
.
Tenth variable is "v10" ...

A: You can use this in a loop :
set.seed(123)
df <- data.frame(V1 = rnorm(5), V2 = rnorm(5), V3 = rnorm(5))
cols <- names(df)

for (i in seq_along(df)) {
  cat(sprintf("\nVariable %d is %s, it's minimum is %.2f, maximum is %.2f and mean is %.2f",
          i, cols[i], min(df[[i]], na.rm = TRUE), max(df[[i]], na.rm = TRUE), mean(df[[i]], na.rm = TRUE)))
}

#Variable 1 is V1, it's minimum is -0.56, maximum is 1.56 and mean is 0.19
#Variable 2 is V2, it's minimum is -1.27, maximum is 1.72 and mean is -0.04
#Variable 3 is V3, it's minimum is -0.56, maximum is 1.22 and mean is 0.31


text:
Q: Proof of the analytic Fredholm theorem in Borthwick I've stumbled across a proof of the analytic Fredholm theorem given in Theorem 6.1 in Spectral Theory of Infinite-Area Hyperbolic Surfaces by David Borthwick (see below).
Given the notion of being "finitely meromorphic" given in that book, how does the author infer that we can choose a small enough neighborhood $N$ of any point $s_0\in N$ so that $N$ contains only finitely many "poles" of $E(s)$?
He didn't define what a "pole" is, but I guess it's supposed to mean (in the context of the definition of finite meromorphicity) that a point $a\in U$ is a "pole", if the Laurent series expansion of $A(s)$ given satisfies $m>0$.
If that's the case, I don't get how he's inferring that $N$ contains only finitely many poles. In the ordinary definition of meromorphicity, it is assumed that the set of poles is discrete. Isn't an assumption of this kind missing here?

A: I'll try to answer with a few general remarks on what a pole is and what a meromorphic function is.
Let $U \subseteq \mathbb{C}$ be non-empty and open and let $X$ be a complex Banach space (for instance, the space of bounded linear operators in $\mathcal{H}$).
Definition 0. (Pole) Let $V \subseteq U$ be non-empty and open, and let $f: V \to X$ be holomorphic. We say that a point $p \in U \setminus V$ is a pole of $f$ if $p$ is isolated in $U \setminus V$ and if the principal part of the Laurent expansion of $f$ about $p$ is a finite sum.
Note that this definition assumes explicitly that $p$ is isolated in $U \setminus V$.
Definition 1. (Meromorphic function) A meromorphic function on $U$ is a holomorphic function $f: V \to X$, where $V$ is an open subset of $U$ and each point in $U \setminus V$ is a pole of $f$.
Note that, in this case, $U \setminus V$ is automatically discrete since every point in $U \setminus V$ is a pole and thus, by the definition of the notion pole, isolated in $U \setminus V$. So one does not need to assume the discreteness $U \setminus V$ explicitly here, since it's implicitely contained in the assumption that all points in $U \setminus V$ are poles.
However, in his book Borthwick apparently takes a somewhat different perspective on meromorphic functions. I'll rephrase his definition, using what I would consider a slightly more precise wording:
Definition 2. (Meromorphic functions, again) Let us call a function $f: U \to X$ B-meromorphic if the following condition is satisfied: for each point $a \in U$ there exists an open ball $D \subseteq U$ with center $a$, an integer $m \ge 0$ and vectors $A_{-m}, A_{-m+1}, \dots, A_0, A_1, A_2, \dots \in X$ such that
$$
  (*) \quad
  f(z) = \sum_{k=-m}^\infty A_k(z-a)^k
  \qquad
  \text{for all } z \in D \setminus \{a\},
$$
where the series converges in norm.
Now, if $f: V \to X$ is meromorphic, we can clearly extend it to a B-meromorphic function by assigning arbitrary values to it on $U \setminus V$. But we also have the converse implication; more precisely:
Proposition 3. Let $f: U \to X$ be B-meromorphic and let $E \subseteq U$ denote the set of all points $a \in U$ at which the number $m$ from the Laurent expansion $(*)$ cannot be chosen as $0$. Then $f|_{U \setminus E}: U \setminus E \to X$ is meromorphic (in particular, $E$ is discrete in $U$).
Proof. It is a consequence of $(*)$ and of the definition of $E$ that, for each $z \in U \setminus E$, the function $f$ is holomorphic in a neighbourhood of $z$ (including $z$ itself); in particular, an entire neighbourhood of $z$ is contained in $U \setminus E$. Thus, $U \setminus E$ is open and $f|_{U \setminus E}$ is holomorphic.
Let us show next that each point in $E$ is isolated in $E$; so assume to the contrary that $E$ accumulates at a point $a \in E$. We know that $(*)$ holds for all $z \in D \setminus \{a\}$, where $D \subseteq U$ is an appropriately chosen open disk with center $a$. In particular this implies that $f$ is holomorphic on $D \setminus \{a\}$.
However, since $E$ accumulates at $a$, there exists a point $a_1 \in E$ which is in $D \setminus \{a\}$. Since $f$ is, as noted in the previous paragraph, holomorphic at $a_1$, the principal part of the Laurent series expansion of $f$ about $a_1$ vanishes. However, this contradicts the fact that $a_1 \in E$.
So we showed that every point in $E$ is isolated in $E$. Hence, it follows from $(*)$ that every point of $E$ is a pole of $f|_{U \setminus E}$. Thus, $f|_{U \setminus E}$ is meromorphic. $\square$
Note that the observations above show that Definition 3 (i.e., the definition from Borthwick's book) has a somewhat strange consequence: the function $f$ is assumed to be defined everywhere on $U$, although it is holomorphic only on $U \setminus E$; in particular, the values of $f$ on $E$ are completely unrelated to the other values of $f$.


text:
Q: Periodically store data from a PostgreSQL table to SQL Server 2005 table (with the same schema) I have a PostgreSQL database that stores real-time data from sensors in a specific table (every 30sec).
What I want to do, is to get periodically the data from the remote PostgreSQL database (for instance every 30sec) and store them in SQL Server 2005 to manipulate them locally. I don't care about having the two databases with duplicate tables. Actually this is what I want to achieve!
So far, I have as Linked Server the PostgreSQL to SQL Server and I can query and retrieve the sensor data. However, I prefer to store them in my SQL Server for performance reasons.
Solution so far:

*

*Make select openquery statements with the linked PostgreSQL and insert the results to my table in SQL Server. Repeat this periodically and store fresh data only (e.g. with a larger timestamp).

I assume that my proposed solution is not ideal. I want to know what are the best practices to achieve this synchronization between the two databases.
Thank you in advance!

A: If you don't want to write your own code(implementations) to do that you can use SymmetricDS to synch the table from postgreSQL to MSSQL .


text:
Q: formdata returns no data when an ng-repeat table is running inside it I have a table where its dynamically populating data, I wanted that when I click a button (that is outside the form) I want to edit these fields. After editing these fields though, Formdata doesn't send any of the table data.
What am I doing wrong here?
       <form role="form" ng-submit="updatestmt(data)"  name="updatedata" id="updatedata" >

                                                                     {{b.key}}
                                                                    {{b.particular}}
                                                                    <input type = "string" value="{{b.amt}}" class="form-control">

                                                                    No data found.

                                                            </form>


text:
Q: Filter data using textbox and view it in the listview in vb.net I want to display  the result in listview that i written in the texbox can you pls help me?

A: If you are asking for the ability to search based on criteria similar to what you type in the textbox (I think that is what you are asking), then change you SQL statement to be
WHERE PatientName LIKE '%" & TextBox1.Text & "%'"

instead of =.  The problem is that you will only get results back on the = if it matches exactly.  The LIKE statement will find things similar to what is entered.  THe % is a wildcard character meaning "any number of characters".  Note that it will work for MOST dbs.  If it does not work for you, look up wildcard characters for your db and replace the %s.


text:
Q: Wrong language for Settings search results - Windows 10 I recently changed the language on Windows 10 (version 1903).
The previous language was French and I wanted to change it to English. Nevertheless, I had to keep the AZERTY keyboard arrangement and the date format in French.
I proceeded in this way:

*

*Settings > Time & Language

*

*Language

*

*Add a preferred language

*

*English (United States) > Checked all boxes [Logout]

*English (United States) > Options

*

*Add a keyboard > French (AZERTY)

*Region

*

*Region format > French (France)

*Administrative language settings

*

*Copy settings > Checked all boxes [Restart]

*Change system locale > English (United States) [Restart]

Attempted resolution made:

*

*Delete the French language pack (and change all other Time & Language settings to English)

*Rebuild the search index

*Change the language code during Windows installation in the registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\Language > InstallLanguage (Language IDs))

*Use Set-Culture (Documentation)

Nevertheless, when I do searches (from the task bar search bar and from the parameter search bar), the results obtained are in French.
Is there a solution to solve this problem?
Thank you.

A: The following worked for me:
Try logging on with a another/new Windows account. If Settings search results are returned in the correct language using this account, then you will want to copy the following file from the working account to the problematic account:
%localappdata%\Packages\Microsoft.Windows.Cortana_cw5n1h2txyewy\LocalState\DeviceSearchCache\SettingsCache.txt
No restart needed, just start the Settings app again and searching should now return results in the correct language

A: The solution is far easier than that. The reason for this "bug" is because Windows indexes the settings options only in a certain scenario, the easiest way to do this I found on this link.
Before I had tried rebuilding index, renaming folders, nothing worked. Here are the steps:

*

*Open Control Panel ("Windows Settings")

*Open "Time & Language"

*Click "Language" (on the left)

*Click "Administrative Language Settings" (on the right)

*A popup opened up, called "Region". In the Tab "Administrative" and te field "Welcome screen and new user accounts", click "Copy Settings".

*Tick the boxes "Welcome screen and system accounts" and "new user accounts".

*Click OK and reboot.

*Now, go to language settings, set back the "old" language (Germany in my case) as    display language, sign out of windows, sign in again.

*Now Set English as display language, sign out of windows and sign in
again.

A: I managed to solve the problem by recreating a new user. I suppose that to solve the problem without creating a new account, you have to reinstall and re-register the system applications (See here)
I hope that this answer will help some of them.

A: This answer https://superuser.com/a/1467284/250690 works great.
Only that in Windows 11, there is no "Time & Language" in Control Panel anymore. You can open the "Administrative Language Settings" direcly in Language system ettings page.


text:
Q: String diagrams of special monoidal categories and higher categories I have two questions related to Selinger: A survey of graphical languages for monoidal categories.
1) On page 60 there is a summary of some monoidal categories with extra structure. Among them are the well known braided and symmetric versions. Due to the periodic table, these two monoidal categories stem from 3- resp. 4-categories. Can some of the other special monoidal categories also be deduced from certain higher categories?
2) There is another type of string diagrams not present on page 60. Namely you can do the following. Assume you have a string diagram of a monoidal category with no extra structure, i.e. a string diagram on a plane square. Bend such a square to a cylinder by identifying the left and right side of that square. The diagram is now "painted" on a cylinder und you can also compose cylinders (but only "vertically"). Does this correspond also to some extra structure on a monoidal category? In fact, this extra structure should somehow reduce the dimension of the monoidal category by one, because tensor expressions are cyclically isomorphic, e.g. the objects $A_1\otimes A_2\otimes A_3$, $A_2\otimes A_3\otimes A_1$, $A_3\otimes A_1\otimes A_2$ are coherently isomorphic. This corresponds to the top and bottom of the cylindrical diagrams being a circle.

A: As you point out, in such a situation it may not be possible to compose horizontally, hence in full generality you cannot assume your underlying category to be monoidal. On the other hand, you still want to keep track somehow of the tensor product. I think it can be handled as follow:
The structure you are looking for should be the data of a (strict, say) monoidal category $C$, an arbitrary category $D$, a functor $F:C\rightarrow D$ and a natural isomorphism $$\gamma_{-,-}:F(-\otimes -)\rightarrow F(-\otimes^{op} -)$$. It seems to me that one natural coherence condition to impose is:
$$\gamma_{Z\otimes X,Y}\circ\gamma_{X\otimes Y,Z} =\gamma_{X,Y\otimes Z}^{-1}$$
Maybe you need the "reversed" condition as well.
Anyway, examples of such categories may be constructed as follows: let $C$ be a rigid monoidal category enriched over some category $D$, let $F$ be the functor $Hom_C(1,-)$ and $\gamma$ be given by
$$Hom_C(1,X\otimes Y)\cong Hom_C(X^*,Y)\cong Hom_C(1,Y\otimes X)$$
I'm not aware of such a definition in the litterature, but the obviously related notion of a categorical structure involving braid diagrams drawn on a surface appears in this paper by Calaque-Enriquez-Etingof for the torus (under the name elliptic structure) and for abritrary surfaces in Philippe Humbert's thesis.

A: 2) You may be interested in this paper.


text:
Q: Is there an existing CSS3 selector parser for JavaScript? Anybody know of snippet that will parse a CSS3 selector like this:
"form#network_template[method='put'][action='#form_{keyname}']"

to this:
{
  tag: "form",
  id: "network_template",
  method: "put",
  action: "#form_{keyname}"
}

or this:
<form id="network_template" method="put" action="#form_{keyname}">

A: Assuming you meant to ask for a CSS3 selector parser in the title, Slick, used in Mootools, may do the job; from the github page:
Slick.parse("h1, h2, ul > li, .things")

{
"raw": "h1, h2, ul > li, .things",
"expressions": [
    [{ "combinator":" ", "tag": "h1" }],
    [{ "combinator":" ", "tag": "h2" }],
    [{ "combinator":" ", "tag": "ul" }, { "combinator": ">", "tag": "li" }],
    [{ "combinator":" ", "tag": "*", "classList": ["things"], "classes": [{"value": "things", "regexp":RegExp }] }]
]
}

Mootools can also create an element with appropriate attributes straight from a selector.

A: Sizzle is used underneath jQuery. And there is also Peppy. Newer versions have at least some CSS3 selector support. YMMV.
Google searches reveal interesting leads.


text:
Q: PHP: Convert date to Javascript date (January = zero) I'm using Highcharts and need the dates formatted like this:
UTC.(2016,11,01) // for December 1st 2016

Is there an easy way to do this? Because
date('Y-m-d', strtotime('-1 month'))

gives me the wrong output for January.

A: You don't need sub the month. Just use other format as ATOM/RFC3339. It's fully supported by javascript Date class
$date = new DateTime('2016-01-01');
echo $date->format(DateTime::ATOM);

Result:
2016-01-01T00:00:00-05:00

Javascript:
var date = new Date('2016-01-01T00:00:00-05:00');
console.log(date)

As I'm live in Brazil, my browser show as
Fri Jan 01 2016 03:00:00 GMT-0200 (Horário brasileiro de verão)

If you have any other format as input, you could use DateTime::createFromFormat and the rest still the same
$date = DateTime::createFromFormat('m/d/Y' , '12/01/2016');


text:
Q: Keep scrolling focused - style CSS flexbox multiple columns with different number of rows I am building a layout that has a variable number of columns, each having an independent number of rows.
It is not strictly a grid (each column should have equal number of rows), I will call it "board" layout.
Goals :

*

*user must be able to scroll horizontally only the board, and scroll vertically only the columns: I want to scroll the currently focused column and to prevent scrolling in diagonal direction of the whole board.

*Vertical scrolling on column must end when user reaches the end of the column, not of the parent board (the board's height could be longer if there are other columns higher than the focused column).
I wonder if I could achieve this behavior only with CSS - eventually also refactoring the html.
Could you illustrate a possible solution for point 1, 2, using CSS only ?
This is what I tried making use of flex css solution.

desired layout
Columns contains different number of rows and their background is rendered accordingly.

attempts
The following code rendered the desired layout, but if I have many columns, the view port will adjust them below the others: instead I want to keep the horizontal order and horizontal scrolling.

        <item>..</item>

.board {
}

.column {
  margin: 10px;
  padding: 10px;
  border: 1px solid #cfcfcf;
  background-color: #ddd;
  display: flex;
  flex-flow: column wrap;
  flex: 1 1 30%;

  width: 20%;
  float:left;
}

I tried with this other solution:
.grid {
  display:flex;
}

and remove width: 20%; float:left; in the column class.
Now the problems are:

*

*The user can move the board object in diagonal (see the scrolling-bars on the image): user can only scrolling horizontally the board , and vertically the focused column.

*The shorter columns' height is 'stretched' to meet the max height of the board, resulting in fully colored columns also if there is only element in it.

A: I believe this snippet begins to address all of your desired points. It fixes the board to the size of the viewport and enables horizontal scrolling for horizontal overflow while hiding vertical overflow. Column scrolling is implemented using nested columns set to scroll vertical overflow
(The reason your columns were being pushed into a second row is that you had specified wrap.)

body {
  margin: 0;
}
.board {
  background-color: green;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  overflow-x: scroll;
  overflow-y: hidden;
  align-items: flex-start;
}
.column{
  margin: 10px;
  padding: 10px;
  flex-basis: 20%;
  min-width: 200px;
  overflow-y: scroll;
  height: 100%;
}
.column-inner {
  border: 1px solid #cfcfcf;
  background-color: #ddd;
  display: flex;
  flex-direction: column;
}
div.item {
  margin: 10px;
  padding: 10px;
  height: 100px;
  background-color: red;
}

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

A: You should use scroll-snap
Here an example with grid layout, if you can use it :

.gallery {
    border: 1px solid lightgray;
    padding: 1rem;
    display: grid;
    grid-template-columns: repeat(10, 30vw);
    grid-template-rows: repeat(10, 30vw);
    grid-column-gap: 1rem;
    grid-row-gap: 1rem;
    flex-wrap: wrap;
    overflow: scroll;
    height: 90vh;
    scroll-snap-type: both mandatory;
    scroll-padding: 1rem;
}

li {
    scroll-snap-align: start;
    display: inline-block;
    border-radius: 3px;
    font-size: 0;
    background-color: red;
}

Lorem, ipsum dolor.

Saepe, blanditiis quam!

Cum, eos reprehenderit.

Alias, saepe asperiores?

Fuga, at exercitationem.

Nihil, magnam! Officia!

Voluptas, laudantium natus!

Tempora, quibusdam sed.

Asperiores, nisi repudiandae.

Soluta, quas voluptatibus.

Ipsam, totam saepe.

Debitis, asperiores ipsum.

Aliquam, minus corporis.

Illum, voluptatem maxime.

Qui, explicabo odio!

Iusto, nihil illum.

Iure, numquam facere.

Possimus, non eos!

Nesciunt, quas consectetur.

Accusantium, earum autem!

Tenetur, asperiores ullam.

Facilis, adipisci repudiandae.

Neque, doloribus eligendi!

Perferendis, vitae suscipit.

Doloremque, aperiam vitae?

Assumenda, obcaecati molestias.

Officiis, laborum omnis!

Blanditiis, itaque vitae.

Quis, impedit cumque!

Omnis, aut repudiandae.

Laboriosam, quidem ullam!

Nihil, neque velit?

Aperiam, voluptatum eligendi.

Ratione, neque debitis!

Sunt, ex exercitationem.

Est, molestias eius.

Praesentium, nulla molestiae.

Illum, at nobis!

Voluptate, tenetur minima!

Atque, fugit cum?

Lorem, ipsum dolor.

Saepe, blanditiis quam!

Cum, eos reprehenderit.

Alias, saepe asperiores?

Fuga, at exercitationem.

Nihil, magnam! Officia!

Voluptas, laudantium natus!

Tempora, quibusdam sed.

Asperiores, nisi repudiandae.

Soluta, quas voluptatibus.

Ipsam, totam saepe.

Debitis, asperiores ipsum.

Aliquam, minus corporis.

Illum, voluptatem maxime.

Qui, explicabo odio!

Iusto, nihil illum.

Iure, numquam facere.

Possimus, non eos!

Nesciunt, quas consectetur.

Accusantium, earum autem!

Tenetur, asperiores ullam.

Facilis, adipisci repudiandae.

Neque, doloribus eligendi!

Perferendis, vitae suscipit.

Doloremque, aperiam vitae?

Assumenda, obcaecati molestias.

Officiis, laborum omnis!

Blanditiis, itaque vitae.

Quis, impedit cumque!

Omnis, aut repudiandae.

Laboriosam, quidem ullam!

Nihil, neque velit?

Aperiam, voluptatum eligendi.

Ratione, neque debitis!

Sunt, ex exercitationem.

Est, molestias eius.

Praesentium, nulla molestiae.

Illum, at nobis!

Voluptate, tenetur minima!

Atque, fugit cum?

Lorem, ipsum dolor.

Saepe, blanditiis quam!

Cum, eos reprehenderit.

Alias, saepe asperiores?

Fuga, at exercitationem.

Nihil, magnam! Officia!

Voluptas, laudantium natus!

Tempora, quibusdam sed.

Asperiores, nisi repudiandae.

Soluta, quas voluptatibus.

Ipsam, totam saepe.

Debitis, asperiores ipsum.

Aliquam, minus corporis.

Illum, voluptatem maxime.

Qui, explicabo odio!

Iusto, nihil illum.

Iure, numquam facere.

Possimus, non eos!

Nesciunt, quas consectetur.

Accusantium, earum autem!

Tenetur, asperiores ullam.

Facilis, adipisci repudiandae.

Neque, doloribus eligendi!

Perferendis, vitae suscipit.

Doloremque, aperiam vitae?

Assumenda, obcaecati molestias.

Officiis, laborum omnis!

Blanditiis, itaque vitae.

Quis, impedit cumque!

Omnis, aut repudiandae.

Laboriosam, quidem ullam!

Nihil, neque velit?

Aperiam, voluptatum eligendi.

Ratione, neque debitis!

Sunt, ex exercitationem.

Est, molestias eius.

Praesentium, nulla molestiae.

Illum, at nobis!

Voluptate, tenetur minima!

Atque, fugit cum?

Lorem, ipsum dolor.

Saepe, blanditiis quam!

Cum, eos reprehenderit.

Alias, saepe asperiores?

Fuga, at exercitationem.

Nihil, magnam! Officia!

Voluptas, laudantium natus!

Tempora, quibusdam sed.

Asperiores, nisi repudiandae.

Soluta, quas voluptatibus.

Ipsam, totam saepe.

Debitis, asperiores ipsum.

Aliquam, minus corporis.

Illum, voluptatem maxime.

Qui, explicabo odio!

Iusto, nihil illum.

Iure, numquam facere.

Possimus, non eos!

Nesciunt, quas consectetur.

Accusantium, earum autem!

Tenetur, asperiores ullam.

Facilis, adipisci repudiandae.

Neque, doloribus eligendi!

Perferendis, vitae suscipit.

Doloremque, aperiam vitae?

Assumenda, obcaecati molestias.

Officiis, laborum omnis!

Blanditiis, itaque vitae.

Quis, impedit cumque!

Omnis, aut repudiandae.

Laboriosam, quidem ullam!

Nihil, neque velit?

Aperiam, voluptatum eligendi.

Ratione, neque debitis!

Sunt, ex exercitationem.

Est, molestias eius.

Praesentium, nulla molestiae.

Illum, at nobis!

Voluptate, tenetur minima!

Atque, fugit cum?


text:
Q: Line break after description label How can I ger a line break after the label of a description environment item? I'd like to keep the indentation and the bold face for the item label, but I'd like to have the body of the item in a separate paragraph, because it starts with an itemize environment and indenting that looks really strange.
Adding \\ does not work (error message "no line to end here"), neither does a blank line or \par (no effect). Even \,\par has no effect.
Example:
\documentclass{article}
\begin{document}
\begin{description}
\item[Animals:]
  \begin{itemize}
  \item Dog
  \item Cat
  \item Fish
  \end{itemize}
\item[Colors:]
  \begin{itemize}
  \item Red
  \item Green
  \item Blue
  \end{itemize}
\end{description}
\end{document}

It renders like this:

A: Adding \leavevmode also has the desired effect and looks reasonably clean.
\documentclass{article}
\begin{document}
\begin{description}
\item[Animals:]\leavevmode
  \begin{itemize}
  \item Dog
  \item Cat
  \item Fish
  \end{itemize}
\item[Colors:]\leavevmode
  \begin{itemize}
  \item Red
  \item Green
  \item Blue
  \end{itemize}
\end{description}
\end{document}

I came up with this answer while writing the question. When I started, \mbox{} was the best solution I had, and that felt sufficiently hackish that I wanted to look for a cleaner solution. Now I'm merely documenting my find.

A: The insertion of an empty item seems to give a better vertical spacing. One can define a  myitemize environment that includes this empty item; that will prevent typing it for each description item:
\documentclass{article}

\usepackage{enumitem}

\newenvironment{myitemize}%
{\begin{itemize}\item[]}
{\end{itemize}}

\begin{document}

\begin{description}[style = sameline, leftmargin = 1em]
\item[Animals:]
  \begin{itemize}
  \item[]
  \item Dog
  \item Cat
  \item Fish
  \end{itemize}

\item[Colors:]
  \begin{myitemize}
  \item Red
  \item Green
  \item Blue
  \end{myitemize}
\end{description}

\end{document}

A: I post a new answer because I feel this question is not a full duplicate of this one, which was voted to be closed. So here is my solution to the latter question, based  on description, and a re-definition of \makedescriptionlabel. One can choose the left margin:
\documentclass{book}

\usepackage{enumitem, etoolbox}%
\renewcommand*{\descriptionlabel}[1]{\hspace\labelsep
\parbox{\linewidth}{\normalfont\bfseries #1}}
\newlist{mydescription}{description}{1}
\setlist[mydescription, 1]{style=nextline, leftmargin =4em, before=\renewcommand*{\descriptionlabel}[1]{\hspace\labelsep}}

\begin{document}

\begin{mydescription}%
  \item[C] Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.

  Some more text. Some more text. Some more text. Some more text. Some more text. Some more text. Some more text.

  \item[C\textsuperscript{++}] Another text. Another text. Another text. Another text. Another text. Another text. Another text. Another text.

  \item[Python 3.4] Blah blah blah. Blah blah. Blah blah blah blah blah blah.
\end{mydescription}

\end{document}


text:
Q: Why does Pandas give me only one SettingWithCopyWarning? I have the following code:
import pandas as pd
import numpy as np
mydf = pd.DataFrame({'UID':[1,2,3],
                     'Price':[10,20,30],
                     'Shipped':[2,4,6]})
grouped = mydf.groupby('UID').aggregate(np.sum)
# Call 1
mydf['Price'].loc[:] = np.round(grouped['Price'], 2)
# Call 2
mydf['Shipped'].loc[:] = grouped['Shipped']

The line that I have preceded with Call 1 executes with no errors or warnings. The line that I have preceded with Call 2 results in a SettingWithCopyWarning error. Why does the one result in the error and not the other? What can I do in my second call in order to get rid of this error?
My code executes fine, I'm just tired on seeing this one lone error every time I run my tests.

A: No SettingWithCopyWarning error
mydf['Shipped'].values[:] = grouped['Shipped']


text:
Q: Intercept calls to HttpSession in Tomcat 6 What's the recommended approach to intercepting session.getAttribute() and session.setAttribute()? This is in a Spring based application so something AOP-based would be great. I'd like to avoid having to override core Tomcat classes if possible.
Update: I want to store the actual serialized attributes in a web service.

A: I am not familiar with AOP or Spring (or Tomcat). :) But I am familliar with Java
The way I do it is set up a filter, and replace the request variable with my own object
request = new MyRequest(request);

Then override getSession() and getSession(boolean) to return an instance of MySession
the javax.servlet.HttpServletRequest and javax.servlet.HttpSession classes are Java EE standard and not Tomcat specific.

A: You could implement your own session org.apache.catalina.Manager and swap it into Tomcat's configuration, although the interface looks rather lengthy - so perhaps look at extending ManagerBase or StandardManager first.
As an alternative, register a HttpSessionAttributeListener to be notified whenever a session attribute is added/removed/updated. This won't change the default storage mechanism - the session data will still be kept in-memory as well - but it would let you persist the data with an alternative mechanism as well.


text:
Q: Where Fermat's last theorem fails It's fairly well known that Fermat's last theorem fails in $\mathbb{Z}/p\mathbb{Z}$. Schur discovered this while he was trying to prove the conjecture on $\mathbb{N}$, and the proof is an application of one of his results in Ramsey theory, now known as Schur's theorem.
I'm wondering whether there are any other places (let's say, unique factorisation domains) where the statement is known to be false?

A: You can also blow FLT out of the water in $p$-adics.  Consider the ordinary Pythagorean triple
$17^2+144^2=145^2$
Render these arguments in $2$-adics:  $17$ and $145$ are each one greater than a multiple of $8$, thus squares of other $2$-adic integers which I shall call $\pm m$ and $\pm n$ respectively (an additive inverse pair of choices for each).  And of course $144$ is the square of $\pm 12$.  So then we have eight $2$-adic equations (four of them "linearly independent") of the form
$(\pm m)^{\color{blue}{4}}+(\pm 12)^{\color{blue}{4}}=(\pm n)^{\color{blue}{4}}$

A: $$(18+17\sqrt2)^3+(18-17\sqrt2)^3=42^3$$ so Fermat fails for $n=3$ in the UFD ${\bf Q}(\sqrt2)$. $$(1+\sqrt{-7})^4+(1-\sqrt{-7})^4=2^4$$ so Fermat fails for $n=4$ in the UFD ${\bf Q}(\sqrt{-7})$.
Looking at a couple more of the imaginary quadratic UFDs:
$(1+\sqrt{-2})^{\color{blue}{3}}+(\sqrt{-2})^{\color{blue}{3}}=(1-\sqrt{-2})^{\color{blue}{3}}$ (failure in ${\bf Q}(\sqrt{-2})$)
$(1+\sqrt{-3})^{\color{blue}{6n+1}}+(1-\sqrt{-3})^{\color{blue}{6n+1}}=2^{\color{blue}{6n+1}}$ (any whole number $n$ at all; failure in ${\bf Q}(\sqrt{-3})$)


text:
Q: one-parameter subgroup and geodesics on Lie group Hi,
Given a Matrix Lie Group, I would like to know if the one-parameter subgroups (which can be written as $\exp^{tX}$) are the same as the geodesics (locally distance minimizing curves). Geodesics depends on the metric used so perhaps a more precise formulation of this question is:
Given a Matrix Lie Group, under what metric the one-parameter subgroups are the same as the geodesics ?
Thanks,
Frank

A: A natural metric is the left-invariant one. Then the equation for geodesics is the so-called 'Euler equation'. Examples are

*

*the equation of the free motion of a solid body (group: $SO_3(\mathbb R)$),

*the equation of a the motion of an incompressible inviscid fluid in a bounded domain (group: measure-preserving diffeormorphism).

In general, a geodesic passing through identity is not a one-parameter subgroup. Because such a geodesic is defined by its tangent at the identity, this is equivalent to saying that a one-parameter subgroup is not always a geodesic. A one-parameter subgroup that is also a geodesic corresponds to a permanent regime in the examples above. For the fluid case, have a look to my paper Sur le principe variationnel des équations de la mécanique des fluides parfaits.  RAIRO Modél. Math. Anal. Numér. 27 (1993), no. 6, 739–758.
The following is a guess, not a claim: a one-parameter subgroup $e^{tX}$ is a geodesic if and only if $\|X\|$ is critical within the adjoint orbit of $X$.

A: I may have a similar answer with an alternative derivation. Given a group $G$ with Lie algebra $\mathfrak{g}$ and right-invariant inner product $\langle A,B\rangle_g=\langle Ag^{-1},Bg^{-1}\rangle_e$ where $A,B\in T_gG$, $Ag^{-1}=(R_{g^{-1}})_*A$, $Bg^{-1}=(R_{g^{-1}})_*B$ and $e$ being the neutral element. Right-translations of a group are generated by left-invariant vector fields which are therefore Killing vector fields. Let us assume that $M_I\in\mathfrak{g}$ for $I\in\{1,\cdots,\dim{G}\}$ is a basis of the Lie algebra. This means we have the left-invariant vector fields
\begin{align}
X_I=gM_I=L_gM_I\in T_gG\,.
\end{align}
It is a well-known fact that the inner product of (affinely parametrized) geodesics $u: [0,1]\to G: t\mapsto u(t)$ have conserved quantities
\begin{align}
C_I&=\langle X_I,\dot{u}(t)\rangle_{u(t)}\\
&=\langle uM_I,\dot{u}\rangle_u\\
&=\langle uM_Iu^{-1},\dot{u}u^{-1}\rangle_e\,.
\end{align}
For a Lie group with right-invariant metric, knowing the $\dim{G}$ conserved quantities $C_I$ and initial point of a geodesics $u(0)$ determine the geodesics uniquely.
Let us check what the condition for a 1-parameter subgroup $u(t)=e^{tA}$ with $A\in\mathfrak{g}$ is to be a geodesic, or equivalently to have the $C_I$ being conserved. Plugging $u(t)$ into above formula gives
\begin{align}
C_I=\langle e^{tA}M_Ie^{-tA},A\rangle_e\,.
\end{align}
We can take the derivative $d/dt$ on both sides and find
\begin{align}
0=\langle e^{tA}[A,M_I]e^{-tA},A\rangle_e\,.
\end{align}
This formula is equivalent to $\frac{d}{dt}\lVert e^{tM_I}Ae^{-tM_I}\rVert=\langle[M_I,A],A\rangle=0$ that Claudio wrote above and that Denis guessed. It's just an alternative derivation without making reference to the Killing form or its properties...

A: Let $G$ be a compact connected semisimple Lie group and fix a left-invariant Riemannian
metric $B$ on $G$. Of course, $B$ is completely determined by its value at the identity. Since $G$ is compact and semisimple, the negative of its Cartan-Killing form, which we denote by $\beta$, is a positive definite inner product; the extension of $\beta$ to a left-invariant Riemannian metric is in fact bi-invariant. Next, we diagonalize $B$ with respect to $\beta$, namely, let $f$ be the positive definite symmetric endomorphism of the
Lie algebra $\mathfrak g$ of $G$ such that $B(X,Y)=\beta(f(X),Y)$ for all $X$, $Y\in\mathfrak g$. One computes easily from the Koszul formula for the Levi-Civita connection associated to $B$ that $\nabla_XY=\frac12(\mathrm{ad}_XY+f^{-1}\mathrm{ad}_Xf(Y)+f^{-1}\mathrm{ad}_Yf(X))$ for left-invariant vector fields $X$, $Y\in\mathfrak g$. In particular $\nabla_XX=f^{-1}\mathrm{ad}_Xf(X)$ and we see that the one-parameter associated to $X$ is a geodesic if and only if $\nabla_XX=0$ if and only if $[X,f(X)]=0$. In particular, this condition is satisfied if $X$ is an eigenvector of $f$.
Note that the Koszul formula above also gives
$B(\nabla_XX,Z)=B([Z,X],X])=\frac12\frac{d}{dt}||\mathrm{Ad}_{\exp tZ}X||^2$ at $t=0$,
which checks Denis guess that $t\mapsto\exp(tX)$ is a geodesic if and only if $X$ is a
critical point of the norm-square in its adjoint orbit.  In particular, there are infinitely many one-parameter groups which are geodesics if the rank of $G$ is bigger than one.


text:
Q: How to find a Newton-Cotes formula with weights? I want to build a Newton-Cotes formula with weights

$\int_0^1f(x)x^\alpha dx = a_0f(0) + a_1f(1) + R(f), \alpha > -1$

But, I cannot find any example, moreover I don't really know where to search or start either.
And, after I have the formula, how could I show that it makes sense and how could I find an expression for the error using an adequate derivative of f?
I need the formula and the error expression to find a formula for

$\int_0^{h} g(t)t^\alpha dt $, for a small h > 0

A: The idea behind Newton-Cotes rule is basically interpolation of the integrand. In case of weighted formula, we can interpolate only $f(x)$.
The interpolation nodes for Newton-Cotes are equally spaced and contain endpoints. Writing $f(x)$ interpolant in terms of Lagrange basis interpolants we have
$$
f(x) \sim P(x) \sum_{i = 1}^{K} f(x_i) \ell_i(x),
$$
where $x_i = a + \frac{i-1}{K-1}(b-a)$ is a set of evenly spaced $K$ points spanning the $[a,b]$ interval and $\ell_i(x)$ is defined as
$$
\ell_i(x) = \prod_{j \neq i} \frac{x - x_j}{x_i - x_j}
$$
Substituting $P(x)$ for $f(x)$ in the integral
$$
\int_a^b f(x) x^\alpha dx \approx \int_a^b P(x) x^\alpha dx =
\sum_{i=1}^K w_i f(x_i)
$$
with $w_i$ being
$$
w_i \equiv \int_a^b \ell_i(x) x^\alpha dx.
$$
The interpolation error could be roughly estimated as
$$
\left|P(x) - f(x)\right| \leq \frac{1}{K!}\max\limits_{z \in [a,b]} \left|f^{(K)}(z)\right| \left|\prod_{i=1}^K (x-x_i)\right|
$$
therefore quadrature error is bounded by
$$
\varepsilon = \left|\int_a^b (f(x) - P(x))x^\alpha dx\right| \leq \int_a^b \left|f(x) - P(x)\right| x^\alpha dx
\leq \frac{1}{K!}\max\limits_{z \in [a,b]} \left|f^{(K)}(z)\right| \int_a^b \left|\prod_{i=1}^K (x-x_i)\right| x^\alpha dx
$$
For your case $K = 2$ and $a = 0, b = 1$. Lagrange basis polynomials are $\ell_1 = 1 - x$ and $\ell_2 = x$, so
$$
w_1 = \int_0^1 (1-x)x^\alpha dx = \frac{1}{\alpha ^2+3 \alpha +2}\\
w_2 = \int_0^1 x \cdot x^\alpha dx = \frac{1}{\alpha + 2}\\
\varepsilon \leq \frac{1}{2}\max\limits_{z \in [a,b]} \left|f''(z)\right| \int_0^1 |(x-0)(x-1)| x^\alpha dx = \\
= \frac{1}{2}\max\limits_{z \in [a,b]} \left|f''(z)\right| \int_0^1 x(1-x) x^\alpha dx = \frac{1}{12+10\alpha +2\alpha^2}\max\limits_{z \in [a,b]} \left|f''(z)\right|
$$
There are more precise ways to esimate quadrature errors, ask if you need them.
Simple test case. Let $\alpha = \frac{1}{2}$, $f(x) = \cos x$.
$$
w_1 = \frac{4}{15}, \qquad w_2 = \frac{6}{15}\\
\int_0^1 \cos x\sqrt{x} dx = 0.5312026830...\\
\sum_{i=1}^2 w_i f(x_i) = w_1 \cos 0 + w_2 \cos 1 = 0.4827875890...
$$
The actual error is $\varepsilon = 0.048415$ and the error estimate is
$$
\varepsilon \leq \frac{2}{35} \max\limits_{z \in [0, 1]} \left|-\cos z\right| = \frac{2}{35} \approx 0.0571429.
$$


text:
Q: Scala: what is the right way to fold a collection of futures? I have a piece of code that sends broadcast message to a set of actors and collects their responses. Please look at the simplified code:
{
  val responses: Set[Future[T] = // ask a set of actors
  val zeroResult: T
  val foldResults: (T, T) => T

  //1. Future.fold(responses)(zeroResult)(foldResults)
  //2. (future(zeroResult) /: responses) { (acc, f) => for { x <- f; xs <- acc } yield foldResults(x, xs) }
} foreach {
   client ! resp(_)
}

Then I noticed that behaviors of lines of code 1 and 2 differ. E.g. there are 4 actors sending Traversable(1) as response, and
zeroResult = Traversable.empty[Int]
foldResults = { _ ++ _ }

The results of the first line are different: usually I get List(1, 1, 1, 1), but sometimes List(1, 1, 1) or even List(1, 1). It wasn't surprising for me, because Future.fold is unblocking, so it seems some responses could be missed.
But the second line always yields List of four ones.
Could anyone explain the reason why these kinds of fold differ and which of them is preferable?

A: The surprising thing for me in your question is the fact that your first fold (which I find preferable by reason of its conciseness) sometimes seems to operate on a list of three (or two) successfully completed futures.
In the normal scheme of things, you have 3 possible outcomes for a future:

*

*Completed normally

*Failed (completed with exception)

*Uncompleted

Both of the folds that you give will yield a single future that is uncompleted while all of its component futures are completed, or failed if any future (or the fold operation) fails, or completed if all goes well. (Your sentence Future.fold is unblocking, so it seems some responses could be missed is incorrect.)
I can only think that you have some other code somewhere that is completing futures with no result if a certain timeout is breached.
Apart from that, you have swapped the order of the operands in the fold operation in line 2 (should be yield foldResults(xs, x)) so the final order is reversed with respect to line 1.


text:
Q: getting null in api response Android retrofit I was testing the API in the Retrofit for first time, I was putting the code that they were showing but I don't know why my code doesn't work
it just shows that I am receiving the null value;
I was learning to implement the Retrofit library in my android app . so i was following some tutorial and i was following the code but don't know why i am getting this error
i tried to solve the error by changing the url but the response is the same it shows the null.
Please help me out
public class Todo {

 private int userId;
    private int id;
    private String todo;
    private boolean completed;

    public int getUserId() {
        return userId;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return todo;
    }

    public boolean isCompleted() {
        return completed;
    }
}

public interface ApiInterface {
@GET("/todo/{id}")
Call<Todo> getTodo(@Path("id") int id);

}

public class ApiClient {
    private static final String BASE_URL ="https://dummyjson.com";
    private static Retrofit retrofit= null;

    public static Retrofit getclient(){

        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

public class MainActivity extends AppCompatActivity {

    TextView hello;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hello= findViewById(R.id.textview);

        ApiInterface apiInterface = ApiClient.getclient().create(ApiInterface.class);

        Call<Todo> call =apiInterface.getTodo(1);
        call.enqueue(new Callback<Todo>() {
            @Override
            public void onResponse(Call<Todo> call, Response<Todo> response) {

                Log.e("info","onResponse"+response.body());

            @Override
            public void onFailure(Call<Todo> call, Throwable t) {

                    Log.e("info","onFailure" + t.getLocalizedMessage());
            }
        });
    }
}

A: You are missing the plural 's' in todo. Change your path to @GET("/todos/{id}")


text:
Q: selected row colour and selected cell colour I have a Datagridview in which I want that when any cell of any row receives focus, its color and the color of full row in which is cell is should change and it should get back to normal when the focus goes to another row. I am new to programming.

A: try CellContentClick event for capturing cell click as well as cell controls click
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Purple;
dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.WhiteSmoke;
}

edit:
it is possible without events
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Purple;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.WhieSmoke;


text:
Q: How to debug a class library on Azure App Service? I have a .NET application running in Azure. It has a library linked to it, but its source code is in a separate solution, and I need to debug this library. How do I link this library in Azure, and connect the debugger?

A: *

*In .Net Application , Right click on the Reference folder and browse your class library and select the dll file (YourClassLibraryName.dll)   from the bin folder of the class library.

*

*dll Reference will be added in the .Net Application Reference folder.

*Build and re-deploy the .Net Application.

*If you have the project's dependencies, using Visual Studio to deploy (via publish profile) will automatically upload all of the project's dependant projects/ libraries.

*Publishing your Solution will  automatically publish your dll's.

*The bin folder and its contents are copied to the target machine when the project is published.

*After publishing the application,check whether all the files and dll's exists in the bin folder

Path - Azure Portal=>Azure Web App=>Advanced Tools=>Go=>Debug Console=>CMD=>site=>wwwroot=> bin

You can see the referenced dlls with extension .dll and .pdb

*

*In VS, Add the namespace of the class library and  Set breakpoints in your code where you want them.

*To begin debugging, press F5. Visual Studio will identify the module load, load the symbols, and then stop at the breakpoint.

*

*In Visual studio => Net Application => In Publish window = >Hosting Settings => Click on Attach Debugger option


text:
Q: Network Configuration for Rocks Cluster So I'm trying to set up a Rocks cluster and seem to be failing at the network configuration part, as I can not get an internet connection in my final install.
So the address of that computer that shows up on my router is 192.168.0.124 and I used this as the IP in the first set up, shown here

I have also tried 192.168.0.1 and 192.168.0.130 (a random address in range). From a windows machine hooked up to the same network I can see that my netmask is 255.255.255.0. It also shows my default gateway as 192.168.0.1
Then I get to the private network and leave it at the defaults. I have tried other address too but I am unsure of what to do. There is just a network switch there in which I'd hook up all my computers to.

Finally I get to the screen about the gateway and DNS. From the Windows machine that is hooked up to the same network I run
ipconfig /all

and I get that the gateway and DNS servers are both on 192.168.0.1, so I used these.
My question is how do I set these up properly? How can I find out the addresses that I need to use? I haven't found any help from Google and this is the only part of the puzzle that I am missing.
I am installing as to the instructions of this youtube video but I am using different networking options.
My computer has an Ethernet connection on the mother board and one through a PCI-E slot. I have assumed that the computer is recognizing the PCI as eth1 and the motherboard connection as eth0. I have also booted into an Arch live cd on the machine, which can ping Google, and running ifconfig I see
enp4s6 with inet 192.168.0.124 and netmask 255.255.255.0
enp6s0 with no inet or addresses.
The ethernet conencted to the public network is connected to the network card in the PCI-E slot and the ethernet connected to the switch is on the motherboard port.
I appreciate any help. Thanks.

A: So I figured out that the problem was actually in that the different OS's loaded the NIC in different orders. Arch had loaded the PCI-E network card as enp4s6 and the motherboard card as enp6s0. How I figured this out was that when in the CentOS install I ran
ethtool eth0; ethtool eth1

and I noticed the different speeds. The cards had similar names so I had missed this but the PCI-E card was 100Mbps and the motherboard interface was a gigabit. The Arch live usb showed the reverse order.
And for anyone else that runs across this problem, here are some useful tools and places to look to help debug
/etc/hosts
/etc/resolve.conf
/etc/nsswitch.conf
ip addr show
ip route show
route
netstat -nr
arp -e
ethtool <interface>

In short, it was a stupid mistake on my part. I did not see any networking tools in the Rocks install (Anaconda installer) and it may just be easier to debug from a bad install where you have terminal access.


text:
Q: JavaFX Intelli J Exception in Application constructor I can't seem to figure out where I am going wrong with this project. I have spent around 4 hours trying to figure out where the problem is and have yet to find it.
FXMLDocumentController.java:
package seminar;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;

public class FXMLDocumentController {

    @FXML
    public TextField nametxt;
    public Label label;
    public TextArea list;
    public CheckBox chbox1,chbox2,chbox3;
    public RadioButton rdbtn1,rdbtn2,rdbtn3,rdbtn4;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        String name = nametxt.getText();
        int regular = 199;
        int instructor = 99;
        int deanandmini = 29;
        int mini = 39;
        int total=0;
        if(chbox1.isSelected()){
            if(rdbtn1.isSelected()){
                total = regular;
            }else if(rdbtn2.isSelected()){
                total = instructor;
            }
        }else if(chbox2.isSelected()){
            if(rdbtn3.isSelected()){
                total = deanandmini;
            }
        }else if(chbox3.isSelected()){
            if(rdbtn1.isSelected()){
                total = deanandmini;
            }else if(rdbtn2.isSelected()){
                total = mini;
            }
        }
        list.appendText("Subscriber Name: "+name+"\tTotal: "+total+"\n");
    }

    @FXML
    private void chechbox1(ActionEvent event) {
        if(chbox1.isSelected()){
            chbox2.setSelected(false);
            chbox3.setSelected(false);
            rdbtn1.setVisible(true);
            rdbtn2.setVisible(true);
            rdbtn3.setVisible(false);
            rdbtn4.setVisible(false);

        }
    }
    @FXML
    private void chechbox2(ActionEvent event) {
        if(chbox2.isSelected()){
            chbox1.setSelected(false);
            chbox3.setSelected(false);
            rdbtn1.setVisible(false);
            rdbtn2.setVisible(false);
            rdbtn3.setVisible(true);
            rdbtn4.setVisible(false);
        }
    }
    @FXML
    private void chechbox3(ActionEvent event) {
        if(chbox3.isSelected()){
            chbox1.setSelected(false);
            chbox2.setSelected(false);
            rdbtn1.setVisible(false);
            rdbtn2.setVisible(false);
            rdbtn3.setVisible(true);
            rdbtn4.setVisible(true);
        }
    }
}

Seminar.java:
package seminar;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Seminar extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        Scene scene = new Scene(root);
        String css = this.getClass().getResource("style.css").toExternalForm();
        scene.getStylesheets().add(css);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

FXMLDocument.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.ToggleGroup?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="399.0" prefWidth="647.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/16" fx:controller="seminar.FXMLDocumentController">
   <children>
      <Label layoutX="38.0" layoutY="82.0" text="Enter Name" />
      <TextField fx:id="nametxt" layoutX="111.0" layoutY="78.0" />
      <CheckBox fx:id="chbox1" layoutX="111.0" layoutY="122.0" mnemonicParsing="false" onAction="#chechbox1" text="subscription type (regular or instructor)" />
      <CheckBox fx:id="chbox2" layoutX="111.0" layoutY="154.0" mnemonicParsing="false" onAction="#chechbox2" text="Checthe optional web speech of a Dean guestBox" />
      <CheckBox fx:id="chbox3" layoutX="111.0" layoutY="184.0" mnemonicParsing="false" onAction="#chechbox3" text="any or all of the extra web mini seminars." />
      <RadioButton fx:id="rdbtn1" layoutX="111.0" layoutY="224.0" mnemonicParsing="false" selected="true" text="Regular ($199)" visible="false">
         <toggleGroup>
            <ToggleGroup fx:id="group1" />
         </toggleGroup>
      </RadioButton>
      <RadioButton fx:id="rdbtn2" layoutX="226.0" layoutY="224.0" mnemonicParsing="false" text="Instructor ($99)" toggleGroup="$group1" visible="false" />
      <RadioButton fx:id="rdbtn3" layoutX="111.0" layoutY="255.0" mnemonicParsing="false" selected="true" text="\$29" visible="false">
         <toggleGroup>
            <ToggleGroup fx:id="group2" />
         </toggleGroup>
      </RadioButton>
      <RadioButton fx:id="rdbtn4" layoutX="165.0" layoutY="255.0" mnemonicParsing="false" text="\$39" toggleGroup="$group2" visible="false" />
      <Button fx:id="button" layoutX="106.0" layoutY="305.0" mnemonicParsing="false" onAction="#handleButtonAction" prefHeight="25.0" prefWidth="82.0" text="Button" />
      <Label layoutX="38.0" layoutY="122.0" text="Choose" />
      <TextArea fx:id="list" layoutX="413.0" layoutY="71.0" prefHeight="200.0" prefWidth="200.0" />
   </children>
</AnchorPane>

I have trippled check my project structure and everything looks to be in place. Im using the m1 macbook but I have also tested this on a windows machine with same errors.
Exception in Application constructor
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class seminar.Seminar
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:891)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.IllegalAccessException: class com.sun.javafx.application.LauncherImpl (in module javafx.graphics) cannot access class seminar.Seminar (in module com.example.project1) because module com.example.project1 does not export seminar to module javafx.graphics
    at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:392)
    at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:674)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:489)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:803)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)


text:
Q: Find Salesforce ORG where a connected app lives using client id This is a bit of a weird question but I am unable to locate the sandbox a specific connected app lives under.We are looking at multiple prod orgs with many sandboxes underneath and haven't  been able to find it yet. Tried cheating the system by hitting the standard test domain hoping something would point at the real domain behind the client_id but the response does not indicate anything:
https://test.salesforce.com/services/oauth2/authorize?response_type=code&client_id=3MVG9GiqKapCZBwFbL74c4xggK0dfEOLAfRXloVgz.aDHEWNvHZYCIx3v5H7tnFtAHJUyFT7YpmMKg6wrlPBq&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fcallback

Any ideas on how to accomplish this without having to open every connected app in every sandbox would be greatly appreciated.

A: Your best option is to write a script that runs through the oAuth authorization for each sandbox. Assuming a vanilla connected app config where you don't require a signature via a JWT and the users are pre-authorized via a profile or a permission set, going in with a username/password flow would be our recommendation.


text:
Q: What are some excellent HTML 5, CSS 3 and JavaScript blogs? I'm following Ajaxian, but I'm wondering if there are other awesome blogs about HTML 5, CSS 3, JavaScript and such?

A: Some Javascript blogs from my Google Reader

*

*http://www.davidflanagan.com/

*http://dreaminginjavascript.wordpress.com

*http://www.dustindiaz.com

*http://www.stevesouders.com/blog

*http://james.padolsey.com

*http://ejohn.org

*http://www.nczonline.net/blog

*http://webreflection.blogspot.com/

A: It is not specific to HTML5 and CSS3, but it is a very helpful blog :
http://perfectionkills.com/
It deals with good practices for the web in general and performance improvements of web apps.

A: Dive into HTML5
24 ways (you'll have to wait until December for 24 more articles, but read the old ones): http://24ways.org/

A: CSS3.info is pretty good for finding out about the latest happenings in the CSS world.
A List Apart usually has great articles regarding web development (not specifically HTML5, CSS3, JavaScript).

A: Ajaxian is probably the best news source.
Smashing magazine also publishes interesting articles about HTML/CSS techniques and web design in general.

A: Me and a lot of people I work with periodically check Chris West's Blog.  His code is pretty good and he seems to always have new ways of looking at things that you wouldn't normally think of.  He also developed a customizable JavaScript library called jPaq so he seems to know his stuff.  One thing to note is that he seems to love and be best in JavaScript, but he does refer to some CSS3 and HTML5 things.

A: http://24ways.org has some really nice introductory articles for CSS3 features.

A: If you want up close and personal information on what is going on with HTML 5, I guess you should go directly to the source and read WHATWG Blog

A: For HTML5 I would also recommend HTML5 Doctor.

A: cssBeauty

A: ScriptAndStyle has a good rotation of CSS HTML and Javascript.

A: i have google alerts for html 5 OR css 3

A: *

*CSS Tricks is excellent (all
kinds of CSS);

*Nettuts has a lot
of useful tutorials on all kinds of
web-related areas;

*Soh Tanaka -
mainly Javascript-focused, seems to have
gone quiet recently though.


text:
Q: Bypassing Dual Stack Lite I am currently having problems connecting to a VPN I need to work with.
Troubles started when my ISP began switching to Dual Stack Lite, meaning that users get a native ipv6 and no public ipv4. (Traffic is routed through ipv6)
However, it seems I need a Ipv4 to connect to that VPN.
Calling my ISP and asking them to give me a public v4 address was of no use since they apparently don't give them to users anymore.
I was thinking of renting a VPN that supports ipv6, gives me a static ipv4 address and tunnel through that, routing all ipv4 traffic to me so that I am reachable for my work VPN. (I guess that would be a 4in6/4over6 routing)
Unfortunatly, it seems there are hardly any ipv6 vpn prodiver, or only some which are very expensive and want me to pay on an annual base.
Another idea was to get some kind of mobile device but I am not sure whether that would work.
Does anyone have an idea how I can bypass that stupid Dual Stack Lite?
Thank you very much

A: Turns out I can use openVPN with Dual Stack Lite. PPTN just doesn't work


text:
Q: Entity Framework: How to disable the LazyLoadingEnabled for just one query I know I can disable the lazy loading by setup:
Configuration.LazyLoadingEnabled = false;

But I'm wondering does this setting affect every queries in the following? If so, are there any way to disable it for just one query?
Can I achieve this by just set Configuration.LazyLoadingEnabled = true after the query or are there any side effects on this?