text:
Q: error in compilation book documentclass It is not the first time I work with the book documentclass. Apparently, I did not do anything different but this time I get a strange error message:
I have, of course, a master document and a series of chapters on different files. If I compile the document from the master everything goes well I I obtain a nice .pdf with all the chapter. However, if I compile from one of the chapters I often (but not always) obtain a series of errors. Not a big deal, because I can go back on the main document, compile, and everything is fixed, but it should not behave in this way and it never did in my previous books.
This is my main document:

    \documentclass[a5paper,12pt]{book}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}
\usepackage{graphicx}
\usepackage{textcomp}
\usepackage{indentfirst}

\begin{document}

\author{Me}
\title{My life}
\date{January 2021}

\frontmatter
\maketitle
\tableofcontents

\mainmatter
\include{./TeX_files/capitolo01}
\include{./TeX_files/capitolo2}

%la "casa"
%a scuola (Aldo Moro, Campanile boia)
%i libri

\backmatter
% bibliography, glossary and index would go here.

\end{document}

The chapter format is simply:
\chapter{Capitolo primo}
text

and the error messages:
Undefined control sequence. \chapter
Missing \begin{document}. \chapter{C
Corrupted NFSS tables. ...qualcuno: scrivo a un ipotetico "voi" ma è
Missing \begin{document}. P
Missing \begin{document}. S
Missing \begin{document}. I
Missing \begin{document}. P
Emergency stop.
Font shape `/cmr/m/n' undefined(Font) using `/cmr/m/n' instead
Font shape `/cmr/m/n' undefined(Font) using `OT1/cmr/m/n' instead
Overfull \hbox (20.0pt too wide) in paragraph
Overfull \hbox (9.44446pt too wide) in paragraph
Overfull \hbox (6.80557pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (5.55557pt too wide) in paragraph
Overfull \hbox (4.44444pt too wide) in paragraph
Overfull \hbox (4.44444pt too wide) in paragraph
Overfull \hbox (4.44444pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (5.55557pt too wide) in paragraph
Overfull \hbox (5.55557pt too wide) in paragraph
Overfull \hbox (5.55557pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (20.0pt too wide) in paragraph
Overfull \hbox (4.44444pt too wide) in paragraph
Overfull \hbox (4.44444pt too wide) in paragraph
Overfull \hbox (4.44444pt too wide) in paragraph
Overfull \hbox (20.0pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (2.77779pt too wide) in paragraph
Overfull \hbox (2.77779pt too wide) in paragraph
Overfull \hbox (20.0pt too wide) in paragraph
Overfull \hbox (5.00002pt too wide) in paragraph
Overfull \hbox (2.77779pt too wide) in paragraph
Overfull \hbox (5.55557pt too wide) in paragraph
Overfull \hbox (5.55557pt too wide) in paragraph

Looks like it does not understand that the chapter is linked to the main document.

A:
If I compile one of the chapters...

You can't compile the chapters separately, as they don't have the document class and the rest of the preamble that make them valid latex documents.  The preamble defines the commands like \chapter and this is why you get the undefined command sequence error.
So you can't run  pdflatex capitolo01.tex and get a nicely formatted version of just one chapter.  If your editor offers to process the current file with latex it needs to process the whole book and not just one chapter at a time.
If you want to preview just one chapter you can create a short stub master file that has the documentclass and the rest of the preamble, but only imports a single chapter. Or you can use the \includeonly command to select particular chapters from the master document.  But as computers can process a complete book in a blink of an eye, there is limited benefit to this.

A: Mystery solved!
I had copied the directory to a different location, and opened one chapter from the old directory. That is the reason that prevented the correct compilation of that specific chapter.


text:
Q: Function to check if object exists, or file exists, and if not create object I am trying to write a function that:

*

*will determine whether an object My_data_table exists in the global environment , and if it does will print a statement saying so, skipping all subsequent steps

*if it does not exist: will search to see whether a file at a specific path Myfile exists at a specific path location.

*

*if the file at Myfile exists, it will load that file as a dataframe of that name, and print a statement to say it has done so.

*if the file at Myfile doesn't exist it will create the empty dataframe as the object My_data_table, and print a statement to say it has done so.
I wrote a function, and it seems like it will read the conditions correctly, but doesn't load the file or create the dataframe object I want. Instead, it creates a value which is equal to the print statement of the relevant condition.
Does anyone know where it am going wrong?
This is what I have so far:
load_data_file_ephys <- function(f) {if (exists("My_data_table") == TRUE){
  print("The object has already been defined in R, data table not created.")
}else {if(file.exists(f)){
  My_data_table <- read_csv(here(f), col_names = TRUE, show_col_types =FALSE)
  print("The current file has been loaded as the data table.")
}  else {
  My_data_table <- data.frame(ID = numeric(0),
                                    Tot_Events = numeric(0),
                                    Freq_Events = numeric(0),
                                    Mean_Amp = numeric(0),
                                    Mean_Interval = numeric(0),
                                    Data_type = numeric(0))
  print("The empty data table has been created.")
}}}

to run
animal_number = "03"
library(here)
Myfile <- paste0("results/results_",animal_number,".csv")
My_data_table <- load_data_file_ephys(Myfile)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error during read JSON file in Swift 3 I use this code in all my projects in swift 2.2 but when I created new project after updated xcode to xcode 8 I faced this problem in reading JSON file with this code
 do {

        let comURL = "mylinkhere"+"customer_key=\(self.customer_key)"

        // NSLog("PostData: %@",post)

        let regURL:NSURL = NSURL(string: comURL)!

        //let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

        //let postLength:NSString = String( postData.length )

        let request:NSMutableURLRequest = NSMutableURLRequest(url: regURL as URL)
        request.httpMethod = "POST"
        //request.HTTPBody = postData
        //request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        var reponseError: NSError?
        var response: URLResponse?

        var urlData: NSData?

        do {
            urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData?
            // print(urlData)
        } catch let error as NSError {
            reponseError = error
            urlData = nil
        }

        if ( urlData != nil ) {

            let res = response as! HTTPURLResponse!;

            //NSLog("Response code: %ld", res?.statusCode);

            if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300)
            {
                let responseData:NSString  = NSString(data:urlData! as Data, encoding:String.Encoding.utf8.rawValue)!

                NSLog("Response Data ==> %@", responseData );

                //var error: NSError?

                let jsonData = try JSONSerialization.jsonObject(with: urlData! as Data,  options: .allowFragments) as! [String:AnyObject]

                self.Appstatus = (jsonData as AnyObject).value("android_app_status") as! NSString

               self.StreamURL = (jsonData as AnyObject).value("android_streaming_url") as! NSString

                //[jsonData[@"success"] integerValue];

               // NSLog("App Status2: %@", self.Appstatus);
               // NSLog("App Stream URL2: %@", self.StreamURL);

                if(self.Appstatus == "true")

                {

                }

                else{

                }

            }

        } else {
            let alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign in Failed!"
            alertView.message = "Connection Failure"
            if let error = reponseError {
                alertView.message = (error.localizedDescription)
            }
            alertView.delegate = self
            alertView.addButton(withTitle: "OK")
            alertView.show()
        }

    } catch {
        let alertView:UIAlertView = UIAlertView()
        alertView.title = "Sign Up Failed!"
        alertView.message = "Server Error!"
        alertView.delegate = self
        alertView.addButton(withTitle: "OK")
        alertView.show()
    }

I got the response correctly but the error in these two line when trying to retrieve data from result
 self.Appstatus = (jsonData as AnyObject).value("android_app_status") as! NSString

 self.StreamURL = (jsonData as AnyObject).value("android_streaming_url") as! NSString

The error is:

A: In Swift 3 most of the AnyObject types has been changed to Any
Basically in Swift

*

*do not use valueForKey to get a value for a dictionary key, use key subscription.

*do not cast types up (as AnyObject) after casting them down (pretty counterproductive).

*do not use Foundation NSString. Use Swift String.
let jsonData = try JSONSerialization.jsonObject(with: urlData! as Data,  options: .allowFragments) as! [String:Any]
self.Appstatus = jsonData["android_app_status"] as! String
self.StreamURL = jsonData["android_streaming_url"] as! String

If the keys are not guaranteed to exist use optional bindings to avoid a runtime error.
And finally do not use deprecated synchronous URL loading API.

A: You don't have to typecast your jsonData to AnyObject, which as i can see from your code is a dictionary with type [String:AnyObject]. If you want to unwrap a string from jsonData i suggest you consider the following code.
if let appStatus = jsonData["android_app_status"] as? NSString{
   self.AppStatus = appStatus
}

with this safe unwrapping you can make sure that your program will not crash even if the dictionary dosen't have "android_app_status" key.
Hope this helps.


text:
Q: Inversion of $2 \times 2$ block matrix $$X=\left(\matrix{A & B\\C & D}\right)$$
where $A,B,C,D$ are all $n \times n$ matrices. Assuming that all stated inverses exist, show that
$$X^{-1}=\begin{pmatrix}(A-BD^{-1}C)^{-1}&(C-DB^{-1}A)^{-1}\\(B-AC^{-1}D)^{-1}&(D-CA^{-1}B)^{-1}\end{pmatrix}$$

It has something to do with Schur complements. But all I can think of is to prove that each element of $X^{-1}$ is the same as the standard block inverse formula but when I do that I keep running back around in circles as this formula contains one of the stated inverses.
Any help would be great, thanks ahead of time!

A: The top left block can be obtained as a Schur complement. The other blocks can be obtained by considering $J(XJ)^{-1}$ (bottom left), $(JX)^{-1}J$ (top right) and $J(JXJ)^{-1}J$ (bottom right), where $J=\pmatrix{0&I\\ I&0}$. For instance, using the result that the top left block of $X^{-1}$ is $(A-BD^{-1}C)^{-1}$, we have
$$X^{-1}=J(XJ)^{-1}=J\pmatrix{B&A\\ D&C}^{-1}=J\pmatrix{(B-AC^{-1}D)^{-1}&\ast \\ \ast&\ast}=\pmatrix{\ast&\ast \\ (B-AC^{-1}D)^{-1}&\ast}.$$


text:
Q: localhost:8000 is not working in loading laravel project I'm working on laravel project. First I encountered a fatal error of maximum number of bytes. I fixed that, after fixing and restarting my Apache when I started to run php artisan it worked correctly but now I'm not able to access my project in browser (after running) php artisan.
The browser just says page not found and the buffering of that page is like infinite. what's happening don't know !!! :(

A: Try to change port using --port param,
php artisan serve --port=8000

A: Try this command and use 8080 port number:
php artisan serve --host=127.0.0.1 --port=8080

A: I changed the port and refreshed the server. It worked.
Initially:
app.listen(3000);

Later:
app.listen(3001);

A: Why not try running Laravel on a virtual host?


text:
Q: foreach not looping all data my first query that gets all rows that contain both the user who requested friendship ( authenticated user id ) and inbound friendship ( inbound user id ). This works if I echo $rowsget, it echos the correct rows, the problem I'm having is that it will only loop through up to two usernames, once I take away the ability for it to loop through the profiles own username it will only loop through one row then stop, I have tried what some people have said to do but it now says this error message when I try to load the profile page, "Object of class Illuminate\Support\Collection could not be converted to int" Here is the code, any help is appreciated, I have been stuck on this for hours now.
Query
$rowsget = DB::table('friends')->where(function(Builder $query) use($uid) {
    $query->where('requesteeid', $uid)
        ->orWhere('inboundid', $uid);
})
->where('approved', true)
->get();

$rowfetchfriend = [];
if(count($rowsget) > 0){
    foreach($rowsget as $get) {
        $getrequestee = $get->requesteeid;
        $getinbound = $get->inboundid;
        $rowfetchfriend += DB::table('users')->where('id', $getrequestee)-
>orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);
}

Loop through usernames
foreach($rowfetchfriend as $loop) {
        if($loop->id != $uid) { //make sure own user isnt displayed
            echo $loop->username; // echo all usernames that are
        }
    }
}

A: Use this method (or the push() method) when adding to an array:
Instead of this:
$rowfetchfriend += DB::table('users')->where('id', $getrequestee)->orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);

Try this:
$rowfetchfriend[] = DB::table('users')->where('id', $getrequestee)->get(['id', 'avatar', 'username']);
$rowfetchfriend[] = DB::table('users')->where('id', $getinbound)->get(['id', 'avatar', 'username']);

The class and its methods are listed here:
https://laravel.com/api/5.5/Illuminate/Support/Collection.html#method_count

A: You can use "push" method of laravel collection.
try this :
$rowfetchfriend = [];
    if(count($rowsget) > 0) {
        foreach($rowsget as $get) {
            $getrequestee = $get->requesteeid;
            $getinbound = $get->inboundid;
            $temp = DB::table('users')->where('id', $getrequestee)->orWhere('id', $getinbound)->get(['id', 'avatar', 'username']);
            array_push($rowfetchfriend, $temp->toArray());
        }
    }

and Loop through usernames :
for ($i=0; $i < count($rowfetchfriend); $i++) {
        if($rowfetchfriend[$i][0]->id != $uid) { //make sure own user isnt displayed
            echo $rowfetchfriend[$i][0]->username; // echo all usernames that are
        }
    }

I tested it and work correctly.


text:
Q: Python plotly | disable ALL rangesliders in a figure that has subplots Using plotly(dash) I add multiple subplots to a figure using figure.add_candlestick(**args)
After the loop is done I disable the xaxis_rangeslider_visible but I still have a rangeslider at the bottom of the second/last chart. Does anyone know how to hide ALL rangeslider in a figure with multiple plots?
PositionFig = PositionFig.update_layout(xaxis_rangeslider_visible=False,
                          title_text="Position Charts",
                          height=1000)

A: UPDATE: you can avoid the loop with fig.update_xaxes(rangeslider_visible=False) or in your case:
PositionFig.update_xaxes(rangeslider_visible=False)

Or you can loop back through and set it off for each axis:
for i in range(number_of_subplots,0,-1): # starting with the last and stopping at 0
    PositionFig.update_xaxes(row=i, col=1, rangeslider_visible=False)

where number_of_subplots is how many subplots you have, and assuming that they are in a single column.


text:
Q: How to specify BatchSize for JPAQueryFactory to avoid round trips I am using JPAQuery to query the database and facing latency while retrieving it, I have also provided BatchSize but looks like it's not getting honored. The query is taking around 2seconds to query and retrieve, however, the actual execution time is on 19 milliseconds. Please advise.
JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);
JPAQuery query = queryFactory.select(queryBase.getColumns()).distinct().from(entityPath);

joinConditionsList.forEach(addDynamicJoins(query));
query
    .where(queryBase.getFilters())
    .orderBy(queryBase.getOrderBy())
    .offset(queryBase.getOffset())
    .limit(50000);
long startTime = System.currentTimeMillis();

List<Tuple> list = query.fetch();

I have provided the following in the application.yml.
jpa:
  show-sql: true
  hibernate:
    ddl-auto: none
    batch_size: 234
  naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
  properties:
    hibernate:
      jdbc:
        lob:
          non_contextual_creation: true
        batch_size: 235
      temp:
        use_jdbc_metadata_defaults: false
  database-platform: org.hibernate.dialect.PostgreSQL9Dialect


text:
Q: Confused of the Poisson kernel for upper half-plane It comes from the steady-heat equation in the upper half-plane $\Bbb R_+^2$ .The solution of this question is to use Fourier transofrm so that you can transform this equation to a new one and the last term $e^{-2\pi |\xi| y}$ is the Fourier transform of the Poisson kernel for $\Bbb R_+^2$
However,I don't understand why this kernel corresponds to $\Bbb R_+^2$ .In other words,if we exchange $\Bbb R_+^2$ to other planes,can we apply this method similarly?(I understand the accessibility of this method of Fourier transform requires "rapidly decreasing"but it doesn't explain why it is feasible for $\Bbb R_+^2$ )
It occurs to me when I first meet the steady-state heat equation for a disc,the Poisson kernel for a disc which we use polar coordinates to represent it corresponds to this situation so naturally because the plane is a disc.But this time,I don't get any links between Poisson kernel for $\Bbb R_+^2$ and the upper half plane?
What am I missing?

A: The Poisson problem for the upper half-plane $\mathbb{R}_{+}$ is
$$
                         \nabla^2 f(x,y)=0\\ -\infty < x < \infty,\; 0 < y < \infty,
                            \\ f(x,0) = g(x).
$$
You could assume $g\in L^{\infty}$, and solve for a bounded solution $f$. Or you could assume $g\in L^p$ for some $1 \le p < \infty$ and require that $\sup_{y > 0} \int_{-\infty}^{\infty}|f(x,y)|^p dx < \infty$. The fundamental solution is
$$
           (Pg)(x,y)=   \frac{1}{\pi}\int_{-\infty}^{\infty}\frac{y g(x')}{(x-x')^2+y^2}dx'.
$$


text:
Q: Instagram API start returning loading page after some calls I am using the code below to get account information of one thousand instagram accounts using asycnio. In the initial requests the output is correct but after 10-20 calls, instagram starts returning loading page's HTML code. What could I be doing wrong here ? Below is the python code.
import random
import asyncio
from aiohttp import ClientSession
import urllib.request
import  aiohttp
async def fetch(url, session,sem):
    print("------")
    print(url)
    async with session.get(url = url) as response:
        print(await response.text())
        await  response.text()
        # exit()
        if response.status == 200:
            await sem.acquire()
            fname = url[22:]
            fname = fname.split('/')
            fname = fname[0] + '.txt'
            f = open(fname , 'w')
            f.write(str(await response.text()))
            sem.release()

        # return (await response.text())

async def run(url_list):
    tasks = []

    # create instance of Semaphore
    sem = asyncio.Semaphore(2)
    # Create client session that will ensure we dont open new connection
    # per each request.
    async with ClientSession() as session:
        for url in url_list:
            task = asyncio.ensure_future(fetch(url, session,sem))
            tasks.append(task)
        responses = asyncio.gather(*tasks)
        await responses

# making the url list here
url_list = []
file = open('url.txt', 'r')
for url in file:
    url_list.append(url)

print(url_list)
import time
old = time.time()
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(url_list))
loop.run_until_complete(future)

print(time.time() - old)

Here are some of the URL's from url.txt file

https://instagram.com/johanna_kre/?__a=1
https://instagram.com/channie_f/?__a=1
https://instagram.com/lilakuh68/?__a=1
https://instagram.com/nataliacallisto/?__a=1
https://instagram.com/edbastian/?__a=1
https://instagram.com/sylvana.h/?__a=1
https://instagram.com/munich_bombon/?__a=1
https://instagram.com/younotus/?__a=1
https://instagram.com/meet.herbert/?__a=1
https://instagram.com/inaaogo/?__a=1
https://instagram.com/dennisaogo/?__a=1
https://instagram.com/mrslight__/?__a=1
https://instagram.com/reneturrek/?__a=1
https://instagram.com/_eeasyyy/?__a=1
https://instagram.com/sentinobln/?__a=1
https://instagram.com/eri.ka_g/?__a=1

A: Your semaphore is not limiting the requests as you want it to; you should acquire it before making the request, not before processing the content.
With your current implementation you are making 100 concurrent requests (aiohttp's client default limit) but only process the responses two at a time (however at this point from the server's perspective the requests are already processed).
Use:
async def fetch(url, session,sem):
    print("------")
    print(url)
    await sem.acquire()
    async with session.get(url = url) as response:
        print(await response.text())
        await  response.text()
        ...
    sem.release()
    ...


text:
Q: How to install AWS SAM CLI on Linux without Brew Update on Dec 2020
The AWS github issue is Provide linux installation without homebrew #1424. Please monitor the update in the github issue for the latest status.
AWS finally decided to provide non brew approach.

we have work currently underway to provide a better install experience via pyinstaller. In the near term we will continue publishing to brew to support people that are already using it, as well as pip but the core artifact will be produced using pyinstaller and hopefully allow for a better experience for Linux and macOS users, and it is my hope this will also en courage downstream packages to be published for Linux distributions eg yum and deb repos similar to how AWS cli is commonly available.

Question
Please suggest a way to install AWS SAM in Linux without using homebrew. AWS documentation tells to use homebrew, however there should be a way without using brew.

AWS documentation
Installing the AWS SAM CLI on Linux Step 5: Install the AWS SAM CLI

Follow these steps to install the AWS SAM CLI using Homebrew:

brew tap aws/tap
brew install aws-sam-cli

A: Build latest version from source
git clone https://github.com/awslabs/aws-sam-cli.git && cd aws-sam-cli
python setup.py install

A: As installing SAM CLI with homebrew is time consuming task, one can simply do following to install it :

*

*Install Python > 3 (I did Python 3.7)

*Then run command python3.7 -m pip install aws-sam-cli
P.s If you face any error due to virtual environment or any python error please run the last command with sudo : sudo python3.7 -m pip install aws-sam-cli

A: Adding to the answer of Alexis Facques, do,
Step-1
git clone https://github.com/awslabs/aws-sam-cli.git && cd aws-sam-cli

Step-2
(On Linux)
sudo python3 setup.py install

OR (On Windows)
sudo python setup.py install

Step-3
cd .. && sudo rm -rf aws-sam-cli

This will install the latest version of the aws-sam-cli directly from the source

A: Use pip

*

*awslabs/aws-sam-cli Provide linux installation without homebrew

I think the docs are bad written. running
pip install aws-sam-cli installs everything OK```


text:
Q: Remove header on one page I use moderncv to create my cv. There I include a pdf document with the includepdf command. The problem is that I defined a fancyheader and that this header is also on the included pdf, but I do not want this.
I called my pagestyle myfancy and I use it with the command:
\pagestyle{myfancy}

Then my pages follow where I want to have my documents with the header. Then I include the pdf via:
\includepdf{Test.pdf}

Then I have the header, but I don't want to have this header.
According to different posts I tried
\pagestyle{plain}
\fancyhf{}
\thispagestyle{empty}

But the all do not work, the header is still there. Where is my mistake?

A: You can use pagecommand like this:
\includepdf[pages=1-6,pagecommand={\thispagestyle{empty}}]{pgfmanual.pdf}

Change appropriate style (plain or empty).
MWE:
\documentclass{article}
\usepackage{kantlipsum}
\usepackage{pdfpages}
\usepackage{fancyhdr}
\fancyhf{}
\renewcommand{\headrulewidth}{1pt}    %% made thick for visibility
\pagestyle{fancy}
\chead{My header}
\lfoot{\emph{My footer}}
\rfoot{\thepage}

\begin{document}
\tableofcontents
\chapter{A chapter}
\section{Introduction}
\kant[1-4]
\includepdf[pages=1-6,pagecommand={\thispagestyle{empty}}]{pgfmanual.pdf}
\section{Another section}
\kant[5-8]
\end{document}

MWE with modercv:
\documentclass[11pt,a4paper,sans]{moderncv}
\usepackage{pdfpages}

\moderncvstyle{casual}                             % style options are 'casual' (default), 'classic', 'oldstyle' and 'banking'
\moderncvcolor{blue}                               % color options 'blue' (default), 'orange', 'green',

\usepackage[scale=0.75]{geometry}

\name{John}{Doe}
\title{Curriculum Vitae}                             % optional, remove / comment the line if not wanted
\address{street and number}{postcode city}{country}
\phone[mobile]{+1~(234)~567~890}
\phone[fixed]{+2~(345)~678~901}
\phone[fax]{+3~(456)~789~012}
\email{john@doe.org}                               % optional, remove / comment the line if not wanted
\homepage{www.johndoe.com}                         % optional, remove / comment the line if not wanted
\social[linkedin]{john.doe}                        % optional, remove / comment the line if not wanted
\social[twitter]{jdoe}                             % optional, remove / comment the line if not wanted
\social[github]{jdoe}                              % optional, remove / comment the line if not wanted
\extrainfo{additional information}                 % optional, remove / comment the line if not wanted
\photo[64pt][0.4pt]{picture}
\quote{Some quote}                                 % optional, remove / comment the line if not wanted

%----------------------------------------------------------------------------------
%            content
%----------------------------------------------------------------------------------
\begin{document}
%-----       resume       ---------------------------------------------------------
\makecvtitle

\section{Education}
\cventry{year--year}{Degree}{Institution}{City}{\textit{Grade}}{Description}  % arguments 3 to 6 can be left empty
\cventry{year--year}{Degree}{Institution}{City}{\textit{Grade}}{Description}

\section{Master thesis}
\cvitem{title}{\emph{Title}}
\cvitem{supervisors}{Supervisors}
\cvitem{description}{Short thesis abstract}

\includepdf[pages=1-6,pagecommand={\thispagestyle{empty}}]{pgfmanual.pdf}

\end{document}


text:
Q: Attendance Management System I am looking for an open source Attendence Management System, I'd like to be able to customise functions.
Please recommend some written in PHP.
I am running BPO with around 20 employees.
I want to track their daily check-in and check-out time.
Thanks
Bharanikumar

A: Have you tried TimeTrex Time and Attendance? Its open source and extremely configurable.

A: I have no idea what an attendance management system would have to be able to do exactly, but take a look at the PHP section on opensourcecms.com. They have a number of calendars, project management tools etc. to test drive, maybe one of them comes close to what you need - it's often just a matter of renaming labels or categories.

A: Attendance Management System is written in PHP and released as an open source project under GPL v3. This software is web based and easier to setup.

A: You could try this freeware that I found for you.
phpTime sheet
I noticed that the files have extention php3 but don't worry they are normal php files. Enjoy!

php Time sheet is an important and powerful program and helpful for / business persons and for individual users to handle their data, it might be personal or employee and also it is useful for web based accounting, managing holidays, project tracking and attendance of employees etc., MySQL database is used to store data.

A: This sounds like a fairly specific request for a timesheet system. There's lots around, mostly web based. But I have to ask ....
Is this a question for this forum?

A: With these requirements, this is easier solved with Excel/OpenOfficeCalc/GoogleSpreadsheets/etc


text:
Q: Add existing UIViewControllers screens to single screen which has UISegmentedControl in swift 2 My swift project has many screens with xib and related swift files. Now I am designing initial screen which has UISegmentedControl at the bottom. UISegmentedControl has 2 segments, that is home screen and my profile screen. I have both home screen and my profile screen designed. I want to add both these screens to Initial screen. I have tried following code to add screens to initial screen view but it throws error "fatal error: unexpectedly found nil while unwrapping an Optional value"
Code i have tried:
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("HomeViewController")
self.addChildViewController(controller)
controller.view.frame = CGRectMake(0, 0, SCREEN_SIZE.width, SCREEN_SIZE.height)
self.view.addSubview(controller.view)
controller.didMoveToParentViewController(self)

Solution:
On click home segement
 let homeViewController: HomeViewController = HomeViewController()
    homeViewController.loadView()
    homeViewController.viewDidLoad()
    homeViewController.view.frame = self.subView1.bounds;
    self.subView1.addSubview(homeViewController.view)
    self.addChildViewController(homeViewController)
    menuViewController.didMoveToParentViewController(self)

On click my profile segment:
let profileViewController: ProfileViewController = ProfileViewController()
   profileViewController.loadView()
   profileViewController.viewDidLoad()
   profileViewController.view.frame = self.subView2.bounds;
   self.subView2.addSubview(profileViewController.view)
   self.addChildViewController(profileViewController)
   profileViewController.didMoveToParentViewController(self)


text:
Q: Insert Date section DIV in between records HTML generated from JavaScript based on date of record I have an Activity Log of events from my Project Management application.
I would like to insert some HTML elements into the view of my Activity Log to show something similar to what Windows File Explorer shows when you sort files by Date...
See image below for a better understanding as it shows some files and folders in a Windows 7 file explorer.  In between them are the labels I am talking about

List of Date values I need to calculate and get using JavaScipt

*

*Today

*Yesterday

*Earlier this Week

*Last Week

*Earlier this Month

*Earlier this Year

*A While Ago

My app shown below...
So each activity row shown below is generated in JavaScript by calling a function which build the correct HTML based on the type of record it is from a JSON string.
I am thinking if I build some functions to compare dates I can process each row checking it's date for a match to one of my date sections mentioned above.
With that method if 3 records match for "yesterday" then it would make 3 DIV's with "Yesterday".
To prevent this, I am thinking maybe I can have a variable for each date section and once 1 record matches, set the variable to "true"
Once a date section is "true" it will start looking for the next date section to insert.
Does this sound like the way to do this or is there another way?
Keeping in mind that each row/record is added to the HTML when it runs through a JavaScript function?

A: You said: "I am thinking maybe I can have a variable for each date section and once 1 record matches, set the variable to 'true'".
Why not use an object?
`pseudo-code`
var labels = {}; // Today, Yesterday, Earlier this Week, etc

function createDivs(date, row) {
    labels[date] = labels[date] || [];
    labels[date].push(row);
}

You could loop through your data and the object will be self-aware if the key exists or not and the data is always appended to the correct label.

A: Try utilizing dl , dt , dd , time elements ; css

[id] {
  font-weight:bold;
  font-size:24px;
  color:blue;
}

dd {
  padding:4px;
  color:green;
}

time {
  color:red;
}

Yesterday

Changed stuff at a <time>12/13/2021</time>

Changed stuff at b <time>12/12/2021</time>


text:
Q: GWT on iPhone 4.0 with 3G network I have just encountered very strange problem - my GWT app hosted on Google App Engine does not want to work on iPhone over 3G, however it works fine over Wi-Fi.
For testing I created empty GWT module with only Window.alert in the onModuleLoad. If I switch on Wi-Fi, the alert is shown, with 3G - just blank page although with correct title.
Safari Developer console on iPhone looks absolutely the same for 3G and Wi-Fi - some 3 errors about wrong placement of meta tags.
Just recently I installed iPhone OS 4.0 (tried beta 1 and beta 2), and I can not roll it back to version 3, so can not really say where the problem is.
Does anyone have any ideas what may be happening here?
Sample page is hosted on http://iphntst.appspot.com

A: This was not a problem neither in iPhone OS 4 nor 3G. Looks like something wrong with Google AppSpot. Now it works well.


text:
Q: Trouble setting items in AlertDialog with OnClickListener Having trouble trying to set up a spinner withing an AlertDialog, keep getting the error
"The method setItems(int, DialogInterface.OnClickListener) in the type AlertDialog.Builder is not applicable for the arguments (String[], new View.OnClickListener(){})"
I'm fairly new to Android programming and I am still getting used to it,  any help would be greatly appreciated! Thanks
AlertDialog.Builder b = new Builder(this);
    b.setTitle("Select Day");
    String[] types = {"1", "2", "3"};
    b.setItems(types, new OnClickListener){
        public void onClick(DialogInterface dialog, int which){
            dialog.dismiss();
            switch(which){
            case 0:
                day = "1";
                break;
            case 1:
                day = "2";
                break;
            }
        }

    });

A: Change:
b.setItems(types, new OnClickListener){

To
b.setItems(types, new DialogInterface.OnClickListener){

And you will have to split
String[] types = {"1", "2", "3"};

to individual ints, or a CharSequence array.
You probably have an OnClickListener for another normal View in your code somewhere, and have it in your imports. As all OnClickListener classes share the same name, Eclipse auto resolves them all to the currently imported one. You can specify the parent class in such cases.
Additionally, the setItems() method that Eclipse has resolved takes a single int for the first parameter, not a String array. You could use the other setItems() method though, which takes a CharSequence Array. In such a case, change
String[] types = {"1", "2", "3"};

to
CharSequence[] types = {"1", "2", "3"};


text:
Q: Diferent ways to rearrange data from one array into another From API, I get array of attendances by date with members data.
My task is to convert that data to array of objects with clients data end attend_date.
I managed to accomplish that in following snippet.
My plea to You is for hint for other, perhaps more performant or more elegant way for solving my task.

const attendances = [
  { _id: '1',
    attend_date: '2020-12-31',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '2',
    attend_date: '2021-01-01',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '3',
    attend_date: '2021-01-04',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  }
]

const mapAttendances = () => {
  let obj,
    arr = [];
  for (let i = 0; i < attendances.length; i++) {
    for (let j = 0; j < attendances[i].members.length; j++) {
      obj = {
        date: attendances[i].attend_date,
        present: attendances[i].members[j].present,
        client: attendances[i].members[j].client,
      };
      arr.push(obj);
    }
  }
  return arr;
}
console.log(mapAttendances())

A: You can also do this with some nested maps and a little destructuring

const attendances = [
  { _id: '1',
    attend_date: '2020-12-31',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '2',
    attend_date: '2021-01-01',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '3',
    attend_date: '2021-01-04',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  }
]

const mapAttendances = () => {
  return attendances.flatMap(({attend_date:date, members}) => {
     return  members.map(({_id,...r}) => ({ date,...r }));
  });
}

console.log(mapAttendances())

A: You can do that

const attendances = [
  { _id: '1',
    attend_date: '2020-12-31',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '2',
    attend_date: '2021-01-01',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '3',
    attend_date: '2021-01-04',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  }
]

const result = attendances.reduce((r,{attend_date,members})=>
  {
  members.forEach(({client,present})=>
    r.push({date:attend_date,present,client}))
  return r
  },[])

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


text:
Q: git и конфигурационные файлы Расскажите, кто и как решает проблему хранения конфигурационных файлов в git?
Полностью исключать их нельзя, так как проект может не собраться и/или не запуститься. В тоже время в таких файлах, как правило, хранится частная информация (данные для авторизации на внешних сервисах и т.д.).
Сейчас я размещаю в git файлы с расширением .sample (например Web.config.sample или config.yml.sample) и пишу в документации, что перед тем как запустить проект, необходимо переименовать sample-файл и заполнить его правильными значениями. Сами конфигурационные файлы я добавляю в  .gitignore.
Недостатки такого подхода:

*

*необходимо постоянно синхронизировать sample-файл c оригинальным конфигурационным файлом (добавились/изменились/удалились опции),

*другим пользователям нужно сделать дополнительное действие (переименовать файл), что они могут забывать делать (кто же читает документацию?)

Возможно существуют и более удачные решения. Можно ли c git придумать что-то более удобное?

A: Я стараюсь делать следующим образом. Сначала программа пытается использовать конфигурацию, специализированную для текущего хоста, из файла config-hostname.xml. Вся чувствительная информация хранится в нём, и в git он не попадает благодаря игнорированию по маске config-*.xml. Если же специализированная конфигурация отсутствует, то используется дефолтная из файла config.xml, который сохраняется в репозитории. По истории изменений этого файла очень удобно отслеживать, когда появились те или иные фичи. Часто удобнее, чем искать по сhangelog'у.
В тех случаях, когда некоему параметру невозможно придумать осмысленное значение по умолчанию, но в то же время и убирать его совсем из дефолтной конфигурации не хочется (должно быть понятно, что он вообще есть), я прописываю ему какое-нибудь заведомо невалидное специальное значение (-1 или строку "must be customized"). Программа при работе с таким параметром понимает это значение, выдаёт соответствующую диагностику и выходит.

A: Я именно храню sample-версии конфиг-файлов. Чисто для того, чтобы почитать пример, как это может выглядеть. Настоящие конфиги собираются при помощи ansible.
Именно он и подставляет критичную информацию типа паролей.
Выгоды налицо: централизованное описание и хранение конфигураций, все файлы промаркированы.
В ряде случаев для упрощения жизни пользуюсь следующим трюком: пароли dev-конфигураций представляют собой md5 от паролей на production.
Как-то так:
[mysql]
host     = "{{ databases_mysql[0].dbhost }}"
dbname   = "{{ databases_mysql[0].dbname }}"
user     = "{{ db_users_mysql[0].name }}"
password = "{{ mask_pwd | ternary(db_users_mysql[0].password|hash("md5"),db_users_mysql[0].password) }}"

, где  mask_pwd - логическая переменная, маскировать или нет пароль (устанавливается в зависимости от вида окружения).

A: Я храню дефолтную конфигурацию в файле .env в корне проекта.
ENV_database_host=127.0.0.1

Этот файл - один и тот же для всех разработчиков, он попадает в git-репозиторий. Файл загружается при запуске docker-compose up -d и значения попадают в контейнер через блок environment в описании сервиса docker
services:
    php:
        environment:
            ENV_database_host: "${ENV_database_host}"

Затем это значение загружается в параметры приложения на Symfony в файле parameters.yml
parameters:
    database_host: "%env(ENV_database_host)%"

И уже параметр database_host используется в сервисах DI контейнера Symfony "как обычно"
На удалённом сервере значения из файла .env должны быть перекрыты другими. Для этого в настройках Pipeline CI\CD в репозитории GitLab создаются переменные для каждого из окружений со своим суффиксом. Например ENV_database_host_MASTER для staging и ENV_database_host_PRODUCTION для production.
Чтобы на удалённый сервер попала правильная конфигурация, значения переменных-с-суффиксом переносятся в переменные без суффикса, файл docker-compose.yml компилируется с уже перекрытыми значениями и результат копируется на сервер
docker-compose -f docker-compose-deploy.yml config > build/docker-compose.yml

A: К сожалению, все так. В систему контроля версий не должны попадать конфигурационные файлы, которые не запустятся на других хостах, поэтому, как правило, ПО распространяется без реальных конфигов, и в консольные команды добавляется команда начальной конфигурации, которые могут сформировать этот файл.
Добавление обязательных конфигурационных опций на ходу - плохая идея, по крайней мере между major-версиями. Они должны иметь свое значение по умолчанию, при котором приложение продолжает вести себя так же, как и раньше. Все эти -webkit-something-tralala в CSS появились ровно оттуда же - давайте добавим эту штуку, но не будем ее пихать как готовую опцию, когда будем готовы к внедрению - внедрим, чтобы она точно не переименовывалась и не менялась потом (конкретно в CSS имена задаются стандартом, но общая идея должна быть ясна).
Впрочем, один хак я для себя нашел - весь dev-env засовывается в вагрант, где можно свободно писать любые конфиги и менять их на ходу, в результате в команде разработчиков можно свободно играться с тестовой конфигурацией.
Еще одна штука, которая помогает - это "параллельные" файлы, в которых переопределяются значения: configuration.yml содержит в себе некоторую конфигурацию, а configuration.local.yml - всего пару опций, который "берут верх" над аналогичными опциями из configuration.yml.

A: На эту тему высказались авторы манифеста 12 factors.
Вот что они пишут о конфигурации:

Лакмусовой бумажкой того, правильно ли разделены конфигурация и код приложения, является факт того, что кодовая база приложения может быть в любой момент открыта в свободный доступ без компрометации каких-либо приватных данных.

Далее:

Другим подходом к конфигурации является использование конфигурационных файлов, которые не сохраняются в систему контроля версий, например, config/database.yml в Rails. Это огромное улучшение перед использованием констант, которые сохраняются в коде, но по-прежнему и у этого метода есть недостатки: легко по ошибке сохранить конфигурационный файл в репозиторий; существует тенденция, когда конфигурационные файлы разбросаны в разных местах и в разных форматах, из за этого становится трудно просматривать и управлять всеми настройками в одном месте.

Это как раз способ, который описан в вопросе. Авторы манифеста предлагают такое решение:

Приложение двенадцати факторов хранит конфигурацию в переменных окружения (часто сокращается до env vars или env). Переменные окружения легко изменить между развёртываниями, не изменяя код; в отличие от файлов конфигурации, менее вероятно случайно сохранить их в репозиторий кода; и в отличие от пользовательских конфигурационных файлов или других механизмов конфигурации, таких как Java System Properties, они являются независимым от языка и операционной системы стандартом.

Естественно, всё это применимо в основном к веб-приложениям. Для десктопных и мобильных приложений эти правила уже не подходят.
От себя добавлю, что Azure-приложения ASP.NET и ASP.NET WebAPI сейчас настраиваются именно так: в панели приложения на вкладке Application settings можно указать переменные окружения. Тоже самое в Heroku.
Пример
В нашем проекте требуется рассылать электронные письма и СМС. Естественно, на локальных контурах разработчиков и на общем контуре разработки ничего рассылать не надо, но при этом нужен доступ к содержимому уведомлений. То есть разработчики должны видеть, что служба уведомлений сработала, и видеть, что именно будет отправлено клиенту на боевом контуре.
Поскольку мы используем внедрение зависимостей, мы сделали несколько реализаций классов, рассылающих уведомления. Продуктовая реализация осуществляет отправку писем, а реализация разработчиков пишет уведомления в файл. В качестве библиотеки IoC мы используем Autofac, который позволяет регистрировать зависимости в конфигурационном файле, так что в нашем Web.config была зарегистрирована служба уведомлений для разработчиков.
MSBuild умеет трансформировать конфигурационные файлы ASP.NET проектов во время развёртывания. Если в вашей папке находятся файлы Web.config и Web.Release.config, при развёртывании проекта в конфигурации Release MSBuild применит трансформации из Web.Release.config к Web.config. Можно менять атрибуты разделов, добавлять и удалять подразделы. Мы у себя меняли регистрируемый класс, так что на контуре Release запускалась реальная служба уведомлений вместо отладочной.
Тогда нас такое решение устроило.
Некоторое время всё работало хорошо, но потом вышла 4-я версия Autofac, которая стала совместима с новой системой конфигурирования .NET. При этом разработчики Autofac выпилили поддержку старого способа, то есть старых добрых Web.config и App.config. При этом MSBuild не умеет автоматически трансформировать новые файлы конфигурации.
Пришлось переделать схему. Теперь для каждого контура мы стали хранить свою версию конфигурации IoC в файлах IoC.Dev.json, IoC.Stage.json, IoC.Release.json. Загрузка нужного файла конфигурации стала осуществляться так:
Startup.cs
var configName = Environment.GetEnvironmentVariable("APPSETTING_CONFIG_NAME") ?? "Dev";
var config = new ConfigurationBuilder().AddJsonFile($"IoC.{configName}.json", optional: true, reloadOnChange: true);
var module = new ConfigurationModule(config.Build());
builder.RegisterModule(module);

Это было стихийное решение, которое мы обнаружили в Google и смогли применить к нашему Azure-проекту. Однако это ещё не идеал с точки зрения 12-тифактороного приложения. Часть настройки действительно вынесена в переменную окружения, но часть находится в файлах IoC.*.json.
Что не так? Администратор системы может решить, что файлы IoC.Dev.json, IoC.Stage.json, IoC.Release.json можно спокойно менять, хотя на самом деле мы довольно суровы относительно них. Нам не нужна здесь универсальность и гибкость, мы бы хотели ограничить настройку двумя вариантами: а) шлём уведомления; б) складываем уведомления в секретное место.
Так что мы можем захардкодить эти две стратегии и при старте приложения выбирать ту из них, которая указана в переменной окружения:
var notifyStrategy = Environment.GetEnvironmentVariable("APPSETTING_NOTIFY_STRATEGY");
switch (notifyStrategy)
{
case "send":
    builder.RegisterType<ReadNotifier>().As<INotifier>();
    break;

case "save":
    builder.RegisterType<FakeNotifier>().As<INotifier>();
    break;

default:
    throw new ArgumentException("Ну всё теперь.", nameof(notifyStrategy));
}

Теперь администратор приложения может конфигурировать его на своём уровне погружения. Он не сломает ничего важного в дебрях XML/JSON IoC.
В результате нам удалось полностью избавиться от файлов конфигурации на этом уровне и стать ближе к идеалам 12-тифакторных приложений.
Исходя из этого, я бы советовал:

*

*Все секретные настройки, включая строки подключения к базам данных, логины и пароли для отправки писем и прочее, брать из переменных окружения. Развёртывание приложения свести к запуску одной команды (для .NET это MSBuild). Переменные окружения и процесс развёртывания описать в README.md.

*Внедрение зависимостей реализовывать непосредственно в коде, предоставляя несколько стратегий, которыми будет управлять администратор. Он скажет вам спасибо, если ему не придётся изучать детали приложения, и он сможет одной настройкой внедрить совершенно другой набор из трёх-пяти-десяти типов, не разбираясь в их взаимосвязях.

*Некоторые конфигурационные файлы на самом деле представляют из себя декларативную часть кода и не требуют изменения после развёртывания. Детали зависит от языка, думаю, что чаще это встречается в интерпретируемых языках. Такие файлы мы не должны считать истинно конфигурационными и можем оставить их в проекте как есть.

*Конфигурацию, которую может менять администратор и которая может сохраняться между развёртываниями, вынести в БД. Можно и в файл, но в этом случае он может быть уничтожен при неаккуратном развёртывании. Значения в базе или в файле, если их нет при первом запуске системы, прописываются стандартные из кода.

A: Все описанное ниже относится к spring приложению, первый пункт можно отнести и к другим технологиям, если возможно подстановка данных из переменных среды.

*

*Есть множество способов задания конфигурации настроек. Но действительно есть определенные чувствительные данные(пароли, credentials и т.д.), которые нельзя хранить в открытом доступе. В этом случае можно использовать вариант хранения скелета настроек в property файлов в git`е, но с подстановками из enviroment переменных. В этом случае чувствительные данные будут прописываться в OC.

*У первого пункта есть один существенный недостаток - синхронизация таких данных между различными серверами. Данная ситуация может возникнуть при микросервисной и SOA архитектурах(одно или несколько приложений используют одни credentials). На этот случай есть spring cloud vault, который позволяет ограничить доступ к таким данным через авторизацию приложений.
Официальное описание проекта.

Spring Cloud Vault Config provides client-side support for externalized configuration in a distributed system. With HashiCorp's Vault you have a central place to manage external secret properties for applications across all environments. Vault can manage static and dynamic secrets such as username/password for remote applications/resources and provide credentials for external services such as MySQL, PostgreSQL, Apache Cassandra, MongoDB, Consul, AWS and more.

A: Как способ, наверно, решить эту проблему использование систем непрерывной интеграции которые сами будут тебе создавать конфигурацию с переменной среды.
Переменная среды устанавливается в самой системе непрерывной интеграции.
TeamCity так может, в других CI думаю присутствует такая возможность. Так же там есть возможность добавлять кроме переменных сред еще и параметры, системные свойства что очень удобно.
Ко всему этому удобностью является написание скриптов сборки.
Пример генерации конфигурации на примере js файла
file=$(cat <<EOF
export const SERVER_URL = '%dev.server_url%';
export const PREFIX = '%dev.api_prefix%';
export const API_URL = '%dev.api_url%';
export const imgPath = '%dev.server_url%';
export const DefaultLanguage = '%dev.default_lang%';
export const GoogleMapsKey = '%dev.google_maps_key%';
export const ConfigAuth = {
    vkontakte: {client_id: '%dev.social.auth.vkontakte%'},
    facebook: {client_id: '%dev.social.auth.facebook%'},
    google: {client_id: '%dev.social.auth.google_client_id%', apiKey: '%dev.social.auth.google_api_key%' }
}
EOF
)

%dev.server_url% - переменная среда, как шаблон, TeamCity парсит эту строку с %property.name%
Результат будет на выходе  уже в созданном конфигурационном файле
export const SERVER_URL = 'http://localhost:8000/';
И в добавок ко всему этому пример конфигурации в репозитории


text:
Q: Chart.js v3 after using of zoom plugin instance persist in memory I recently switched Chart.js from v2.x to 3.x. I also use the chartjs-plugin-zoom 1.0.1 which is compatibile with version v3.x. My situation is this I have SPA with some tabs, on one tab are the charts, between them line chart and for this one I use the zoom plugin, because data are usually huge. My options looks like
this._options = {
            animation: false,
            responsive: true,
            tooltips: {
                mode: 'nearest',
                intersect: false
            },
            maintainAspectRatio: false,
            legend:
            {
               display: false
            },
            scales: {
                x:
                {
                    title:
                    {
                        display: true,
                        text: `Message order`
                    },
                },
                y:
                {
                    title:
                    {
                        display: true,
                        text: `log10 of time difference`
                    },
                }
            },
            plugins: {
                legend: {
                    display: false
                },
                zoom: {
                    zoom: {
                      wheel: {
                        enabled: true,
                      },
                      drag:
                      {
                          enabled: true,
                          borderWidth: 1
                      },
                      mode: 'x',
                    }
                },
                decimation: {
                    enabled: true
                }
            }
        };

When I transit from page with charts to another, this is called for cleaning:
if (this._chart)
{
    this._chart.options.onClick = null;
    //desperate attempt to save situation
    this._chart.options.plugins = null;
    this._chart.clear();
    this._chart.destroy();
}

I expected that destroy do everything necessary from memory perspective. For version 2 it is working, but here I observe strange behavior. When I switch from chart page to another and inspect memory I saw LineController(object asociated with chart.js) between objects. When I switch back to chart page and then again to another memory consumption raise and count of LineController too.

What i find out is this, when I comment the zoom plugin from options
zoom: {
                    zoom: {
                      wheel: {
                        enabled: true,
                      },
                      drag:
                      {
                          enabled: true,
                          borderWidth: 1
                      },
                      mode: 'x',
                    }
                }

Everything is working again, no more raising LineControll instances no visible memory consumption raise between pages switching. But this plugin is necessary for me, so commenting out is not good option. I tried manually set plugins for chart to null:
this._chart.options.plugins = null;

But this not solve the memory problem. Has anybody face such condition?

A: From what I find out problem was at chartjs-plugin-zoom 1.0.1. Some event listeners where not unsubscribed corretly which lead to observed memory leak. This issue was addressed at Fix removing event listeners.
This fix is included at chartjs-plugin-zoom 1.1.0. After repeat the same scenario with this version I not more observe the problem.


text:
Q: "temporary of type 'A' has protected destructor", but its type is B In the following code, compiled with Clang 8.0.0+ and -std=c++17, creating a derived class instance using B{} gives an error error: temporary of type 'A' has protected destructor. Why is A appearing in this message when the temporary has type B (and thus should have a public destructor)?
https://godbolt.org/z/uOzwYa
class A {
protected:
    A() = default;
    ~A() = default;
};

class B : public A {
// can also omit these 3 lines with the same result
public:
    B() = default;
    ~B() = default;
};

void foo(const B&) {}

int main() {

    // error: temporary of type 'A' has protected destructor
    foo(B{});
    //    ^

    return 0;
}

A: This is a subtle issue of aggregate initialization before C++20.
Before C++20, B (and A) are aggregate types:
(emphasis mine)

no user-provided, inherited, or explicit constructors (explicitly defaulted or deleted constructors are allowed) (since C++17) (until C++20)

Then

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default member initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).

So B{} constructs a temporary object via aggregate initialization, which will initialize the base subobject directly with empty list, i.e. perform aggregate initialization to construct the A base subobject. Note that the constructor of B is bypassed. The problem is that in such context, the protected desctructor can't be called to destroy the directly constructed base subobject of type A. (It doesn't complain about the protected constructor because it's bypassed by the aggregate initialization of A too.)
You can change it to foo(B()); to avoid aggregate initialization; B() performs value-initialization, the temporary object will be initialized by B's constructor, then anything is fine.
BTW since C++20 you code will work fine.

no user-declared or inherited constructors (since C++20)

B (and A) are not aggregate types again. B{} performes list initialization, and then the temporary object is initialized by B's constructor; the effect is just same as B().


text:
Q: How do I add i386 architecture in Ubuntu MATE 15.04? So I want to install wine:i386 so I can use PlayOnLinux.
http://wiki.playonlinux.com/index.php/Installing_PlayOnLinux

For users' Debian wheezy and Ubuntu Precise (and higher), they'll need to install the i386 version of Wine. For this, we must enable support for i386 in your repository manager.

sudo echo "foreign-i386 architecture"> /etc/dpkg/dpkg.cfg.d/multiarch simply returned nothing and jumped to the next line. I checked the file later and it had been edited to contain the line "foreign-i386 architecture".
sudo apt-get update worked just fine.
sudo apt-get install wine:i386 returned
Do you want to continue? [Y/n] y after which it returned:
Extracting templates from packages: 100%
Preconfiguring packages ...
dpkg: error: configuration error: /etc/dpkg/dpkg.cfg.d/multiarch:1: unknown option 'foreign-i386'
E: Sub-process /usr/bin/dpkg returned an error code (2)

"unknown option 'foreign-i386'".
How can I resolve this?
P.S. I'm very new to Linux, please be patient.

A: To resolve it, run this command:
sudo dpkg --add-architecture i386

Or, if fails, you can still add it using the other answer's method below.

A: Check that the only file in the below folder is multiarch using:-
ls /etc/dpkg/dpkg.cfg.d/
See if the output is multiarch.
If the output is multiarch then run below:-
sudo sh -c "echo 'foreign-architecture i386' > /etc/dpkg/dpkg.cfg.d/multiarch"
NOTE:- First, check the output of uname -m, if it is already i386, then no-need to follow above steps, i.e, i386 is enabled by default.


text:
Q: How to get the last n day score change for each user along with rank for multiple columns using MYSQL? I have a MYSQL database that keeps track of all the users' daily total scores (and some other similar score/count type metrics like "badgesEarned", I am only including 2 fields here out of the 5 I need to track). It only has data for the days in which a user was active (earning score points or badges). So the db wont have data for every date there is.
Here's a toy example:
Example Database Table: "User"
Now my goal is to get the last 7 days change in score for each user (I also need to do last 30 days and 365 day but let's stick to just 7 for this example). Since the db table stores a snapshot of total scores for all active days for each user, I wrote a SQL query that finds the two appropriate rows/snapshots and gets the difference in score/badges between them. These 2 rows would be the current date row (or if that doesnt exist, use the row just prior to it) vs the (current_date - 7)th row (or if that doesnt exist, use the row just prior to it).
To make matters worse, I also have to keep track of the "ranks" of each player via the dense_rank() SQL method and add that in as a column in the final result table.
There are 2 ways so far that I can achieve this using 2 different SQL queries.
My main question is - is one of these "better" in terms of performance/good practice/efficiency than the other? Or are they both horrendous and I have completely gone down the wrong route to begin with and totally missed a more efficient approach? I am not great with SQL stuff, so apologies in advance if the question and code examples are horrifying:
First Approach:
Use multiple nested subqueries only (no join).
SELECT *, dense_rank() OVER (ORDER BY t3.score DESC) AS ranking
FROM
(
  SELECT t1.userId,

                                (SELECT t2.score
                                FROM User t2
                                WHERE t2.date <= CURDATE() AND t2.userId=t1.userId
                                ORDER BY t2.date DESC LIMIT 1)
                                -
                                (SELECT t2.score
                                FROM User t2
                                WHERE t2.date <= DATE_ADD(CURDATE(), INTERVAL - 7 DAY) AND t2.userId=t1.userId
                                ORDER BY t2.date DESC LIMIT 1) as score,

                                (SELECT t2.badgesEarned
                                FROM User t2
                                WHERE t2.date <= CURDATE() AND t2.userId=t1.userId
                                ORDER BY t2.date DESC LIMIT 1)
                                -
                                (SELECT t2.badgesEarned
                                FROM User t2
                                WHERE t2.date <= DATE_ADD(CURDATE(), INTERVAL - 7 DAY) AND t2.userId=t1.userId
                                ORDER BY t2.date DESC LIMIT 1) as badgesEarned

    FROM User t1
    GROUP BY t1.userId) t3

Second Approach:
Get 2 separate tables for each date point, then do Inner Join to subtract relevant columns.
SELECT *, dense_rank() OVER (ORDER BY T0.score_delta DESC) AS ranking
FROM
(SELECT T1.userId,
        (T1.score - T2.score),
        (T1.badgesEarned - T2.badgesEarned)

FROM

(select *
from (
   select *, row_number() over (partition by userId order by date desc) as ranking
   from User
   where date<=date_add(CURDATE(),interval -7 day)
) t
where t.ranking = 1) as T2

INNER JOIN

(select *
from (
   select *, row_number() over (partition by userId order by date desc) as ranking
   from User
   where date<=CURDATE()
) t
where t.ranking = 1) as T1

on T1.userId= T2.userId ) T0

Side-question: One of my colleagues was suggesting that I handle the column subtractions in the code itself - like, I would call the database twice, get the two tables (one for CURDATE() and another for CURDATE-7), and then loop through all the User objects and subtract the relevant fields to construct my final result list. I'm not sure if that would be the better approach, so should I be doing that instead of handling it all through the SQL way?
Here's the SQLfiddle of the db if you want to play around with dummy data: http://sqlfiddle.com/#!9/86c58f0/1
Also, the above two code segments run just fine on my MySQL 8.0 workbench with no errors.

A: I'm not quite getting your expected results. But could you not just work with window functions, in conjunction with the RANGE clause?
I'm just creating the central backbone table, and it will then be up to you to subtract whatever you need to subtract from each other, and finally to dense_rank() what you need to dense_rank(). Basically, I think you need to put a final select, containing DENSE_RANK() , to select from my with_a_week_before in-line table.
WITH
-- your input
usr(userid,dt,score,badgesearned) AS (
          SELECT 1234,DATE '2020-08-06', 100, 10
UNION ALL SELECT 1234,DATE '2020-08-07', 120, 12
UNION ALL SELECT 1234,DATE '2020-08-08', 130, 13
UNION ALL SELECT 1234,DATE '2020-08-12', 140, 14
UNION ALL SELECT 1234,DATE '2020-08-14', 150, 15
UNION ALL SELECT  100,DATE '2020-08-05', 100, 10
UNION ALL SELECT  100,DATE '2020-08-10', 100, 10
UNION ALL SELECT  100,DATE '2020-08-14', 200, 10
UNION ALL SELECT    1,DATE '2020-08-05', 140, 14
UNION ALL SELECT    1,DATE '2020-08-08', 145, 14
UNION ALL SELECT    1,DATE '2020-08-12', 150, 15
)
,
with_a_week_before AS (
  SELECT
    *
  , FIRST_VALUE(score) OVER(
      PARTITION BY userid ORDER BY dt
      RANGE BETWEEN INTERVAL '7 DAYS' PRECEDING AND CURRENT ROW
    ) AS score_a_week
  , FIRST_VALUE(badgesearned) OVER(
      PARTITION BY userid ORDER BY dt
      RANGE BETWEEN INTERVAL '7 DAYS' PRECEDING AND CURRENT ROW
    ) AS badgesearned_a_week
  , FIRST_VALUE(dt) OVER( -- check the date of the previous row
      PARTITION BY userid ORDER BY dt
      RANGE BETWEEN INTERVAL '7 DAYS' PRECEDING AND CURRENT ROW
    ) AS dt_a_week
  FROM usr
)
SELECT * FROM with_a_week_before ORDER BY userid
-- out  userid |     dt     | score | badgesearned | score_a_week | badgesearned_a_week | dt_a_week
-- out --------+------------+-------+--------------+--------------+---------------------+------------
-- out       1 | 2020-08-05 |   140 |           14 |          140 |                  14 | 2020-08-05
-- out       1 | 2020-08-08 |   145 |           14 |          140 |                  14 | 2020-08-05
-- out       1 | 2020-08-12 |   150 |           15 |          140 |                  14 | 2020-08-05
-- out     100 | 2020-08-05 |   100 |           10 |          100 |                  10 | 2020-08-05
-- out     100 | 2020-08-10 |   100 |           10 |          100 |                  10 | 2020-08-05
-- out     100 | 2020-08-14 |   200 |           10 |          100 |                  10 | 2020-08-10
-- out    1234 | 2020-08-06 |   100 |           10 |          100 |                  10 | 2020-08-06
-- out    1234 | 2020-08-07 |   120 |           12 |          100 |                  10 | 2020-08-06
-- out    1234 | 2020-08-08 |   130 |           13 |          100 |                  10 | 2020-08-06
-- out    1234 | 2020-08-12 |   140 |           14 |          100 |                  10 | 2020-08-06
-- out    1234 | 2020-08-14 |   150 |           15 |          120 |                  12 | 2020-08-07


text:
Q: Complex SQL PIVOT with log data
I have this two tables at my db , as you see they have 1->N relation.
it's a log for each participant that answers questionnaire at a unique date,
at each date the participant can answer 3 questionnaires M(Morning) N(Noon) E(Evening), and each questionnaire contains question that are numbered (1,2,3..)
Note: the unique key for participant is participantid ignore the research and group ids
the result a I need is:

As you see each questionnaire can be with different number of questions (the morning ques. contains 4 ,the noon ques. contains 3 and the evening ques. contains 2).

A: You are trying to use row data and convert them into columns (pivot), i.e every date/time/question will be a column in your desired output.
This normally is difficult to do in SQL, if not impossible, when the data you are pivoting is not constant or enumerable.
What you need to do in these cases is access the data from a reporting layer and do the pivoting at report level, as you could do in SSRS or Qlikview for instance.
If you don't have a reporting layer, as I said on the comments, you can always download the data to spreadsheet and create the pivot table. If you need to know how to pivot in Excel, you can do a search on the web and you will find many tutorials, for example this one:
https://support.office.com/en-gb/article/Quick-start-Create-a-PivotTable-report-0c220f35-e478-49aa-beaf-24018b7f0f64
You can also use other spreadsheet software like LibreOffice to create Pivot tables as well:
https://help.libreoffice.org/Calc/Creating_Pivot_Tables


text:
Q: Empty numeric type into format specifer Is there any way to pass an "empty" numeric type into a numeric format specifier and have it print the blank space associated with that specifier?
ie.
n = "Scientific:"
v = 123.321
strfmt = "%5.4E"
output = "%s|"+strfmt+"|"
print output % (n, v)

>   Scientific:|1.2332E+02|

v = EMPTY
print output % (n, v)

>   Scientific:|          |

The ultimate goal is to deal with incomplete lines without adaptively changing the format string while looping
perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
output = ("%s|"+strfmt+"|  ")*perline+"\n"

for args in map(EMPTY,*[iter(n),iter(v)]*perline):
    print output % args

>   1st:|1.0000E+00|  2nd:|2.0000E+00|  3rd:|3.0000E+00|
>   4th:|4.0000E+00|  5th:|          |  6th:|          |

To execute the above code I replaced EMPTY with None although that gives an error when you pass None to the format string

A: You won't be able to do it with just number formatting. You'll need some logic:
strfmt = "%5.4E"
v = None

if v in [None, '']:
  output = "%s|          |"
else:
  output = "%s|"+strfmt+"|"

A: One option would be to replace the numeric format in output with %s, and then in the replacing tuple create either the correct numeric output or the empty space depending on what v is:
>>> v = 123.321
>>> "%s|%s|" % (n, "%5.4E" % v if v is not None else " "*10)
'Scientific:|1.2332E+02|'
>>> v = None
>>> "%s|%s|" % (n, "%5.4E" % v if v is not None else " "*10)
'Scientific:|          |'

You could make this a little more functional with a simple closure:
def make_default_blank_formatter(format, default):
    def default_blank_formatter(v):
        return format % v if v is not None else default
    return default_blank_formatter

scientific_formatter = make_default_blank_formatter("%5.4E", " "*10)

>>> v = 123.321
>>> "%s|%s|" % (n, scientific_formatter(v))
'Scientific:|1.2332E+02|'
>>> v = None
>>> "%s|%s|" % (n, scientific_formatter(v))
'Scientific:|          |'

edit: Here is how you could rework your printing code to use this:
perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0, None, None]

strfmt = "%5.4E"
output = ("%s|%s|  ")*perline

for args in zip(*[iter(n),iter(map(scientific_formatter, v))]*perline):
    print output % args

A: Short answer: for a field n positions wide, '%ns' %  '' will do. That is, to '%15s' % '' will print 15 spaces.
Long answer: when you specify a width in format specifiers, the first number is the minimum width of the entire field. "%5.4E" will take more than 5 places, though, because just the exponent will take 3 places already.
Specify something like "%12.4E" and get consistent results. For missing values, specify "%12s" and pass an empty string (not None) instead of the value.

A: You could use itertools.izip_longest to pair the items in n and v, and fill in missing values with the empty string.
To get the proper formatting for the items in v, you could pre-format the floats with strfmt, and use something like
output = "%s|%10s|  "

to join the items in n and v. By doing it this way, the items in v are now all strings, including the empty strings, and not a mixture of floats and empty strings.

import itertools

perline = 3
n = ["1st:", "2nd:", "3rd:", "4th:", "5th:", "6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
v = (strfmt % val for val in v)
output = "%s|%10s|  "

pairs = itertools.izip_longest(n, v, fillvalue = '')
items = (output % (place, val) for place, val in pairs)
for row in zip(*[items]*perline):
    print(''.join(row))

yields
1st:|1.0000E+00|  2nd:|2.0000E+00|  3rd:|3.0000E+00|
4th:|4.0000E+00|  5th:|          |  6th:|          |

A: As suggested above, just convert your numbers to strings before printing, and replace missing numbers with empty strings of the equal length. This can be actually written very compact, however I would never use this in serious code:
from itertools import izip_longest, groupby, chain

perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
output = ("%s|%s|  ")*perline

for _, args in groupby(enumerate(chain(*izip_longest(n, (strfmt % x for x in v),
                                                     fillvalue = ' '*len(strfmt % 0)))),
                       lambda (i, v): i/perline/2):
    print output % zip(*args)[1]

More readable and reliable version of the last loop:
l = ()
for pair in izip_longest(n, (strfmt % x for x in v),
                         fillvalue = ' '*len(strfmt % 0)):
    l += pair
    if len(l) == perline*2:
        print output % l
        l = ()

A: After viewing the responses it appears that there is no thing you can pass to a numeric format specifier to have it print the blank space associated with it.
There are a number of ways to work around this shown below. Personally I liked parts of Unutbu's answer. I think the way I will ultimately do it is create two format specifiers at the beginning and use logic as suggested by Blender.


text:
Q: UIDocumentPickerModeExportToService does not show Drive or DropBox in iOS11 I have been using UIDocumentMenuViewController and UIDocumentPickerViewController in my app to import images and pdfs from 3rd party apps like Google Drive, DropBox, iCloud etc. This is also used for exporting some pdfs from my app to these other apps. It was working fine until the latest iOS update.
In iOS 11, the import service works just as expected, but the place in my app where I try to export a pdf, the app just shows 'iCloud Drive' and 'On my iPhone' options. It does not show Google Drive or DropBox. This behavior is specific to iOS 11.
I read the documentation on Apple for UIDocumentMenuViewController, UIDocumentPickerViewController and UIDocumentBrowserViewController. None of them have specified any change for the 'UIDocumentPickerModeExportToService' mode in iOS11. Am I missing any update information from Apple?
Update: Dropbox and Google Drive released new versions of their apps compatible with iOS11. Updating these apps to the new version solves the issue!

A: Dropbox and Google Drive released new versions of their apps compatible with iOS11. Updating these apps to the new version solves the issue!


text:
Q: Distance between two points - by ID in QGIS I have a dataset of 350 or so individuals. Each individual has a start point (2 columns with Lat and Long) and end point (2 columns with Lat and Long). I would like calculate the distance between these in QGIS and have the output as a new column in the data set. (so for each row calculate the distance between two points)
Now - I have achieved this in the R statistical package pretty easily with the following code:
library(geosphere)

Dataset$distance<-distVincentyEllipsoid(Dataset[,c('gps.of.start.point_e','gps.of.start.point_s')], bb[,c('gps.of.end_e','gps.of.end_s')]

What I have tried so far in QGIS: I can create two point layers - "start points" and "end points" and use a distance matrix to calculate the distances between points. I get the data I want but also get thousands of permutations that I am not interested in and so sorting them and extraction them for my data set is time consuming and difficult.
Is there an easier way of doing this in QGIS?

A: Assuming your data structure is like below
id, start_x, start_y, end_x, end_y

This is straighforward in QGIS if you have data in a projected CRS. You can add your text file as a vector layer, and add a virtual field in the Field Calculator with the extression such as below.
distance(make_point( "start_x" , "start_y" ), make_point( "end_x" , "end_y" ))
The caveat is that this will be the distance in the units of layer CRS, which from your question is WGS84 (you are using gps coordinates) and thus distance will be in degrees. If you want ellipsoidal distance in meters, there is a longer way.

*

*Add your table to QGIS as a vector layer

*Use 'Create point layer from table' algorithm and select 'start_x' and 'start_y' as you X and Y fields. Name the layer 'start'

*Use 'Create point layer from table' algorithm and select 'end_x' and 'end_y' as you X and Y fields. Name the layer 'end'

*Use 'Join by Lines (hub lines)' algorithm. Select 'start' as your hub layer and 'end' as your spoke layer. Keep 'id' as both hub and spoke ids.

*Now you have lines joining your start and end points.

*Open Field Calculator and add a virtual field with the expression $length. You will get a new column for each line which will have distance in meters.


text:
Q: Difference between timezones with Carbon Time in CEST = UTC time+2h
but my code showing only 1h and I don't know why... (you can test it here )
require 'Carbon/Carbon.php';
use Carbon\Carbon;

$timestamp = '2018-04-06 14:30:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'UTC');
var_dump($date);
//{ ["date"]=> string(26) "2018-04-06 14:30:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
$date->tz('CEST');
var_dump($date);
//{ ["date"]=> string(26) "2018-04-06 15:30:00.000000" ["timezone_type"]=> int(2) ["timezone"]=> string(4) "CEST" }

A: The issue is that CEST is not a supported timezone in PHP, and can therefore exhibit "undefined behaviour". I suspect it's being interpreted as CET, which is UTC+1.
If you use a specific geographical identifier instead, such as Europe/Berlin, it should present the correct result (i.e. +2 hours from UTC). Try:
$date->tz('Europe/Berlin');

See https://3v4l.org/c4lve


text:
Q: RecyclerView getAdapterPosition() returns -1 on a callback so I can't show the new appearance for the item Each item on my RecyclerView has a button that has three states: OPEN, LOADING, and CLOSED.
Initially all the buttons are in the OPEN state. When a button is clicked, the state is changed to LOADING and a network call is performed in the background. After the network call succeeds, the button state should be changed to CLOSED.
So in my adapter I used the following:
holder.button.setOnClickListener(v -> {
    holder.state = LOADING;
    notifyItemChanged(holder.getAdapterPosition()); /* 1 */
    callNetwork(..., () -> {
        /* this is the callback that runs on the main thread */
        holder.state = CLOSED;
        notifyItemChanged(holder.getAdapterPosition()); /* 2 */
    });
});

The LOADING state is always visualized correctly at /* 1 */ because getAdapterPosition() gives me the correct position.
However, the CLOSED state of the button is never visualized, because getAdapterPosition at /* 2 */ always returns -1.
I might understand getAdapterPosition() wrongly in this case.
How do I refresh the appearance of an item on a callback?

A: From the docs:

Note that if you've called notifyDataSetChanged(), until the next
layout pass, the return value of this method will be NO_POSITION

NO_POSITION is a constant whose value is -1. This might explain why you are getting a return value of -1 here.
In any case, why don't you find the position of the model in the underlying dataset and then call notifyItemChanged(int position)? You could save the model as a field in the holder.
For example:
public class MyHolder extends RecyclerView.ViewHolder {

    private Model mMyModel;

    public MyHolder(Model myModel) {
        mMyModel = myModel;
    }

    public Model getMyModel() {
        return mMyModel;
    }
}

holder.button.setOnClickListener(v -> {
    holder.state = LOADING;
    notifyItemChanged(holder.getAdapterPosition());
    callNetwork(..., () -> {
        /* this is the callback that runs on the main thread */
        holder.state = CLOSED;
        int position = myList.indexOf(holder.getMyModel());
        notifyItemChanged(position);
    });
});

Alternatively you can just ignore if the position is -1, like this:
holder.button.setOnClickListener(v -> {
    holder.state = LOADING;
    int preNetworkCallPosition = holder.getAdapterPosition();
    if (preNetworkCallPosition != RecyclerView.NO_POSITION) {
        notifyItemChanged(preNetworkCallPosition);
    }
    callNetwork(..., () -> {
        /* this is the callback that runs on the main thread */
        holder.state = CLOSED;
        int postNetworkCallPosition = holder.getAdapterPosition();
        if (postNetworkCallPosition != RecyclerView.NO_POSITION) {
             notifyItemChanged(postNetworkCallPosition);
        }
    });
});

A: getAdapterPosition(); It will always return -1 when recyclerview makes layout calculations. You are calling this methods inside ViewHolder.. It means RecyclerView is doing calculations.
If you need position inside click actions of view, call it in the public void onClick(final View v) method for example:
"@Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    final Students user = mUsers.get(position);
    holder.Name.setText(user.getFullname());
    holder.Index.setText(user.getIndex_number());

    if (user.getThumbnail().equals("default")) {
        holder.profile_image.setImageResource(R.drawable.profile_pic);
    } else {
        Picasso.get().load(user.getThumbnail())
                .placeholder(R.drawable.profile_pic)
                .into(holder.profile_image);
    }

  holder.itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(final View v) {
           **list_user_id = mUsers.get(position).getId();**

           Intent Sub = new Intent(mContext, UserProfileActivity.class);
           Sub.putExtra("user_id1", list_user_id);
           mContext.startActivity(Sub);

BUT NOT
getAdapterPosition(); It will always return -1 when recyclerview makes layout calculations. You are calling this methods inside ViewHolder.. It means RecyclerView is doing calculations.
If you need position inside click actions of view, call it in the public void onClick(final View v) method for example:
@Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    final Students user = mUsers.get(position);
    holder.Name.setText(user.getFullname());
    holder.Index.setText(user.getIndex_number());

**list_user_id = mUsers.get(position).getId();**

    if (user.getThumbnail().equals("default")) {
        holder.profile_image.setImageResource(R.drawable.profile_pic);
    } else {
        Picasso.get().load(user.getThumbnail())
                .placeholder(R.drawable.profile_pic)
                .into(holder.profile_image);
    }

  holder.itemView.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(final View v) {

           Intent Sub = new Intent(mContext, UserProfileActivity.class);
           Sub.putExtra("user_id1", list_user_id);
           mContext.startActivity(Sub);


text:
Q: Mi login en cakePHP 3.x no funciona estoy intentando hacer un loguin en cakePHP siguiendo los pasos de la documentación oficial:
https://book.cakephp.org/3/en/tutorials-and-examples/cms/authentication.html
pero por más que lo intente siempre que intento loguearme con cualquier user me dice que el usuario o contraseña son incorrectas, la contraseña tiene el método hash para encriptarse y aunque lo quité sigue pasando lo mismo, ya probé con iniciar sesión con un usuario sin contraseña encriptada quitando el método etc. y como estoy siguiendo la documentación no sé qué puede estar pasando.
Voy a poner los códigos de los archivos que creería tienen relevancia, en caso de que falte alguno, por favor dímelo y lo agregaré
este es el AppController
    <?php

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;

class AppController extends Controller
{

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler', [
            'enableBeforeRedirect' => false,
        ]);
        $this->loadComponent('Flash');

        $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'

                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'unauthorizedRedirect' => $this->referer()
        ]);

        $this->Auth->allow(['display', 'view', 'index', 'add']);
    }}

mi UsersController:
 <?php
namespace App\Controller;

use App\Controller\AppController;

class UsersController extends AppController
{
    public function index()
    {
        $this->paginate = [
            'contain' => ['Rols'],
        ];
        $users = $this->paginate($this->Users);

        $this->set(compact('users'));
    }

    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => ['Rols', 'Trainings'],
        ]);

        $this->set('user', $user);
    }

    public function add()
    {
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $rols = $this->Users->Rols->find('list', ['limit' => 200]);
        $this->set(compact('user', 'rols'));
    }

    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => [],
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $rols = $this->Users->Rols->find('list', ['limit' => 200]);
        $this->set(compact('user', 'rols'));
    }

    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
            $this->Flash->success(__('The user has been deleted.'));
        } else {
            $this->Flash->error(__('The user could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            $this->log($user);
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error('Your username or password is incorrect.');
        }
    }
}

Mi model entity de Users:
<?php

namespace App\Model\Entity;

use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;

/**
 * User Entity
 *
 * @property int $id
 * @property string $name
 * @property string $email
 * @property string $password
 * @property int $rol_id
 *
 * @property \App\Model\Entity\Rol $rol
 * @property \App\Model\Entity\Training[] $trainings
 */
class User extends Entity
{
    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        'name' => true,
        'email' => true,
        'password' => true,
        'rol_id' => true,
        'rol' => true,
        'trainings' => true,
    ];

    /**
     * Fields that are excluded from JSON versions of the entity.
     *
     * @var array
     */
    protected $_hidden = [
        'password',
    ];

    protected function _setPassword($value)
    {
        if (strlen($value)) {
            $hasher = new DefaultPasswordHasher();

            return $hasher->hash($value);
        }
    }
}

y por ultimo mi login.ctp:

Login

<?= $this->Form->create() ?>
<?= $this->Form->control('email') ?>
<?= $this->Form->control('password') ?>
<?= $this->Form->button('Login') ?>
<?= $this->Form->end() ?>


text:
Q: Weird timestamp output in MySQL shell mysql-sql> select time_stamp, unix_timestamp(time_stamp) from historical_data
where time_stamp > '2014-07-31' and time_stamp < '2014-10-05';
+---------------------+----------------------------+
| time_stamp          | unix_timestamp(time_stamp) |
+---------------------+----------------------------+
| 2014-07-31 19:04:00 |                 1406826240 |
| 2014-00-00 0:00:00  |                 1406913840 |
| 2014-00-00 0:00:00  |                 1407002040 |
| 2014-00-00 0:00:00  |                 1407088440 |
| 2014-00-00 0:00:00  |                 1407174840 |

I have a table with a TIMESTAMP column. I noticed that when I query the table from mysql shell it shows many dates as 2014-00-00 0:00:00. But when I convert to unix timestamp in my query it seems like the data is saved correctly. As if it is only the output formatting there is something wrong with...(the time stamps are also part of primary key).
This happens from august 1, 2014 until october 1, 2014, then it goes back to normal output.
Not sure if the following is relevant, but as I have no idea what causes this to happen here it is:
I have a java application that uses gson to handle json data from the web.Amongst the data is unix timestamps. These are converted to Instant objects, which is then written to the database using MyBatis.
Now, when reading back from the database everything seems to work OK, I get correct Instant objects. It is only in the mysql shell this is a problem it seems. But it is strange and uncomfortable.
Here is the problem reproduced from scratch in MySQL shell:
mysql-sql> select version();
+------------+
| version()  |
+------------+
| 5.7.18-log |
+------------+
1 row in set (0.00 sec)
mysql-sql> create table test(`time_stamp` TIMESTAMP NOT NULL PRIMARY KEY);
Query OK, 0 rows affected (0.05 sec)
mysql-sql> insert into test (time_stamp) values ('2014-07-31');
Query OK, 1 row affected (0.01 sec)
mysql-sql> insert into test (time_stamp) values ('2014-08-15');
Query OK, 1 row affected (0.01 sec)
mysql-sql> insert into test (time_stamp) values ('2014-09-15');
Query OK, 1 row affected (0.01 sec)
mysql-sql> insert into test (time_stamp) values ('2014-10-01');
Query OK, 1 row affected (0.00 sec)
mysql-sql> select * from test;
+--------------------+
| time_stamp         |
+--------------------+
| 2014-07-31 0:00:00 |
| 2014-00-00 0:00:00 |
| 2014-00-00 0:00:00 |
| 2014-10-01 0:00:00 |
+--------------------+
4 rows in set (0.00 sec)
mysql-sql> select time_stamp, unix_timestamp(time_stamp) from test;
+--------------------+----------------------------+
| time_stamp         | unix_timestamp(time_stamp) |
+--------------------+----------------------------+
| 2014-07-31 0:00:00 |                 1406757600 |
| 2014-00-00 0:00:00 |                 1408053600 |
| 2014-00-00 0:00:00 |                 1410732000 |
| 2014-10-01 0:00:00 |                 1412114400 |
+--------------------+----------------------------+
4 rows in set (0.00 sec)

So at least I know it is not in the application layer the problem is.

A: While I can't reproduce the problem, there clearly seems to be a bug in MySQL Shell (see the dates in the INSERT and the result in the SELECT):
Welcome to MySQL Shell 1.0.9

Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type '\help', '\h' or '\?' for help, type '\quit' or '\q' to exit.

Currently in SQL mode. Use \js or \py to switch the shell to a scripting language.
mysql-sql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.18    |
+-----------+
1 row in set (0.00 sec)

mysql-sql> DROP TABLE IF EXISTS `_`.`historical_data`;
Query OK, 0 rows affected (0.03 sec)

mysql-sql> CREATE TABLE IF NOT EXISTS `_`.`historical_data` (
       ...   `time_stamp` TIMESTAMP NOT NULL PRIMARY KEY
       ... );
Query OK, 0 rows affected (0.00 sec)

mysql-sql> INSERT INTO `_`.`historical_data`
       ...   (`time_stamp`)
       ... VALUES
       ...   ('2014-07-31 19:04:00'),
       ...   ('2014-07-31 17:04:00'),
       ...   ('2014-08-01 17:24:00'),
       ...   ('2014-08-02 17:54:00'),
       ...   ('2014-08-03 17:54:00'),
       ...   ('2014-08-04 17:54:00');
Query OK, 6 rows affected (0.00 sec)

mysql-sql> SELECT
       ...   `time_stamp`
       ... FROM
       ...   `_`.`historical_data`;
+---------------------+
| time_stamp          |
+---------------------+
| 2014-08-31 17:04:00 |
| 2014-08-31 19:04:00 |
| 2014-09-01 17:24:00 |
| 2014-09-02 17:54:00 |
| 2014-09-03 17:54:00 |
| 2014-09-04 17:54:00 |
+---------------------+
6 rows in set (0.00 sec)

mysql-sql> SELECT
       ...   `der`.`time_stamp`,
       ...   `der`.`ut`,
       ...   FROM_UNIXTIME(`der`.`ut`)
       ... FROM (
       ...   SELECT
       ...     `time_stamp`,
       ...     UNIX_TIMESTAMP(`time_stamp`) `ut`
       ...   FROM
       ...     `_`.`historical_data`
       ...   WHERE
       ...     `time_stamp` > '2014-07-31' AND
       ...     `time_stamp` < '2014-10-05'
       ... ) `der`;
+---------------------+------------+---------------------------+
| time_stamp          | ut         | FROM_UNIXTIME(`der`.`ut`) |
+---------------------+------------+---------------------------+
| 2014-08-31 17:04:00 | 1406826240 | 2014-08-31 17:04:00       |
| 2014-08-31 19:04:00 | 1406833440 | 2014-08-31 19:04:00       |
| 2014-09-01 17:24:00 | 1406913840 | 2014-09-01 17:24:00       |
| 2014-09-02 17:54:00 | 1407002040 | 2014-09-02 17:54:00       |
| 2014-09-03 17:54:00 | 1407088440 | 2014-09-03 17:54:00       |
| 2014-09-04 17:54:00 | 1407174840 | 2014-09-04 17:54:00       |
+---------------------+------------+---------------------------+
6 rows in set (0.00 sec)

MySQL Shell:
mysql-sql> SELECT FROM_UNIXTIME('1406826240'),
       ...        FROM_UNIXTIME('1406826240', '%Y-%m-%d %H:%i:%S');
+-----------------------------+--------------------------------------------------+
| FROM_UNIXTIME('1406826240') | FROM_UNIXTIME('1406826240', '%Y-%m-%d %H:%i:%S') |
+-----------------------------+--------------------------------------------------+
| 2014-08-31 17:04:00         | 2014-07-31 17:04:00                              |
+-----------------------------+--------------------------------------------------+
1 row in set (0.00 sec)

MySQL Command-Line:
mysql> SELECT FROM_UNIXTIME('1406826240'),
    ->        FROM_UNIXTIME('1406826240', '%Y-%m-%d %H:%i:%S');
+-----------------------------+--------------------------------------------------+
| FROM_UNIXTIME('1406826240') | FROM_UNIXTIME('1406826240', '%Y-%m-%d %H:%i:%S') |
+-----------------------------+--------------------------------------------------+
| 2014-07-31 17:04:00.000000  | 2014-07-31 17:04:00                              |
+-----------------------------+--------------------------------------------------+
1 row in set (0.00 sec)

A possible workaround until the bug is solved:
MySQL Shell:
mysql-sql> SELECT
       ...   CONCAT(`time_stamp`) `time_stamp`
       ... FROM
       ...   `_`.`historical_data`;
+---------------------+
| time_stamp          |
+---------------------+
| 2014-07-31 17:04:00 |
| 2014-07-31 19:04:00 |
| 2014-08-01 17:24:00 |
| 2014-08-02 17:54:00 |
| 2014-08-03 17:54:00 |
| 2014-08-04 17:54:00 |
+---------------------+
6 rows in set (0.00 sec)

mysql-sql> SELECT
       ...   `der`.`time_stamp`,
       ...   `der`.`ut`,
       ...   CONCAT(FROM_UNIXTIME(`der`.`ut`))
       ... FROM (
       ...   SELECT
       ...     CONCAT(`time_stamp`) `time_stamp`,
       ...     UNIX_TIMESTAMP(`time_stamp`) `ut`
       ...   FROM
       ...     `_`.`historical_data`
       ...   WHERE
       ...     `time_stamp` > '2014-07-31' AND
       ...     `time_stamp` < '2014-10-05'
       ... ) `der`;
+---------------------+------------+-----------------------------------+
| time_stamp          | ut         | CONCAT(FROM_UNIXTIME(`der`.`ut`)) |
+---------------------+------------+-----------------------------------+
| 2014-07-31 17:04:00 | 1406826240 | 2014-07-31 17:04:00               |
| 2014-07-31 19:04:00 | 1406833440 | 2014-07-31 19:04:00               |
| 2014-08-01 17:24:00 | 1406913840 | 2014-08-01 17:24:00               |
| 2014-08-02 17:54:00 | 1407002040 | 2014-08-02 17:54:00               |
| 2014-08-03 17:54:00 | 1407088440 | 2014-08-03 17:54:00               |
| 2014-08-04 17:54:00 | 1407174840 | 2014-08-04 17:54:00               |
+---------------------+------------+-----------------------------------+
6 rows in set (0.01 sec)