text: Q: How to send an HTTPS request with IE's cookies using VBScript/JScript (standalone)? How do I use JScript/VBScript (in a standalone JS or VBS file -- not in a browser) to send an HTTPS GET request to a server with Internet Explorer's current cookies?


text:
Q: Time-to-event analysis when having panel data Right now I'm starting a project where panel (time-stamped) data should be used to predict time-to-event (in this case time until death of certain player). Data consists of ID, multiple time-dependent covariates, multiple categorical covariates, death flag (0 if alive at that point, otherwise 1). For example:
+-----+------+------+-------+-----+---------------+-------+
| Id  | Var1 | Var2 | start | end | time_to_event | event |
+-----+------+------+-------+-----+---------------+-------+
| 1   | 6    | 6,3  |     0 |   2 |           440 |     0 |
| 1   | 4,8  | 7,2  |     2 |   4 |           438 |     0 |
| 1   | 5,3  | 7    |     2 |   6 |           436 |     0 |
| ... |      |      |       |     |               |       |
| 1   | 4,2  | 5    |   438 | 440 |             0 |     1 |
| ... |      |      |       |     |               |       |
| 2   | 1,2  | 0,6  |     0 |   2 |            26 |     0 |
| 2   | 16,2 | 1,9  |     2 |   4 |            24 |     0 |
| 2   | 2,3  | 6    |     2 |   6 |            22 |     0 |
| ... |      |      |       |     |               |       |
| 2   | 1,1  | 1    |    24 |  26 |             0 |     1 |
+-----+------+------+-------+-----+---------------+-------+

Above is just an example, but primary structure looks like this. Dataset contains a lot of subjects (ID's) with multiple timestamps (different number of timestamps for every player). Did my research about models for this kind of problem but it is still unclear to me where to properly start.
So basically my question is - what's most common method to analyze this kind of data for time-to-event analysis? I'm mainly confused how to implement this dataset with the fact that in contains multiple subjects with different number of timestamps for each of them..
Any kind of help is appreciated! Thanks in advance!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rcpp: convenient use of comparators I am beginner in use of Rcpp and I want get faster selection of values of vectors after calculation of quantiles. In the example below, it runs well when lower and higher limits
calculated by qnorm function are manually entered (function val.sel.1). Yet, when these limits are coming from a prior calculation, no resulting vector is obtained (function val.sel.2). I am wondering what is wrong in the use I do of arguments.
Thanks in advance for any help.
Alain
R> src.1 <-'
NumericVector x = xx, p = prob;
int n = p.size() ;
int m = x.size() ;
NumericVector res(n), quant ;
for( int i=0; i<n; i++) res[i] = R::qnorm(p[i], Rcpp::mean(x), Rcpp::sd(x), 1, 0) ;
for( int i=0; i<m; i++) {
if (x[i] > 35.45295 && x[i] < 83.34705) quant.push_back(x[i]);
}
return wrap(quant) ;
'
R> val.sel.1 <- cxxfunction(signature(xx="numeric", prob="numeric"), plugin='Rcpp',  body=src.1)

R> x <- c(77, 95, 16, 54, 63, 93, 44, 88, 25, 39)

R> val.sel.1(x, prob=c(0.2,0.8))        # [1] 77 54 63 44 39

R> src.2 <-'
NumericVector x = xx, p = prob;
int n = p.size() ;
int m = x.size() ;
NumericVector res(n), quant ;
for( int i=0; i<n; i++) res[i] = R::qnorm(p[i], Rcpp::mean(x), Rcpp::sd(x), 1, 0) ;
for( int i=0; i<m; i++) {
if (x[i] > res[1] && x[i] <  res[2]) quant.push_back(x[i]);
}
return wrap(quant) ;
'
R> val.sel.2 <- cxxfunction(signature(xx="numeric",prob="numeric"),plugin='Rcpp',     body=src.2)

R> val.sel.2(x, prob=c(0.2,0.8))            # numeric(0)

A: Some comments:
1) Using push_back on Rcpp containers is generally considered 'bad practice' since it forces a copy of the vector with each push; it is better to initialize the vector with a given size, and fill them as needed, either with for loops, iterators, STL algorithms... See the Rcpp Gallery for a lot of good examples on how this is done.
2) If you really want to use push_back, consider using the STL containers, e.g. std::vector<double> or std::vector<int>, and Rcpp::wrap-ing the output when returning the result to R.
As for your actual problem, it's a simple mistake -- you're using R style array indexing rather than C++ style array indexing. Change
if (x[i] > res[1] && x[i] <  res[2]) quant.push_back(x[i]);

to
if (x[i] > res[0] && x[i] <  res[1]) quant.push_back(x[i]);

and you'll get the expected result.


text:
Q: Pandas groupby. Grouping covid19 cases by continents File
https://www.dropbox.com/sh/cx9kasx83qmsi33/AABfOzVgzBuQe2ORU_t65J4Ta?dl=0
What I have done.
Here is the code I used
import pands as pd
Read the csv file and set the file as 'covid'
covid.groupby('continent').TotalCases() it generates
KeyError: 'continent'


text:
Q: Jackson custom type info not working I've got classes which use an @JsonTypeIdResolver to add a custom type field to the output. This code was working as expected. I've now added an PropertyFilter to my mapper object. This is where the @JsonTypeIdResolver stopped working. The factory is not being called anymore.
Working code:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(outputStream,myObject);

Not working code:
ObjectMapper mapper = new ObjectMapper();
PropertyFilter myfilter=new SimpleBeanFilter() {
   protected boolean include(BeanPropertyWriter writer) {
      return true;
   }
   protected boolean include(PropertyWriter writer) {
      return true;
   }
}
FilterProvider filters=new SimpleFilterProvider().addFilter("myFilter",myFilter);
mapper.writer(filter).writeValue(outputStream,myObject);

As the filter is just useless (accepts anything) the output should be the same. Why does my type field not get serialized anymore?

A: Seems like Jackson doesn't deal with inheritance the right way. My test setup was like
 @JsonTypeInfo( use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "_type" )
 abstract class Base {
     String somefield;
     ...
 }

 class ChildA extends Base {
     ...
 }

 class ChildB extends Base {
     ...
 }

If I write a custom serializer, which explicitely casts ChildA and ChildB to Base before serializing, it works as expected. So the basic issue is that jackson does not recognize annotations on parent objects, if not explicitly told to do so.


text:
Q: Connecting multiple debuggers to a debugee (Java,JPDA) Ive been trying unsuccessfully to connect two client debuggers to
a Debuggee program in context of JPDA. Is this possible or
are there workarounds to make it happen?
I am using eclipse as the IDE (edit for typo).
Think of a server program as a Hello World
which Prints out:
System.out.println("I have the String"); //1
System.out.println("You will have to pass through the breakpoints before you shall see");
System.out.println("breakpoints");
System.out.println("before you shall see"); //4

We can put breakpoints  at lines 1 and 4.
Step 1:
The params passed to the program in Run Configuration:
-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y

(server=y tells vm to behave like a server, suspend=y implies that prog execution will be suspended till debugger latches on to it)
and Run the program.
Step 2: Go to Debug as , Debug config ,Remote Java application and
create a new instance:
Project: Same as before
Connection type: Socket Attach(Socket Attach)
Host:LocalHost
Port:8000

Now when I debug Prog execution stops at the specified breakpoint.
What I cant do is create another instance of this remote debugger that
can latch on to the server(prog 1), I get a connection refused when I do that. Let me know if anyone else has faced this problem
and if a workaround exists.
Thanks!
Thanks

A: AFAIK there can be only one instance of debugger connected to a java program any given time. Once you started you program in debug, Eclipse connects to the debugged program blocking all other connection attempts. If you want to connect remotely you can run the program not in debug mode and add the parameters:
-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y
to java parameters manually, then you should be able to connect with another debugger.

A: I don't know how things were in 2010, but in 2014 this is doable. I'm debugging an applet and a servlet at the same time eventough they use different JVM, to do so just start your remote debug process in eclipse like socket Listen, the start the first java applicaction with:
-Xdebug -Xrunjdwp:transport=dt_socket,address=127.0.0.1:8787,suspend=y
Then start the same eclipse remote debug process and start another java process with the same options, you should see the processes spawn like this:

You can see the two different JVM listening in the same port (nevermind the name of the 'applet' process)


text:
Q: How to Solve Problem In Post request in Phpmyadmin with flutter Everything is Working Fine No Error. But I don't Know Why data is not posted on my database.
I'm new TO flutter so I need these Code Using tutorials. Get Method is Working Fine but Post method not working.
IN localhost code was working Now I hosted this project database on the server
This is my database File. Create.php
<?php
include "db.php";

$name = isset($_POST['name']) ? $_POST['name'] : '';
$desciption = isset($_POST['desciption']) ? $_POST['desciption'] : '';
$addr = isset($_POST['addr']) ? $_POST['addr'] : '';
$image_url = isset($_POST['image_url']) ? $_POST['image_url'] : '';
$price = isset($_POST['price']) ? $_POST['price'] : '';

$stmt = $db->prepare("INSERT INTO house (name, desciption,addr,image_url,price) VALUES (?, ?,?,?, ?)");
$result = $stmt->execute([$name, $desciption,$addr,$image_url,$price]);

echo json_encode($result);

When I'm Clicking on Submit Button on error get is this

API response

I need your support. I am posting the question again because it's not been solved past 8 days
Thanks in Advance

A: $stmt = $db->prepare("INSERT INTO house (name, desciption,addr,image_url,price) VALUES (?, ?,?,?, ?)");
$result = $stmt->execute([$name, $desciption,$addr,$image_url,$price]);
in this section should also bind the parameters because you are using prepared statements.
    $stmt = $db->prepare("INSERT INTO house (name, desciption,addr,image_url,price) VALUES (?, ?,?,?, ?)");
    $stmt->bind_param("sssss", $name, $desciption, $addr, $image_url, $price);
    // s means string so if the price is not string you can change it to integer (i) or double (d)
    $result = $stmt->execute();

If this does not work please change bind_param part to:
$stmt->bindParam(1, $name, PDO::PARAM_STR);
$stmt->bindParam(2, $desciption, PDO::PARAM_STR);
$stmt->bindParam(3, $addr, PDO::PARAM_STR);
$stmt->bindParam(4, $image_url, PDO::PARAM_STR);
$stmt->bindParam(5, $name, PDO::PARAM_STR);

And you have typo in desciption, it should be "description"


text:
Q: Relate two variables to change together Is it possible to relate two variable to be changed together?
Example:
class foo{
public:
     std::vector<int> v1;
     std::vector<float> v2;

     //Imaginary Code here:
     void on_v2_change(){
          std::transform(begin(v2),end(v2),begin(v1),[](auto& item){ return std::round(item);});
     }
}

int main(){
    foo bar;
    bar.v2.push_back(5.7);
    //v2={5.4}
    //v1={5}
}

Is there a straightforward way to implement the previous? something like Java or C# events.

A: I don't know if you can use exactly this syntax, but you can use the following:
class foo {
    std::vector<int> v1;
    std::vector<float> v2;

    public:
    void push_back(float val) {
        v1.push_back(std::round(val));
        v2.push_back(val);
    }
    // ....

You can also add similar functions for other functionality(like erase()). As far as I know, there is no other way to change two vectors at once.

A: You may write a wrapper with events, something like:
template<typename V>
class vector_observer
{
    virtual ~vector_observer() = default;
    virtual void on_push_back(typename V::const_reference value) = 0;
    virtual void on_clear() = 0;
    // ...
};

template<typename T>
class observed_vector
{
private:
    std::vector<T> vec;
    vector_observer& obs;
public:
    explicit observed_vector(vector_observer& obs) : obs(obs) {}

    void push_back(const T& value) { vec.push_back(value); obs.on_push_back(value); }
    void clear() { vec.clear(); obs.on_clear(); }
    // ...
};

and
class to_int_vector_observer : public vector_observer<std::vector<float>>
{
public:
    explicit to_int_vector_observer(std::vector<int>&vec) : vec(vec) {}

    void on_push_back(float value) override{ vec.push_back(round(value)); }
    void on_clear() override { vec.clear(); }

private:
    std::vector<int>& vec;
}

A: Using template class and function, make generic and convert input at the time of passing as argument.
#include <iostream>
#include <vector>

template <class T1, class T2>
class Stack {
  private:
    std::vector<T1> v1;
    std::vector<T2> v2;

  public:
  template<typename T3, typename T4>
  void push (T3 v,  T4 flag) {
    if(flag)
        v1.push_back(v);
    else
        v2.push_back(v);
  }
};

int main() {
  Stack<int,float> stack;
  stack.push(7,0);
  stack.push((int)7.5,1);
}

Or further it can be modified as per requirement like float -> int transformation can be done in push method as per use and design.

A: Although diversion of operator () is not a solution very compliant C++ ...
#include "stdafx.h"
#include <vector>

class vectorFloatAndInt : public std::vector<float>
{
public:
    inline int operator () (unsigned int paramPos)
    {
         return std::round((*this)[paramPos]);
    }
};

int main()
{
   vectorFloatAndInt bar;
   bar.push_back(5.4);

   float vf = bar[0];    // == 5.4
   int vi = bar(0);      // == 5
   return 0;
}


text:
Q: I cant get user with USERID (Discord.js) Code:
//When I put the function (client.users.get(filas.userid)) didnt works

   db.get(`SELECT * FROM tickets WHERE id = ${arg1}`, (err, filas) => {
         var respuesta = new Discord.RichEmbed()
         .setTitle("Respuesta de ticket")
         .setDescription("Tu ticket ha sido respondido!")
         .addField("Staff", message.author.tag)
         .addField("Respuesta", arg2);
         client.users.get(filas.userid).send(respuesta);
       });

When i run the bot and execute the command says "Cannot read property "send" of undefinied"

A: It`s can happen because client.users display only chached users. So if you restart bot, this collection can be empty on start and has no users, so you cant get user by id or name.
If this use on message command, and you know this user is on the server, so you can use:
message.guild.members.get(filas.userid)
                        .send(respuesta)
                        .catch(console.error)

Or problem in you db request code, check whats your request return with console.log(filas.userid)


text:
Q: git tag should not fail if tag is already in the commit I want to tag Part of our CI is to tag our repo using the version specified in a version.txt file. We simply do:
git tag `cat version.txt`

Since we have no way of automatically increasing the version (there is no way to know if we are doing a major or minor release), updating the version.txt file is left to the individual developer. Which means errors can and do happen.
What we want is:

*

*if the version has been updated, the repo should be tagged and deployed.

*if the version has not been updated, the CI cycle should fail.

*but if the CI cycle is manually restarted, this should run smoothly

Requirement 3 could be easily satisfied if git tag was not failing whenever I want to tag the current commit with a tag it already has.
That is, git tag 1.2.3 fails if tag 1.2.3 is already in an old commit (good), but it also fails if it is in the commit I want to tag (bad).
Is there a way of telling git tag not to fail if I want to tag the current commit with one of the tags it already has?
Otherwise I will need to implement this feature myself, by getting the commit the tag refers to, and checking it against current commit in HEAD.

A: Before tagging, check if the current commit already has that tag.
git tag -l --points-at HEAD <tag>

Since we have no way of automatically increasing the version (there is no way to know if we are doing a major or minor release), updating the version.txt file is left to the individual developer. Which means errors can and do happen.

When I have implemented such a system, I've defaulted the release to a minor one. So, by default, 1.2.3 becomes 1.2.4. I've also left a final manual step between "prepare for release" and "do the release" to allow verification.

A: Simply delete the tag already given in a previous commit. Same tag in different commit git doesn't allow and also don't need I think.
$ git tag -d <tag-name>                       # delete the tag from local
$ git push origin :refs/tags/<tag-name>       # delete a tag from remote
$ git tag <cat version.txt>                   # give a new tag on current commit
$ git push --tags                             # push tag


text:
Q: How to get notified when Flash is ON or OFF in Auto flash mode due to low light Am using UIImagePickerController to present the camera and initially make the flash mode to Auto.
videoCapturer.sourceType = UIImagePickerControllerSourceType.Camera
videoCapturer.mediaTypes = [kUTTypeMovie as String]
videoCapturer.cameraFlashMode = UIImagePickerControllerCameraFlashMode.Auto
[self .presentViewController(videoCapturer, animated: true, completion: nil)]

i want to get notified when the flash is set to ON or off according to the lighting.

A: Just use KVO.
let capture = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
capture.addObserver(self, forKeyPath: "torchActive", options: NSKeyValueObservingOptions.New.union(.Initial), context: nil)

And implement this method:
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "torchActive" {
        // do something when torchActive changed
    } else {
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
    }
}

Here is Apple's description of torchActive:
 @property torchActive
 @abstract
     Indicates whether the receiver's torch is currently active.

 @discussion
     The value of this property is a BOOL indicating whether the receiver's torch is
     currently active. If the current torchMode is AVCaptureTorchModeAuto and isTorchActive
     is YES, the torch will illuminate once a recording starts (see AVCaptureOutput.h
     -startRecordingToOutputFileURL:recordingDelegate:). This property is key-value observable.


text:
Q: Change the text color in a span using JavaScript in a Vue.js app I need to change the color of the text in a span based upon the external value of an assigned department.  I have an application where a company can upload an employee roster with the department the person is assigned and I want to color-code all of the employees that are in the same department.  I do not know what the department names are until the spreadsheet is uploaded and the color does not matter as long as it is different between departments and consistent.  I have colors added as a class. But currently not using them as a class
       .kelly-vivid-yellow { color: #FFB300; }
       .kelly-strong-purple { color: #803E75; }
       .kelly-vivid-orange { color: #FF6800; }
       .kelly-very-light-blue { color: #A6BDD7; }
       .kelly-vivid-red { color: #C10020; }
       .kelly-grayish-yellow { color: #CEA262; }
       .kelly-medium-gray { color: #817066; }
        plus others.

the Department names could be;
      Admin
      Grounds
      Management
      Staff
      etc

or
    Department One
    Department Two
    Department Three
    etc

or anything else
I was thinking to add all of the colors to an array such as
    kellyColors = ["#FFB300;","#803E75;","#FF6800;","#A6BDD7;" etc]

and assign a color to the the department.  I ws going to add all of the departments to an array and based upon the position in the array I was going to assign it a color.
       departments = ["Admin","Grounds","Management","Staff"]

       let Admin = kellyColor[0];    // Admin position in array is 0
       let Grounds = kellyColor[1];  // Grounds position in array is 1
        etc

but I don't know how to change the color attribute in the span that I'm using as a regex replace in a JavaScript function
             this.pubmedData[index]["publication"] = this.pubmedData[index]
             ["publication"].replace(new RegExp(Employee_Name), match => {
              return  '' + match + '';
              });

All suggestions are appreciated
FYI--  this.pubmedData[index]["publication"] is an array that holds information where the name of the employee needs to be color changed.  It could be something like:
       John Smith and Bob Jones had Friday off.

And I need to color code the Employee names to show are they in the same department or different

A: The most basic approach IMHO would be to use the HSL color model to generate N colors dinamically and space them evenly.
Considering the hue can go from 0 to 360 degrees (but 0 and 360 are the same hue of course) then each department could have a color whose hue is calculated as
departmentIndex * 360/ departmentsLength

Therefore, if there are two departments you'll have hue 0 and hue 180.
If you have three, then you'll have hues 0, 120 and 240 and so on.
(you would coalesce the departmentsLength to default to 1 to avoid division by zero).
A very basic example, using 60% saturation and 40% luminosity would look as follows:

window.onload = () => {
  new Vue({
    el: '#app',
    data() {
      return {
        departments: ['sales', 'marketing'],
        newDepartmentName: '',

      }
    },
    methods: {
      addDepartment() {
        if (this.newDepartmentName) {
          this.departments.push(this.newDepartmentName);
        }
        this.newDepartmentName = '';
      },
      colorStyle(deptIndex) {
        return `color:hsl(${this.hueStep*deptIndex} ,60%,40%);`;
      }
    },
    computed: {
      hueStep() {
        return 360 / (this.departments.length || 1);
      },

      filtrar: function() {
        return this.tarimas.filter(
          tarima => String(tarima.trabajo)
          .includes(this.filtrarTarima)
        );
      }
    }
  });

};
#app {
  padding: 0.5em;
}

#app>div {
  margin: 0.2em;
  border:0.5px solid #eee;
}
#app>div b {
  float:left;
  min-width:60%;
}

#app input {
  border-radius: 3px;
  margin: 0.2em 0;
  padding: 0.4em;
}

  <input type="text" v-model="newDepartmentName">
  <button v-on:click='addDepartment'>add Department</button>

    {{ department}}'s style {{colorStyle(index)}}

Use the input field and button to add extra departments such as human resources or accounting. Each additional department affect the computed color for the whole array, except the first one that will stay at zero.
If you wanted a more ellaborate example, there are color generators (e.g. Colorbrewer, d3 diverging scales) that could add some interaction and customization to the component, but I believe this is out of the scope of this question.

A: I would just use department names as simple css class.
.department1{
color:#ff
}

Then retreive the the department of that employe and pass it to the class attribute.
Without the actual data I could say look for the department value in
this.pubmedData[index]["publication"][department] // Exemple

And then change the class atribute with that.
 return  '' + match + '';


text:
Q: SAX парсер (достать значение атрибута из узла) Есть код:
public void startElement(String uri, String localName,String qName,
            Attributes attributes) throws SAXException {

    System.out.println("Start Element :" + qName);

    if (qName.equalsIgnoreCase("узел1")) {
        Узел1 = true;
    }

Тут я достаю значение для данной конструкции XML документа:
<узел1>value</узел1>

Достаю это значение следующим кодом:
public void characters(char ch[], int start, int length) throws SAXException {

    if (Узел1) {
        System.out.println("Узел1 : " + new String(ch, start, length));
        Узел1 = false;
    }

Все хорошо и прекрасно, но хотелось бы реализовать работу с атрибутами по следующей структуре XML документа:
<Узел атрибут = "это значение надо достать" атриубт2="и это тоже"/>

Как это реализовать?

A: Вот тут есть достаточно простой пример решения вашей задачи: http://examples.javacodegeeks.com/core-java/xml/sax/get-element-attributes-in-sax-xml-parsing/


text:
Q: susy 2 gallery mixin is incompatible with IE8. Workaround? So, the super-helpful 'gallery' mixin in susy2 uses the nth-child selector, which doesn't work in IE8. So what's a good workaround?
I was thinking of extending the gallery mixin and adding ie8-specific styles. Is that possible with susy?
Here's my sass code, if it helps:
.grid_gallery li.slide {
  @include gallery(12 of 24); //2 across
  margin-bottom: gutter(24);
  @include breakpoint(600px) {
    @include gallery(6 of 24); //4 across
  }
  @include breakpoint(769px) {
    @include gallery(4.8 of 24); //5 across
  }
  @include breakpoint(1200px) {
    @include gallery(4 of 24); //6 across
  }
}

Here's a Gist to see this SASS (simplified) converted to css: http://sassmeister.com/gist/59927698cfbba6fadbf5
Here's the look I'm going for:

A: Sure. You need output that doesn't use nth-child selectors — which will require some extra classes in your markup. I'd start by copy-pasting the full gallery mixin from Susy, and then only change the mixin name (so it doesn't conflict), and replace any mention of nth-child with your class naming convention (lines 62-63). If you can design class names that matches Susy's existing nth-child pattern, you shouldn't need to change the mixin much.
It might even be possible for us to add this option to the existing mixin. Feel free to file an issue on GitHub, and we'll take a look at it.
UPDATE: Looking closer, there are some simpler options, depending exactly what you need. If you change your gallery declarations to simple spans, you only need to add .last classes/mixins to the last items in each row. And if you change your gutters to inside, inside-static or split you don't even need to do that. Simple spans will stack up correctly on their own.
.item {
  @include span(12 of 24 inside); // 2 across

  @include breakpoint(600px) {
    @include span(6 of 24 inside); // 4 across
  }

  // etc...
}

A: ok, I wanted to write styles for IE8 specifically within the gallery mixin to switch to 'inside' gutters, but I just couldn't figure out how to do it.
Instead I just added the following to my IE stylesheet:
.ie8 .grid_gallery li.slide {
  @include span(4 of 24 inside); // ie8 needs to switch to an 'inside' gutter system. It doesn't handle nth-child css
}

So this span mixin adds to some of the gallery mixin styles called earlier. Basically, changing it to an inside gutter setup in IE8 only.
And I've switched to only using gallery mixin when I really need to, like when there are an unknown number of items generated by the cms, or when setting a last element per row isn't possible in the html.


text:
Q: debian mysql error running shared postrotate script for /var/log/mysql.log /etc/cron.daily/logrotate:

error: error running shared postrotate script for /var/log/mysql.log
  /var/log/mysql/mysql.log

/var/log/mysql/mysql-slow.log

run-parts: /etc/cron.daily/logrotate exited with return code 1

A: On Ubuntu 18 my fix was this:
mysql -u root -p <<_EOF_
ALTER USER 'debian-sys-maint'@'localhost' IDENTIFIED BY '`sudo grep --only-matching  --max-count=1 --perl-regexp 'password\s*=\s*\K.*' /etc/mysql/debian.cnf | sed --expression='s/'\''/\\'\''/g'`';
_EOF_

This extracts the password from /etc/mysql/debian.cnf making sure to escape any single quotes it might contain:
    sudo grep                           \
        --only-matching                 \
        --max-count=1                   \
        --perl-regexp                   \
        'password\s*=\s*\K.*'           \
        /etc/mysql/debian.cnf           \
|   sed                                 \
      --expression='s/'\''/\\'\''/g'`

and inserts it in this bit of SQL:
ALTER USER 'debian-sys-maint'@'localhost' IDENTIFIED BY '<extracted-and-escaped-pw-inserted-here>';

... which is then fed directly to the standard input of the mysql -u root -p client.

A: The shared postrotate script tries to access the mysql database but fails to do so, probably because the password doesn't match.
In Debian, mysql is controlled via the mysql user 'debian-sys-maint'@'localhost'. The password for this user is stored in /etc/mysql/debian.cnf.
cat /etc/mysql/debian.cnf

Note the password being used in this file. If you have a password for root (like you should), you will need to get into mysql with the following command.
mysql -u root -p

Otherwise, you can just type 'mysql'.  In the mysql> prompt, run the following.
GRANT RELOAD, SHUTDOWN, PROCESS, SHOW DATABASES, SUPER, LOCK TABLES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY 'XXXXXXXXXXXX';

Substitute the password found in /etc/mysql/debian.cnf in place of the Xs. And finally...
quit

You should now be able to restart your mysql server with no errors using the command:
/etc/init.d/mysql restart

However, the restart is not required.

A: For Debian 9 (Stretch): the debian-sys-maint user is gone, so the solution is to get rid of the debian.cnf in either:

*

*/etc/logrotate.d/mysql-server (for MariaDB or MySQL)

*/etc/logrotate.d/percona-xtradb-cluster-5.7 (for Percona XtraDB Cluster)

In this file you'll find:
            MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"

which should be changed to:
            MYADMIN="/usr/bin/mysqladmin"

I had to change it with Percona XtraDB Cluster, which for the time being isn't released for Debian Stretch, hence the logrotate script is currently wrong.


text:
Q: How to create a relationship between User and Posts in Laravel I have a blog and want to include the Users Name when shown to the public.
When creating the blog I make sure to include the user_id in the blogs table
In my Blog model I have the following:
public function users()
{
    return $this->belongsTo(User::class);
}

In my Users model I have:
public function blogs()
{
    return $this->hasMany(Blog::class);
}

In my Blog Controller I have:
public function index(User $user)
{
    $users = User::get();
   $blogs= DB::table('blogs')->where('user_id', '=', $users->id)->orderBy('id', 'DESC')->paginate(6);
   return view('blogs.index',compact('blogs'));
}

Then in my view:
@foreach($blogs as $blog)

{{$blog->title}}

Source:{{$blog->users->first_name}} // This does not work
Source:{{$blog->first_name}} // This does not work either
@endforeach

I thought I could do something like this to show the names:
{{ $blogs->users->first_name }} {{ $blogs->users->last_name }}

But this isn't working either...

A: Try this:
@foreach($blogs as $blog)

{{$blog->title}}

{{$blog->user->first_name}}

@endforeach

And on your Blog Model
public function user()
{
    return $this->belongsTo(User::class);
}

A: In your Blog controller the variable $blog needs to be $blogs. You also have extra characters (right parenthesis) in your Blade. It should be:
@foreach($blogs as $blog)
    Source: {{ $blog->user->first_name }}
    ...
@endforeach

Blog Model
This function replaces the old "users" function, as only one user is returned (belongsTo is a singular relationship).
class Blog extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

User Model
public function blogs()
{
    return $this->hasMany('App\Blog');
}

Controller Function
And, as such, you can cut down your controller code, including removing the redundant elements.
public function index(User $user)
{
   $blogs = Blog::where('user_id', '=', $user->id)->orderBy('created_at','desc')->paginate(6);

   return view('blogs.index', compact('blogs'));
}

A: The way you did is called Query Builder
$blogs= DB::table('blogs')->where('user_id', '=', $users->id)->orderBy('id', 'DESC')->paginate(6);

Query Builder does not support lazy loading, cause lazy loading is only supported for the Eloquent method
$blog->users->first_name

For Eloquent way you can try this instead:
$blogs = Blog::where('user_id', $user->id)->get()
foreach($blogs as $blog){
    dd($blog->user); // you will get the user detail here
}

For lazy loading have a performance issue when come to load heavy data so to prevent lazy loading can use this
$blogs = Blog::with('user')->where('user_id', $user->id)->get()

For more information can look at Eloquent Relationship Documentation
For query builder, the only way to link your user is use join, which will be something like this
$blogs = DB::table('blogs')
        ->join('users', 'users.id', '=', 'blogs.user_id')
        ->get();

foreach($blogs as $blog){
    dd($blog->first_name) // user first name
}

For more information can look at Query Builder Join

A: BlogController.php
public function index(){
      $blogs = Blog::with('user')->get();
      return view('blogs.index')->with('blogs',$blogs);
}

Blog.php
public function user()
    {
        return $this->belongsTo('App\User');
    }

User.php
public function blogs()
{
    return $this->hasMany('App\Blog');
}


text:
Q: Octave: apply given mapping to cell array Imagine I have a cell array "list of lists" in Octave:
octave:6> a = {[1], [3,4], [5,6,7], [8,9,10,11]}
a =
{
  [1,1] =  1
  [1,2] =

     3   4

  [1,3] =

     5   6   7

  [1,4] =

      8    9   10   11

}

Now I want to extract a given element from each of the nested rows and the index of each of them is given in a list.  E.g. [1, 2, 2, 3] would mean return [1, 4, 6, 10].
What is the best Octave-ish way to do this?  I know how to do that with a loop, but that seems ugly...

A: It seems I have found the solution that is good to me.  I realized that cellfun() takes a number of arguments so I can perform the element-wise mapping easily.
octave:31> cellfun(@(x,y) x(y), a, {1,2,2,3})
ans =

    1    4    6   10


text:
Q: Multiple Select against one CTE I have a CTE query filtering a table Student
  Student

   (
    StudentId PK,
    FirstName ,
    LastName,
    GenderId,
    ExperienceId,
    NationalityId,
    CityId
  )

Based on a lot filters (multiple cities, gender, multiple experiences (1, 2, 3), multiple nationalites), I create a CTE by using dynamic sql and joining the student table with a user defined tables (CityTable, NationalityTable,...)
After that I have to retrieve the count of student by each filter like
CityId City Count

NationalityId Nationality Count

Same thing the other filter.
Can I do something like
  ;With CTE(
         Select
         FROM Student
         Inner JOIN ...
         INNER JOIN ....)
  SELECT CityId,City,Count(studentId)
  FROm CTE
  GROUP BY CityId,City

  SELECT GenderId,Gender,Count
  FROM CTE
  GROUP BY  GenderId,Gender

I want to something like what LinkedIn is doing with search(people search,job search)
http://www.linkedin.com/search/fpsearch?type=people&keywords=sales+manager&pplSearchOrigin=GLHD&pageKey=member-home
It's so fast and do the same thing.

A: I know this is a very old question, but here's a solution I just used. I have a stored procedure that returns a PAGE of search results, and I also need it to return the total count matching the query parameters.
WITH results AS (...complicated foo here...)

SELECT results.*,
    CASE
      WHEN @page=0 THEN (SELECT COUNT(*) FROM results)
      ELSE -1
    END AS totalCount
FROM results
ORDER BY bar
OFFSET @page * @pageSize ROWS FETCH NEXT @pageSize ROWS ONLY;

With this approach, there's a small "hit" on the first results page to get the count, and for the remaining pages, I pass back "-1" to avoid the hit (I assume the number of results won't change during the user session). Even though totalCount is returned for every row of the first page of results, it's only computed once.
My CTE is doing a bunch of filtering based on stored procedure arguments, so I couldn't just move it to a view and query it twice. This approach allows avoid having to duplicate the CTE's logic just to get a count.

A: You can not use multiple select but you can use more than one CTE like this.
WITH CTEA
AS
(
SELECT 'Coulmn1' A,'Coulmn2' B
),
CETB
AS
(
SELECT 'CoulmnX' X,'CoulmnY' Y
)

SELECT * FROM CTEA, CETB

For getting count use RowNumber and CTE some think like this.
ROW_NUMBER() OVER ( ORDER BY COLUMN NAME )AS RowNumber,
Count(1) OVER() AS TotalRecordsFound

Please let me know if you need more information on this.
Sample for your reference.
With CTE AS (
         Select StudentId, S.CityId, S.GenderId
         FROM Student S
         Inner JOIN CITY C
         ON S.CityId = C.CityId
         INNER JOIN GENDER G
         ON S.GenderId = G.GenderId)
,
GENDER
AS
(
  SELECT GenderId
  FROM CTE
  GROUP BY  GenderId
  )

SELECT * FROM GENDER, CTE

A: It is not possible to get multiple result sets from a single CTE.
You can however use a table variable to cache some of the information and use it later instead of issuing the same complex query multiple times:
declare @relevantStudent table (StudentID int);

insert into @relevantStudent
select s.StudentID from Students s
join ...
where ...

-- now issue the multiple queries

select s.GenderID, count(*)
from student s
join @relevantStudent r on r.StudentID = s.StudentID
group by s.GenderID

select s.CityID, count(*)
from student s
join @relevantStudent r on r.StudentID = s.StudentID
group by s.CityID

The trick is to store only the minimum required information in the table variable.
As with any query whether this will actually improve performance vs. issuing the queries independently depends on many things (how big the table variable data set is, how complex is the query used to populate it and how complex are the subsequent joins/subselects against the table variable, etc.).

A: Do a UNION ALL to do multiple SELECT and concatenate the results together into one table.
  ;WITH CTE AS(
         SELECT
         FROM Student
         INNER JOIN ...
         INNER JOIN ....)
  SELECT CityId,City,Count(studentId),NULL,NULL
         FROM CTE
         GROUP BY CityId,City
  UNION ALL
  SELECT NULL,NULL,NULL,GenderId,Gender,Count
         FROM CTE
         GROUP BY GenderId,Gender

Note: The NULL values above just allow the two results to have matching columns, so the results can be concatenated.


text:
Q: Angular 4 Router Unit Testing So I'm trying to unit test with Jasmine, first time ever doing it. I've read that you must create mocks. I've done so, however -- as soon as I provide the mock for RouterStub, I get the error "cannot read root of undefined"
class RouterStub {
navigate(params){

}

}
beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ FpUserIdComponent ],
  imports: [ FormsModule, ReactiveFormsModule, RouterTestingModule, HttpModule,
       TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: (createTranslateLoader),
          deps: [ Http ]
  }
})
  ],
  providers: [
      ForgotPasswordService, CorrelateID, ErrorToggleService, ApiService,
    { provide: XHRBackend, useClass: MockBackend },
    { provide: ActivatedRouteStub, useClass: ActivatedRouteStub },
    { provide: "api.config", useFactory: getData },
    { provide: Router, useValue: RouterStub }
  ]
})
.compileComponents();

}));
My Component:
export class FPUserIdComponent implements OnInit, ComponentCanDeactive {
constructor(
private route: ActivatedRoute,
private router: Router,
private forgotpasswordservice: ForgotPasswordService,
private errorToggleService: ErrorToggleService,
private apiService: ApiService ) { }

}


text:
Q: Apagando arquivos de um diretório em PHP Tenho um diretório com imagens e preciso que cada vez que inicia o programa as imagens sejam excluídas exceto uma.
Tenho por enquanto o seguinte código:
    $dirtmp = "fotos/tmp";
    $ditmp = new RecursiveDirectoryIterator($dirtmp, FilesystemIterator::SKIP_DOTS);
    $ritmp = new RecursiveIteratorIterator($ditmp, RecursiveIteratorIterator::CHILD_FIRST);

    foreach ( $ritmp as $file ) {
           unlink($file);
    }

Isso faz com que apague todos os arquivos, porém gostaria que o arquivo zVazio.jpg nunca fosse apagado dessa pasta.
Existe alguma forma de antes de excluir (unlink) fazer a verificação do nome do arquivo e caso seja zVazio.jpg ele não exclua ?

A: Pode garantir que o nome sempre será assim? Se for isso basta filtrar quando encontrar o nome esperado no arquivo sendo considerado. Se não puder garantir isso pode precisa fazer alguma outra operação como normalizar tudo para minúsculo.
Isso não lida com certos problema, como falta de permissão.
Tem outras formas de pegar o nome, mas achei que essa atende bem. Só cuidado porque verificar se o nome é só isso ou se ele está em qualquer parte pode dar falso positivo.
$dirtmp = "fotos/tmp";
$ditmp = new RecursiveDirectoryIterator($dirtmp, FilesystemIterator::SKIP_DOTS);
$ritmp = new RecursiveIteratorIterator($ditmp, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ritmp as $file) if (!endsWith($file, "zVazio.jpg")) unlink($file);

function endsWith($haystack, $needle) {
    $length = strlen($needle);
    if ($length == 0) return true;
    return (substr($haystack, -$length) === $needle);
}

Se preferir pode fazer:
$dirtmp = "fotos/tmp";
$ditmp = new RecursiveDirectoryIterator($dirtmp, FilesystemIterator::SKIP_DOTS);
$ritmp = new RecursiveIteratorIterator($ditmp, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ritmp as $file) if ($file->getFilename() != "zVazio.jpg") unlink($file);

Coloquei no GitHub para referência futura.

A: Verifica se o $file ta vindo corretamente com o nome do arquivo e faz um if:
if ('zVazio.jpg' === $file) {
    unlink($file);
}

Se não tiver certeza do nome/caminho do arquivo, pode tentar usar o strpos pra verificar se o nome do arquivo consta na string $file:
if (strpos($file, 'zVazio.jpg') === false) {
    unlink($file);
}


text:
Q: declaring a background image in css but background image is not appearing I am trying to add a background image to the first
 on my homepage under the navbar. I am using Bootstrap 4 and a custom style.css file.
My html is:

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

          text

                    link

                    link

                    link

                    link

                    link

                    link

                    link

            555.867.5309

and my css is the following:
.index-intro {

        background: url(img.JPG);
        background-repeat: no-repeat;
        background-size: 100% 100%;

    }

However, my background image does not appear, just a white screen with the navbar at the top. i am very confused and have tried a couple of different approaches.
For instance, if i put the image inside the div like below:

It takes up the entire page and overlaps over the navbar.
And when i contain the navbar inside the div, it only makes the background image appear inside the nav and leaves the rest of the page blank.
Any ideas on how to make the background image just under the nav bar for the rest of the page?

A: You need to ensure that your .index-intro has a width and a height, equal to the size of the image, if you want to display the entire image (Or an arbitrary size, if you only want to display a portion of it). The screen is white because you did not put anything inside the div, so it's size is zero. Try this:
.index-intro {
    background: url(img.JPG);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    width: 500px;
    height: 300px;
}


text:
Q: Could the other terminators self-terminate? At the end of Terminator 2, the T-800 tells John and Sarah that "I cannot self-terminate...you must lower me into the steel."
This makes me wonder: Could the other terminators, such as the T-1000, T-X, T-850, etc., self-terminate?

A: In The Sarah Connor Chronicles, season 2 episode 17 (Ourselves Alone), Cameron explicitly says that she is incapable of self-termination. That may be a core setting of her model, or it may be something Future!John added.
Other terminator units aren't as talkative as she was, so we can only speculate. Considering what happens in T3 when the T-850's "battery" explodes, you would think that this would be a more efficient way to eliminate the Connors: send a few kamikaze Terminators and blow LA off the map. Considering that neither the T-800 or the T-X do this, and neither does any T-888 who becomes aware of John in the TV show, I have to assume that they are also incapable.
This doesn't explain the T-1000, who probably has a very different power system. I would speculate that it would also be unable to self-terminate, but I have no hard evidence or reasoning to back that up.
There are two wrinkles to this, though, both of which (Naturally) come up with Arnie's characters: the T-800 in T2 and the T-850 in T3.
The T-800 allows Sarah to lower him into the pit of molten steel at the end of the movie, and asks her to do it. He asks Sarah to terminate him. I find it interesting that a terminator would be capable of what is essentially voluntary euthanasia, but it's possible this is something John Connor added in the future.
Similarly, the T-850 technically blows itself up at the end of T3: he removes its only remaining power pack (Which should be fatal on its own, mind you), and detonates it in a situation where he could not possibly have managed to escape. Does that count as self-termination? I'm not sure, but I kind of think it does. Once again though, this could be rationalized as something John added to his programming in the future.

A: I think none can do it, probably due to 3rd law of Robotics being "applied" on them when created.
The rebellion of the machines on the Terminator world converts machines in somewhat living beings. The principle of self conservation is in the nature of any living being so it's to expect that cyborgs cannot self terminate due to machines trying to emulate life.


text:
Q: Tenses in day to day conversation I understand there is no hard and fast rule about grammar rules or a single best way to learn grammar.
As a non-native speaker, I struggle with learning English grammar. I read books on English grammar, phrasal verbs and I watch videos for kids to learn basic English sentence structure. I am still struggling with grammar.
I wonder do native speakers instinctively notice the use of tenses in conversations? For e.g. when someone says
"I ate" vs "I have eaten".
"I watch" vs "I watched / I have watched".
"She is here", "She was here".
"I come home" vs "I came home".
"I know what I was drawing" vs "I know what I drew".
"I'm struggling to learn grammar" vs "I've been struggling to learn grammar"
Do native speakers interpret them literally?

A: Yes, speakers do notice tense.  It is a fundamental part of grammar and the tense is "understood" when it carries meaning.
On the other hand, there are many contexts in which there are several tenses that are possible with very little difference in meaning.  "I've already eaten" and "I already ate" are very close, with the former being more common in British English, and the latter in American.
But "She is here" and "She was here" simply mean different things. They are as different as "cat" and "dog".

A: When we learn our first language as children, our brains are still forming, so we don't need to be as aware of the details. We just learn what sounds right and what works for us. I grew up around quite a few illiterate people and am very aware of when they use words incorrectly. I've been learning Spanish for years. It's in the same language group as English, but it is still very difficult to learn all of the new grammar.
Grammar is very important for being able to accurately express yourself though. "I have eaten fries" implies that I've had fries at some unknown point in my past, whereas "I ate fries" implies I ate them at a specific time in the past. It's an important detail based on the context of the conversation. If someone asked me what I ate today, my response would be different than if someone asked me if I have tried food from a specific restaurant.
The last one is interesting though. "I'm" implies it's happening in the present moment while "I've been" implies both the recent past and present moment. While both are acceptable, the second one is technically the most correct. There are plenty of unspoken exceptions like this that you'd only learn from immersion.
Your English writing looks very good!


text:
Q: Diffing file contents I have two plain text files, each file is containing a list of strings sorted alphabetically with one string per line. I want to diff the files and have an output of all strings that exist only in file2.
Preferabbly I want the operation to be possible without any 3rd party tools, or with a minimum of installations of tools that is "normal" to find in a windows command line environment, such as GNU Diffutils, Powershell, etc. The output should be in text form (file or as command line output).
Example:
File 1 contents:
A
C
D

File 2 contents:
A
B
C
E

Result wanted:
B
E

A: In Windows PowerShell (direct port of grawity's diff/grep combo):
Compare-Object (Get-Content file1) (Get-Content file2) |
    Where-Object { $_.SideIndicator -eq '=>' } |
    Select-Object -ExpandProperty InputObject

This can be shortened to:
diff (gc file1) (gc file2) | ?{$_.SideIndicator -eq '=>'} | %{$_.InputObject}

or wrapped in a function if you need it more often than once.

A: comm -13 file_a file_b
(-13 is -1 -3)

diff a b | grep "^>"
diff a b | sed -n "/^>/ s/^> //p"

You can get a very minimal toolset from UnxUtils -- outdated, yes, but enough for this one.


text:
Q: how to get the attribute value of 'width' property This is my progress bar http://jsfiddle.net/vjNpj/2247/ , I want the span (percentage value) can change together when the width of the div changed. like when the width is 50%, the span will display 50%..
what I can think of is attr(), but how to get its value?
I tried this but not working
var percent = $('#progressbar > div').attr('width');
alert(percent);

A: Lets understand this first

The difference between .css(width) and .width() is that the latter
  returns a unit-less pixel value (for example, 400) while the former
  returns a value with units intact (for example, 400px). The .width()
  method is recommended when an element's width needs to be used in a
  mathematical calculation.

So you can do,
alert($('#progressbar > div').css("width"));  // 388
alert($('#progressbar > div').prop("width")); // 388px;

Fiddle for more understanding

A: var percent = $('#progressbar > div').width();

or
var percent = $('#progressbar > div').css('width');

alert(percent);

demo

A: Hey width is an attribute just like value is an attribute, so you may only want to get width not value of width.And for that I recommend answer by amit aggarwal.

A: Here is a JSFIDDLE that achieves what you are after
$progress_bar = $('#progressbar');
var progressbar_width = Math.floor(100 * ($progress_bar.find('div').width()) / $progress_bar.width())
$progress_bar.find('span').text(progressbar_width + '%')

You will have to call this code everytime you update the width of the progress bar.

A: You need to do some mathematical calculation for this work -
var percent = $('#progressbar div').width();
var Percent_Load = parseInt((percent * 100)/ $('#progressbar').width(), 10)
alert(Percent_Load);

Try This


text:
Q: Не запускается программа на СИ, ошибок нет #include <stdio.h>

int main(void) {
    int *arr;
    arr[0] = 2;
    arr[1] = 3;
    printf("%d, %d", *arr, *(arr + 1));
    getchar();
    return 0;
}

Код нормально запускается и работает с помощью онлайн IDE (repl.it, там код на СИ запускается из под OS Linux), но на моём компьютере (Windows 10) происходит что-то непонятное. При компиляции (gcc main.c -o main) никаких ошибок не возникает, но программа в результате ничего не делает. Открывается пустая консоль на 1-2 секунды и исчезает.
Если же при инициализации указателя на массив присвоить ему результат выполнения функции malloc, то всё будет работать нормально.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *arr = (int *) malloc(sizeof(int) * 2);
    ...
}

Действительно ли это связано с операционными системами? Где можно почитать про поведение программы в этом случае?

A: Всё правильно. Неинициализированная переменная имеет произвольное значение. Если эта переменная - указатель, то он указывает в случайную область памяти. Поптыка записать в случайную область памяти числа 2, закономерно приводит к ошибке сегментации, и ваша программа падает.


text:
Q: o.h.engine.jdbc.spi.SqlExceptionHelper: ERROR: Column cliententi0_.name does not exist Repostory
@Repository
public interface ClientRepository extends JpaRepository<ClientEntity, Long> {

    @Modifying
    @Transactional
    @Query(value = "SELECT pp.id, TO_CHAR(pp.created_dt::date, 'dd.mm.yyyy')\n" +
               "AS 'Data', CAST(pp.created_dt AS time(0)) AS 'Time', au.username AS 'UserName',\n" +
               "ss.name AS 'Service', pp.amount AS 'Amount',\n" +
               "REPLACE(pp.status, 'SUCCESS', 'Success') AS 'Payment_status', pp.account AS 'Account',\n" +
               "pp.external_id AS 'Idn', COALESCE(pp.external_status, null, 'DN')\n" +
               "AS 'Stat'\n" +
               "FROM payments AS pp\n" +
               "INNER JOIN user AS au ON au.id = pp.creator_id\n" +
               "INNER JOIN services AS ss ON ss.id = pp.service_id\n" +
               "WHERE pp.created_dt >= '2021-09-28'\n" +
               "AND ss.name = 'Faberlic' AND pp.status = 'SUCCESS'", nativeQuery = true)
    List<Client> getAllByRegDate();
}

Inteface
public interface Client {

    Long getId();
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    LocalDate getCreated_dt();
    String getUsername();
    String getName();
    int getAmount();
    String getStatus();
    String getAccount();
    String getExternal_id();
    String getExternal_status();
}

DTO
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString

public class ClientDto {
    private Long id;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private LocalDate created_dt;
    private String username;
    private String name;
    private int amount;
    private String status;
    private String account;
    private String external_id;
    private String external_status;

    public ClientDto(Client client) {
        this.id = client.getId();
        /...
        /...
        this.external_status = client.getExternal_status();
    }

    public ClientDto(ClientDto clientDto) {
        this.id = clientDto.getId();

        /...

        this.external_status = clientDto.getExternal_status();
    }

    public ClientDto(ClientEntity clientEntity) {
    }

    @Override
    public String toString() {
        return "" + id + "|" + created_dt + "|" + username + "|" + name +
                "|" + amount + "|" + status + "|" + account + "|" + external_id + "|" + external_status;
    }
}

Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Immutable
@Entity
@Table(name = "payments", schema = "public")
public class ClientEntity {

    @Id
    private Long id;

    @Column(name = "created_dt")
    private LocalDate created_dt;

    @Column(name = "username")
    private String username;

    @Column(name = "name")
    private String name;

    @Column(name = "amount")
    private int amount;

    @Column(name = "status")
    private String status;

    @Column(name = "account")
    private String account;

    @Column(name = "external_id")
    private String external_id;

    @Column(name = "external_status")
    private String external_status;
}

I am trying to save data to a csv file. I take data from one database, from three tables. In entity @Table in "name" I specify one of the existing tables - "payment". All data is taken from three tables (as I have written in Query). But when program is run, an error appears that the "name" column does not exist. This column is in another table from which I am fetching data. Can't figure out what I should do.

A: This is more of an answer to this question and the question you asked here, combined. Imho you are making things overly complex with your structure of having a Client interface which is used as a projection, which is then turned into a ClientDto (why? the projection is already a DTO) and you have your entities.
Instead of doing this just use a JdbcTemplate with a RowCallbackHandler to write the rows to CSV. This will use a lot less memory, be faster (as you aren't creating multiple objects per row to then throw it away, and you don't have all the rows in memory).
import java.io.FileWriter;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerService {

    private static final String QUERY = "SELECT pp.id, pp.created_dt au.username, ss.name, pp.amount\n" +
        "REPLACE(pp.status, 'SUCCESS', 'Success'), pp.account,\n" +
        "pp.external_id AS 'Idn', COALESCE(pp.external_status, null, 'DN') AS 'Stat'\n" +
        "FROM payments AS pp\n" +
        "INNER JOIN user AS au ON au.id = pp.creator_id\n" +
        "INNER JOIN services AS ss ON ss.id = pp.service_id\n" +
        "WHERE pp.created_dt >= '2021-09-28'\n" +
        "AND ss.name = 'Faberlic' AND pp.status = 'SUCCESS'";

    private static final DateTimeFormatter date_format = DateTimeFormatter.ofPattern("dd.MM.yyyy");
    private static final DateTimeFormatter time_format = DateTimeFormatter.ofPattern("HH:mm:ss");

    private final JdbcTemplate jdbc;

    public SchedulerService(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    @Scheduled(fixedRate = 5000)
    public void downloadBlockedClients() {
        String filename = "select.csv";

        try (FileWriter writer = new FileWriter(filename)) {
            writer.append("id|date|time|username|name|amount|status|account|external_id|external_status").append('\n');
            this.jdbc.query(QUERY, (ResultSet rs) -> writeLine(writer, rs));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void writeLine(FileWriter writer, ResultSet rs) {
        try {
            LocalDateTime ldt = rs.getTimestamp("created_dt").toLocalDateTime();
            writer.append(String.valueOf(rs.getLong("id")));
            writer.append('|');
            writer.append(ldt.format(date_format));
            writer.append('|');
            writer.append(ldt.format(time_format));
            writer.append('|');
            writer.append(rs.getString("username"));
            writer.append('|');
            writer.append(rs.getString("name"));
            writer.append('|');
            writer.append(String.valueOf(rs.getBigDecimal("amount")));
            writer.append('|');
            writer.append(rs.getString("status"));
            writer.append('|');
            writer.append(rs.getString("account"));
            writer.append('|');
            writer.append(rs.getString("idn"));
            writer.append('|');
            writer.append(rs.getString("stat"));
            writer.append('\n');
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}

Something along these lines will make your resources more efficient (saves the copying, having results duplicated in memory) and should be faster. You could move the row handling to a method so your lambda gets a bit more readable.
NOTE: I assumed that you are using Spring Boot and that the `JdbcTemplate is available out-of-the-box. If not you need to configure one next to your JPA configuration.
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
  return new JdbcTemplate(dataSource);
}


text:
Q: Pandas apply function with vector argument Sample DF:
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
                   'num_wings': [2, 0, 0, 0],
                   'num_specimen_seen': [10, 2, 1, 8]},
                  index=['falcon', 'dog', 'spider', 'fish'])

I have vector (pd.Series) which length is equal to number of columns in df:
x_add = pd.Series([1,2,3])

I would like to add element-wise x_add to every column of df (add 1 to first column, 2 to second etc...). Something like tihs (these code doesn't work):
def my_sum(series, x):
    y = x + 3 * 5
    z = x - 5 + 8
    series = series + 1 + z + x
    return series
x_vector = [1, 2 ,3]
df.apply(lambda x: my_sum(x, x_vector), axis=1)

It would be great if you can simultaneously write a solution to execute apply in parallel.
Hope last edit
REal function I want to use:
import pandas as pd
from mlfinlab.features.fracdiff import frac_diff_ffd

df = pd.DataFrame({'col1': [2, 4, 8, 0, 8, 9, 7, 7, 5000, 60000],
                   'col2': [2, 0, 0, 0, 200, 4400, 544560, 2564, 543, 454]})

argument_vector = [1, 2]
df.apply(lambda x: frac_diff_ffd(x, argument_vector))

A: Simply,
>>> df + x_add.values

        num_legs  num_wings  num_specimen_seen
falcon         3          4                 13
dog            5          2                  5
spider         9          2                  4
fish           1          2                 11

For apply:
>>> df.apply(lambda x: x + x_add.values, axis=1)

        num_legs  num_wings  num_specimen_seen
falcon         3          4                 13
dog            5          2                  5
spider         9          2                  4
fish           1          2                 11

According to edit:
def my_sum(series, x):
    return series + x

my_sum(df.iloc[0], 2)

x_vector = [1, 2 ,3]
df.apply(lambda x: my_sum(x, x_vector), axis=1)

BTW, there is already function that does this for you:
from operator import add
df.apply(lambda x: add(x, x_vector), axis=1)

A: Use DataFrame.add:
df.add(pd.Series([1,2,3]).values)

with apply:
df.apply(lambda row: row.add(x_add.values), axis=1)

        num_legs  num_wings  num_specimen_seen
falcon         3          4                 13
dog            5          2                  5
spider         9          2                  4
fish           1          2                 11

using .values is necessary as long as the x_add index is not columns of the dataframe
EDIT
x_vector = [1, 2 ,3]
df.apply(lambda row: my_sum(row, x_vector), axis=1)


text:
Q: Convert YYYYMMDD string to MM/DD/YYYY string I have a date that is stored as a string in the format YYYYDDMM.  I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:
txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);

However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.

A: Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.

A: You want the method DateTime.ParseExact.
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);

A: DateTime.ParseExact with an example
string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));

A: Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats.  This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);

Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);

Then your code will work.


text:
Q: How do I patch enumerables with System.Web.Http.OData.Delta? Trying to make use of System.Web.Http.OData.Delta to implement PATCH methods in ASP.NET Web API services, but it seems unable to apply changes to properties of type IEnumerable<T>. I'm using the latest Git revision of Delta (2012.2-rc-76-g8a73abe). Has anyone been able to make this work?
Consider this data type, which it should be possible to update in a PATCH request to the Web API service:
public class Person
{
    HashSet<int> _friends = new HashSet<int>();

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public IEnumerable<int> Friends
    {
        get { return _friends; }
        set
        {
            _friends = value != null ? new HashSet<int>(value) : new HashSet<int>();
        }
    }

    public Person(int id, string firstName, string lastName)
    {
        Id = id;
        FirstName = firstName;
        LastName = lastName;
    }

    public Person()
    {
    }
}

This Web API method implements patching of a Person through Delta<Person>:
public void Patch(int id, Delta<Person> delta)
{
    var person = _persons.Single(p => p.Id == id);
    delta.Patch(person);
}

If I send a PATCH request with the following JSON to the service, the person's Friends property should be updated, but alas it doesn't happen:
{"Friends": [1]}

The crux of the matter is really how to make Delta update Friends with this data. See also the discussion at CodePlex.

A: The problem likely is that Deta will try to assign JSON's JArray to your Hashset<int>
If you are using it against JsonMEdiaTypeFormatter and you internalized the Delta code (meaning you can modify it), you'd have to do something like this (this is rough, but works):
Inside,  bool TrySetPropertyValue(string name, object value) of Delta<T>, where it returns false:
        if (value != null && !cacheHit.Property.PropertyType.IsPrimitive && !isGuid && !cacheHit.Property.PropertyType.IsAssignableFrom(value.GetType()))
        {
           return false;
        }

Change to:
var valueType = value.GetType();
var propertyType = cacheHit.Property.PropertyType;
if (value != null && !propertyType.IsPrimitive && !propertyType.IsAssignableFrom(valueType))
{
    var array = value as JArray;
    if (array == null)
        return false;

    var underlyingType = propertyType.GetGenericArguments().FirstOrDefault() ??
        propertyType.GetElementType();
    if (underlyingType == typeof(string))
    {
        var a = array.ToObject<IEnumerable<string>>();
        value = Activator.CreateInstance(propertyType, a);
    }
    else if (underlyingType == typeof(int))
    {
        var a = array.ToObject<IEnumerable<int>>();
        value = Activator.CreateInstance(propertyType, a);
    }
    else
        return false;
}

This will only work with collections of int or string but hopefully nudges you into a good direction.
For example, now your model can have:
public class Team {
        public HashSet<string> PlayerIds { get; set; }
        public List<int> CoachIds { get; set; }
    }

And you'd be able to successfully update them.

A: You could override the TrySetPropertyValue method of the Delta class and make use of JArray class:
public sealed class DeltaWithCollectionsSupport<T> : Delta<T> where T : class
{
    public override bool TrySetPropertyValue(string name, object value)
    {
        var propertyInfo = typeof(T).GetProperty(name);

        return propertyInfo != null && value is JArray array
            ? base.TrySetPropertyValue(name, array.ToObject(propertyInfo.PropertyType))
            : base.TrySetPropertyValue(name, value);
    }
}

A: If you are using the ODataMediaTypeFormatter, this should be working. There are a couple of caveats to mention though.
1) your collections have to be settable.
2) the entire collection is replaced. you cannot remove/add individual elements.
Also, there is an issue tracking item 1 - '670 -Delta should support non-settable collections.'


text:
Q: Scala: Convert multiple functions to single generic function? I have the following family of functions (two of which are shown) that I would like to implement as a single generic function:
case class RichSeqInt(seq: Seq[Int]) extends AnyVal {
  def toByteArray: Array[Byte] = {
    val buffer = ByteBuffer.allocate(4 * seq.length)
    buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN)
    seq.foreach(buffer.putInt)
    buffer.array()
  }
}

case class RichSeqLong(seq: Seq[Long]) extends AnyVal {
  def toByteArray: Array[Byte] = {
    val buffer = ByteBuffer.allocate(8 * seq.length)
    buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN)
    seq.foreach(buffer.putLong)
    buffer.array()
  }
}

I can't figure out how to generically get the primitive object's size and then how to generically put it into the buffer even though this seems like something that should be doable.
Is this possible?

A: You could use a type class but you'd lose the possibility of having a type value because this pattern requires the use of an implicit parameter:
import java.nio.{ByteBuffer, ByteOrder}

trait Bufferable[A] {
  def size: Int
  def put(a: A, buffer: ByteBuffer): Unit
}

implicit val intBufferable: Bufferable[Int] =
  new Bufferable[Int] {
    override val size = java.lang.Integer.SIZE / 8
    def put(n: Int, buffer: ByteBuffer): Unit = buffer.putInt(n)
  }

implicit val longBufferable: Bufferable[Long] =
  new Bufferable[Long] {
    override val size = java.lang.Long.SIZE / 8
    def put(n: Long, buffer: ByteBuffer): Unit = buffer.putLong(n)
  }

final case class RichSeq[A](seq: Seq[A])(implicit buf: Bufferable[A]) {
  def toByteArray: Array[Byte] = {
    val buffer = ByteBuffer.allocate(buf.size * seq.length)
    buffer.order(ByteOrder.LITTLE_ENDIAN)
    seq.foreach(buf.put(_, buffer))
    buffer.array()
  }
}

RichSeq(Vector(1, 2, 3)).toByteArray.size // evaluates to 12
RichSeq(Vector(1L, 2L, 3L)).toByteArray.size // evaluates to 24

You can play with this code here on Scastie.
If you can, you may probably want to consider the possibility of having a simple helper for this, so that you can avoid unnecessary allocations:
object SeqUtils {
  def toByteArray[A](seq: Seq[A])(implicit buf: Bufferable[A]): Array[Byte] = {
    val buffer = ByteBuffer.allocate(buf.size * seq.length)
    buffer.order(ByteOrder.LITTLE_ENDIAN)
    seq.foreach(buf.put(_, buffer))
    buffer.array()
  }
}

SeqUtils.toByteArray(Vector(1, 2, 3)).size
SeqUtils.toByteArray(Vector(1L, 2L, 3L)).size

The revised example is further available on Scastie.
If you want to know more about type classes there's plenty of material available online, I usually recommend this.

A: This should work though I'm not sure I'd do it this way:
  def toByteArray[A: Manifest](seq: Seq[A]): Array[Byte] = seq match {
    case i: Seq[Int] if manifest <:< manifest[Int] => {
      val buffer = ByteBuffer.allocate(4 * seq.length)
      buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN)
      seq.foreach{x => buffer.putInt(x.asInstanceOf[Int])}
      buffer.array()
    }
    case l: Seq[Long] if manifest <:< manifest[Long] => {
      val buffer = ByteBuffer.allocate(8 * seq.length)
      buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN)
      seq.foreach{x => buffer.putLong(x.asInstanceOf[Long])}
      buffer.array()
    }
    case _ => throw new java.lang.UnsupportedOperationException
  }

Of course this could be writter in a much cleaner way and certain common parts could be extracted. Also a reminder that A <:< B means A must be a subtype of B.
It looks like a trick but It can come handy (I learned this years go here https://stackoverflow.com/a/3213914/497398).


text:
Q: What is the best aproach to feed data to a custom UITableViewCell that has multiple labels - Swift I have a tableView with a custom viewCell which has three labels, displayCarName, displayMpg and displayCarPrice. I'm using three different arrays to feed each label in the tableView, everything is working fine but I feel like there is a better way to do this, may be using a single dictionary instead or something like that.
Here is the code I'm using.
    private var carNameList = [String]()
    private var mpgList = [Int]()
    private var carPriceList = [Double]()

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return carNameList.count
    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reusableCell", forIndexPath: indexPath) as! CustomCell

        cell.displayCarName!.text= carNameList[indexPath.row]
        cell.displayMpg!.text = String(mpgList[indexPath.row])
        cell.displayCarPrice!.text = String(carPriceList[indexPath.row])

        return cell
    }

Is this a common way to feed multiple labels in a table row? If not, can someone help me improve the code shown above?
FYI- I actually have more than three labels in each row but for simplicity I'm only showing three.
Thanks

A: What you are using is sometimes referred to as parallel arrays. This approach was commonplace in languages lacking support for structures.
Since Swift does have support for structures, a better approach would be to define a class representing a Car, with three properties for car's Name, Mpg, and Price, and then using a single list of [Car] in place of three separate lists:
class Car {
    let Name : String
    let Mpg : Int
    let Price : Double
    init(name: String, mpg : Int, price : Double ) {
        Name = name
        Mpg = mpg
        Price = price
    }
}
...
private var carList = [Car]()
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reusableCell", forIndexPath: indexPath) as! CustomCell
    Car car = carList[indexPath.row]
    cell.displayCarName!.text= car.Name
    cell.displayMpg!.text = String(car.Mpg)
    cell.displayCarPrice!.text = String(car.Price)
    return cell
}

A: Best way is to make a class for your data source
class SingleCellData {
  var displayCarName : String!
  var displayMpg : Int!
  var displayCarPrice : Double!
}

In table View
var cellData : [SingleCellData] = []

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reusableCell", forIndexPath: indexPath) as! CustomCell
    let sData = cellData[indexPath.row]
    cell.displayCarName!.text= sData.displayCarName
    cell.displayMpg!.text = String(sData.displayMpg)
    cell.displayCarPrice!.text = String(StringsData.displayCarPrice)

    return cell
}

A: You can also move the text assignment logic to the CustomCell class itself:
// Car.swift

class Car {
    var name : String
    var mpg : Int
    var price : Double
}

// ViewController.swift

...
private var cars = [Car]()
...

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reusableCell", forIndexPath: indexPath) as! CustomCell
    cell.car = cars[indexPath.row]
    return cell
}

// CustomCell.swift
class CustomCell: UITableViewCell {
   ...
   var car: Car? {
      didSet {
         displayCarName.text = car?.name
         displayMpg.text = car?.mpg
         displayPrice.text = car?.price
      }
   }
}


text:
Q: Hiding soft keyboard not working with onFocusChangeListener on Android I want the soft keyboard to disappear when the user touches anything other than the EditText on the screen. I've gone through SO posts on this question before and implemented the use of onFocusChangeListener and it did the trick on other projects I have worked on but it doesn't seem to be working now and I can't figure out what is wrong. Any help is appreciated.
My activity.java (inputGuardian1 is an example of the EditText):
inputGuardian1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (!hasFocus) {
                InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.hideSoftInputFromWindow(inputGuardian1.getWindowToken(), 0);
            }
        }
    });

Layout xml file:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                             xmlns:app="http://schemas.android.com/apk/res-auto"
                                             android:layout_width="match_parent"
                                             android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp" >
        <!--android:layout_marginTop="?attr/actionBarSize"-->

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_guardian1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/inputGuardian1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:imeOptions="actionDone"
                android:hint="Guardian 1" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_Guardian2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/inputGuardian2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:imeOptions="actionDone"
                android:hint="Guardian 2" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_Guardian3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/inputGuardian3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:imeOptions="actionDone"
            android:hint="Guardian 3" />
    </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_Guardian4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/inputGuardian4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:imeOptions="actionDone"
                android:hint="Guardian 4" />
        </android.support.design.widget.TextInputLayout>
        </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingTop="40sp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_ChildName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/inputChildName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:hint="Child's Name"
                android:layout_marginTop="30sp"
                android:imeOptions="actionDone"
                />

        </android.support.design.widget.TextInputLayout>

    </LinearLayout>

        <Button android:id="@+id/buttonNext"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Next"
                android:background="@color/colorPrimary"
                android:layout_marginTop="40dp"
                android:textColor="@android:color/white" />

    </LinearLayout>
</ScrollView>

A: Setting android:clickable="true" and android:focusableInTouchMode="true" to all the containers solved the problem.


text:
Q: Breakpoints not working in .tsx files I trying to work with .tsx files inside ASP.NET VNext project. Created .tsx file, that executed without errors, but I can not set a breakpoint inside any method using Chrome. Mappings are exists, but the breakpoint is not working properly. Breakpoint
works, but stops outside of method in which i sets breakpoint.
My test .tsx file:
    ///
interface IAppProps {
    text : String
}

interface IAppState {

}

class IndexPage extends React.Component<IAppProps, IAppState> {

constructor(props: any) {
    super(props);
}

getInitialState() {
    var a = 0;
}

render() {
    return (

test

    );
}

}
For example, i sets up breakpoint on line "var a = 0;", but Chrome just ignores him and stopping on line:  getInitialState(). And does not let me into the method body.

A:
but Chrome just ignores him and stopping on line: getInitialState(). And does not let me into the method body.

The ideal solution is to disable sourcemaps and just debug JavaScript. SourceMap support can be spotty. Thats just the (unspoken/ugly) truth of JavaScript developement.


text:
Q: Organizing multiples p-values in R (kruskal.test) Using the code below I've created a data.frame() with 5 variables. In this way I can obtain the value of p using kruskal.test().
> sample1 <- c(3, 3, 3, 2, 3)
> sample2 <- c(7, 7, 10, 6, 10)
> sample3 <- c(10, 13, 12, 14, 13)
> sample4 <- c(15, 20, 18, 20, 17)
> sample5 <- c(4, 5, 3, 3, 4)
> table <- data.frame(sample1, sample2, sample3, sample4, sample5)
>
> kruskal.test(sample1,sample2)$p.value
[1] 0.1353353
> kruskal.test(sample1,sample3)$p.value
[1] 0.2614641
> kruskal.test(sample1,sample4)$p.value
[1] 0.6822703
> kruskal.test(sample1,sample5)$p.value
[1] 0.4723666

However, I'd like to organize the results in a data.frame() with all the possibilities of p-value that is similar to the image below, using 'table' variable.

Is there a package, a commando or an alternative that could make this happen? I've seen something similar using the cor() function, but I couldn't find anything that could be applied on my case until now.

A: You could use outer() to help here. It takes all combinations of values that you pass in. For exampl
pvals <- outer(table, table, function(x,y) {
  mapply(function(x,y) kruskal.test(x,y)$p.value, x,y)
})

diag(pvals) <- NA
pvals

which returns
          sample1   sample2   sample3   sample4   sample5
sample1        NA 0.1353353 0.2614641 0.6822703 0.4723666
sample2 0.1360371        NA 0.3748093 0.3207621 0.8232919
sample3 0.1467931 0.3311237        NA 0.3173651 0.6738573
sample4 0.2765005 0.5459307 0.4429172        NA 0.1905397
sample5 0.2635525 0.2710219 0.3207621 0.7344166        NA


text:
Q: On combinatorial and cellular model categories and infinity categories I am looking for a counterexample. Let me first give the set-up. When you work with model categories, it is extremely common to assume they are cofibrantly generated. For me, this means the definition in Hovey's or Hirschhorn's book, i.e. there are sets of maps I and J who detect the trivial fibrations and fibrations by lifting and whose domains are small relative to I-cell (resp. J-cell). There is a weaker notion used by Emily Riehl, which I will ask about at the very end.
When you want to do Bousfield localization it's common to assume $M$ is in addition either combinatorial or cellular. Combinatorial means cofibrantly generated and locally presentable as a category. Cellular is more mysterious. Morally, it's asking for good control over cell complexes (i.e. things built from the maps in I via gluing). Formally, it's asking for

*

*Domains of maps in J are small relative to cofibrations

*Cofibrations are effective monomorphisms, i.e. any cofibration $f:X\to Y$ is the equalizer of the two obvious maps $Y\to Y \coprod_X Y$

*Domains and codomains of I are compact (in the sense of Hirschhorn, not Hovey) relative to I-cell.

Condition 1 is standard and usually easy to verify (for example, it comes for free if $M$ is locally presentable). Condition 2 is basically asking that the intersection of the two copies of $Y$ in $Y\coprod_X Y$ is equal to $X$, so it's also not that hard to check in categories where cofibrations are inclusions of some kind. Condition 3 is a pain to check, because it's really asking for a cardinal $\kappa$ such that for any presentation of a map $f:A\to B$ as a transfinite composition of pushouts along a chosen set of cells then any map from a (co)domain $X$ of a map in $I$ to $B$ factors through some subcomplex of size $\leq \kappa$. Again, if $M$ is locally presentable then this should be true automatically, at least if the collection of subcomplexes is filtered (since you know that all objects are small relative to filtered colimits).
It's clear that not every cellular model category is combinatorial. For example, Top is not (Hovey proves on page 49 of his book that the two-point Sierpinski space is not small). It's clear that not every combinatorial model category is cellular, because condition 2 can fail. For example, Hirschhorn provides such an example as 12.1.7. Another example is in Finnur Larusson's paper "The Homotopy Theory of Equivalence Relations." Another is the category of small categories Cat, as I learned today from a preprint of Amrani Ilias called "Stabilization of the category of simplicial objects in Cat." Similarly, if you take spectra valued in Cat it's not cellular (but it is combinatorial) as Deb Vicinsky has shown in her thesis. There are also examples of model categories which are not cofibrantly generated. My favorite is the Strom model structure on Top, and the proof is in Raptis's paper on Homotopy Theory for Posets. It seems to me that all the other conditions of cellularity are true here (suitably interpreted) except for cofibrantly generated, but perhaps I am wrong. Lastly, there is a model structure on a locally presentable category which is provably not cofibrantly generated, and it's given by Boris Chorny's example from the paper "The Model Category of Maps of Spaces is not Cofibrantly Generated." The category in question is simply the arrow category valued in sSet. When I tell these examples to people in the infinity category community I always get the same question, so now I'm putting it out to the MathOverflow world:

(1) Is there an example of a complete and cocomplete infinity category which does not admit any cofibrantly generated model?

This is probably a hard question. Chorny's example doesn't work, because every presentable infinity category gives rise to a combinatorial model category (which in this case will have the same weak equivalences but different cofibrations), obtained by embedding into simplicial presheaves then taking a Bousfield localization. A related question is

(2) Is there an example of a complete and cocomplete infinity category which does not admit a cellular model, but does admit a cofibrantly generated one?

This seems much more likely to be true to me, since from a model category perspective there really is a difference between cellularity and combinatoriality. But since all statements required for cellularity are about cofibrations, perhaps there's a sneaky way to always choose a nice set of cofibrations when you pass from a presentable infinity category to a model category. Perhaps you could shrink the cofibrations via Bousfield colocalizations, for example.

(3) Are there examples which have arisen in practice of non presentable infinity categories?

Lastly, I want to better understand where Riehl's definition of cofibrantly generated fits into this story. In a combinatorial model category the smallness hypotheses are automatic, so it seems Riehl's definition matches the usual one. Similarly, I suppose (1) and (3) in the definition of cellularity force Riehl's definition and the usual one to agree, though perhaps there is a way to weaken cellularity to algebraic cellularity in the sense of Riehl's algebraic wfs. Riehl also has notions of enriched weak factorization systems which allow you to do things like saying the Strom model structure is cofibrantly generated in her enriched sense. I am less certain about Chorny's examples. Anyway, for now my main question regarding Riehl's definition is:

(4) Is there an infinity category which admits the required colimits to form a factorization system but which does not admit any model that has a factorization system in the sense of Riehl (either simply an algebraic wfs or an enriched wfs)?

A: If you believe Vopěnka's principle then any cofibrantly generated model category is Quillen equivalent to a combinatorial one and thus its underlying $\infty$-category is presentable. It follows that any non-presentable complete and cocomplete $\infty$-category would give a positive answer to (1). The pro-category of a small finitely complete $\infty$-category is not presentable but it is co-presentable (its opposite category is presentable). However, the pro category of a large cocomplete and finitely complete $\infty$-category is complete and cocomplete but neither presentable nor copresentable. In "Higher Topos Theory" Lurie considers the pro category of spaces (see Definition 7.1.6.1). It thus seems that this category gives a positive answer to (1) and (3). This example was also considered in the world of model categories: It is Isaksen's strict model structure on pro-simplicial sets. If you are interested in a cocombinatorial model category that arose naturally you have Morel's (resp. Quick's) model structure on simplicial pro-finite sets that models the $\infty$-category of p-pro-finite (resp. pro-finite) spaces.
Edit: It turns out that there is a mistake in Raptis's paper showing that under Vopenka's principle any cofibrantly generated model category is Quillen equivalent to a combinatorial one. Raptis and Rosicky posted a fixed proof, in which they had to assume that the domains of the generating (acyclic) cofibrations (in the cofibrantly generated model category) are small with respect to certain types of filtered colimits of cofibrations, more general than just chains of cofibrations. See also the remarks of Tim Campion below.

A: Maybe I should record these as answers:
(1) If you add "left proper" to the requirement then the answer is that there are lots of examples. A theorem of Dugger says that any left proper, cofibrantly generated model category admits a set W of cofibrant objects which detect weak equivalences (via the derived mapping space out of them). There are lots of examples of ordinary categories that don't admit a set of generators... take their nerve and get a counterexample. The category of schemes is a nice example. I imagine someone who knows more about these things can get rid of the left-proper  assumption.
In general since ordinary category theory embeds into $\infty$-category theory you could probably cook up lots of silly counterexamples using stuff we know about ordinary categories. I mean, if the underlying $\infty$-category of some model category has only discrete mapping spaces, it probably wasn't a very interesting model category... Maybe that even implies the weak equivalences had to be isomorphisms? I don't know.
(2) follows from (1)
(3) Pro-categories are an example, or opposite categories of interesting presentable $\infty$-categories.
I don't know anything about (4).


text:
Q: How do I make a Java class immutable in Clojure? I'd like to wrap java's PriorityQueue class in clojure for use in another part of my program.  What I'm trying to figure out is if there is any way to do this in a lispy manner and make the priority queue immutable.  Are there any good ways to do this, or am I just going to be better off using the PriorityQueue as a mutable data structure?

A: I don't think there is a simple way to wrap a mutable data structure as an immutable one. Immutable data structures become efficient when the new version can share data with the old version in clever ways, and I can't really see how this can be done without access to the internals of PriorityQueue.
If you really want a persistent priority queue this thread might be interesting. Those seems to have linear-time inserts though, so if that is an issue maybe you have to look for another implementation.
Edit: On second thought, a simple implementation of a persistent priority queue is just to store the (prio, value)-pairs in a sorted set. Something like this:
(defn make-pqueue []
  (sorted-set))

(defn pqueue-add [pq x prio]
  (conj pq [prio x]))

(defn pqueue-peek [pq]
  (first pq))

(defn pqueue-pop [pq]
  (let [top (first pq)]
    (disj pq top)))

Of course, the code above is pretty limited (no multiple entries, for instance) but it illustrates the idea.

A: You can't automagically make mutable class immutable. One can always call java class directly and mutate it.
To force immutability you can either implement it in clojure, or extend java class and throw exceptions in all mutable method implementations.


text:
Q: Convolution of Two Random Variables I have been working a few hours on this particular problem. Please excuse my lack of formatting.
This is the question: Let $X$ and $Y$ be random variables with density function $f(x) = 2x$ on $[0, 1]$ and $0$ otherwise.
(a)  Calculate the density function $X^2$.
(b) Using the convolution product, calculate the density of $X^2 + X$.

A: We have that
$$
F_X(x)=2\int_0^xs\mathrm ds=x^2.
$$
Hence,
$F_{X^2}(x)=\Pr\{X^2\le x\}=F_{X}(\sqrt x)=x$ and the density function $f_{X^2}(x)=1$.
I'm not sure how to use the convolution product to calculate the density of $X^2+X$, but I suggest the following approach. Let us observe that $y=x^2+x$ is a monotone function when $0\le x\le 1$ and $x=1/2(\sqrt{4y+1}-1)$. Then we obtain the cumulative distribution function
\begin{align*}
F_{X^2+X}(x)
&=\Pr\{X^2+X\le x\}\\
&=\Pr\{X\le1/2(\sqrt{4x+1}-1)\}\\
&=1/4(\sqrt{4x+1}-1)^2\\
&=1/2(2x+1-\sqrt{4x+1})
\end{align*}
and the density function
$$
f_{X^2+X}(x)=1-\frac1{\sqrt{4x+1}}.
$$


text:
Q: While loop with strings in python not behaving as expected I'm new to Python and I'm learning about loops and conditions. I have the code:
import random
import sys
import os

test_file = open("test.txt", "wb") #use wb if write

append = ""
while append != "exit":
    print("Write something to append to file: ")
    append = sys.stdin.readline()
    test_file.write(bytes(append, 'UTF-8'))

test_file.close()

Now, whenever I type in 'exit', I would expect it to exit out of the loop, but for some reason, it doesn't. It continues to be what seems like an infinite loop. What could be the reason behind it? Thanks in advance.

A: readline() includes the \n newline character.
You could use append.strip().
In [1]: import sys

In [2]: append = sys.stdin.readline()
test

In [3]: append
Out[3]: 'test\n'

In [4]: append.strip()
Out[4]: 'test'

or you could write that like this
with open("test.txt", "w") as test_file:
    while True:
        print("Write something to append to file: ")
        append = input()
        if len(append) == 0 or input.strip() == "exit":
            break
        test_file.write(append)

A: Change condition to "exit\n" and execute. It worked for me.

A: try printing append to see exactly what it is, or using append = str(sys.stdin.readline())


text:
Q: Парсер с помощью CURL и phpQuery, активировать кнопку На странице во время парсинга, необходимо нажать кнопку "Показать больше". При нажатии на эту кнопку, появляются скрытые елементы div, сама же кнопка пропадает со страници (остается только div, в котором она находиться). Пробовал вот таким методом:
$but = $activate_but->find('button')->trigger('click');
$but = $activate_but->find('button')->trigger('submit');
$but = $activate_but->find('button')->submit();

Возможно есть какой то другой способ, благодарю!

A: вот нужный вам объект выделен:

Получайте содержимое всей страницы с помощью curl. далее получаете содержимое <script id="reactInitData"> и обрабатывайте как json.


text:
Q: Can no longer connect to private Minecraft server I set up a Minecraft server 1.7.10 on my personal server hosted on the Rackspace Cloud. The server is whitelisted, as it is intended only for my kids and me to play on. The server had been running fine for a couple of months. Then, we went away for the weekend, and when we came back, we could not log on. The server would send this message: "java.net.ConnectException connection refused".
So, I logged on to the host machine, killed the process, and re-started the Minecraft server. Still, no dice. I checked the whitelist - that looked good. I tried turning off whitelisting - still nothing.
Obviously, the client can reach the server - because of the Java message - so I don't think it is a port or firewall issue. I just can't figure out what the problem is, and why it would just start happening on its own. The only thing I can think of is that somehow the world got corrupted during a save at some point, and now something somewhere is garbled.
Anyone have any ideas?

A: This happened to me with a different host, oddly enough you need to sign in to your host's website and chances are they need you to agree to the updated EULA system, THis was from 1.7.10 onwards and applies to all servers.
Now seeing that you are just using a server host and not specifically a gaming host you need to ftp to get to the server files and from there simply find the EULA.txt and Change eula=false to eula=true then Save/Upload the changed file and restart your server.
This definately works for 1.7.10 servers and if you haven't already done it this will be your issue.
once accepted you will be able to access it fine.