问:
Use sed to find and replace a number following by its successor in bash
I have a string that contains multiple occurrences of number ranges, which are separated by a comma, e.g.,

2-12,59-89,90-102,103-492,593-3990,3991-4930

Now I would like to remove all directly neighbouring ranges and remove them from the string, i.e., remove anything that is of the form -(x),(x+1), to get something like this:

2-12,59-492,593-4930

Can anyone think of a method to accomplish this? I can honestly not post anything that I have tried, because all my tries were highly unsuccessful. To me it seems like it is not possible to actually find anything of the form -(x),(x+1) using sed, since that would require doing operations or comparisons of a found number by another number that has to be part of the command that is currently searching for numbers.

If everybody agrees that sed is NOT the correct tool for doing this, I will do it another way, but I am still interested if it's possible.

答:
This might work for you (GNU sed):

```<code>sed -r ' s/^/\n/;:a;ta;s/\n([^-]*-)([0-9]*)(.*,)/\1\n\2\n\2\n\3/;Td;:b;s/(\n.*\n.*)9(_*\n)/\1_\2/;tb;s/(\n.*\n)(_*\n)/\10\2/;s/$/\n0123456789/;s/(\n.*\n[0-9]*)([0-8])(_*\n.*)\n.*\2(.).*/\1\4\3/;:z;tz;s/(\n.*\n[^_]*)_([^\n]*\n)/\10\2/;tz;:c;tc;s/([0-9]*-)\n(.*)\n(.*)\n,(\3)-/\n\1/;ta;s/\n(.*)\n.*\n,/\1,\n/;ta;:d;s/\n//g' file
</code>```

This proof-of-concept sed solution, iteratively increments and compares the end of one range with the start of another. If the comparison is true it removes both and repeats, otherwise it moves on to the next range and repeats until all ranges have been compared.

Body:
This might work for you (GNU sed):

sed -r ' s/^/\n/;:a;ta;s/\n([^-]*-)([0-9]*)(.*,)/\1\n\2\n\2\n\3/;Td;:b;s/(\n.*\n.*)9(_*\n)/\1_\2/;tb;s/(\n.*\n)(_*\n)/\10\2/;s/$/\n0123456789/;s/(\n.*\n[0-9]*)([0-8])(_*\n.*)\n.*\2(.).*/\1\4\3/;:z;tz;s/(\n.*\n[^_]*)_([^\n]*\n)/\10\2/;tz;:c;tc;s/([0-9]*-)\n(.*)\n(.*)\n,(\3)-/\n\1/;ta;s/\n(.*)\n.*\n,/\1,\n/;ta;:d;s/\n//g' file

This proof-of-concept sed solution, iteratively increments and compares the end of one range with the start of another. If the comparison is true it removes both and repeats, otherwise it moves on to the next range and repeats until all ranges have been compared.


来源: stackexchange

问:
java.net.SocketTimeoutException when sending video using OkhttpClient 3.2 and Retrofit 2
I using OkhttpClient to send a video with 15 seconds long to the server using OkhttpClient 3.2 and Retrofit2,sometimes it work fine but sometimes I get the error below,which is very inconsistent.

java.net.SocketTimeoutException: timeout

Here is my code for sending the video up to server

```<code>private void sendVideoToServer( final String videoFilePath,final String api_key)
    {
        File videoFile = new File(videoFilePath);
        RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
        MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();

        VideoInterface videoInterface = retrofit.create(VideoInterface.class);
        Call<ResultObject> serverCom = videoInterface.sendVideoToServer(vFile);

        serverCom.enqueue(new Callback<ResultObject>() {
            @Override
            public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
                ResultObject result = response.body();
                if(!TextUtils.isEmpty(result.getSuccess())){
                    Log.d("video Result " , result.getSuccess());
                }
            }

            @Override
            public void onFailure(Call<ResultObject> call, Throwable t) {
               Log.d("video error",t.toString());
            }
        });
    }
</code>```

After reading some question,I tried to set the connection timeout to the OkhttpClient like below,but still cant solve the problem.

```<code>OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                });
builder.connectTimeout(5, TimeUnit.MINUTES)
       .writeTimeout(5, TimeUnit.MINUTES)
       .readTimeout(5, TimeUnit.MINUTES);
OkHttpClient httpClient = builder.build();
</code>```

I totally dont know what was doing wrong in this part,somebody please give me some guidance. Tq

答:
```<code>OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                })
                // Add below line to your okhttp client
                .connectTimeout(60, TimeUnit.SECONDS)
                .build();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I using OkhttpClient to send a video with 15 seconds long to the server using OkhttpClient 3.2 and Retrofit2,sometimes it work fine but sometimes I get the error below,which is very inconsistent.

java.net.SocketTimeoutException: timeout

Here is my code for sending the video up to server

private void sendVideoToServer( final String videoFilePath,final String api_key)
    {
        File videoFile = new File(videoFilePath);
        RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
        MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();

        VideoInterface videoInterface = retrofit.create(VideoInterface.class);
        Call<ResultObject> serverCom = videoInterface.sendVideoToServer(vFile);

        serverCom.enqueue(new Callback<ResultObject>() {
            @Override
            public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
                ResultObject result = response.body();
                if(!TextUtils.isEmpty(result.getSuccess())){
                    Log.d("video Result " , result.getSuccess());
                }
            }

            @Override
            public void onFailure(Call<ResultObject> call, Throwable t) {
               Log.d("video error",t.toString());
            }
        });
    }

After reading some question,I tried to set the connection timeout to the OkhttpClient like below,but still cant solve the problem.

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Request.Builder ongoing = chain.request().newBuilder();
                        ongoing.addHeader("authorization", api_key);
                        return chain.proceed(ongoing.build());
                    }
                });
builder.connectTimeout(5, TimeUnit.MINUTES)
       .writeTimeout(5, TimeUnit.MINUTES)
       .readTimeout(5, TimeUnit.MINUTES);
OkHttpClient httpClient = builder.build();

I totally dont know what was doing wrong in this part,somebody please give me some guidance. Tq


问:
How to parse csv in PHP having multiline data in a column
Consider s CSV file like this

```<code>item1,"description 1"
item2,"description 2"
item3,"description 3
description 3 continues on new line"
item4,"description 4"
</code>```

which should be parsed like this

```<code>item1,"description 1"
item2,"description 2"
item3,"description 3 description 3 continues on new line"
item4,"description 4"
</code>```

Is there a way to parse this CSV in PHP which has multiline values?

答:
fgetcsv should be able to properly parse this.

I wouldn't recommend doing this by hand anyway, there are many such gotchas in parsing CSV.

ContentLicense: CC BY-SA 2.5

Body:
Consider s CSV file like this

item1,"description 1"
item2,"description 2"
item3,"description 3
description 3 continues on new line"
item4,"description 4"

which should be parsed like this

item1,"description 1"
item2,"description 2"
item3,"description 3 description 3 continues on new line"
item4,"description 4"

Is there a way to parse this CSV in PHP which has multiline values?


问:
python | tkinter and threading: "main thread is not in main loop"
I'm working on an "multilayered" GUI for my company to monitor temperature and status. Because I'm quite new to the python programming, I could use some help with my code.

Quick code explanation:

The code is structured by classes. The "Main" inits the main window (tkinter) and creates the other frames to display if wanted. Every other class, except "canvas", is a frame which will display different things.

The canvas in each contains an image and some text/variable text.
A thread is used to get data from a database and change the text in the canvas.

The Problem:

Every time, the thread accessed the canvas and tries to change the text or create an new one, the error "main thread is not in main loop" is thrown.

```<code>Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.4/threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
  File "/home/pi/Documents/Programme/MM/TEST_Dateien/TEST_QUEUE.py", line 154, in __call__
    canvUbersicht.create_text(500,500, text="HOIIIIII")
  File "/usr/lib/python3.4/tkinter/__init__.py", line 2345, in create_text
    return self._create('text', args, kw)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 2321, in _create
    *(args + self._options(cnf, kw))))
RuntimeError: main thread is not in main loop
</code>```

If I init the thread without calling the canvas (e.g. "print("hey")), everything works fine.

Where does my mainloop / mainthread begin and where do they end?

I have already read several Questions and rearranged the code / thread, but it won't change anything.

I would be really happy, if someone could help me.

important code:

```<code>from tkinter import*
from DataSQL import*

class Main(Tk):
    def __init__(self, vollbild=False):
        print("Main INIT")
        Tk.__init__(self)                               #Initialisieren von Tkinter und somit erzeugen des Fensters
        Tk.geometry(self, ("1920x1080"))                #setzen von verschiedenen Parametern für das Fenster
        Tk.title(self, ("Laborüberwachung"))
        Tk.wm_overrideredirect(self, vollbild)

        container = Frame(self)                             #Frame "container" wird im eigenen Objekt(also main fenster) erstellt
        container.pack(side="top",fill="both",expand=True)  #Platzieren des Frames und ausfüllen des ganzen Fensters
        container.grid_rowconfigure(0, weight=1)            #Platzieren im Grid
        container.grid_columnconfigure(0, weight=1)         #Platzieren im Grid

        self.frames = {}                                #Erstellt leere Liste

        for F in (Ubersicht, Settings, Pin, BR167, BR213, Star3, Telematik):
            frame = F(container, self)                  #Objekt frame wird erzeugt durch aufruf von Konstruktoren der Klassen(Frameklassen zB "Übersicht")
            self.frames[F] = frame                      #Objekte werden in der Liste gespeichert, unter dem Namen der Klasse(zB "frames[Übersicht]")
            frame.grid(row=0, column=0, sticky="nsew")  #Platzieren des Frames im Grid, wobei das Grid aus nur einem Feld besteht, wird nur für die Funktionalität benötigt

        self.show_frame(Ubersicht)                      #Zeigt immer die Übersichtsseite bei StartUp
        #print(self.frames)

    def show_frame(self, cnt):                         #Methode zum Framewechsel und somit umschalten zwischen 'Tabs'
        frame = self.frames[cnt]
        frame.tkraise()
        print("frame raised",cnt)

class Ubersicht(Frame):

    def __init__(self, parent, controller):
        print("Ubersicht INIT")
        Frame.__init__(self, parent)

        self.interfaceImage = PhotoImage(file="/home/pi/Documents/Programme/Laborueberwachung3/IMG 1080/Übersicht.png")
        canvUbersicht = canv(self, controller, img=self.interfaceImage, Uber=1)

        self.__eventExit = threading.Event()
        self.__thread = threading.Thread(target=self, args=(canvUbersicht, self.__eventExit,))
        self.__thread.start()

    def __call__(self,canvUbersicht,stop_event):
        while not stop_event.wait(1):
            canvUbersicht.create_text(500,500,text="HEY")

class canv(Canvas):
    def __init__(self, parent, controller, img=None, Uber=None):
        Canvas.__init__(self, parent)
        print("canvas INIT")
        self.config(width=1920,height=1080)
        self.place(x=0,y=0)
        if (img != None):
            self.create_image(0,0,anchor=NW,image=img)

        if (Uber == 1):
            clickAreaSettings = self.create_rectangle(0,0,350,60, fill="", outline="")
            self.tag_bind(clickAreaSettings, '<Button-1>',lambda event: controller.show_frame(Pin))
        else:
            clickAreaBack = self.create_rectangle(0,0,350,60, fill="", outline="")
            self.tag_bind(clickAreaBack,'<Button-1>', lambda event: controller.show_frame(Ubersicht))

        clickAreaBR167 = self.create_rectangle(0,60,350,315, fill="", outline="")
        clickAreaBR213 = self.create_rectangle(0,316,350,570, fill="", outline="")
        clickAreaStar3 = self.create_rectangle(0,571,350,825, fill="", outline="")
        clickAreaTelematik = self.create_rectangle(0,826,350,1080, fill="", outline="")
        self.tag_bind(clickAreaBR167,'<Button-1>', lambda event: controller.show_frame(BR167))
        self.tag_bind(clickAreaBR213,'<Button-1>', lambda event: controller.show_frame(BR213))
        self.tag_bind(clickAreaStar3,'<Button-1>', lambda event: controller.show_frame(Star3))
        self.tag_bind(clickAreaTelematik,'<Button-1>', lambda event: controller.show_frame(Telematik))

app = Main(vollbild=False)
app.mainloop
</code>```

答:
Where does my mainloop / mainthread begin and where do they end?

The main thread is all the code that you don't explicitly call in another thread.

Tkinter is single-threaded, and all access to widgets must be from the same thread. When you do self.__thread = threading.Thread(target=self, ...) you are causing some tkinter code to run in another thread.

You will need to rewrite your application so that the data gathering is in a separate thread which communicates with the main GUI thread via a thread-safe queue. You can push information on the queue from the thread, and the gui thread can poll the queue.

Body:
I'm working on an "multilayered" GUI for my company to monitor temperature and status. Because I'm quite new to the python programming, I could use some help with my code.

Quick code explanation:

The code is structured by classes. The "Main" inits the main window (tkinter) and creates the other frames to display if wanted. Every other class, except "canvas", is a frame which will display different things.

The canvas in each contains an image and some text/variable text.
A thread is used to get data from a database and change the text in the canvas.

The Problem:

Every time, the thread accessed the canvas and tries to change the text or create an new one, the error "main thread is not in main loop" is thrown.

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.4/threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
  File "/home/pi/Documents/Programme/MM/TEST_Dateien/TEST_QUEUE.py", line 154, in __call__
    canvUbersicht.create_text(500,500, text="HOIIIIII")
  File "/usr/lib/python3.4/tkinter/__init__.py", line 2345, in create_text
    return self._create('text', args, kw)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 2321, in _create
    *(args + self._options(cnf, kw))))
RuntimeError: main thread is not in main loop

If I init the thread without calling the canvas (e.g. "print("hey")), everything works fine.

Where does my mainloop / mainthread begin and where do they end?

I have already read several Questions and rearranged the code / thread, but it won't change anything.

I would be really happy, if someone could help me.

important code:

from tkinter import*
from DataSQL import*

class Main(Tk):
    def __init__(self, vollbild=False):
        print("Main INIT")
        Tk.__init__(self)                               #Initialisieren von Tkinter und somit erzeugen des Fensters
        Tk.geometry(self, ("1920x1080"))                #setzen von verschiedenen Parametern für das Fenster
        Tk.title(self, ("Laborüberwachung"))
        Tk.wm_overrideredirect(self, vollbild)

        container = Frame(self)                             #Frame "container" wird im eigenen Objekt(also main fenster) erstellt
        container.pack(side="top",fill="both",expand=True)  #Platzieren des Frames und ausfüllen des ganzen Fensters
        container.grid_rowconfigure(0, weight=1)            #Platzieren im Grid
        container.grid_columnconfigure(0, weight=1)         #Platzieren im Grid

        self.frames = {}                                #Erstellt leere Liste

        for F in (Ubersicht, Settings, Pin, BR167, BR213, Star3, Telematik):
            frame = F(container, self)                  #Objekt frame wird erzeugt durch aufruf von Konstruktoren der Klassen(Frameklassen zB "Übersicht")
            self.frames[F] = frame                      #Objekte werden in der Liste gespeichert, unter dem Namen der Klasse(zB "frames[Übersicht]")
            frame.grid(row=0, column=0, sticky="nsew")  #Platzieren des Frames im Grid, wobei das Grid aus nur einem Feld besteht, wird nur für die Funktionalität benötigt

        self.show_frame(Ubersicht)                      #Zeigt immer die Übersichtsseite bei StartUp
        #print(self.frames)

    def show_frame(self, cnt):                         #Methode zum Framewechsel und somit umschalten zwischen 'Tabs'
        frame = self.frames[cnt]
        frame.tkraise()
        print("frame raised",cnt)

class Ubersicht(Frame):

    def __init__(self, parent, controller):
        print("Ubersicht INIT")
        Frame.__init__(self, parent)

        self.interfaceImage = PhotoImage(file="/home/pi/Documents/Programme/Laborueberwachung3/IMG 1080/Übersicht.png")
        canvUbersicht = canv(self, controller, img=self.interfaceImage, Uber=1)

        self.__eventExit = threading.Event()
        self.__thread = threading.Thread(target=self, args=(canvUbersicht, self.__eventExit,))
        self.__thread.start()

    def __call__(self,canvUbersicht,stop_event):
        while not stop_event.wait(1):
            canvUbersicht.create_text(500,500,text="HEY")

class canv(Canvas):
    def __init__(self, parent, controller, img=None, Uber=None):
        Canvas.__init__(self, parent)
        print("canvas INIT")
        self.config(width=1920,height=1080)
        self.place(x=0,y=0)
        if (img != None):
            self.create_image(0,0,anchor=NW,image=img)

        if (Uber == 1):
            clickAreaSettings = self.create_rectangle(0,0,350,60, fill="", outline="")
            self.tag_bind(clickAreaSettings, '<Button-1>',lambda event: controller.show_frame(Pin))
        else:
            clickAreaBack = self.create_rectangle(0,0,350,60, fill="", outline="")
            self.tag_bind(clickAreaBack,'<Button-1>', lambda event: controller.show_frame(Ubersicht))

        clickAreaBR167 = self.create_rectangle(0,60,350,315, fill="", outline="")
        clickAreaBR213 = self.create_rectangle(0,316,350,570, fill="", outline="")
        clickAreaStar3 = self.create_rectangle(0,571,350,825, fill="", outline="")
        clickAreaTelematik = self.create_rectangle(0,826,350,1080, fill="", outline="")
        self.tag_bind(clickAreaBR167,'<Button-1>', lambda event: controller.show_frame(BR167))
        self.tag_bind(clickAreaBR213,'<Button-1>', lambda event: controller.show_frame(BR213))
        self.tag_bind(clickAreaStar3,'<Button-1>', lambda event: controller.show_frame(Star3))
        self.tag_bind(clickAreaTelematik,'<Button-1>', lambda event: controller.show_frame(Telematik))

app = Main(vollbild=False)
app.mainloop


问:
Bootstrap 4 navbar not collapsing on large screen
I am trying to implement a Navbar using Bootstrap 4. Currently, the Navbar correctly collapses when the viewport is shrunk to mobile size. However, when attempting to toggle menu, nothing happens. The jsFiddle example demonstrates this behavior. I have attached the HTML as well.

Steps I have taken:

Removing all custom CSS

Ensuring jQuery link is before Bootstrap JS file

Script tags in the header and the footer

Copy and paste exact examples from Bootstrap Docs (and I get the same behavior)

Ensuring that JS is being used in the Chrome browser

Validated HTML using WC3 validator

And of course, read various posts on SO about this issue but none lead to a resolution

jsFiddle link https://jsfiddle.net/u7v5jba9/

<title>Site title</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

         Brand Name

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

              </button>

Link 1

Link 2

Link 3

Sign In

Register

Log Out

Footer

```

答:
You need to include Popper as per the Getting Started Docs.

Use these for your scripts instead.

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</code>```

Updated working Fiddle: https://jsfiddle.net/u7v5jba9/1/

Advice: In future, always open the dev inspector console in your browser to find any error messages.

ContentLicense: CC BY-SA 4.0

Body:
You need to include Popper as per the Getting Started Docs.

Use these for your scripts instead.

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

Updated working Fiddle: https://jsfiddle.net/u7v5jba9/1/

Advice: In future, always open the dev inspector console in your browser to find any error messages.


问:
Maximum call stack size exceeded in angularjs using ng-view
I am new to angular and using routing in my code.  In index file i have a menu bar in which i am using concept of routing.

```<code>    <div class="menuBar">
        <a href="#!home" class="menuBarItems">Home</a> <a href="#!about"
            class="menuBarItems">About</a> <a href="#!services"
            class="menuBarItems">Services</a> <a href="#!contact"
            class="menuBarItems">Contact Us</a>
    </div>
    <div ng-view></div>
<script>
        var app = angular.module("myApp", [ "ngRoute" ]);
        app.config(function($routeProvider) {
            $routeProvider.when("/home", {
                templateUrl : "home.html"
            }).when("/about", {
                templateUrl : "about.html"
            }).when("/services", {
                templateUrl : "services.html"
            }).when("/contact", {
                templateUrl : "contactus.html"
            });
        });
    </script>
</code>```

From this i am routing to four different html pages, but with in the home page i want nested routing. Code for home.html is as follows:

```<code>    <div>
        <section class="section1">
            <div class="section1Element"
                style="border-bottom: 2px solid rgba(0, 0, 0, 0.16);">
                <a href="#!london" class="link">London</a><br>
            </div>
            <div class="section1Element">
                <a href="#!paris" class="link">Paris</a>
            </div>
        </section>
        <section class="section2" ng-view></section>
    </div>
</div>

<script>
    var app = angular.module("myHome", [ "ngRoute" ]);
    app.config(function($routeProvider) {
        $routeProvider.when("/london", {
            templateUrl : "london.html"
        }).when("/paris", {
            templateUrl : "paris.html"
        });
    });
</script>
</code>```

Here when I am using ng-view in section element it is showing an error of maximum call stack exceeded. I don't know how to fix it. Can anyone help me out in this please?

答:
```<code>var myApp = angular.module("myApp", ['ui.router']);

myApp.config(['$stateProvider', '$urlRouterProvider',function
($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/Home/London");

$stateProvider
.state("Home", {
    url: "/Home",
    templateUrl: "Home.html"
})
.state("Home.Paris", {
    url: "/Paris",
    templateUrl: "Paris.html"
})
.state("Home.London", {
    url: "/London",
    templateUrl: "London.html"
})
.state("About", {
    url: "/About",
    templateUrl: "About.html"
})
.state("services", {
    url: "/services",
    templateUrl: "services.html"
})
.state("contactus", {
    url: "/contactus",
    templateUrl: "contactus.html"
});
}]);
</code>```

This is the required js file that is need to be done.

Body:
I am new to angular and using routing in my code.  In index file i have a menu bar in which i am using concept of routing.

        Home About Services Contact Us

From this i am routing to four different html pages, but with in the home page i want nested routing. Code for home.html is as follows:

                London

                Paris

Here when I am using ng-view in section element it is showing an error of maximum call stack exceeded. I don't know how to fix it. Can anyone help me out in this please?

Body:
var myApp = angular.module("myApp", ['ui.router']);

myApp.config(['$stateProvider', '$urlRouterProvider',function
($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/Home/London");

$stateProvider
.state("Home", {
    url: "/Home",
    templateUrl: "Home.html"
})
.state("Home.Paris", {
    url: "/Paris",
    templateUrl: "Paris.html"
})
.state("Home.London", {
    url: "/London",
    templateUrl: "London.html"
})
.state("About", {
    url: "/About",
    templateUrl: "About.html"
})
.state("services", {
    url: "/services",
    templateUrl: "services.html"
})
.state("contactus", {
    url: "/contactus",
    templateUrl: "contactus.html"
});
}]);

This is the required js file that is need to be done.


问:
How to click on a link based on another cell in same row C# asp.net
I have a landlord table, tenant table and a property table in my database.I have a html table that is dynamically created which shows the properties of the landlord that is signed in.When a tenant signs up it enters the propery ID which is the foreign key in the tenant table. When I click the view link on that html table, I would like it to be redirected to a new page showing the tenants that belong to that property.. I am unsure how to do this when the view link is clicked based on the property id in that row </p>

<p>This is my html table
and here is the code for the dynamically created table </p>

```<code>public partial class LandlordIndex : System.Web.UI.Page
{
    //creating an empty string
    string checkEmail = String.Empty;
    //constructing a string called table that will be used to create a dynamic table
    StringBuilder table = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        checkEmail += Session["LandlordLogin"];
    //if session is not empty then show label with corresponding email used in log in
        if (Session["LandlordLogin"] != null)
        {
            lblWelcome.Text += Session["LandlordLogin"].ToString();
        }
        else
        {
            Response.Redirect("Login.aspx");
        }
        if (!Page.IsPostBack)
        {
        //Creating a connection to my database using the connection string
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["rent-dbConnectionString1"].ToString();
            con.Open();
            SqlCommand comm = new SqlCommand();
            //preparing a query which will select all properties matching the landlord that is logged in at that moment
            comm.CommandText = "select p.Property_Id, p.Property_Address, p.Property_Num_Of_Tenants, p.Property_Vacant from Properties p inner join Landlords l On p.Landlord_Id = l.Landlord_Id where l.Landlord_Id = p.Landlord_Id and l.Landlord_Email = '" + checkEmail + "'";
            comm.Connection = con;
            SqlDataReader rd = comm.ExecuteReader();
            //creating a table depending on the data that is selected from the query
            table.Append("<table border='2' class='table table-striped table-bordered'>");
            table.Append("<tr><th>Property Number</th>");
            table.Append("<th>Address</th>");
            table.Append("<th>Number of Tenants</th>");
            table.Append("<th>Vacant?</th>");
            table.Append("<th>View</th>");
            table.Append("</tr>");
            if (rd.HasRows)
            {
                while(rd.Read())
                {
                    table.Append("<tr>");
                    table.Append("<td>" + rd[0] + "</td>");
                    table.Append("<td>" + rd[1] + "</td>");
                    table.Append("<td>" + rd[2] + "</td>");
                    table.Append("<td>" + rd[3] + "</td>");
                    table.Append("<td><a href=''>View</a></td>");
                    table.Append("</tr>");
                }
            }
            table.Append("</table>");
            PlaceHolder1.Controls.Add(new Literal { Text = table.ToString() });
            rd.Close();
        }
   }
}
</code>```

答:
you can achive that using jquery or javascript

for of all you need to add an id to view link like:

```<code><td><a id='"+rd[0]+"' href=''>View</a></td>
</code>```

then you need to put the below code in head. (if you are already using jquery the remove the jquery link)

```<code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
        $('a').click(function () {
            debugger;
            var id = $(this).attr('id');
            var redirecttoAnotherPage = location.href + "?id=" + id;
            window.open(redirecttoAnotherPage);
            return false;
        });
        });
    </script>
</code>```

do let me know in case you need any help

Body:
I have a landlord table, tenant table and a property table in my database.I have a html table that is dynamically created which shows the properties of the landlord that is signed in.When a tenant signs up it enters the propery ID which is the foreign key in the tenant table. When I click the view link on that html table, I would like it to be redirected to a new page showing the tenants that belong to that property.. I am unsure how to do this when the view link is clicked based on the property id in that row

This is my html table
and here is the code for the dynamically created table

public partial class LandlordIndex : System.Web.UI.Page
{
    //creating an empty string
    string checkEmail = String.Empty;
    //constructing a string called table that will be used to create a dynamic table
    StringBuilder table = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        checkEmail += Session["LandlordLogin"];
    //if session is not empty then show label with corresponding email used in log in
        if (Session["LandlordLogin"] != null)
        {
            lblWelcome.Text += Session["LandlordLogin"].ToString();
        }
        else
        {
            Response.Redirect("Login.aspx");
        }
        if (!Page.IsPostBack)
        {
        //Creating a connection to my database using the connection string
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["rent-dbConnectionString1"].ToString();
            con.Open();
            SqlCommand comm = new SqlCommand();
            //preparing a query which will select all properties matching the landlord that is logged in at that moment
            comm.CommandText = "select p.Property_Id, p.Property_Address, p.Property_Num_Of_Tenants, p.Property_Vacant from Properties p inner join Landlords l On p.Landlord_Id = l.Landlord_Id where l.Landlord_Id = p.Landlord_Id and l.Landlord_Email = '" + checkEmail + "'";
            comm.Connection = con;
            SqlDataReader rd = comm.ExecuteReader();
            //creating a table depending on the data that is selected from the query
            table.Append("
");
            table.Append("
Property Number	");
            table.Append("Address	");
            table.Append("Number of Tenants	");
            table.Append("Vacant?	");
            table.Append("View	");
            table.Append("
");
            if (rd.HasRows)
            {
                while(rd.Read())
                {
                    table.Append("
");
                    table.Append("" + rd[0] + "	");
                    table.Append("" + rd[1] + "	");
                    table.Append("" + rd[2] + "	");
                    table.Append("" + rd[3] + "	");
                    table.Append("View	");
                    table.Append("
");
                }
            }
            table.Append("
");
            PlaceHolder1.Controls.Add(new Literal { Text = table.ToString() });
            rd.Close();
        }
   }
}

Body:
you can achive that using jquery or javascript

for of all you need to add an id to view link like:

<td><a id='"+rd[0]+"' href=''>View</a></td>

then you need to put the below code in head. (if you are already using jquery the remove the jquery link)

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
        $('a').click(function () {
            debugger;
            var id = $(this).attr('id');
            var redirecttoAnotherPage = location.href + "?id=" + id;
            window.open(redirecttoAnotherPage);
            return false;
        });
        });
    </script>

do let me know in case you need any help


问:
gettimeofday and time() jumps on BeagleBone - timesyncd?
I have tasks that need to run at reasonably precise intervals in the range of one second.

I use gettimeofday() to establish start_usec. After task execution is done, it calls a timedSleep() function. timedSleep() invokes gettimeofday() to calculate sleep time in microseconds, increments the calling function's start_usec variable, then calls usleep().

It works perfectly, except that about once a minute it will 'skip' - the timedSleep function returns after one second (as close as I can tell), but gettimeofday returns a value that's three or four seconds ahead.

Here's a code snippet followed by some output. On the last line, time has moved forward by about four seconds, but the actual elapsed time was just a second.

The BeagleBone is running a Debian distro that uses timesyncd. Could that be causing this behavior?

```<code>struct timeval now;
gettimeofday(&now,NULL);
printf("Start: %02d %06d Now: %02d %06d... ",(int)((start_usec / 1000000) %100), (int)(start_usec % 1000000),  now.tv_sec %100, + now.tv_usec);

// Sleep for desired interval
shm.timedSleep(rule_id, &start_usec);

gettimeofday(&now,NULL);
printf("%02d %06d ",now.tv_sec %100, + now.tv_usec);
time(&curtime);
loctime = localtime(&curtime);
strftime(msgbuff, sizeof(msgbuff), "%Y-%m-%dT%H:%M:%S",loctime);
printf("%s\n",msgbuff);

Start: 78 117538 Now: 04 355933... 05 354979 2017-11-15T13:58:25
Start: 79 117538 Now: 05 355818... 06 354980 2017-11-15T13:58:26
Start: 80 117538 Now: 06 355816... 07 354981 2017-11-15T13:58:27
Start: 81 117538 Now: 07 355819... 08 354981 2017-11-15T13:58:28
Start: 82 117538 Now: 08 355819... 09 354979 2017-11-15T13:58:29
Start: 83 117538 Now: 09 355232... 10 354838 2017-11-15T13:58:30
Start: 84 117538 Now: 10 355776... 14 041276 2017-11-15T13:58:34
</code>```

This BeagleBone has an external RTC which seems to be fine:

```<code>root@vesta:/usr/local/vesta/bbb/src# timedatectl
      Local time: Wed 2017-11-15 14:24:06 EST
  Universal time: Wed 2017-11-15 19:24:06 UTC
        RTC time: Wed 2017-11-15 19:24:06
       Time zone: America/New_York (EST, -0500)
 Network time on: yes
NTP synchronized: no
 RTC in local TZ: no
</code>```

答: OK - it's timesyncd. The BeagleBone system clock is painfully slow, and timesyncd bumps it a few seconds every minute or so. Stopping timesyncd eliminates the problem. Now investigating ntp as an alternative. </p>

Body:
I have tasks that need to run at reasonably precise intervals in the range of one second.

I use gettimeofday() to establish start_usec. After task execution is done, it calls a timedSleep() function. timedSleep() invokes gettimeofday() to calculate sleep time in microseconds, increments the calling function's start_usec variable, then calls usleep().

It works perfectly, except that about once a minute it will 'skip' - the timedSleep function returns after one second (as close as I can tell), but gettimeofday returns a value that's three or four seconds ahead.

Here's a code snippet followed by some output. On the last line, time has moved forward by about four seconds, but the actual elapsed time was just a second.

The BeagleBone is running a Debian distro that uses timesyncd. Could that be causing this behavior?

struct timeval now;
gettimeofday(&now,NULL);
printf("Start: %02d %06d Now: %02d %06d... ",(int)((start_usec / 1000000) %100), (int)(start_usec % 1000000),  now.tv_sec %100, + now.tv_usec);

// Sleep for desired interval
shm.timedSleep(rule_id, &start_usec);

gettimeofday(&now,NULL);
printf("%02d %06d ",now.tv_sec %100, + now.tv_usec);
time(&curtime);
loctime = localtime(&curtime);
strftime(msgbuff, sizeof(msgbuff), "%Y-%m-%dT%H:%M:%S",loctime);
printf("%s\n",msgbuff);

Start: 78 117538 Now: 04 355933... 05 354979 2017-11-15T13:58:25
Start: 79 117538 Now: 05 355818... 06 354980 2017-11-15T13:58:26
Start: 80 117538 Now: 06 355816... 07 354981 2017-11-15T13:58:27
Start: 81 117538 Now: 07 355819... 08 354981 2017-11-15T13:58:28
Start: 82 117538 Now: 08 355819... 09 354979 2017-11-15T13:58:29
Start: 83 117538 Now: 09 355232... 10 354838 2017-11-15T13:58:30
Start: 84 117538 Now: 10 355776... 14 041276 2017-11-15T13:58:34

This BeagleBone has an external RTC which seems to be fine:

root@vesta:/usr/local/vesta/bbb/src# timedatectl
      Local time: Wed 2017-11-15 14:24:06 EST
  Universal time: Wed 2017-11-15 19:24:06 UTC
        RTC time: Wed 2017-11-15 19:24:06
       Time zone: America/New_York (EST, -0500)
 Network time on: yes
NTP synchronized: no
 RTC in local TZ: no


问:
Check if new starttime and endtime overlaps with starttime and endtime records in db using linq
I went through few answers and few match the solution I already have.

In my job scheduling app I want to check if a new added task overlaps with a task that is already in the db. The solution below gives me results for the basic scenarios but does not quite work for few. Like in case where endtime for a new task is the same as starttime of another.

e.g:

```<code>//this returns false as it should - no overlaps
New Task      : 14:00 - 15:00
Existing Task : 16:00 - 17:00

//this returns true, as existing taskstart is < new takend - 17:00 overlap
New Task      : 14:00 - 17:00
Existing Task : 16:00 - 17:00

//this scenario should return false
/*udpated*/the tasks do not overlap here but touch each other
New Task      : 14:00 - 16:00
Existing Task : 16:00 - 17:00

private bool CheckForOtherTasks(int UserId, DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    bool _bTasksExist = false;
    using (var _dbContext = new task_Entities())
    {
        _bTasksExist = (from t in _dbContext.Tasks
                        where t.UserId == UserId
                        where t.dtTaskStart < _dtTaskEnd && _dtTaskStart < t.dtTaskEnd
                        select t).Any();
    }

    return _bTasksExist;
}
</code>```

The above solution works fine until there new endtime == existing starttime or vice versa.

This solution seems to solve it but I am unsure how to implement it along with LINQ without iterating through all the records. How check intersection of DateTime periods

Would using LINQ for this task be a good approach or using a Stored Procedure to returns results be a better option?

Also, would a library such as https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET be ideal for a small project.

Cheers

答:
With the above test scenario, Initially the returned value was "True". After posting the question, I took a break and got back to start again and it gave me the results as expected.

It's 1:30 AM here is NZ and what I require before writing any more code is some sleep. The test that returned "False" had the endtime "17:00" which was from a previous debug session and the breakpoint was never cleared.

So the answer to my question is. Rest and then Test.

Body:
I went through few answers and few match the solution I already have.

In my job scheduling app I want to check if a new added task overlaps with a task that is already in the db. The solution below gives me results for the basic scenarios but does not quite work for few. Like in case where endtime for a new task is the same as starttime of another.

e.g:

//this returns false as it should - no overlaps
New Task      : 14:00 - 15:00
Existing Task : 16:00 - 17:00

//this returns true, as existing taskstart is < new takend - 17:00 overlap
New Task      : 14:00 - 17:00
Existing Task : 16:00 - 17:00

//this scenario should return false
/*udpated*/the tasks do not overlap here but touch each other
New Task      : 14:00 - 16:00
Existing Task : 16:00 - 17:00

private bool CheckForOtherTasks(int UserId, DateTime _dtTaskStart, DateTime _dtTaskEnd)
{
    bool _bTasksExist = false;
    using (var _dbContext = new task_Entities())
    {
        _bTasksExist = (from t in _dbContext.Tasks
                        where t.UserId == UserId
                        where t.dtTaskStart < _dtTaskEnd && _dtTaskStart < t.dtTaskEnd
                        select t).Any();
    }

    return _bTasksExist;
}

The above solution works fine until there new endtime == existing starttime or vice versa.

This solution seems to solve it but I am unsure how to implement it along with LINQ without iterating through all the records. How check intersection of DateTime periods

Would using LINQ for this task be a good approach or using a Stored Procedure to returns results be a better option?

Also, would a library such as https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET be ideal for a small project.

Cheers


问:
The spool command does not save all rows in sql plus
I'm using the spool command in sqlplus to generate a file with the rows of some queries.

First I assign an output format and secondly I do the spool to generate the output file, but it does not save all the rows.

```<code>set lines 100
set pages 1500
set colsep ';'
spool /home/bsoinst/users/example.txt
</code>```

select name,salary from employees (query example)

The original query generates 1433 rows, but in the file it only shows 1414

Thanks

答:
Spool writes to a file, but the output is buffered. If you spool from an interactive session as you've shown then until you either exit the session or end the spool with spool off (or starting another spool) anything you do is still being written to the file, via the buffer.

SQL*Plus continues to spool information to the file until you turn spooling off...

Until the buffer is full, it won't be flushed to the filesystem. So if you look at the file it will be incomplete.

If you do:

```<code>spool off
</code>```

then the remaining partial buffer will be flushed and the file will be closed, and will then be complete on the filesystem too. (You'll also now see anything you did between running the query and issuing that command, of course).

I believe the buffer size is operating-system/filesystem-dependent, and not something you can control from within SQL*Plus.

Body:
I'm using the spool command in sqlplus to generate a file with the rows of some queries.

First I assign an output format and secondly I do the spool to generate the output file, but it does not save all the rows.

set lines 100
set pages 1500
set colsep ';'
spool /home/bsoinst/users/example.txt

select name,salary from employees (query example)

The original query generates 1433 rows, but in the file it only shows 1414

Thanks

Body:
Spool writes to a file, but the output is buffered. If you spool from an interactive session as you've shown then until you either exit the session or end the spool with spool off (or starting another spool) anything you do is still being written to the file, via the buffer.

SQL*Plus continues to spool information to the file until you turn spooling off...

Until the buffer is full, it won't be flushed to the filesystem. So if you look at the file it will be incomplete.

If you do:

spool off

then the remaining partial buffer will be flushed and the file will be closed, and will then be complete on the filesystem too. (You'll also now see anything you did between running the query and issuing that command, of course).

I believe the buffer size is operating-system/filesystem-dependent, and not something you can control from within SQL*Plus.


问:
Android scroll whole screen instead of only listview
I have the following layout structure:

```<code>RelativeLayout
  -LinearLayout(Vertical)
  |  ...
  |  ...
  -LinearLayout(Vertical)
     ListView
</code>```

The ListView has a bunch of items set by an ArrayAdapter. Currently, only the ListView is scrollable, the first LinearLayout stays in its place. However, I want the whole screen to be scrollable, so if the user scrolls far enough, the ListView will potentially occupy the whole screen, if there are enough list items.

This image illustrates the desired behaviour (before and after scrolling)
The red box is the first LinearLayout, and the green box is the LinearLayout with the ListView

Thank you for your precious help!

答:
You can use a RecyclerView instead of a ListView, then you can wrap the list in a NestedScrollView and call ViewCompat.setNestedScrollingEnabled(recyclerView, false). On top you can use another ScrollView with all that content (red marked views in your graphic) and put that NestedScrollView (green marked list) as a child inside of it.

The NestedScrollView takes care of the dynamically set height, otherwise the recyclerView would only use one fixed height. Be aware that, if the list gets too long, it might have an unwanted UI lag, then it's more efficient to set everything as a part of the list in the adapter by inflating different layouts on the list. On the other side, this could be also a bit tricky since the whole layout is now a part of a list and all changes which are done to that needs to go through the adapter.

Body:
I have the following layout structure:

RelativeLayout
  -LinearLayout(Vertical)
  |  ...
  |  ...
  -LinearLayout(Vertical)
     ListView

The ListView has a bunch of items set by an ArrayAdapter. Currently, only the ListView is scrollable, the first LinearLayout stays in its place. However, I want the whole screen to be scrollable, so if the user scrolls far enough, the ListView will potentially occupy the whole screen, if there are enough list items.

This image illustrates the desired behaviour (before and after scrolling)
The red box is the first LinearLayout, and the green box is the LinearLayout with the ListView

Thank you for your precious help!


问:
Idea commit failure with hg

0 files committed, 1 file failed to commit: test transaction abort!
  rollback completed abort: decoding near 'ʷ��ͦ': 'utf8' codec can't
  decode byte 0xc0 in position 2: invalid start byte!

答: Could happen IDEA has passed the file name using wrong encoding. If it works fine from the command line, but fails from the IDEA, it is worth reporting it to https://youtrack.jetbrains.com/issues/IDEA</p>

Title: Idea commit failure with hg


问:
How to shuffle data in python keeping some n number of rows intact
I want to shuffle my data in such manner that each 4 rows remain intact. For example I have 16 rows then first 4 rows can go to last and then second four rows may go to third  and so on in any particular order. I am trying to do thins in python</p>

答:
Below code in python does the magic </p>

```<code>from random import shuffle
import numpy as np
from math import ceil

#creating sample dataset
d=[[i*4 +j for i in range(5)] for j in range(25)]
a = np.array(d, int)
print '--------------Input--------------'
print a

gl=4 #group length i.e number of rows needs to be intact
parts=ceil(1.0*len(a)/gl) #no of partitions based on grouplength for the given dataset

#creating partition list and shuffling it to use later
x = [i for i in range(int(parts))]
shuffle(x)

#Creates new dataset based on shuffled partition list
fg=x.pop(0)
f = a[gl*fg:gl*(fg+1)]
for i in x:
 t=a[gl*i:(i+1)*gl]
 f=np.concatenate((f, t), axis=0)
print '--------------Output--------------'
print f
</code>```

Body:
Below code in python does the magic

from random import shuffle
import numpy as np
from math import ceil

#creating sample dataset
d=[[i*4 +j for i in range(5)] for j in range(25)]
a = np.array(d, int)
print '--------------Input--------------'
print a

gl=4 #group length i.e number of rows needs to be intact
parts=ceil(1.0*len(a)/gl) #no of partitions based on grouplength for the given dataset

#creating partition list and shuffling it to use later
x = [i for i in range(int(parts))]
shuffle(x)

#Creates new dataset based on shuffled partition list
fg=x.pop(0)
f = a[gl*fg:gl*(fg+1)]
for i in x:
 t=a[gl*i:(i+1)*gl]
 f=np.concatenate((f, t), axis=0)
print '--------------Output--------------'
print f


问:
WebDriver chaining within a for loop only iterates the loop without executing the callback
I am writing Appium (v1.7.1) iOS automation tests where I am chaining a webdriver session and trying loop through the elements to fetch the data.

```<code>setFilterOptions: function (driver, loc) {
    var chain = driver;                  //I am assigning the driver to chain
    chain = chain
         .getFilterElementListCount()    //This gives me back the count for elements
         .then((count) => {
            console.log("Number of Filters - ",count);

            for(var i=1; i<=count; i++) {
              ((i) => {
                console.log("Value of i - ", i);
                //This gives me the label for each Cell->StaticText
                chain = chain
                      .getElAttribute('label',util.format('//XCUIElementTypeCell[%d]/XCUIElementTypeStaticText[1]', i), 'xpath')
                      .then((filterTitle, i) => {
                            console.log("Filter Title - ", filterTitle);
                            console.log("I value - ", i);
                      });
              })(i);
            }
         });
  return chain;
},

The Console o/p i am getting is -
Number of Filters -  3
Value of i -  1
Value of i -  2
Value of i -  3
</code>```

The loop iterates but doesn't execute the chain within the for loop. Is there a way for the chain to finish all callback execution before returning it.

答:
Your goal is to return a promise that will resolve once all the work performed in the loop is done. However, that's not what you are doing. Your problem is that you have this:

```<code>  chain = chain.//
                // Bunch of asynchronous operations, some of which assign
                // to the variable `chain`.
                //
  return chain;
</code>```

In order for your code to work, the asynchronous operations would have to assign to chain before the return statement executes. But this is not how asynchronous operations work. When you call any asynchronous method, you are only scheduling the asynchronous operation for future execution. It will execute at some point in the future, but definitely not immediately. In the code you have, you schedule an asynchronous operation and the immediately you return chain. The value of chain that you return cannot be a value that is set in your loop. Your loop has not executed yet.

You should do something like the following. The important thing is to create a chain of operations inside the loop and return that chain from the function you pass to .then so that the topmost promise resolves to the chain you create in your loop. This way, the promise you return from your method will have to wait for all inner operations to be done before being resolved.

```<code>setFilterOptions: function (driver, loc) {
    return driver
         .getFilterElementListCount()    //This gives me back the count for elements
         .then((count) => {
            var chain = Promise.resolve();
            console.log("Number of Filters - ",count);

            for(var i=1; i<=count; i++) {
              ((i) => {
                console.log("Value of i - ", i);
                //This gives me the label for each Cell->StaticText
                chain = chain
                      .getElAttribute('label',util.format('//XCUIElementTypeCell[%d]/XCUIElementTypeStaticText[1]', i), 'xpath')
                      .then((filterTitle, i) => {
                            console.log("Filter Title - ", filterTitle);
                            console.log("I value - ", i);
                      });
              })(i);
            }

            // Return your promise!
            return chain;
         });
},
</code>```

Also note that if you use let i instead of var i for your loop, you could get rid of that immediately invoked arrow function you have in your loop, which seems to be there only to ensure that the closures inside the loop get sequential values of i (instead of all executing with the last value of i).

Body:
I am writing Appium (v1.7.1) iOS automation tests where I am chaining a webdriver session and trying loop through the elements to fetch the data.

setFilterOptions: function (driver, loc) {
    var chain = driver;                  //I am assigning the driver to chain
    chain = chain
         .getFilterElementListCount()    //This gives me back the count for elements
         .then((count) => {
            console.log("Number of Filters - ",count);

            for(var i=1; i<=count; i++) {
              ((i) => {
                console.log("Value of i - ", i);
                //This gives me the label for each Cell->StaticText
                chain = chain
                      .getElAttribute('label',util.format('//XCUIElementTypeCell[%d]/XCUIElementTypeStaticText[1]', i), 'xpath')
                      .then((filterTitle, i) => {
                            console.log("Filter Title - ", filterTitle);
                            console.log("I value - ", i);
                      });
              })(i);
            }
         });
  return chain;
},

The Console o/p i am getting is -
Number of Filters -  3
Value of i -  1
Value of i -  2
Value of i -  3

The loop iterates but doesn't execute the chain within the for loop. Is there a way for the chain to finish all callback execution before returning it.

Body:
Your goal is to return a promise that will resolve once all the work performed in the loop is done. However, that's not what you are doing. Your problem is that you have this:

  chain = chain.//
                // Bunch of asynchronous operations, some of which assign
                // to the variable `chain`.
                //
  return chain;

In order for your code to work, the asynchronous operations would have to assign to chain before the return statement executes. But this is not how asynchronous operations work. When you call any asynchronous method, you are only scheduling the asynchronous operation for future execution. It will execute at some point in the future, but definitely not immediately. In the code you have, you schedule an asynchronous operation and the immediately you return chain. The value of chain that you return cannot be a value that is set in your loop. Your loop has not executed yet.

You should do something like the following. The important thing is to create a chain of operations inside the loop and return that chain from the function you pass to .then so that the topmost promise resolves to the chain you create in your loop. This way, the promise you return from your method will have to wait for all inner operations to be done before being resolved.

setFilterOptions: function (driver, loc) {
    return driver
         .getFilterElementListCount()    //This gives me back the count for elements
         .then((count) => {
            var chain = Promise.resolve();
            console.log("Number of Filters - ",count);

            for(var i=1; i<=count; i++) {
              ((i) => {
                console.log("Value of i - ", i);
                //This gives me the label for each Cell->StaticText
                chain = chain
                      .getElAttribute('label',util.format('//XCUIElementTypeCell[%d]/XCUIElementTypeStaticText[1]', i), 'xpath')
                      .then((filterTitle, i) => {
                            console.log("Filter Title - ", filterTitle);
                            console.log("I value - ", i);
                      });
              })(i);
            }

            // Return your promise!
            return chain;
         });
},

Also note that if you use let i instead of var i for your loop, you could get rid of that immediately invoked arrow function you have in your loop, which seems to be there only to ensure that the closures inside the loop get sequential values of i (instead of all executing with the last value of i).


问:
Access website using server name instead of www
I am new to IIS, setting up servers and load balancer so please do not mind my ignorance.

I have an old website, say, www.mywebsite.com.

There are 3 IIS 6.1 web servers on which my ASP.NET code is hosted.

Lets call them web01, web02 and web03.

They are identical in configuration like OS, etc.

There is a load balancer which handles the requests coming in from the clients through www and routes it to the respective server based on whatever algorithm is put in place.

However, we were able to send requests directly to individual servers like this web01.mywebsite.com for all 3 servers.

I do not have access to the load balancer.

Recently there were some problems with the web02 server so the client took it out from the load balancer.

We then reinstalled IIS and now, when we are trying to access the server using web02.mywebsite.com, it is throwing 404 - Not Found error.

I am able to open the website from inside the server using www.mywebsite.com and I am able to see that the requests is catered by the web02 server.

However, from inside the server also web02.mywebsite.com is throwing 404 - Not Found error.

I am sure I am missing something in configuration at the IIS level but not able to figure out.

I tried searching on the internet but they all gave me generic solutions.

Please help.

Thanks in advance!

答:
I was able to get this resolved on my own.

Strangely there was not a single answer or comment to this question.

I will try to answer so that others might also benefit.

There were 2 things that were required, out of which 1 was already present in my case:

In the hosts file, the mapping of IP address of the server to the actual name of the server should be present (This was there in my case)

In IIS, under bindings, I removed the host name i.e. www.mywebsite.com.

I was able to figure this through the posts here and here although they did not give the answer directly.

Hope this helps others.


问:
Websockets service crashes after unexpected closing connections
I have an Asp.Net MVC backend and a mobile application (cordova).
I added a websockets service to backend using this library as starting point.

Websockets service crashes if client disconnects very often without normal closing connection (just close application). Usually three times enough for reproducing.

I added try-catch block to this function and it works fine for one unexpectedly closed connection.

After reproducing service responses "503 Service Unavailable" some times, after that works fine.

I added try-catch to all functions and use ILooger object in catch block for logging but I don't see errors in logs and on Azure portal.

Any ideas?

答: I moved a websockets code to a separate app service and it works fine. I use sevice bus for communication between a general service and the websockets service.</p>


问:
how to fetch records based upon the order of rows of a column
So I am having below table /colums

Table A

```<code>filedName  newValue   OldValue
name        a           b
email       x           y
contactNo   123         432
name        aa          bb
email       xx          yy
contactNo   1234        4324
</code>```

I want the data based upon the name ,contact and email basis like the date should come like below

```<code>name --a
contact -123
email-x
name ---aa
contact--1234
email--xx
</code>```

This is basically the order of rows for the column field name.
Anyone please advice.

FYI:I had joined this table with few more table as well.

答:
I think this does what you want, if error let me know, not on a pc</p>

```<code>Select *
From
(
    Select filedvalue, newvalue, oldvalue,
    row_number() over (partition by filedname order by newvalue) r ,
   Case filedvalue
        When 'name' then 1
        When 'Contactno' then 2
        When 'Email' then 3
        Else 9999
   End ordby
   From table
) x
Order by r,ordby
</code>```

Body:
So I am having below table /colums

Table A

filedName  newValue   OldValue
name        a           b
email       x           y
contactNo   123         432
name        aa          bb
email       xx          yy
contactNo   1234        4324

I want the data based upon the name ,contact and email basis like the date should come like below

name --a
contact -123
email-x
name ---aa
contact--1234
email--xx

This is basically the order of rows for the column field name.
Anyone please advice.

FYI:I had joined this table with few more table as well.

Body:
I think this does what you want, if error let me know, not on a pc

Select *
From
(
    Select filedvalue, newvalue, oldvalue,
    row_number() over (partition by filedname order by newvalue) r ,
   Case filedvalue
        When 'name' then 1
        When 'Contactno' then 2
        When 'Email' then 3
        Else 9999
   End ordby
   From table
) x
Order by r,ordby


问:
copy uiimageview origin to CGPoint
I am new to iPhone/Objective-C programming. I have a UIImageView *myImage whose x,y,width,height are set using CGRect with values (20,20,100,100) or whatever;

Q1) When I do the following why can't i fetch the origin values into CGPoint.

```<code>CGPoint myPoint = myImage.frame.origin;

NSLog(@"X:%f Y:%f",mypoint.x, mypoint.y) // Prints X: 0.0 and Y: 0.0 instead of X:20.0 and Y: 20.o
NSLog(@"X:%f Y:%f",myImage.frame.origin.x, myImage.frame.origin.x) // Prints X: 20.0 and Y: 20.0
</code>```

The above NSLog statements do not print the expected values for myPoint but prints the right values for myImage.frame.origin. Why?

Q2) Also why can't I set @property to CGPoint ?

答:
1) Have you tried :

```<code>CGPoint myPoint = CGPointMake(myImage.fram.origin.x, myImage.frame.origin.y);
</code>```

2) After som testing I have found that you should be able to have your CGPoint as a property like this:

```<code>@interface MyClass : NSObject {

CGPoint myPoint;
...
}
@property (nonatomic) CGPoint myPoint;

...
@end
</code>```

And then:

```<code>@implementation MyClass
@synthesize myPoint;

...

@end
</code>```

that worked for me.

(I must admit I have not yet understood the (nonatomic) and if it is necessary but as long as it works...)

Title: copy uiimageview origin to CGPoint

Body:
I am new to iPhone/Objective-C programming. I have a UIImageView *myImage whose x,y,width,height are set using CGRect with values (20,20,100,100) or whatever;

Q1) When I do the following why can't i fetch the origin values into CGPoint.

CGPoint myPoint = myImage.frame.origin;

NSLog(@"X:%f Y:%f",mypoint.x, mypoint.y) // Prints X: 0.0 and Y: 0.0 instead of X:20.0 and Y: 20.o
NSLog(@"X:%f Y:%f",myImage.frame.origin.x, myImage.frame.origin.x) // Prints X: 20.0 and Y: 20.0

The above NSLog statements do not print the expected values for myPoint but prints the right values for myImage.frame.origin. Why?

Q2) Also why can't I set @property to CGPoint ?

Body:
1) Have you tried :

CGPoint myPoint = CGPointMake(myImage.fram.origin.x, myImage.frame.origin.y);

2) After som testing I have found that you should be able to have your CGPoint as a property like this:

@interface MyClass : NSObject {

CGPoint myPoint;
...
}
@property (nonatomic) CGPoint myPoint;

...
@end

And then:

@implementation MyClass
@synthesize myPoint;

...

@end

that worked for me.

(I must admit I have not yet understood the (nonatomic) and if it is necessary but as long as it works...)


问:
Trigger Select event
I'm using my code to fetch data from a server and show it with inputs and labels.

My only problem is that, when I enter the page the select change is not triggered therefore I don't get any data. The only way to make it work is select another option and select the same again so the change event is triggered. $('#selectMRPC').trigger('change'); doesn't help.

How can I make my selectorMRPC() and $('#selectMRPC').change be executed when the page loads?

$(document).ready(function () {

    selectorMRPC();
    $('#selectMRPC').trigger('change');

    $('#selectMRPC').change(function () {
        //fetch data
        var mrpc = $(this).find('option:selected').data('mrpc');

        $('#paramBody').empty();
        for (var i = 1; i <= 10; i++) {
            var field = mrpc["field" + i];
            if (field !== undefined) {
                var parsedField = field.split('_');
                var value = parsedField[0];
                var type = parsedField[1];

                switch (type) {
                    case  "S":
                        type = "text";
                        if (value === '""')
                            value = null;
                        break;
                    case "B":
                        type = "checkbox";
                        break;
                    case "N":
                        type = "number";
                        value = parseInt(value);
                        break;
                    case "D":
                        type = "number";
                        value = parseInt(value);
                        if (value === '""')
                            value = null;
                        break;
                }
                //else use checkbox
                if(type === "checkbox")
                {
                    $('#paramBody').append('
' + i + '	' + type + '
' +
                        '<input class="text-center" id="field'+i+'" name="Fields" type="checkbox" value="' +value + '">

');
                }
                else
                {
                    $('#paramBody').append('
' + i + '	' + type + '	<input class="text-center" name="Fields" type="' + type + '" value="' +value + '">
');
                }
            }
        }
    });

    function selectorMRPC() {
        $.ajax({
            type: 'post',
            url: 'IndividualSimulator',
            success: function (result) {
                $('#selectMRPC').empty();
                JSON.parse(result).forEach(function (mrpc) {
                    var option = $('<option>', {
                        value: mrpc.name,
                        text: mrpc.name
                    });

                    //Persist data with option
                    option.data('mrpc', mrpc);

                    $('#selectMRPC').append(option);
                });
            },
            error: function () {

            }
        });
        return false;
    }
});```

答:
How can I make my selectorMRPC() and $('#selectMRPC').change be
  executed when the page loads?

From your code and comments, following seems to be the sequence

selectorMRPC() creates data-mrpc attribute for the option

When the change event triggers, it looks for data-mrpc attribute

But you seem to trigger change event before AJAX success happens

Make it as following

```<code>$(document).ready(function() {
  selectorMRPC(); //notice that only this method is invoked
});

function selectorMRPC() {
  $.ajax({
    type: 'post',
    url: 'IndividualSimulator',
    success: function(result) {
      $('#selectMRPC').empty();
      JSON.parse(result).forEach(function(mrpc) {
        var option = $('<option>', {
          value: mrpc.name,
          text: mrpc.name
        });
        //Persist data with option
        option.data('mrpc', mrpc);

        $('#selectMRPC').append(option);
      });
      $('#selectMRPC').change(function() {
        //fetch data
        var mrpc = $(this).find('option:selected').data('mrpc');
        //rest of the code removed for simplification
      });
      $('#selectMRPC').trigger('change');

    },
    error: function() {

    }
  });
  //return false; this line doesn't make sense
}
</code>```

Title: Trigger Select event

Body:
How can I make my selectorMRPC() and $('#selectMRPC').change be
  executed when the page loads?

From your code and comments, following seems to be the sequence

selectorMRPC() creates data-mrpc attribute for the option

When the change event triggers, it looks for data-mrpc attribute

But you seem to trigger change event before AJAX success happens

Make it as following

$(document).ready(function() {
  selectorMRPC(); //notice that only this method is invoked
});

function selectorMRPC() {
  $.ajax({
    type: 'post',
    url: 'IndividualSimulator',
    success: function(result) {
      $('#selectMRPC').empty();
      JSON.parse(result).forEach(function(mrpc) {
        var option = $('<option>', {
          value: mrpc.name,
          text: mrpc.name
        });
        //Persist data with option
        option.data('mrpc', mrpc);

        $('#selectMRPC').append(option);
      });
      $('#selectMRPC').change(function() {
        //fetch data
        var mrpc = $(this).find('option:selected').data('mrpc');
        //rest of the code removed for simplification
      });
      $('#selectMRPC').trigger('change');

    },
    error: function() {

    }
  });
  //return false; this line doesn't make sense
}


问:
Find cell by value with google api v4 (google sheets)
can I find cell by value using google api v4 ?, in my task I want change background color if cell_value == my_value.

I know only one variant it`s:

using gspread I can find cell coordinates

using google api v4 I can change background color

but I want to use only google api v4, because find cell by value using gspread very slowly.

答:
this is how the JSON should look like:

```<code>{
  "find": string,
  "replacement": string,
  "matchCase": boolean,
  "matchEntireCell": boolean,
  "searchByRegex": boolean,
  "includeFormulas": boolean,

  // Union field scope can be only one of the following:
  "range": {
    object(GridRange)
  },
  "sheetId": number,
  "allSheets": boolean,
  // End of list of possible types for union field scope.
}
</code>```

select just one of the scope options (range, sheetID or allSheets).

Body:
this is how the JSON should look like:

{
  "find": string,
  "replacement": string,
  "matchCase": boolean,
  "matchEntireCell": boolean,
  "searchByRegex": boolean,
  "includeFormulas": boolean,

  // Union field scope can be only one of the following:
  "range": {
    object(GridRange)
  },
  "sheetId": number,
  "allSheets": boolean,
  // End of list of possible types for union field scope.
}

select just one of the scope options (range, sheetID or allSheets).


问:
How do I sort a list of words by their letter endings?
How do I sort a list of strings by the last two characters

Input:

```<code> ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']
</code>```

Output:

```<code>**aa
**ab
**ac
**ad
**ae
**af
**ag
**ah
**ai
**aj
**ak
**al
**am
**an
**ao
**ap
**aq
**ar
**as
**at
**au
**av
**aw
**ax
**ay
**az
etc...
**ba
**ca
**da
**ea
**fa
**ga
etc...
</code>```

答:
Use a function that takes a string and returns the last two character substring as the key in sort function.

```<code>data.sort(key= lambda x : x[-2:])
</code>```

Body:
How do I sort a list of strings by the last two characters

Input:

 ['abby', 'acts', 'aden', 'afro', 'agni', 'agra', 'aida', 'ainu', 'alba', 'aldo', 'alec', 'alex', 'alma', 'alpo', 'alps', 'alta', 'alva', 'amie', 'amos']

Output:

**aa
**ab
**ac
**ad
**ae
**af
**ag
**ah
**ai
**aj
**ak
**al
**am
**an
**ao
**ap
**aq
**ar
**as
**at
**au
**av
**aw
**ax
**ay
**az
etc...
**ba
**ca
**da
**ea
**fa
**ga
etc...

Body:
Use a function that takes a string and returns the last two character substring as the key in sort function.

data.sort(key= lambda x : x[-2:])


问:
background-position percentage not working
Everywhere I read says this should be working fine, but for some reason it's not.

This was to fix someone else's issue so fixing it doesn't matter to me, I just want to know why. The problem is on .br .bg-image. I know I'm trying to use calc() but using a simple background-position: 50% doesn't work either.

http://jsfiddle.net/uLaa9fnu/2/

html {
  height: 100%;
  width: 100%;
}
body {
  margin: 0px;
  height: 100%;
  width: 100%;
  overflow: hidden;
}
.bg-image {
  height: 600px;
  width: 800px;
  background-image: url('http://media1.santabanta.com/full1/Outdoors/Landscapes/landscapes-267a.jpg');
  background-size: 100%;
  background-repeat: no-repeat;
}
.relative {
  position: relative;
}
.containeroverlay {
  background-color: rgba(0, 0, 0, 0.6);
  height: 100%;
  width: 100%;
}
.framesizer {
  height: 340px;
  width: 300px;
  overflow: hidden;
  position: absolute;
}
.frame {
  background-image: url('http://i.imgur.com/4AcIXsD.png');
  background-repeat: no-repeat;
  background-size: 100%;
  height: 340px;
  width: 300px;
}
.tl {
  top: 30px;
  left: 30px;
}
.tl .bg-image {
  background-position: right 30px bottom 30px;
}
.br {
  top: calc(100% - 340px - 30px);
  /* Height of frame, plus 30px spacing */
  left: calc(100% - 300px - 30px);
  /* Width of frame, plus 30px spacing */
}
.br .bg-image {
  background-position: right calc(800px - 300px - 30px) bottom calc(600px - 340px - 30px);
  /* Background Position doesn't like percentages for some reason */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bg-image">
  <div class="containeroverlay relative">
    <div class="framesizer tl">
      <div class="bg-image">
        <div class="frame"></div>
      </div>
    </div>
    <div class="framesizer br">
      <div class="bg-image">
        <div class="frame"></div>
      </div>
    </div>
  </div>
</div></code>```

答:
background-position

Initial value  0% 0%

refer to the size of the background positioning area minus size of
  background image; size refers to the width for horizontal offsets and
  to the height for vertical offsets

So any differences on the size of the background image and the size of the element
are welcome and that what makes background positioning work with percentages. Otherwise they don't.

Example:

Consider an image with a size of 500X500 px;

Using a background-position: 50% 50%;

If your div has a width of 600px;

your background image will be shifted to the right by

50% * (600px - 500px) that is 50px

Similarly, if the div has a height of 700px your background image will be shifted down by

50% * (700px - 500px) that is 100px

div{
    background-image: url(https://i.imgur.com/gcnJ2Qi.png);
    background-repeat: no-repeat;
    background-position: 50% 50%;
    border: solid grey;
    width: 600px;
    height:700px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

In case the div is narrower than the image

Now you're div element is 300X400 px,and you want to position your background image the same as before (50px right and 100px down)

You will need to specify a negative background-position: -25% -100%;

Because -25% * (300-500) = 50px and -100% (400-500) = 100px

div{
    background-image: url(https://i.imgur.com/gcnJ2Qi.png);
    background-repeat: no-repeat;
    background-position: -25% -100%;
    border: solid grey;
    width: 300px;
    height:400px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

In the case where both div and image have the same size:

Any percentage you specify at background-position would be multiplied by zero.
And the image will be always aligned with the top left corner of the div. To fix that make the image smaller or bigger by resetting background-size:80% or 120%;

div{
    background-image: url(https://i.imgur.com/gcnJ2Qi.png);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    border: solid grey;
    width: 500px;
    height:500px;
    background-size:80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

The docs

Body:
background-position

Initial value  0% 0%

refer to the size of the background positioning area minus size of
  background image; size refers to the width for horizontal offsets and
  to the height for vertical offsets

So any differences on the size of the background image and the size of the element
are welcome and that what makes background positioning work with percentages. Otherwise they don't.

Example:

Consider an image with a size of 500X500 px;

Using a background-position: 50% 50%;

If your div has a width of 600px;

your background image will be shifted to the right by

50% * (600px - 500px) that is 50px

Similarly, if the div has a height of 700px your background image will be shifted down by

50% * (700px - 500px) that is 100px

div{
    background-image: url(https://i.imgur.com/gcnJ2Qi.png);
    background-repeat: no-repeat;
    background-position: 50% 50%;
    border: solid grey;
    width: 600px;
    height:700px;
}

<div></div>

In case the div is narrower than the image

Now you're div element is 300X400 px,and you want to position your background image the same as before (50px right and 100px down)

You will need to specify a negative background-position: -25% -100%;

Because -25% * (300-500) = 50px and -100% (400-500) = 100px

div{
    background-image: url(https://i.imgur.com/gcnJ2Qi.png);
    background-repeat: no-repeat;
    background-position: -25% -100%;
    border: solid grey;
    width: 300px;
    height:400px;
}

<div></div>

In the case where both div and image have the same size:

Any percentage you specify at background-position would be multiplied by zero.
And the image will be always aligned with the top left corner of the div. To fix that make the image smaller or bigger by resetting background-size:80% or 120%;

div{
    background-image: url(https://i.imgur.com/gcnJ2Qi.png);
    background-repeat: no-repeat;
    background-position: 50% 100%;
    border: solid grey;
    width: 500px;
    height:500px;
    background-size:80%;
}

<div></div>

The docs


问:
Making inner html content jump down instead of outer one
I have days of the week, and timestamps which can be in any number

When timestamps number increases or we shrink the browser, the expected behavior is to make timestamps jump down like this

However, the behavior is like this

Here is my simplified HTML codes for one day; Monday

```<code><div class="form-group">
    <button class="btn btn-secondary days">
         Monday
         <span class="sprite-1-arrow-black-right"></span>
     </button>
     <div class="timestamps">
         <div class="timestamp">
             00:00 am - 00:00 pm
          </div>
          <div class="timestamp">
            00:00 am - 00:00 pm
           </div>
     </div>
 </div>
</code>```

in simplified css/sass

```<code>.days {
        display: inline-block;
}
.timestamps {
       display:inline-block;
}
.timestamp {
       display: inline-block;
}
</code>```

I think, there should be flex solution, but I don't know how!

答:
Why do you want to use flex ?
The flow of the document is the naturaly going from top to bottom for blocks.

The solution is not to write more styles but less code:

```<code>.days {
  display: inline-block;
}
.timestamps {
  display: inline-block;
  vertical-align: top;
}
</code>```

https://codepen.io/anon/pen/gXGBZO

Writing unecessary code should always be avoided: it makes your project less maintanable, harder to understand and can also hinder performance (using complex layout can augment your reflow/repaint time)

Body:
I have days of the week, and timestamps which can be in any number

When timestamps number increases or we shrink the browser, the expected behavior is to make timestamps jump down like this

However, the behavior is like this

Here is my simplified HTML codes for one day; Monday

    <button class="btn btn-secondary days">
         Monday

     </button>

             00:00 am - 00:00 pm

            00:00 am - 00:00 pm

in simplified css/sass

.days {
        display: inline-block;
}
.timestamps {
       display:inline-block;
}
.timestamp {
       display: inline-block;
}

I think, there should be flex solution, but I don't know how!

Body:
Why do you want to use flex ?
The flow of the document is the naturaly going from top to bottom for blocks.

The solution is not to write more styles but less code:

.days {
  display: inline-block;
}
.timestamps {
  display: inline-block;
  vertical-align: top;
}

https://codepen.io/anon/pen/gXGBZO

Writing unecessary code should always be avoided: it makes your project less maintanable, harder to understand and can also hinder performance (using complex layout can augment your reflow/repaint time)


问:
How to make a field that is an entity as hidden in the form with SonataAdmin?
I need to add entity field as a hidden in my form
In the admin form with sonata I have:

```<code>protected function configureFormFields(FormMapper $formMapper)
    {
        if ($this->getRoot()->getSubject()->getId()) {
            $formMapper
                ->add('driverNight', 'hidden', array(), array('admin_code' => 'cab.admin.driver'))
            ->add('monday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Monday', 'value' => '0'))
            ->add('tuesday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Tuesday', 'value' => '0'))
            ->add('wednesday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Wednesday', 'value' => '0'))
            ->add('thursday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Thursday', 'value' => '0'))
            ->add('friday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Friday', 'value' => '0'))
            ->add('saturday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Saturday', 'value' => '0'))
            ->add('sunday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Sunday', 'value' => '0'))

}
</code>```

Actually, no value in the input (see the inspect image)

How to make the driverNight field as hidden knowing that it is of type entity?

答:
You could use a data transformer as detailed here: data transformer

I suggest that you create a transformer class which transforms the entity to an int in the view layer and reverses from int to entity in the model layer and the use the addModelTransformer method in your config form.

Create the model Transformer class which implements Symfony\Component\Form\DataTransformerInterface and contains 2 methods transform and reverseTransform. This class could be constructed by passing 2 arguments: Entity manager and the user entity object that will be transformed to int.

.

```<code>class DriverToIntTransformer implements DataTransformerInterface {
private $manager;
private $driver;

public function __construct(ObjectManager $manager, $oUser)
{
    $this->manager = $manager;
    $this->driver = $oUser;
}
public function transform($user)
{
    if (null === $user) {
        return $this->driver->getId();
    }
    return $user->getId();
}
public function reverseTransform($driverNumber)
{
    if (!$driverNumber) {
        return;
    }
    $oDriver = $this->manager
        ->getRepository('YourUserBundle:User')
        // query for the driver with this id
        ->find($driverNumber);
    if (null === $oDriver) {
        throw new TransformationFailedException(sprintf(
            'An user with number "%s" does not exist!',
            $driverNumber
        ));
    }
    return $oDriver;
}
</code>```

2 call the transform method:

```<code>if ($this->getRoot()->getSubject()->getId()) {
        $driver = $this->getRoot()->getSubject()->getId();
$em = $this->container->get('doctrine.orm.entity_manager');
        $oDriver = $em->getRepository('YourUserBundle:User')->find($driver);
        $formMapper
            ->add('driverNight', 'hidden', array(), array('admin_code' => 'cab.admin.driver'));
        $formBuilder = $formMapper->getFormBuilder();
        $formBuilder->get('driverNight')->addModelTransformer(new DriverToIntTransformer($em, $oDriver));

    $formMapper
        ->add('monday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Monday', 'value' => '0'));//.....
}
</code>```

Body:
I need to add entity field as a hidden in my form
In the admin form with sonata I have:

protected function configureFormFields(FormMapper $formMapper)
    {
        if ($this->getRoot()->getSubject()->getId()) {
            $formMapper
                ->add('driverNight', 'hidden', array(), array('admin_code' => 'cab.admin.driver'))
            ->add('monday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Monday', 'value' => '0'))
            ->add('tuesday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Tuesday', 'value' => '0'))
            ->add('wednesday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Wednesday', 'value' => '0'))
            ->add('thursday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Thursday', 'value' => '0'))
            ->add('friday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Friday', 'value' => '0'))
            ->add('saturday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Saturday', 'value' => '0'))
            ->add('sunday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Sunday', 'value' => '0'))

}

Actually, no value in the input (see the inspect image)

How to make the driverNight field as hidden knowing that it is of type entity?

Body:
You could use a data transformer as detailed here: data transformer

I suggest that you create a transformer class which transforms the entity to an int in the view layer and reverses from int to entity in the model layer and the use the addModelTransformer method in your config form.

Create the model Transformer class which implements Symfony\Component\Form\DataTransformerInterface and contains 2 methods transform and reverseTransform. This class could be constructed by passing 2 arguments: Entity manager and the user entity object that will be transformed to int.

.

class DriverToIntTransformer implements DataTransformerInterface {
private $manager;
private $driver;

public function __construct(ObjectManager $manager, $oUser)
{
    $this->manager = $manager;
    $this->driver = $oUser;
}
public function transform($user)
{
    if (null === $user) {
        return $this->driver->getId();
    }
    return $user->getId();
}
public function reverseTransform($driverNumber)
{
    if (!$driverNumber) {
        return;
    }
    $oDriver = $this->manager
        ->getRepository('YourUserBundle:User')
        // query for the driver with this id
        ->find($driverNumber);
    if (null === $oDriver) {
        throw new TransformationFailedException(sprintf(
            'An user with number "%s" does not exist!',
            $driverNumber
        ));
    }
    return $oDriver;
}

2 call the transform method:

if ($this->getRoot()->getSubject()->getId()) {
        $driver = $this->getRoot()->getSubject()->getId();
$em = $this->container->get('doctrine.orm.entity_manager');
        $oDriver = $em->getRepository('YourUserBundle:User')->find($driver);
        $formMapper
            ->add('driverNight', 'hidden', array(), array('admin_code' => 'cab.admin.driver'));
        $formBuilder = $formMapper->getFormBuilder();
        $formBuilder->get('driverNight')->addModelTransformer(new DriverToIntTransformer($em, $oDriver));

    $formMapper
        ->add('monday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Monday', 'value' => '0'));//.....
}