问:
How can I scale font size based on android displayMetrics?
I'm writing an app to show a simple digital clock in Android and I need to scale the font size of the TextView so that it fills the screen as much as possible. I found a quite simple way to scale text size using displayMetrics but it doesn't work correctly on some devices.
What I want to achieve looks like this:

I would work only in landscape mode, and I would like it to run on my old smartphones and tablets lying around as well as on newer devices. So I have a variety of screen types to cater to.

To scale the font I do the following

```<code>    ...
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_clock);

    // Get screen size and calculate text size needed to fit
    // TODO: doesn't work well on some devices
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    DisplayMetrics displayMetrics = new DisplayMetrics(); // From: https://stackoverflow.com/questions/4743116/get-screen-width-and-height
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    // The screen height and width are recalculated automatically by Android when the screen is redrawn on a rotation
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;
    textSP = width / 12; // Empirical value
    String hString = Integer.toString(height);
    String wString = Integer.toString(width);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            // Display time of day
            Date curDate = new Date();
            TextView tvTime = findViewById(R.id.clockView);
            String timeStr = format.format(curDate);

            tvTime.setText(timeStr);
            tvTime.setScaleY(1.5f);
            tvTime.setWidth(width * 8 / 10); // Make it fill 80% of the screen
            tvTime.setHeight(height * 8 / 10);
            tvTime.setTextSize(textSP);
            ...
</code>```

The quid is with the line:

```<code>textSP = width / 12; // Empirical value
</code>```

For some screens a value of 6 works well. For other screens this creates a font so big that only a small part is visible. Changing this value to 12 does the trick.

It seems that I'm missing something related to the density of the screen, but what?

Thanks!

FINAL RESULT: For anyone trying to scale text like me, here's the final code after input from ismail:

The activity_main.xml file:

```<code>?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/tvClockFace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="6dp"
    android:text="12:34"
    android:textColor="@android:color/holo_red_dark"
    android:textSize="30sp"
    android:textStyle="bold"
    android:typeface="monospace"
    app:fontFamily="monospace"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvScreenSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="H:... W:..."
    android:textSize="14sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

And the MainActivity.java:

```<code>package com.schalkx.testautosizeclockdisplay;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

    // Scale the textsize automatically
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics ();
    display.getMetrics(outMetrics);

    float density  = getResources().getDisplayMetrics().density;
    float dpHeight = outMetrics.heightPixels / density;
    float dpWidth  = outMetrics.widthPixels / density;

    // Convert height and width to integer values
    float fTextSize = dpWidth/4; // Trial and error
    // int iTextSize = Math.round(fTextSize);
    int scrHeight = Math.round(dpHeight);
    int scrWidth = Math.round(dpWidth);

    // Display de height and width on screen (for reference)
    String wString = Integer.toString(scrWidth); // In case you need the width
    String hString = Integer.toString(scrHeight); // Same for height
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    // Scale the font of the clock face
    TextView tvClockFace = findViewById(R.id.tvClockFace);
    // tvClockFace.setHeight(50);
    // tvClockFace.setWidth(100);
    tvClockFace.setTextSize(fTextSize);
    tvClockFace.setScaleY(1.5f);
    }
}
</code>```

答:
For a better display experience you should work with dp instead of px , here how to get dp size :

```<code>Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;
</code>```

so now you can set your text size accordingly to the screen dpHeight and dpWidht

Body:
I'm writing an app to show a simple digital clock in Android and I need to scale the font size of the TextView so that it fills the screen as much as possible. I found a quite simple way to scale text size using displayMetrics but it doesn't work correctly on some devices.
What I want to achieve looks like this:

I would work only in landscape mode, and I would like it to run on my old smartphones and tablets lying around as well as on newer devices. So I have a variety of screen types to cater to.

To scale the font I do the following

    ...
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_clock);

    // Get screen size and calculate text size needed to fit
    // TODO: doesn't work well on some devices
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    DisplayMetrics displayMetrics = new DisplayMetrics(); // From: https://stackoverflow.com/questions/4743116/get-screen-width-and-height
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    // The screen height and width are recalculated automatically by Android when the screen is redrawn on a rotation
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;
    textSP = width / 12; // Empirical value
    String hString = Integer.toString(height);
    String wString = Integer.toString(width);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            // Display time of day
            Date curDate = new Date();
            TextView tvTime = findViewById(R.id.clockView);
            String timeStr = format.format(curDate);

            tvTime.setText(timeStr);
            tvTime.setScaleY(1.5f);
            tvTime.setWidth(width * 8 / 10); // Make it fill 80% of the screen
            tvTime.setHeight(height * 8 / 10);
            tvTime.setTextSize(textSP);
            ...

The quid is with the line:

textSP = width / 12; // Empirical value

For some screens a value of 6 works well. For other screens this creates a font so big that only a small part is visible. Changing this value to 12 does the trick.

It seems that I'm missing something related to the density of the screen, but what?

Thanks!

FINAL RESULT: For anyone trying to scale text like me, here's the final code after input from ismail:

The activity_main.xml file:

?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/tvClockFace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="6dp"
    android:text="12:34"
    android:textColor="@android:color/holo_red_dark"
    android:textSize="30sp"
    android:textStyle="bold"
    android:typeface="monospace"
    app:fontFamily="monospace"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvScreenSize"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    android:text="H:... W:..."
    android:textSize="14sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

And the MainActivity.java:

package com.schalkx.testautosizeclockdisplay;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

    // Scale the textsize automatically
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics ();
    display.getMetrics(outMetrics);

    float density  = getResources().getDisplayMetrics().density;
    float dpHeight = outMetrics.heightPixels / density;
    float dpWidth  = outMetrics.widthPixels / density;

    // Convert height and width to integer values
    float fTextSize = dpWidth/4; // Trial and error
    // int iTextSize = Math.round(fTextSize);
    int scrHeight = Math.round(dpHeight);
    int scrWidth = Math.round(dpWidth);

    // Display de height and width on screen (for reference)
    String wString = Integer.toString(scrWidth); // In case you need the width
    String hString = Integer.toString(scrHeight); // Same for height
    TextView tvScreenSize = findViewById(R.id.tvScreenSize);
    tvScreenSize.setText("h: " + hString + "  w:" + wString);

    // Scale the font of the clock face
    TextView tvClockFace = findViewById(R.id.tvClockFace);
    // tvClockFace.setHeight(50);
    // tvClockFace.setWidth(100);
    tvClockFace.setTextSize(fTextSize);
    tvClockFace.setScaleY(1.5f);
    }
}

Body:
For a better display experience you should work with dp instead of px , here how to get dp size :

Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

so now you can set your text size accordingly to the screen dpHeight and dpWidht


来源: stackexchange

问:
How to change colors of a Sharepoint list which is embedded in a section of a Sharepoint website
I managed to format my Sharepoint list so that every second row is colored in the theme color. As soon as I embed the list as a section on a Sharepoint website the color is gone. How do I fix this?! I'm clueless. Any tips are highly appreciated.  </p>

<p>{
  "schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
  "additionalRowClass": "=if(@rowIndex%2==0,'ms-bgColor-themeLighterAlt','')"
}</p>

答: It's a known case https://github.com/SharePoint/sp-dev-list-formatting/issues/15, one workaround is using 'Embed' webpart instead of List webpart.</p>

ContentLicense: CC BY-SA 4.0

Body:
I managed to format my Sharepoint list so that every second row is colored in the theme color. As soon as I embed the list as a section on a Sharepoint website the color is gone. How do I fix this?! I'm clueless. Any tips are highly appreciated.

{
  "schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
  "additionalRowClass": "=if(@rowIndex%2==0,'ms-bgColor-themeLighterAlt','')"
}


问:
Integrity error in django foreign key field in django-rest-framework
I'm fairly new in django. I've had a foreignkey field as supervisor as shown below

```<code>class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)
</code>```

The serializer for this is:

```<code>class SiteSerializer(serializers.ModelSerializer):

supervisor = serializers.ReadOnlyField(source='supervisor.username')

class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')
</code>```

and the view for this is:

```<code>@csrf_exempt
def site_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        sites = Site.objects.all()
        serializer = SiteSerializer(sites, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':

    data = JSONParser().parse(request)

    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)
</code>```

Whenever I post data from postman, it says IntegrityError at /sites/
(1048, "Column 'supervisor_id' cannot be null")

I named the model field as supervisor and the db field becomes supervisor_id as django does it. But,how do I sort this error out.
This might be a really little thing but I couldnt figure out where to make the nexessary adjustments.
Please help.

My post request is {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor" : "1"
} OR

```<code>{
"sitename" : "Putalisadak",
"start_date" :"2019-5-5",
"supervisor_id" : "1"
}
</code>```

both yielding the same output

答:
Django expects you to pass a User object and not an id as you did, which is why it is throwing the integrity error. For example, if supervisor is current user it should be serializer.save(supervisor=request.user)

Ps: Typed this using my phone, hope I got the code markup correct.

Body:
I'm fairly new in django. I've had a foreignkey field as supervisor as shown below

class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)

The serializer for this is:

class SiteSerializer(serializers.ModelSerializer):

supervisor = serializers.ReadOnlyField(source='supervisor.username')

class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')

and the view for this is:

@csrf_exempt
def site_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        sites = Site.objects.all()
        serializer = SiteSerializer(sites, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':

    data = JSONParser().parse(request)

    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)

Whenever I post data from postman, it says IntegrityError at /sites/
(1048, "Column 'supervisor_id' cannot be null")

I named the model field as supervisor and the db field becomes supervisor_id as django does it. But,how do I sort this error out.
This might be a really little thing but I couldnt figure out where to make the nexessary adjustments.
Please help.

My post request is {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor" : "1"
} OR

{
"sitename" : "Putalisadak",
"start_date" :"2019-5-5",
"supervisor_id" : "1"
}

both yielding the same output


问:
Groupby - count of pandas df with duplicate values
I am trying to perform a groupby count of a pandas df with duplicate values. I'm hoping to return the unduplicated values only. For the intended output, I only want to determine the count of values between Val_A and Val_B. The returned column can be labelled anything as I will rename it. For the purposes of this question, I'll label it Val_X

```<code>d = ({
    'Date' : ['1/2/18','1/2/18','1/2/18','1/2/18','1/2/18','1/2/18'],
    'Val_A' : [1,1,2,2,1,1],
    'Val_B' : ['X','X','X','X','Y','Y'],
    })

df = pd.DataFrame(data=d)

df1 = pd.pivot_table(df, index=['Date'],values=['Val_A','Val_B'],aggfunc= 'count')
</code>```

Output:

```<code>            Val_A  Val_B
    Date
    1/2/18      6      6
</code>```

Intended Output:

```<code>            Val_X
    Date
    1/2/18      3
</code>```

答:
Try this:</p>

```<code>df.drop_duplicates().groupby('Date').Val_A.count().reset_index(name='Val_x')

Out[1996]:
     Date  Val_x
0  1/2/18      3
</code>```

Body:
I am trying to perform a groupby count of a pandas df with duplicate values. I'm hoping to return the unduplicated values only. For the intended output, I only want to determine the count of values between Val_A and Val_B. The returned column can be labelled anything as I will rename it. For the purposes of this question, I'll label it Val_X

d = ({
    'Date' : ['1/2/18','1/2/18','1/2/18','1/2/18','1/2/18','1/2/18'],
    'Val_A' : [1,1,2,2,1,1],
    'Val_B' : ['X','X','X','X','Y','Y'],
    })

df = pd.DataFrame(data=d)

df1 = pd.pivot_table(df, index=['Date'],values=['Val_A','Val_B'],aggfunc= 'count')

Output:

            Val_A  Val_B
    Date
    1/2/18      6      6

Intended Output:

            Val_X
    Date
    1/2/18      3

Body:
Try this:

df.drop_duplicates().groupby('Date').Val_A.count().reset_index(name='Val_x')

Out[1996]:
     Date  Val_x
0  1/2/18      3


问:
Is there a way to completely remove an inode when the Link count is 2?
Currently my data is organised in a volume which has a cache directory (where all the files are first created or transferred). After that there are suitable directories on the volume which in their subdirs, contain files hardlinked to files in the cache.
This is done so that the same inode (file) can be hardlinked multiple times in multiple directories.

Now when trying to clean up the volume, I recurively go through the dirs(not the cache) and based on certain criterion, unlink the files (which basically reduces the inode count of the cache entry by 1). Is there a way for me to delete the cache entry directly, when I am deleting the last hardlink (that is bringing down the count from 2 to 1). This way I would not have to manually parse through the whole cache directory to clear any inodes from it, which have a link count of just 1.

I have gone through unlink/remove functions, and could not find anything specific of use. Is there some purging algorithm that internally takes care of this, then I can try to implement that.

Any help on this would be highly appreciated. In anticipation of a prompt reply.

答:
No, there isn't anything that does what you want out of the box.

It might be useful to do the deletion when unlinking the hardlink and noticing that the link count is 1, since at that point the inode should be in the page cache; this of course is dependent on knowing the name of the file in the cache directory.

ContentLicense: CC BY-SA 3.0


问:
Can i iterate over a database to produce views from many tables at once?
I have a PostGIS database with several tables with foreign key related to one table that holds the primary key. I have to apply certain select ..to each one of these tables, can I loop over the primary key table to get it done?
Can this be done without even use the primary-foreign key relation?
I can't find any information on iterating inside a database, any help would be much appreciated.</p>

答:
The most performant way to execute a query across multiple tables in Postgres is to use join statements. https://www.postgresql.org/docs/current/tutorial-join.html

Executing multiple queries, one for each table, and then, within your application logic, aggregating the results and then iterating over the aggregation to implement, for example, a SELECT or ORDER BY statement will always be less efficient than using a single query.

Setting indexes on the foreign keys of the tables you are joining will greatly improve the performance of the query. You can also improve query performance by scaling up the CPU and RAM over your server or by using something like Citus to horizontally scale your database across multiple servers.


问:
ExoPlayer: get songs metadata from HTTP stream
I use the following code to play a music stream through ExoPlayer:

```<code>        exoPlayer = ExoPlayer.Factory.newInstance(numRenderers, minBufSize, maxBufSize);
        String url = Helper.getPr().getString("url", "http://mp3.nashe.ru:80/ultra-128.mp3");
        Uri uri = Uri.parse(url);
        Log.i(TAG, "Going to open " + url);
        Allocator allocator = new DefaultAllocator(BUFFER_SEGMENT_SIZE);
        DataSource dataSource = new DefaultUriDataSource(getApplicationContext(), USER_AGENT);
        ExtractorSampleSource sampleSource = new ExtractorSampleSource(uri, dataSource, allocator, BUFFER_SEGMENT_COUNT * BUFFER_SEGMENT_SIZE);
        audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource);
        exoPlayer.addListener(this);
        exoPlayer.sendMessage(audioRenderer, MediaCodecAudioTrackRenderer.MSG_SET_VOLUME, volume);
        exoPlayer.prepare(audioRenderer);
        exoPlayer.setPlayWhenReady(true);
</code>```

I can't find any info on how to get metadata like artist and name of the current song.  Is it possible to get the metadata and if yes, how?

Thanks a lot.

答: In the case of Icy metadata, exoplayer has built in support as of version 2.10. see: https://stackoverflow.com/a/56333429/1898380</p>

Body:
I use the following code to play a music stream through ExoPlayer:

        exoPlayer = ExoPlayer.Factory.newInstance(numRenderers, minBufSize, maxBufSize);
        String url = Helper.getPr().getString("url", "http://mp3.nashe.ru:80/ultra-128.mp3");
        Uri uri = Uri.parse(url);
        Log.i(TAG, "Going to open " + url);
        Allocator allocator = new DefaultAllocator(BUFFER_SEGMENT_SIZE);
        DataSource dataSource = new DefaultUriDataSource(getApplicationContext(), USER_AGENT);
        ExtractorSampleSource sampleSource = new ExtractorSampleSource(uri, dataSource, allocator, BUFFER_SEGMENT_COUNT * BUFFER_SEGMENT_SIZE);
        audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource);
        exoPlayer.addListener(this);
        exoPlayer.sendMessage(audioRenderer, MediaCodecAudioTrackRenderer.MSG_SET_VOLUME, volume);
        exoPlayer.prepare(audioRenderer);
        exoPlayer.setPlayWhenReady(true);

I can't find any info on how to get metadata like artist and name of the current song.  Is it possible to get the metadata and if yes, how?

Thanks a lot.


问:
How can Ionic be setup to render in the iOS style by default?
Right now the ionic app renders with android styling by default. Instead of using the ?ionicplatform=ios param every single time I'd like that to be the default option.

I looked for hints in the config.xml as well as the config settings in app.module.ts such as:

```<code>IonicModule.forRoot(
      MyApp,
      {
        swipeBackEnabled: true,
        platforms: {
          ios: {
            swipeBackEnabled: true,
            statusbarPadding: false
          }
        }
      }
    ),
</code>```

and was unable to find an elegant way of doing it...Any ideas?

答:
in index.html just define mode

For iOS

```<code><html lang="en" mode="ios">
</code>```

For android

```<code><html lang="en" mode="md">
</code>```

Body:
Right now the ionic app renders with android styling by default. Instead of using the ?ionicplatform=ios param every single time I'd like that to be the default option.

I looked for hints in the config.xml as well as the config settings in app.module.ts such as:

IonicModule.forRoot(
      MyApp,
      {
        swipeBackEnabled: true,
        platforms: {
          ios: {
            swipeBackEnabled: true,
            statusbarPadding: false
          }
        }
      }
    ),

and was unable to find an elegant way of doing it...Any ideas?

Body:
in index.html just define mode

For iOS

<html lang="en" mode="ios">

For android

<html lang="en" mode="md">


问:
is it possible to plot timelines with matplotlib?
Im trying to plot dates with values like this csv.

```<code>Tue  2 Jun 16:55:51 CEST 2015,3
Wed  3 Jun 14:51:49 CEST 2015,3
Fri  5 Jun 10:31:59 CEST 2015,3
Sat  6 Jun 20:47:31 CEST 2015,3
Sun  7 Jun 13:58:23 CEST 2015,3
Mon  8 Jun 14:56:49 CEST 2015,2
Tue  9 Jun 23:39:11 CEST 2015,1
Sat 13 Jun 16:55:26 CEST 2015,2
Sun 14 Jun 15:52:34 CEST 2015,3
Sun 14 Jun 16:17:24 CEST 2015,3
Mon 15 Jun 13:23:18 CEST 2015,1
...
</code>```

Im doing something very similar to the first answer here: Matplotlib timelines

But is really hard to get a good grasp of the data looking at that kind of visualization. Then I realize that im trying to plot periods and that I dont need a significant y-axis, only x-axis with the dates and the values can be colors

Something like this:

```<code>---===-===---****
DDDDDDDDDDDDDDDDD

-=* = type of values (using colors for example, but any representation would do)
D = dates
</code>```

I dont seem to see anything similar looking at the matplotlib examples

colorbars seems like they might work, but not quite, since the axis need to be date intervals
http://matplotlib.org/examples/api/colorbar_only.html

答:
I wasn't able to find the answer i was looking for so here is my take on it. This function will take in a time series, then plot a random positive and negative point within the range. By giving it a series you will allow for a label on the graph, and a second series will allow you to click on it for more data. </p>

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import mplcursors
import numpy as np

    # expects series, annotation, and the annotation data to be shown on click

def stimeline(timeseries, annotation, onclick):

    neg = np.random.randint(low=-500, high=0, size=len(timeseries))
    pos = np.random.randint(low=0, high=500, size=len(timeseries))
    i = 0
    d = []
    while i < len(timeseries):
        if i < len(timeseries):
            d.append(pos[i])
            i += 1
        if i < len(timeseries):
            d.append(neg[i])
            i += 1
    (fig, ax) = plt.subplots(figsize=(8.8, 4), constrained_layout=True)
    ax.stem(timeseries, d, basefmt=' ')
    ax.set(title='Timeline')
    ax.set_ylim(-545, 545)

    levels = np.tile(d, int(np.ceil(len(timeseries)
                     / 6)))[:len(timeseries)]
    (markerline, stemline, baseline) = ax.stem(timeseries, levels,
            linefmt='C3-', basefmt='k-')
    plt.setp(markerline, mec='k', mfc='w', zorder=3)
    vert = np.array(['top', 'bottom'])[(levels > 0).astype(int)]
    for (d, l, r, va) in zip(timeseries, levels, annotation, vert):
        ax.annotate(
            r,
            xy=(d, l),
            xytext=(-3, np.sign(l) * 3),
            textcoords='offset points',
            va=va,
            ha='right',
            )

    ax.get_yaxis().set_visible(False)
    for spine in ['left', 'top', 'right']:
        ax.spines[spine].set_visible(False)

    mplcursors.cursor(ax).connect('add', lambda sel: \
                                  sel.annotation.set_text(onclick[sel.target.index]))

    ax.margins(y=0.1)
    plt.show()

</code>```

Body:
Im trying to plot dates with values like this csv.

Tue  2 Jun 16:55:51 CEST 2015,3
Wed  3 Jun 14:51:49 CEST 2015,3
Fri  5 Jun 10:31:59 CEST 2015,3
Sat  6 Jun 20:47:31 CEST 2015,3
Sun  7 Jun 13:58:23 CEST 2015,3
Mon  8 Jun 14:56:49 CEST 2015,2
Tue  9 Jun 23:39:11 CEST 2015,1
Sat 13 Jun 16:55:26 CEST 2015,2
Sun 14 Jun 15:52:34 CEST 2015,3
Sun 14 Jun 16:17:24 CEST 2015,3
Mon 15 Jun 13:23:18 CEST 2015,1
...

Im doing something very similar to the first answer here: Matplotlib timelines

But is really hard to get a good grasp of the data looking at that kind of visualization. Then I realize that im trying to plot periods and that I dont need a significant y-axis, only x-axis with the dates and the values can be colors

Something like this:

---===-===---****
DDDDDDDDDDDDDDDDD

-=* = type of values (using colors for example, but any representation would do)
D = dates

I dont seem to see anything similar looking at the matplotlib examples

colorbars seems like they might work, but not quite, since the axis need to be date intervals
http://matplotlib.org/examples/api/colorbar_only.html

Body:
I wasn't able to find the answer i was looking for so here is my take on it. This function will take in a time series, then plot a random positive and negative point within the range. By giving it a series you will allow for a label on the graph, and a second series will allow you to click on it for more data.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import mplcursors
import numpy as np

    # expects series, annotation, and the annotation data to be shown on click

def stimeline(timeseries, annotation, onclick):

    neg = np.random.randint(low=-500, high=0, size=len(timeseries))
    pos = np.random.randint(low=0, high=500, size=len(timeseries))
    i = 0
    d = []
    while i < len(timeseries):
        if i < len(timeseries):
            d.append(pos[i])
            i += 1
        if i < len(timeseries):
            d.append(neg[i])
            i += 1
    (fig, ax) = plt.subplots(figsize=(8.8, 4), constrained_layout=True)
    ax.stem(timeseries, d, basefmt=' ')
    ax.set(title='Timeline')
    ax.set_ylim(-545, 545)

    levels = np.tile(d, int(np.ceil(len(timeseries)
                     / 6)))[:len(timeseries)]
    (markerline, stemline, baseline) = ax.stem(timeseries, levels,
            linefmt='C3-', basefmt='k-')
    plt.setp(markerline, mec='k', mfc='w', zorder=3)
    vert = np.array(['top', 'bottom'])[(levels > 0).astype(int)]
    for (d, l, r, va) in zip(timeseries, levels, annotation, vert):
        ax.annotate(
            r,
            xy=(d, l),
            xytext=(-3, np.sign(l) * 3),
            textcoords='offset points',
            va=va,
            ha='right',
            )

    ax.get_yaxis().set_visible(False)
    for spine in ['left', 'top', 'right']:
        ax.spines[spine].set_visible(False)

    mplcursors.cursor(ax).connect('add', lambda sel: \
                                  sel.annotation.set_text(onclick[sel.target.index]))

    ax.margins(y=0.1)
    plt.show()


问:
How do I increase a variable until a number is reached in JavaScript, leaving all other spaces blank?
I need numbers on a PDF in Adobe Acrobat Pro DC to continue to 30, but in various positions across the PDF pages. Rather than rearrange over and over again (and yet more in the future), I'd rather have a form with autofill boxes extending into the spaces beyond where I need them (think blank monthly calendar spread, filling in those numbers) where I input "1" in one of the boxes and it increases until it gets to 30, leaving the rest of the boxes blank.

What I need help with is getting the numbers to stop there.

Someone else gave me this to get the numbers to increase like I needed:

```<code>if (this.getField("Box1").valueAsString!="") event.value =
  Number(this.getField("Box1").valueAsString)+1;
</code>```

Line break added by editor to reduce scrolling.

Where this is assigned to the one named Box2. That part works beautifully! What I can't figure out is how to tell the numbers to stop at 30. Again, I'm brand spanking new, so I don't really know what I'm doing to begin with.

Some other guys I talked to suggested doing a Date field, but I'm not experienced enough to make the chain of numbers continue and stop where I need them to. That's way beyond me, though I did try with that, too. I'll work up to that one day, but for now I wanted to know if there's a way to code it to stop at a given number, instead.

答:
slite better solution then @snow answer, take option that user input number bigger than 30

var stringVal = this.getField("Box1").valueAsString;
if (stringVal !== '') {
  var numVal = Number(stringVal);
  event.value = Math.max(numVal + 1, 30);
}

```

Body:
I need numbers on a PDF in Adobe Acrobat Pro DC to continue to 30, but in various positions across the PDF pages. Rather than rearrange over and over again (and yet more in the future), I'd rather have a form with autofill boxes extending into the spaces beyond where I need them (think blank monthly calendar spread, filling in those numbers) where I input "1" in one of the boxes and it increases until it gets to 30, leaving the rest of the boxes blank.

What I need help with is getting the numbers to stop there.

Someone else gave me this to get the numbers to increase like I needed:

if (this.getField("Box1").valueAsString!="") event.value =
  Number(this.getField("Box1").valueAsString)+1;

Line break added by editor to reduce scrolling.

Where this is assigned to the one named Box2. That part works beautifully! What I can't figure out is how to tell the numbers to stop at 30. Again, I'm brand spanking new, so I don't really know what I'm doing to begin with.

Some other guys I talked to suggested doing a Date field, but I'm not experienced enough to make the chain of numbers continue and stop where I need them to. That's way beyond me, though I did try with that, too. I'll work up to that one day, but for now I wanted to know if there's a way to code it to stop at a given number, instead.


问:
Is it possible to group elements without closing the stream?
Is it possible to group elements in a Stream, but then continue streaming instead of having to create a new stream from the EntrySet of the returned map?

For example, I can do this:

```<code>public static void main(String[] args) {
    // map of access date to list of users
    // Person is a POJO with first name, last name, etc.
    Map<Date, List<Person>> dateMap = new HashMap<>();
    // ...
    // output, sorted by access date, then person last name
    dateMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> {
        Date date = e.getKey();
        // group persons by last name and sort
        // this part seems clunky
        e.getValue().stream().collect(Collectors.groupingBy(Person::getLastName, Collectors.toSet()))
                .entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e2 -> {
            // pool agent id is the key
            String lastName = e2.getKey();
            Set<Person> personSet = e2.getValue();
            float avgAge = calculateAverageAge(personSet);
            int numPersons = personSet.size();
            // write out row with date, lastName, avgAge, numPersons
        });
    });
}
</code>```

Which works just fine, but seems a little clunky, especially the streaming into a map, and then immediately streaming on the entry set of that map.

Is there a way to group objects in a stream, but continue streaming?

答:
There are several different ways to interpret the question, but if we restate the question as, "Is it possible to group elements within a Stream without using a terminal operation and apply stream operations to the resulting groups within the same stream pipeline," then the answer is "Yes." In this restatement of the question, terminal operation is defined in the way that the Java 8 streams API defines it.

Here is an example that demonstrates this.

```<code>import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

class StreamGrouper {

    public static class GroupableObj<K extends Comparable<? super K>, T>
            implements Comparable<GroupableObj<K, T>> {

        private K key;
        private T obj;
        private Set<T> setOfObj;

        public GroupableObj(K key, T obj) {
            if (key == null) {
                throw new NullPointerException("Key may not be null");
            }
            this.key = key;
            this.obj = obj;
        }

        @Override
        public int compareTo(GroupableObj<K, T> otherGroupable) {
            return key.compareTo(otherGroupable.key);
        }

        @Override
        public boolean equals(Object otherObj) {
            if (otherObj == null) {
                return false;
            }
            if (otherObj instanceof GroupableObj) {
                GroupableObj<?, ?> otherGroupable =
                        (GroupableObj<?, ?>)otherObj;
                return setOfObj == otherGroupable.setOfObj &&
                        key.equals(otherGroupable.key);
            }
            return false;
        }

        public Set<T> getGroup() {
            return setOfObj;
        }

        public K getKey() {
            return key;
        }

        public T getObject() {
            return obj;
        }

        @Override
        public int hashCode() {
            return key.hashCode();
        }

        public void setGroup(Set<T> setOfObj) {
            this.setOfObj = setOfObj;
        }
    }

    public static class PeekGrouper<K extends Comparable<? super K>, T>
            implements Consumer<GroupableObj<K, T>> {

        private Map<K, Set<T>> groupMap;

        public PeekGrouper() {
            groupMap = new HashMap<>();
        }

        @Override
        public void accept(GroupableObj<K, T> groupable) {
            K key = groupable.getKey();
            Set<T> group = groupMap.computeIfAbsent(key,
                    (k) -> new HashSet<T>());
            groupable.setGroup(group);
            group.add(groupable.getObject());
        }
    }

    public static void main(String[] args) {

        Function<Double, Long> myKeyExtractor =
                (dblObj) -> Long.valueOf(
                (long)(Math.floor(dblObj.doubleValue()*10.0)));
        PeekGrouper<Long, Double> myGrouper = new PeekGrouper<>();

        Random simpleRand = new Random(20190527L);
        simpleRand.doubles(100).boxed().map((dblObj) ->
                new GroupableObj<Long, Double>(
                myKeyExtractor.apply(dblObj), dblObj)).peek(myGrouper).
                distinct().sorted().
                map(GroupableObj<Long, Double>::getGroup).
                forEachOrdered((grp) -> System.out.println(grp));
    }
}
</code>```

In order to make a program that can be compiled and executed on its own, this example moves away from using the Person objects that are referenced in the question, but the grouping concept is the same, and the code from the question could turn into something like the following.

```<code>PeekGrouper<String, Person> myGrouper = new PeekGrouper<>();
e.getValue().stream().map((p) -> new GroupableObj<String, Person>(
        p.getLastName(), p)).peek(myGrouper).distinct().sorted().
        forEachOrdered(e2 -> {
    String lastName = e2.getKey();
    Set<Person> personSet = e2.getGroup();
    float avgAge = calculateAverageAge(personSet);
    int numPersons = personSet.size();
    // write out row with date, lastName, avgAge, numPersons
});
</code>```

Please note that in order for this example to work, it is required that the stream call both the distinct function (which reduces the stream to only a single instance of each group) and the sorted function (which ensures that the entire stream has been processed and the groups have been fully "collected" before processing continues). Also note that as implemented here GroupableObj is not safe to use with parallel streams.  If the terminal operation of the stream does not require that the groups be fully "collected" when it processes the objects -- for example, if the terminal operation were something like Collectors.toList() -- then a call to sorted would not be required.  The critical point is that any portion of the stream that sees the groups prior to a call to sorted and prior to the end of a terminal operation (including processing during a terminal operation) may see a group that is incomplete.

For the specific example in the question, it may be somewhat less time-efficient to sort the objects before grouping them if many of them are in the same group, but if you are willing to sort the objects before grouping them, you can achieve the same functionality without performing any streaming after doing the grouping.  The following is a rewrite of the first example from this answer that demonstrates this.

```<code>import java.util.Comparator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collector;

class PreSortOrderedGrouper {

    public static void main(String[] args) {

        Function<Double, Long> myKeyExtractor =
                (dblObj) -> Long.valueOf(
                (long)(Math.floor(dblObj.doubleValue()*10.0)));
        Random simpleRand = new Random(20190527L);
        Consumer<Set<Double>> groupProcessor =
                (grp) -> System.out.println(grp);
        simpleRand.doubles(100).boxed().sorted(
                Comparator.comparing(myKeyExtractor)).
                collect(Collector.of(HashSet<Double>::new,
                (set, dblObj) -> {
                    if (set.isEmpty() || myKeyExtractor.apply(set.iterator().
                            next()) == myKeyExtractor.apply(dblObj)) {
                        set.add(dblObj);
                    } else {
                        groupProcessor.accept(set);
                        set.clear();
                        set.add(dblObj);
                    }
                },
                (setOne, setTwo) -> {
                    throw new UnsupportedOperationException();
                },
                (finalSet) -> {
                    groupProcessor.accept(finalSet);
                    return Integer.valueOf(0);
                }));
    }
}
</code>```

I can't be sure that either of these examples will feel less "clunky" to you, but if the example in your question is a pattern you use frequently, you could probably adapt one or both of these examples in ways that will suit your purposes and, aside from a few utility classes, result in no more code than you are currently using.

Body:
Is it possible to group elements in a Stream, but then continue streaming instead of having to create a new stream from the EntrySet of the returned map?

For example, I can do this:

public static void main(String[] args) {
    // map of access date to list of users
    // Person is a POJO with first name, last name, etc.
    Map<Date, List<Person>> dateMap = new HashMap<>();
    // ...
    // output, sorted by access date, then person last name
    dateMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> {
        Date date = e.getKey();
        // group persons by last name and sort
        // this part seems clunky
        e.getValue().stream().collect(Collectors.groupingBy(Person::getLastName, Collectors.toSet()))
                .entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e2 -> {
            // pool agent id is the key
            String lastName = e2.getKey();
            Set<Person> personSet = e2.getValue();
            float avgAge = calculateAverageAge(personSet);
            int numPersons = personSet.size();
            // write out row with date, lastName, avgAge, numPersons
        });
    });
}

Which works just fine, but seems a little clunky, especially the streaming into a map, and then immediately streaming on the entry set of that map.

Is there a way to group objects in a stream, but continue streaming?

Body:
There are several different ways to interpret the question, but if we restate the question as, "Is it possible to group elements within a Stream without using a terminal operation and apply stream operations to the resulting groups within the same stream pipeline," then the answer is "Yes." In this restatement of the question, terminal operation is defined in the way that the Java 8 streams API defines it.

Here is an example that demonstrates this.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

class StreamGrouper {

    public static class GroupableObj<K extends Comparable<? super K>, T>
            implements Comparable<GroupableObj<K, T>> {

        private K key;
        private T obj;
        private Set<T> setOfObj;

        public GroupableObj(K key, T obj) {
            if (key == null) {
                throw new NullPointerException("Key may not be null");
            }
            this.key = key;
            this.obj = obj;
        }

        @Override
        public int compareTo(GroupableObj<K, T> otherGroupable) {
            return key.compareTo(otherGroupable.key);
        }

        @Override
        public boolean equals(Object otherObj) {
            if (otherObj == null) {
                return false;
            }
            if (otherObj instanceof GroupableObj) {
                GroupableObj<?, ?> otherGroupable =
                        (GroupableObj<?, ?>)otherObj;
                return setOfObj == otherGroupable.setOfObj &&
                        key.equals(otherGroupable.key);
            }
            return false;
        }

        public Set<T> getGroup() {
            return setOfObj;
        }

        public K getKey() {
            return key;
        }

        public T getObject() {
            return obj;
        }

        @Override
        public int hashCode() {
            return key.hashCode();
        }

        public void setGroup(Set<T> setOfObj) {
            this.setOfObj = setOfObj;
        }
    }

    public static class PeekGrouper<K extends Comparable<? super K>, T>
            implements Consumer<GroupableObj<K, T>> {

        private Map<K, Set<T>> groupMap;

        public PeekGrouper() {
            groupMap = new HashMap<>();
        }

        @Override
        public void accept(GroupableObj<K, T> groupable) {
            K key = groupable.getKey();
            Set<T> group = groupMap.computeIfAbsent(key,
                    (k) -> new HashSet<T>());
            groupable.setGroup(group);
            group.add(groupable.getObject());
        }
    }

    public static void main(String[] args) {

        Function<Double, Long> myKeyExtractor =
                (dblObj) -> Long.valueOf(
                (long)(Math.floor(dblObj.doubleValue()*10.0)));
        PeekGrouper<Long, Double> myGrouper = new PeekGrouper<>();

        Random simpleRand = new Random(20190527L);
        simpleRand.doubles(100).boxed().map((dblObj) ->
                new GroupableObj<Long, Double>(
                myKeyExtractor.apply(dblObj), dblObj)).peek(myGrouper).
                distinct().sorted().
                map(GroupableObj<Long, Double>::getGroup).
                forEachOrdered((grp) -> System.out.println(grp));
    }
}

In order to make a program that can be compiled and executed on its own, this example moves away from using the Person objects that are referenced in the question, but the grouping concept is the same, and the code from the question could turn into something like the following.

PeekGrouper<String, Person> myGrouper = new PeekGrouper<>();
e.getValue().stream().map((p) -> new GroupableObj<String, Person>(
        p.getLastName(), p)).peek(myGrouper).distinct().sorted().
        forEachOrdered(e2 -> {
    String lastName = e2.getKey();
    Set<Person> personSet = e2.getGroup();
    float avgAge = calculateAverageAge(personSet);
    int numPersons = personSet.size();
    // write out row with date, lastName, avgAge, numPersons
});

Please note that in order for this example to work, it is required that the stream call both the distinct function (which reduces the stream to only a single instance of each group) and the sorted function (which ensures that the entire stream has been processed and the groups have been fully "collected" before processing continues). Also note that as implemented here GroupableObj is not safe to use with parallel streams.  If the terminal operation of the stream does not require that the groups be fully "collected" when it processes the objects -- for example, if the terminal operation were something like Collectors.toList() -- then a call to sorted would not be required.  The critical point is that any portion of the stream that sees the groups prior to a call to sorted and prior to the end of a terminal operation (including processing during a terminal operation) may see a group that is incomplete.

For the specific example in the question, it may be somewhat less time-efficient to sort the objects before grouping them if many of them are in the same group, but if you are willing to sort the objects before grouping them, you can achieve the same functionality without performing any streaming after doing the grouping.  The following is a rewrite of the first example from this answer that demonstrates this.

import java.util.Comparator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collector;

class PreSortOrderedGrouper {

    public static void main(String[] args) {

        Function<Double, Long> myKeyExtractor =
                (dblObj) -> Long.valueOf(
                (long)(Math.floor(dblObj.doubleValue()*10.0)));
        Random simpleRand = new Random(20190527L);
        Consumer<Set<Double>> groupProcessor =
                (grp) -> System.out.println(grp);
        simpleRand.doubles(100).boxed().sorted(
                Comparator.comparing(myKeyExtractor)).
                collect(Collector.of(HashSet<Double>::new,
                (set, dblObj) -> {
                    if (set.isEmpty() || myKeyExtractor.apply(set.iterator().
                            next()) == myKeyExtractor.apply(dblObj)) {
                        set.add(dblObj);
                    } else {
                        groupProcessor.accept(set);
                        set.clear();
                        set.add(dblObj);
                    }
                },
                (setOne, setTwo) -> {
                    throw new UnsupportedOperationException();
                },
                (finalSet) -> {
                    groupProcessor.accept(finalSet);
                    return Integer.valueOf(0);
                }));
    }
}

I can't be sure that either of these examples will feel less "clunky" to you, but if the example in your question is a pattern you use frequently, you could probably adapt one or both of these examples in ways that will suit your purposes and, aside from a few utility classes, result in no more code than you are currently using.


问:
fixed element is lost when it is on top of another absolute
I have an arrow for the navigation that is fixed, its operation is correct, until it passes over an absolute element with a sliding animation to the left, at that moment my "fixed" arrow goes along with the animation, it is lost from the screen.

I have two absolute divs in a relative container, when the user scrolls up to that position the two divs move out of the screen, left and right respectively. When the animation is triggered, my navigation arrow falls with it.

```<code>//this is my scss

/*******
 ARROW
********/

@import '../../scss/variables';

.arrow{
display: block;
position: fixed;
 right: 15px;
 bottom: 15px;
  svg{
    fill: #fff;
    width:50px;
  }
}
.my_bounce {
  animation-name: my_bounce;
  animation-duration: 2s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
}

/***********
BOXES
************/
.about_cont{
  background: url('../../images/about-movil.jpg') top center;
  background-size: cover;
  display: flex;
  height: 100vh;
  position: relative;
}
.about_boxes{
  display: flex;
  width: 50vw;
  align-items: center;
  font-family: 'Panton';
  position: absolute;
  height: 100vh;;
}
#about_box_1{
  justify-content: flex-end;
  background: $sec;
  left: 0;
  p{
    font-size: 2.5rem;
  }
}
#about_box_2{
  color: #fff;
  background: $prim;
  right: 0;
 p{
   font-size: 2.5rem;
  }
}
</code>```

Does anyone have any idea what is wrong?

答:
Since we can't see your html we can't be certain what the problem is, but I'm pretty sure that adding

z-index: 1;
```

to your arrow will fix the problem. If that doesn't work, try a bigger number.

Body:
I have an arrow for the navigation that is fixed, its operation is correct, until it passes over an absolute element with a sliding animation to the left, at that moment my "fixed" arrow goes along with the animation, it is lost from the screen.

I have two absolute divs in a relative container, when the user scrolls up to that position the two divs move out of the screen, left and right respectively. When the animation is triggered, my navigation arrow falls with it.

//this is my scss

/*******
 ARROW
********/

@import '../../scss/variables';

.arrow{
display: block;
position: fixed;
 right: 15px;
 bottom: 15px;
  svg{
    fill: #fff;
    width:50px;
  }
}
.my_bounce {
  animation-name: my_bounce;
  animation-duration: 2s;
  animation-direction: alternate;
  animation-iteration-count: infinite;
}

/***********
BOXES
************/
.about_cont{
  background: url('../../images/about-movil.jpg') top center;
  background-size: cover;
  display: flex;
  height: 100vh;
  position: relative;
}
.about_boxes{
  display: flex;
  width: 50vw;
  align-items: center;
  font-family: 'Panton';
  position: absolute;
  height: 100vh;;
}
#about_box_1{
  justify-content: flex-end;
  background: $sec;
  left: 0;
  p{
    font-size: 2.5rem;
  }
}
#about_box_2{
  color: #fff;
  background: $prim;
  right: 0;
 p{
   font-size: 2.5rem;
  }
}

Does anyone have any idea what is wrong?

Body:
Since we can't see your html we can't be certain what the problem is, but I'm pretty sure that adding

z-index: 1;

to your arrow will fix the problem. If that doesn't work, try a bigger number.


问:
Why would one choose standalone socket.io server vs. Express vs. node http?
I'm making my first steps in websockets and socket.io and going through some tutorials online.

This tutorial is using what seems to be socket.io's standalone server. My question is what is the motivation for using a standalone server over using Express (or node http server for that matter).

I tried searching online but couldn't find what would be the motivation to use a standalone server.

答:
This is all you need to have knowledge about differences between two of them: https://github.com/rsp/node-websocket-vs-socket.io

There are few common misconceptions regarding WebSocket and Socket.IO:

The first misconception is that using Socket.IO is significantly easier than using WebSocket which doesn't seem to be the case. See examples below.

The second misconception is that WebSocket is not widely supported in the browsers. See below for more info.

The third misconception is that Socket.IO downgrades the connection as a fallback on older browsers. It actually assumes that the browser is old and starts an AJAX connection to the server, that gets later upgraded on browsers supporting WebSocket, after some traffic is exchanged.


问:
Lotka-Volterra equations(predator prey) using Runge-Kutta in Python
I am trying to write a program using the Lotka-Volterra equations for predator-prey interactions. Solve Using ODE's:

```<code>dx/dt = a*x - B*x*y
dy/dt = g*x*y - s*y
</code>```

Using 4th order Runge-Kutta method

I need to plot a graph showing both x and y as a function of time from t = 0 to t=30.

a = alpha = 1

  b = beta  = 0.5

  g = gamma = 0.5

  s = sigma = 2

  initial conditions x = y = 2

Here is my code so far but not display anything on the graph. Some help would be nice.

```<code>#!/usr/bin/env python

from __future__ import division, print_function
import matplotlib.pyplot as plt
import numpy as np

def rk4(f, r, t, h):
        """ Runge-Kutta 4 method """
        k1 = h*f(r, t)
        k2 = h*f(r+0.5*k1, t+0.5*h)
        k3 = h*f(r+0.5*k2, t+0.5*h)
        k4 = h*f(r+k3, t+h)
        return (k1 + 2*k2 + 2*k3 + k4)/6

def f(r, t):
        alpha = 1.0
        beta = 0.5
        gamma = 0.5
        sigma = 2.0
        x, y = r[2], r[2]
        fxd = x*(alpha - beta*y)
        fyd = -y*(gamma - sigma*x)
        return np.array([fxd, fyd], float)

tpoints = np.linspace(0, 30, 0.1)
xpoints = []
ypoints = []

r = np.array([2, 2], float)
for t in tpoints:
        xpoints += [r[2]]
        ypoints += [r[2]]
        r += rk4(f, r, t, h)

plt.plot(tpoints, xpoints)
plt.plot(tpoints, ypoints)
plt.xlabel("Time")
plt.ylabel("Population")
plt.title("Lotka-Volterra Model")
plt.savefig("Lotka_Volterra.png")
plt.show()
</code>```

答:
1) define 'h' variable.

2) use

tpoints = np.arange(30)          #array([0, 1, 2, ..., 30])

not

np.linspace()

and don't forget to set time step size equal to h:

```<code>h=0.1
tpoints = np.arange(0, 30, h)
</code>```

3) be careful with indexes:

```<code>def f(r,t):
    ...
    x, y=r[0], r[1]
    ...
</code>```

```<code>for t in tpoints:
    xpoints += [r[0]]
    ypoints += [r[1]]
    ...
</code>```

and better use .append(x):

```<code>for t in tpoints:
    xpoints.append(r[0])
    ypoints.append(r[1])
    ...
</code>```

Here's tested code for python 3.7 (I've set h=0.001 for more presize)

```<code>import matplotlib.pyplot as plt
import numpy as np

def rk4(r, t, h):                    #edited; no need for input f
        """ Runge-Kutta 4 method """
        k1 = h*f(r, t)
        k2 = h*f(r+0.5*k1, t+0.5*h)
        k3 = h*f(r+0.5*k2, t+0.5*h)
        k4 = h*f(r+k3, t+h)
        return (k1 + 2*k2 + 2*k3 + k4)/6

def f(r, t):
        alpha = 1.0
        beta = 0.5
        gamma = 0.5
        sigma = 2.0
        x, y = r[0], r[1]
        fxd = x*(alpha - beta*y)
        fyd = -y*(gamma - sigma*x)
        return np.array([fxd, fyd], float)

h=0.001                               #edited
tpoints = np.arange(0, 30, h)         #edited
xpoints, ypoints  = [], []
r = np.array([2, 2], float)
for t in tpoints:
        xpoints.append(r[0])          #edited
        ypoints.append(r[1])          #edited
        r += rk4(r, t, h)             #edited; no need for input f
plt.plot(tpoints, xpoints)
plt.plot(tpoints, ypoints)
plt.xlabel("Time")
plt.ylabel("Population")
plt.title("Lotka-Volterra Model")
plt.savefig("Lotka_Volterra.png")
plt.show()
</code>```

You can also try to plot "cycles":

```<code>plt.xlabel("Prey")
plt.ylabel("Predator")
plt.plot(xpoints, ypoints)
plt.show()
</code>```

https://i.stack.imgur.com/NB9lc.png

Body:
I am trying to write a program using the Lotka-Volterra equations for predator-prey interactions. Solve Using ODE's:

dx/dt = a*x - B*x*y
dy/dt = g*x*y - s*y

Using 4th order Runge-Kutta method

I need to plot a graph showing both x and y as a function of time from t = 0 to t=30.

a = alpha = 1

  b = beta  = 0.5

  g = gamma = 0.5

  s = sigma = 2

  initial conditions x = y = 2

Here is my code so far but not display anything on the graph. Some help would be nice.

#!/usr/bin/env python

from __future__ import division, print_function
import matplotlib.pyplot as plt
import numpy as np

def rk4(f, r, t, h):
        """ Runge-Kutta 4 method """
        k1 = h*f(r, t)
        k2 = h*f(r+0.5*k1, t+0.5*h)
        k3 = h*f(r+0.5*k2, t+0.5*h)
        k4 = h*f(r+k3, t+h)
        return (k1 + 2*k2 + 2*k3 + k4)/6

def f(r, t):
        alpha = 1.0
        beta = 0.5
        gamma = 0.5
        sigma = 2.0
        x, y = r[2], r[2]
        fxd = x*(alpha - beta*y)
        fyd = -y*(gamma - sigma*x)
        return np.array([fxd, fyd], float)

tpoints = np.linspace(0, 30, 0.1)
xpoints = []
ypoints = []

r = np.array([2, 2], float)
for t in tpoints:
        xpoints += [r[2]]
        ypoints += [r[2]]
        r += rk4(f, r, t, h)

plt.plot(tpoints, xpoints)
plt.plot(tpoints, ypoints)
plt.xlabel("Time")
plt.ylabel("Population")
plt.title("Lotka-Volterra Model")
plt.savefig("Lotka_Volterra.png")
plt.show()

Body:
1) define 'h' variable.

2) use

tpoints = np.arange(30)          #array([0, 1, 2, ..., 30])

not

np.linspace()

and don't forget to set time step size equal to h:

h=0.1
tpoints = np.arange(0, 30, h)

3) be careful with indexes:

def f(r,t):
    ...
    x, y=r[0], r[1]
    ...

for t in tpoints:
    xpoints += [r[0]]
    ypoints += [r[1]]
    ...

and better use .append(x):

for t in tpoints:
    xpoints.append(r[0])
    ypoints.append(r[1])
    ...

Here's tested code for python 3.7 (I've set h=0.001 for more presize)

import matplotlib.pyplot as plt
import numpy as np

def rk4(r, t, h):                    #edited; no need for input f
        """ Runge-Kutta 4 method """
        k1 = h*f(r, t)
        k2 = h*f(r+0.5*k1, t+0.5*h)
        k3 = h*f(r+0.5*k2, t+0.5*h)
        k4 = h*f(r+k3, t+h)
        return (k1 + 2*k2 + 2*k3 + k4)/6

def f(r, t):
        alpha = 1.0
        beta = 0.5
        gamma = 0.5
        sigma = 2.0
        x, y = r[0], r[1]
        fxd = x*(alpha - beta*y)
        fyd = -y*(gamma - sigma*x)
        return np.array([fxd, fyd], float)

h=0.001                               #edited
tpoints = np.arange(0, 30, h)         #edited
xpoints, ypoints  = [], []
r = np.array([2, 2], float)
for t in tpoints:
        xpoints.append(r[0])          #edited
        ypoints.append(r[1])          #edited
        r += rk4(r, t, h)             #edited; no need for input f
plt.plot(tpoints, xpoints)
plt.plot(tpoints, ypoints)
plt.xlabel("Time")
plt.ylabel("Population")
plt.title("Lotka-Volterra Model")
plt.savefig("Lotka_Volterra.png")
plt.show()

You can also try to plot "cycles":

plt.xlabel("Prey")
plt.ylabel("Predator")
plt.plot(xpoints, ypoints)
plt.show()

https://i.stack.imgur.com/NB9lc.png


问:
Show (slide in) or hide (slide out) flutter AppBar on screen tap
Please I am trying to create this effect where the AppBar slides out when the screen is tapped and slides in when it is tapped again.

I am able to create something similar in SliverAppBar by setting floating and snap to true. The difference is that the appBar shows when scrolling down and hides when screen is tapped or scrolled up.

Here is the sample code for the SliverAppBar:

```<code> @override
  Widget build(BuildContext context) {

    return Scaffold(
          body: CustomScrollView(
            controller: _ctrlr,

                slivers: <Widget>[
                  SliverAppBar(
                    floating: true,
                    snap: true,

                  ),
                  SliverList(
                    delegate: SliverChildListDelegate([
                      Text('1', style: TextStyle(fontSize: 160.0),),
                      Text('2', style: TextStyle(fontSize: 160.0),),
                      Text('3', style: TextStyle(fontSize: 160.0),),
                      Text('4', style: TextStyle(fontSize: 160.0),),
                    ]),
                  )
                ],
        ),
    );
  }
</code>```

How can I be able to achieve this? I also considered placing the AppBar in a Stack but i don't think that is the best approach. Your help will be greatly appreciated!

答:
I came upon a similar need, and discovered your question.  Since there were no answers, I took it upon myself to try and solve the problem.  I know you asked this 6 months ago, but I'm putting in an (nearly complete) answer in case anybody else happens upon it.

(I apologize if my approach is less than elegant, but as of this writing, I've only been using Flutter for about a week. :)

```<code>import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';

class FramePage extends StatefulWidget {
  final String title;
  final String imageUrl;

  FramePage({Key key, this.title, this.imageUrl}) : super(key: key);

  @override
  _FramePageState createState() => _FramePageState();
}

class _FramePageState extends State<FramePage> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  bool _appBarVisible;

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

    _appBarVisible = true;
    _controller = AnimationController(
      duration: const Duration(milliseconds: 700),
      value: 1.0,
      vsync: this,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _toggleAppBarVisibility() {
    _appBarVisible = !_appBarVisible;
    _appBarVisible ? _controller.forward() : _controller.reverse();
  }

  Widget get _imageWidget {
    return Center(
      child: GestureDetector(
      onTap: () => setState(() { _toggleAppBarVisibility(); } ),
      child: Container(
          foregroundDecoration: new BoxDecoration(color: Color.fromRGBO(155, 85, 250, 0.0)),
          child: FadeInImage.memoryNetwork(
            placeholder: kTransparentImage,
            image: widget.imageUrl,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context)
  {
    Animation<Offset> offsetAnimation = new Tween<Offset>(
      begin: Offset(0.0, -70),
      end: Offset(0.0, 0.0),
    ).animate(_controller);

    return Scaffold(
      body: Stack(
        children: <Widget>[
          _imageWidget,
          SlideTransition(
            position: offsetAnimation,
            child: Container(
              height: 75,
              child: AppBar(
                title: Text(widget.title),
              ),
            ),
          ),
        ],
      )
    );
  }
}
</code>```

Essentially, the AppBar is removed as a direct part of the Scaffold, and instead is added to the Stack, where it can actually be animated.  In order to make sure the image is visible behind it, it is placed into a Container so it's height can be controlled (otherwise, you would not be able to see the image).

In my code above, tapping on the image makes the AppBar retract, and tapping again makes it re-appear.  For some reason, though, I haven't been able to actually get it to smoothly animate forward and back, but the effect is there.

In practice, it looks like this:

If somebody figures out (before I do) what I've missed to make it animate smoothly, please feel free to help out.

Body:
Please I am trying to create this effect where the AppBar slides out when the screen is tapped and slides in when it is tapped again.

I am able to create something similar in SliverAppBar by setting floating and snap to true. The difference is that the appBar shows when scrolling down and hides when screen is tapped or scrolled up.

Here is the sample code for the SliverAppBar:

 @override
  Widget build(BuildContext context) {

    return Scaffold(
          body: CustomScrollView(
            controller: _ctrlr,

                slivers: <Widget>[
                  SliverAppBar(
                    floating: true,
                    snap: true,

                  ),
                  SliverList(
                    delegate: SliverChildListDelegate([
                      Text('1', style: TextStyle(fontSize: 160.0),),
                      Text('2', style: TextStyle(fontSize: 160.0),),
                      Text('3', style: TextStyle(fontSize: 160.0),),
                      Text('4', style: TextStyle(fontSize: 160.0),),
                    ]),
                  )
                ],
        ),
    );
  }

How can I be able to achieve this? I also considered placing the AppBar in a Stack but i don't think that is the best approach. Your help will be greatly appreciated!

Body:
I came upon a similar need, and discovered your question.  Since there were no answers, I took it upon myself to try and solve the problem.  I know you asked this 6 months ago, but I'm putting in an (nearly complete) answer in case anybody else happens upon it.

(I apologize if my approach is less than elegant, but as of this writing, I've only been using Flutter for about a week. :)

import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';

class FramePage extends StatefulWidget {
  final String title;
  final String imageUrl;

  FramePage({Key key, this.title, this.imageUrl}) : super(key: key);

  @override
  _FramePageState createState() => _FramePageState();
}

class _FramePageState extends State<FramePage> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  bool _appBarVisible;

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

    _appBarVisible = true;
    _controller = AnimationController(
      duration: const Duration(milliseconds: 700),
      value: 1.0,
      vsync: this,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _toggleAppBarVisibility() {
    _appBarVisible = !_appBarVisible;
    _appBarVisible ? _controller.forward() : _controller.reverse();
  }

  Widget get _imageWidget {
    return Center(
      child: GestureDetector(
      onTap: () => setState(() { _toggleAppBarVisibility(); } ),
      child: Container(
          foregroundDecoration: new BoxDecoration(color: Color.fromRGBO(155, 85, 250, 0.0)),
          child: FadeInImage.memoryNetwork(
            placeholder: kTransparentImage,
            image: widget.imageUrl,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context)
  {
    Animation<Offset> offsetAnimation = new Tween<Offset>(
      begin: Offset(0.0, -70),
      end: Offset(0.0, 0.0),
    ).animate(_controller);

    return Scaffold(
      body: Stack(
        children: <Widget>[
          _imageWidget,
          SlideTransition(
            position: offsetAnimation,
            child: Container(
              height: 75,
              child: AppBar(
                title: Text(widget.title),
              ),
            ),
          ),
        ],
      )
    );
  }
}

Essentially, the AppBar is removed as a direct part of the Scaffold, and instead is added to the Stack, where it can actually be animated.  In order to make sure the image is visible behind it, it is placed into a Container so it's height can be controlled (otherwise, you would not be able to see the image).

In my code above, tapping on the image makes the AppBar retract, and tapping again makes it re-appear.  For some reason, though, I haven't been able to actually get it to smoothly animate forward and back, but the effect is there.

In practice, it looks like this:

If somebody figures out (before I do) what I've missed to make it animate smoothly, please feel free to help out.


问:
Adding custom number class to Python int results in "TypeError"
Is there a way to be able to add an instance of a Python class to an integer (default int class). For example, if I have a class with magic methods:

class IntType:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.value + other

# Works
print(IntType(10) + 10)

# Doesn't Work
print(10 + IntType(10))
```

<p>I can't add my <code>IntType</code> to the built-in <code>int</code> class. If I try to add <code>IntType</code> to an integer, I get the following error:</p>

```Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(10 + IntType(10))
TypeError: unsupported operand type(s) for +: 'int' and 'IntType'
```

The only way I can think of to get this to work is to somehow change the int class' __add__ method. If you are wondering why I don't just add the int to the IntType (e.g. IntType(10) + 10) is because I need this to work for all operators, for example subtraction (where the order is important). I'm using Python 3.

答:
Implementing reverse addition (__radd__) for your IntType class should fix this:

```<code>>>> class IntType:
...     def __init__(self, value):
...         self.value = value
...
...     def __add__(self, other):
...        return self.value + other
...
...     def __radd__(self, other):
...         return self.value + other

>>> IntType(10) + 10 == 10 + IntType(10)
True
</code>```

This is the operation that Python tries to use when all else fails (i.e, int.__add__(IntType) is not a defined operation).

Body:
Is there a way to be able to add an instance of a Python class to an integer (default int class). For example, if I have a class with magic methods:

class IntType:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.value + other

# Works
print(IntType(10) + 10)

# Doesn't Work
print(10 + IntType(10))

I can't add my IntType to the built-in int class. If I try to add IntType to an integer, I get the following error:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(10 + IntType(10))
TypeError: unsupported operand type(s) for +: 'int' and 'IntType'

The only way I can think of to get this to work is to somehow change the int class' __add__ method. If you are wondering why I don't just add the int to the IntType (e.g. IntType(10) + 10) is because I need this to work for all operators, for example subtraction (where the order is important). I'm using Python 3.

Body:
Implementing reverse addition (__radd__) for your IntType class should fix this:

>>> class IntType:
...     def __init__(self, value):
...         self.value = value
...
...     def __add__(self, other):
...        return self.value + other
...
...     def __radd__(self, other):
...         return self.value + other

>>> IntType(10) + 10 == 10 + IntType(10)
True

This is the operation that Python tries to use when all else fails (i.e, int.__add__(IntType) is not a defined operation).


问:
How to stringify dates with timezones properly in javascript?
In javascript, I have a date in UTC, and I want to stringify it and parse it but maintain it's UTC. I did this code

var f = { f : new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)")}

undefined

JSON.stringify(f)

"{"f":"2019-05-28T00:11:13.000Z"}"

JSON.parse(JSON.stringify(f))

{f: "2019-05-28T00:11:13.000Z"}

You can see that after I stringified it, it changed to the next day. And then when I parse it, it kept it as a string and even of the next day. I want it so that after I parse it, I get back the Date object of Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time).

Does anyone know what's wrong?

Thanks

答:
You can see that after I stringified it, it changed to the next day

No, it didn't. "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" was parsed to a time value of 1559002273000, which defines a moment in time that is that many milliseconds after 1970-01-01T00:00:00Z. It's equivalent to 2019-05-28T00:11:13.000Z (and other timestamps in other time zones). E.g. on a system set to an eastern Australian timezone you'd get "Tue May 28 2019 10:11:13 GMT+1000 (AEST)".

I want it so that after I parse it, I get back the Date object of Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)

The date object has no knowledge of the timezone of the original timestamp, it just stores the time value. The string produced by toString just uses the host system timezone setting to generate a "local" timestamp in the format specified by ECMA-262. Note that the timezone name is implementation dependent and since they aren't standardised, the names and abbreviations differ between implementations. E.g. Safari shows "AEST" and Firefox "Australian Eastern Standard Time".

You can use toLocaleString to generate timestamps for different timezones, but the date object doesn't know what the original timezone was and the format may not be what you want.

Also, toLocaleString uses IANA timezone identifiers (e.g. Africa/Kinshasa), which relate to geographic locations that are used to deduce the applicable timezone rather than common names like "Eastern Daylight Time" which are not standardised and can be ambiguous or obscure. The IANA designators mean things like daylight saving and historic timezone offset changes can be applied more easily than with other designators.


问:
Problem regarding using priority queues using my own created class
I made a triplet class, and want to use its object as members in the Min Priority queue, but I am getting an error. The code is for merging k sorted arrays.
Please help me solve this doubt. I tried a number of ways to solve this but majority times getting an error.</p>

```<code>    #include<queue>
    using namespace std;

    class triplet{
        public:
        int element;
        int ai;
        int ei;
        bool operator()(triplet &a, triplet &b);
    };

    class Comp{
        public:
        bool operator()(triplet &a, triplet &b){
            return a.element > b.element;
        }
    };

    vector<int> mergeKSortedArrays(vector<vector<int>*> input){
        /* Don't write main().
         * Don't read input, it is passed as function argument.
         * Return the output.
         * Taking input and printing output is handled automatically.
         */
        vector<int> ans;
        priority_queue<triplet , vector<triplet> , Comp> pq;

        for(int i = 0; i < input.size(); i++){
            triplet *temp = new triplet();
            temp->element = input[i]->at(0);
            temp->ai = i;
            temp->ei = 0;
            pq.push(temp);
        }

        while(!pq.empty()){
            triplet current = pq.top();
            ans.push_back(current);
            pq.pop();

            if(current.ei < input[current.ai]->size())
                pq.push_back(input[current.ai]->at(current.ei + 1) , current.ai , ei + 1);
        }
        return ans;
    }

Compilation Failed
In file included from Runner.cpp:4:0:
Solution.h: In function 'std::vector mergeKSortedArrays(std::vector*>)':
Solution.h:34:21: error: no matching function for call to 'std::priority_queue, Comp>::push(triplet*&)'
         pq.push(temp);
                     ^
In file included from /usr/include/c++/5/queue:64:0,
                 from Solution.h:1,
                 from Runner.cpp:4:
/usr/include/c++/5/bits/stl_queue.h:499:7: note: candidate: void std::priority_queue<_Tp, _Sequence, _Compare>::push(const value_type&) [with _Tp = triplet; _Sequence = std::vector; _Compare = Comp; std::priority_queue<_Tp, _Sequence, _Compare>::value_type = triplet]
       push(const value_type& __x)
       ^
/usr/include/c++/5/bits/stl_queue.h:499:7: note:   no known conversion for argument 1 from 'triplet*' to 'const value_type& {aka const triplet&}'
/usr/include/c++/5/bits/stl_queue.h:507:7: note: candidate: void std::priority_queue<_Tp, _Sequence, _Compare>::push(std::priority_queue<_Tp, _Sequence, _Compare>::value_type&&) [with _Tp = triplet; _Sequence = std::vector; _Compare = Comp; std::priority_queue<_Tp, _Sequence, _Compare>::value_type = triplet]
       push(value_type&& __x)
</code>```

答: temp is a pointer to a triplet, but your priority queue stores triplet objects.  Change temp to be triplet temp; (making other appropriate code changes).  Or give triplet a constructor, get rid of temp completely, and use pq.emplace(/*...*/); instead.

Body:
I made a triplet class, and want to use its object as members in the Min Priority queue, but I am getting an error. The code is for merging k sorted arrays.
Please help me solve this doubt. I tried a number of ways to solve this but majority times getting an error.

    #include<queue>
    using namespace std;

    class triplet{
        public:
        int element;
        int ai;
        int ei;
        bool operator()(triplet &a, triplet &b);
    };

    class Comp{
        public:
        bool operator()(triplet &a, triplet &b){
            return a.element > b.element;
        }
    };

    vector<int> mergeKSortedArrays(vector<vector<int>*> input){
        /* Don't write main().
         * Don't read input, it is passed as function argument.
         * Return the output.
         * Taking input and printing output is handled automatically.
         */
        vector<int> ans;
        priority_queue<triplet , vector<triplet> , Comp> pq;

        for(int i = 0; i < input.size(); i++){
            triplet *temp = new triplet();
            temp->element = input[i]->at(0);
            temp->ai = i;
            temp->ei = 0;
            pq.push(temp);
        }

        while(!pq.empty()){
            triplet current = pq.top();
            ans.push_back(current);
            pq.pop();

            if(current.ei < input[current.ai]->size())
                pq.push_back(input[current.ai]->at(current.ei + 1) , current.ai , ei + 1);
        }
        return ans;
    }

Compilation Failed
In file included from Runner.cpp:4:0:
Solution.h: In function 'std::vector mergeKSortedArrays(std::vector*>)':
Solution.h:34:21: error: no matching function for call to 'std::priority_queue, Comp>::push(triplet*&)'
         pq.push(temp);
                     ^
In file included from /usr/include/c++/5/queue:64:0,
                 from Solution.h:1,
                 from Runner.cpp:4:
/usr/include/c++/5/bits/stl_queue.h:499:7: note: candidate: void std::priority_queue<_Tp, _Sequence, _Compare>::push(const value_type&) [with _Tp = triplet; _Sequence = std::vector; _Compare = Comp; std::priority_queue<_Tp, _Sequence, _Compare>::value_type = triplet]
       push(const value_type& __x)
       ^
/usr/include/c++/5/bits/stl_queue.h:499:7: note:   no known conversion for argument 1 from 'triplet*' to 'const value_type& {aka const triplet&}'
/usr/include/c++/5/bits/stl_queue.h:507:7: note: candidate: void std::priority_queue<_Tp, _Sequence, _Compare>::push(std::priority_queue<_Tp, _Sequence, _Compare>::value_type&&) [with _Tp = triplet; _Sequence = std::vector; _Compare = Comp; std::priority_queue<_Tp, _Sequence, _Compare>::value_type = triplet]
       push(value_type&& __x)


问:
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array

```<code>HTTP 200 OK
Allow: GET, POST, PUT, DELETE, PATCH
Content-Type: application/json
Vary: Accept

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        3,
        4,
        5,
        6,
        9,
        10
    ],
    "cardio": [
        4
    ]
},
{
    "id": 2,
    "title": "Pull Workout Loddekopinge",
    "description": "",
    "exercises": [
        1,
        2,
        7,
        8
    ],
    "cardio": []
},
{
    "id": 3,
    "title": "CardioPass",
    "description": "",
    "exercises": [],
    "cardio": [
        2,
        3,
        4
    ]
}
]
</code>```

Serializer (So I want to display the title and not the id for every exercise)

```<code>class WorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workout
        fields = ('id', 'title', 'description', 'exercises', 'cardio')
</code>```

Here are the models, note that I want to display the exercise name for every exercise in the api array, I don't want the id! - That is passed right now! :)

```<code>class Bodypart(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Exercise(models.Model):
    name = models.CharField(max_length=40)
    bodyparts = models.ManyToManyField(Bodypart, blank=True)

    def __str__(self):
        return self.name

class Cardio(models.Model):
    name = models.CharField(max_length=40)
    time = models.IntegerField(default=10)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'cardio'

class Workout(models.Model):
    title = models.CharField(max_length=120)
    description = models.CharField(max_length=1000, blank=True)
    exercises = models.ManyToManyField(Exercise, blank=True)
    cardio = models.ManyToManyField(Cardio, blank=True)

    def __str__(self):
        return self.title
</code>```

答:
Try adding exercises field in serializer as below
exercises = serializers.SlugRelatedField(read_only=True, slug_field='title')

Body:
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array

HTTP 200 OK
Allow: GET, POST, PUT, DELETE, PATCH
Content-Type: application/json
Vary: Accept

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        3,
        4,
        5,
        6,
        9,
        10
    ],
    "cardio": [
        4
    ]
},
{
    "id": 2,
    "title": "Pull Workout Loddekopinge",
    "description": "",
    "exercises": [
        1,
        2,
        7,
        8
    ],
    "cardio": []
},
{
    "id": 3,
    "title": "CardioPass",
    "description": "",
    "exercises": [],
    "cardio": [
        2,
        3,
        4
    ]
}
]

Serializer (So I want to display the title and not the id for every exercise)

class WorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workout
        fields = ('id', 'title', 'description', 'exercises', 'cardio')

Here are the models, note that I want to display the exercise name for every exercise in the api array, I don't want the id! - That is passed right now! :)

class Bodypart(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Exercise(models.Model):
    name = models.CharField(max_length=40)
    bodyparts = models.ManyToManyField(Bodypart, blank=True)

    def __str__(self):
        return self.name

class Cardio(models.Model):
    name = models.CharField(max_length=40)
    time = models.IntegerField(default=10)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'cardio'

class Workout(models.Model):
    title = models.CharField(max_length=120)
    description = models.CharField(max_length=1000, blank=True)
    exercises = models.ManyToManyField(Exercise, blank=True)
    cardio = models.ManyToManyField(Cardio, blank=True)

    def __str__(self):
        return self.title


问:
SVG element not receiving onclick in Chrome
I am writing a javascript application for Chrome Version 66.0.3359.139 (and maybe other versions eventually). I am trying to make SVG elements that are clickable. I.e., their onclick methods should be called when they are clicked.

Here is my first attempt:

<svg id="svg" width="100%" height="100%"></svg>

```
</div>
</div>
</p>

<p>This code creates one circle at the top of the page, and one at the bottom. The circles are also recalculated when the page resizes, so that they are always visible. As a test, I want to delete the circle when it is clicked.</p>

<p>Sometimes the above code works. However, when I run it full screen, after opening developer tools at the bottom of the window, and then closing the developer tools, then the bottom circle cannot be clicked -- until after the next time I either zoom or resize the window.</p>

<p>I thought maybe it was a browser bug because it shows up when I use developer tools as described above, and does not occur at all in Firefox. However then I noticed that other websites do not have this problem. Besides it can't be that easy to find a browser bug, as so many sites work in Chrome.</p>

<p>Does anyone see a problem with my Javascript code that could be making the bottom circle fail to receive <code>onclick</code> events?</p>

<p><strong>update</strong></p>

<p>I cannot reproduce this problem in Chrome Version 74.0.3729.169 Linux or Windows. It may be specific to Linux chrome Version 66.0.3359.139.</p>

<p>However, that still doesn't mean it's a browser bug... should the code work or not?</p>

<p><strong>update</strong></p>

<p>The problem is also reproducible in Linux Chrome Version 66.0.3359.181. I am having difficulty downgrading to 66.0.3359.139 (I can't find the deb. Google can be annoying that way). So I am now targeting 66.0.3359.181.</p>

<p><strong>update</strong></p>

<p>The present problem seems to be caused by</p>

```
```

<p>If that style is removed, then the present problem does not occur, but another problem occurs. The present problem occurs equally with:</p>

```
```

<p>This is the case both in my version and the D3 version posted by Dataminion.</p>

<p>So we really have a lump under the rug here... we can step on it but it causes a lump somewhere else. Solve the events, but then SVG can't fill the page. Solve both of the above, but upgrade browser (and deal with a new set of bugs).</p>

<p><strong>update</strong></p>

<p>It works with</p>

```
```

<p>with the only drawbacks being the svg is 1 pixel off, and there is an unwanted scrollbar. Note that:</p>

```
```

removes the scrollbar and reintroduces the bug.

So either overflow:hidden or margin:0 causes the problem. Either of these removes the scrollbar. So the problem is related to there not being a scrollbar (regardless of how it is removed).

答:
@kaiido is correct the issue here is browser related as the original code posted functions as expected in modern browsers.

Suggest OP look at canIuse do identify what their current browser supports when it comes to svg

Leaving my incorrect(for this question) and ultimately unnecessary d3.js example here as proof that I am willing to admit it when I am wrong and totally misread a question.

```<code>let myCircles = [
   { "x_axis": 30, "y_axis": 30, "radius": 20, "color" : "green" },
   { "x_axis": 70, "y_axis": 70, "radius": 20, "color" : "purple"},
   { "x_axis": 110, "y_axis": 100, "radius": 20, "color" : "red"}];

function onresize()
{
    clear();
   let circles = d3.select("svg")
     .selectAll("circle")
     .data(myCircles).enter()
     .append("circle");

   let attributes = circles
     .attr("cx", function (d) { return d.x_axis; })
     .attr("cy", function (d) { return d.y_axis; })
     .attr("r", function (d) { return d.radius; })
     .attr("id", function(d, i){ return 'c' + i; })
     .attr('onclick',function(d, i){ return 'c' + i; })
     .style("fill", function(d) { return d.color; });
}

onresize()
</code>```

Edit for clarity

It could be said that this is a duplicate of D3: How delete shape on click event?

However I would argue that the upvoted answer iterates the item name in a non d3 canonical way.

A callback in an attribute is the where the first input is the "data" and the second is the positional index is more faithful to the design of d3 than to use an externally declared variable to set it.
.attr('onclick',function(d, i){ return 'c' + i; })

Body:
I am writing a javascript application for Chrome Version 66.0.3359.139 (and maybe other versions eventually). I am trying to make SVG elements that are clickable. I.e., their onclick methods should be called when they are clicked.

Here is my first attempt:

<svg id="svg" width="100%" height="100%"></svg>

This code creates one circle at the top of the page, and one at the bottom. The circles are also recalculated when the page resizes, so that they are always visible. As a test, I want to delete the circle when it is clicked.

Sometimes the above code works. However, when I run it full screen, after opening developer tools at the bottom of the window, and then closing the developer tools, then the bottom circle cannot be clicked -- until after the next time I either zoom or resize the window.

I thought maybe it was a browser bug because it shows up when I use developer tools as described above, and does not occur at all in Firefox. However then I noticed that other websites do not have this problem. Besides it can't be that easy to find a browser bug, as so many sites work in Chrome.

Does anyone see a problem with my Javascript code that could be making the bottom circle fail to receive onclick events?

update

I cannot reproduce this problem in Chrome Version 74.0.3729.169 Linux or Windows. It may be specific to Linux chrome Version 66.0.3359.139.

However, that still doesn't mean it's a browser bug... should the code work or not?

update

The problem is also reproducible in Linux Chrome Version 66.0.3359.181. I am having difficulty downgrading to 66.0.3359.139 (I can't find the deb. Google can be annoying that way). So I am now targeting 66.0.3359.181.

update

The present problem seems to be caused by

If that style is removed, then the present problem does not occur, but another problem occurs. The present problem occurs equally with:

This is the case both in my version and the D3 version posted by Dataminion.

So we really have a lump under the rug here... we can step on it but it causes a lump somewhere else. Solve the events, but then SVG can't fill the page. Solve both of the above, but upgrade browser (and deal with a new set of bugs).

update

It works with

with the only drawbacks being the svg is 1 pixel off, and there is an unwanted scrollbar. Note that:

removes the scrollbar and reintroduces the bug.

So either overflow:hidden or margin:0 causes the problem. Either of these removes the scrollbar. So the problem is related to there not being a scrollbar (regardless of how it is removed).

Body:
@kaiido is correct the issue here is browser related as the original code posted functions as expected in modern browsers.

Suggest OP look at canIuse do identify what their current browser supports when it comes to svg

Leaving my incorrect(for this question) and ultimately unnecessary d3.js example here as proof that I am willing to admit it when I am wrong and totally misread a question.

let myCircles = [
   { "x_axis": 30, "y_axis": 30, "radius": 20, "color" : "green" },
   { "x_axis": 70, "y_axis": 70, "radius": 20, "color" : "purple"},
   { "x_axis": 110, "y_axis": 100, "radius": 20, "color" : "red"}];

function onresize()
{
    clear();
   let circles = d3.select("svg")
     .selectAll("circle")
     .data(myCircles).enter()
     .append("circle");

   let attributes = circles
     .attr("cx", function (d) { return d.x_axis; })
     .attr("cy", function (d) { return d.y_axis; })
     .attr("r", function (d) { return d.radius; })
     .attr("id", function(d, i){ return 'c' + i; })
     .attr('onclick',function(d, i){ return 'c' + i; })
     .style("fill", function(d) { return d.color; });
}

onresize()

Edit for clarity

It could be said that this is a duplicate of D3: How delete shape on click event?

However I would argue that the upvoted answer iterates the item name in a non d3 canonical way.

A callback in an attribute is the where the first input is the "data" and the second is the positional index is more faithful to the design of d3 than to use an externally declared variable to set it.
.attr('onclick',function(d, i){ return 'c' + i; })


问:
Install caffe on ubuntu 18.04 LTS
I'm installing caffe-cpu and anaconda on Ubuntu 18.04 LTS version.

Anyway, I success to install Anaconda on my system, but I'm getting in trouble to install caffe.

I found many pages such as youtube, but it isn't helpful, so i read many times to official installation manual page (I think here is the official page). In this page,

```<code>Installing Caffe from source

We may install the dependencies by merely one line
sudo apt build-dep caffe-cpu        # dependencies for CPU-only version
sudo apt build-dep caffe-cuda       # dependencies for CUDA version
</code>```

It requires a deb-src line in your sources.list. Continue with compliation

I can't know end line means. I tried to fix /etc/apt/sources.list as disabled

'#' part, but it's fail. I can't find the correct way on the internet. when I just follow the compliation link, they say compliation with Make or CMake. I also don't know how to follow these information. I found some makefile.config Github page, it fails when I use make all command.

Could you give me some advice to help install caffe-cpu version? Thanks for read my question.

答:
You can append these deb-src lines in your source.list:

```<code>deb http://ftp2.cn.debian.org/debian sid main contrib non-free
deb-src http://ftp2.cn.debian.org/debian sid main contrib non-free
</code>```

If you get some public key errors, these commands will help you.

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 04EE7237B7D453EC
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7638D0442B90D010
</code>```

Title: Install caffe on ubuntu 18.04 LTS

Body:
I'm installing caffe-cpu and anaconda on Ubuntu 18.04 LTS version.

Anyway, I success to install Anaconda on my system, but I'm getting in trouble to install caffe.

I found many pages such as youtube, but it isn't helpful, so i read many times to official installation manual page (I think here is the official page). In this page,

Installing Caffe from source

We may install the dependencies by merely one line
sudo apt build-dep caffe-cpu        # dependencies for CPU-only version
sudo apt build-dep caffe-cuda       # dependencies for CUDA version

It requires a deb-src line in your sources.list. Continue with compliation

I can't know end line means. I tried to fix /etc/apt/sources.list as disabled

'#' part, but it's fail. I can't find the correct way on the internet. when I just follow the compliation link, they say compliation with Make or CMake. I also don't know how to follow these information. I found some makefile.config Github page, it fails when I use make all command.

Could you give me some advice to help install caffe-cpu version? Thanks for read my question.

Body:
You can append these deb-src lines in your source.list:

deb http://ftp2.cn.debian.org/debian sid main contrib non-free
deb-src http://ftp2.cn.debian.org/debian sid main contrib non-free

If you get some public key errors, these commands will help you.

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 04EE7237B7D453EC
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7638D0442B90D010