问:
TLS version used in JDK 8
We initialise our SSL context with the following code and are running on Java 8.

```<code>SSLContext context = SSLContext.getInstance("SSL");
</code>```

Since Java 8 uses TLSv1.2 by default? Does it mean the above code will start sending TLSv1.2 requests if my server supports it.

Want to understand if "SSL" protocol name is just an alias but java runtime starts sending the requests with default TLS version.

UPDATE

I ran my code against "https://www.google.co.in/" and found this in fiddler

```<code>A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Version: 3.3 (TLS/1.2
</code>```

And also if i change my protocol to TLSv1 which only supports 1.0. Then Fiddler tells me

```<code>A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Version: 3.1 (TLS/1.0)
</code>```

So, I guess the above code with "SSL" protocol name should work well with TLS 1.2 servers.

答:
Yes. In Java 7, server side default TLS version was 1.2. In Java 8 both server and client have default TLS version 1.2.

As TLS version is backward compatible on both side unless server is configured strictly to specific version should not be an issue.

Title: TLS version used in JDK 8

Body:
We initialise our SSL context with the following code and are running on Java 8.

SSLContext context = SSLContext.getInstance("SSL");

Since Java 8 uses TLSv1.2 by default? Does it mean the above code will start sending TLSv1.2 requests if my server supports it.

Want to understand if "SSL" protocol name is just an alias but java runtime starts sending the requests with default TLS version.

UPDATE

I ran my code against "https://www.google.co.in/" and found this in fiddler

A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Version: 3.3 (TLS/1.2

And also if i change my protocol to TLSv1 which only supports 1.0. Then Fiddler tells me

A SSLv3-compatible ClientHello handshake was found. Fiddler extracted the parameters below.

Version: 3.1 (TLS/1.0)

So, I guess the above code with "SSL" protocol name should work well with TLS 1.2 servers.


来源: stackexchange

问:
Can I configure the frequency range of getByteFrequencyData()?
I am using the JavaScript Web Audio API to create a frequency viewer.
Apparently the getByteFrequencyData distributes the gain of frequencies from 0 to 255 in an array, but the frequencies are apparently from 20Hz to 20kHz and I would like to know if I can regulate the frequency range that is stored. For example, instead of 20Hz to 20kHz, I would like 20Hz to 800Hz.
Edit:

Apparently, fftSize causes the frequency range to decrease, but increasing it a lot, leaves the analysis with a lot of delay.

答:
No, you can't really configure the range.  The frequency range is always 0 to context.sampleRate / 2.  Changing fftSize just changes the number of bins that cover the range.

If you want just the range 20-800 Hz, just take the set of bins that cover this region.  You will throw away a lot of data, but there's not much that can be done.

I really think AnalyserNode is really meant for visualization, not analysis, despite the name.

ContentLicense: CC BY-SA 4.0


问:
Slicing n points or as many as possible from list
I'm using python slicing to take elements from a list but don't know if there are going to be enough in there.

At the moment I'm doing this, which feels ugly:

```<code>        if index + num_to_take > len(values):
            bit = values[index: ]
        else:
            bit = values[index:index + num_to_take]
</code>```

Is there a better way?

答:
You can skip the if condition altogether.

bit = values[index:index + num_to_take] would run just fine.

Taking advantage of how slicing works in python. Read this for more information.

Body:
I'm using python slicing to take elements from a list but don't know if there are going to be enough in there.

At the moment I'm doing this, which feels ugly:

        if index + num_to_take > len(values):
            bit = values[index: ]
        else:
            bit = values[index:index + num_to_take]

Is there a better way?


问:
Merge sort function in C
I have the following piece of code which represents a merge sort function

```<code>/* perform merge sort */
void merge_sort(int arr[], int left, int right) {
    if (left < right) {
        int middle = left + (right - left) / 2;
        merge_sort(arr, left, middle);
        merge_sort(arr, middle + 1, right);
        merge(arr, left, middle, right);
    }
}
</code>```

What is the use of this merge_sort(arr, middle + 1, right);?

答:
The basic idea of the merge sort algorithm is to divide the sequence to be sorted in half, sort each half, and then merge them together. This is frequently done recursively, as in this case. As a result, there must be two recursive calls, one for each half of the sequence.

If the merge_sort(arr, middle+1, right); call were not present, the algorithm would not be complete and the sort would not work.

As an experiment, you could try writing an example program using the merge sort function you posted. Try it with and without the line in question and see what results you get.

Title: Merge sort function in C

Body:
I have the following piece of code which represents a merge sort function

/* perform merge sort */
void merge_sort(int arr[], int left, int right) {
    if (left < right) {
        int middle = left + (right - left) / 2;
        merge_sort(arr, left, middle);
        merge_sort(arr, middle + 1, right);
        merge(arr, left, middle, right);
    }
}

What is the use of this merge_sort(arr, middle + 1, right);?


问:
Simple A/B randomization script with PHP
I have two ad options in my theme, Adsense and "Custom". If the user enters code into the "Custom" field, it trumps whatever they have in the "Adsense" code field, so the theme places their custom ad atop the content area. If they have adsense enabled, and nothing in the custom ad spot, the theme places their adsense code there.

I'd like to add an option to allow the user to opt to have my theme automatically rotate ads between adsense and their custom ads. The custom ads may be Ebay, Amazon, ClickBank, etc.

How would you set up a PHP script that will randomly choose between two options?

Alternately, I'd like to be able to give the user the option to choose a percentage value so that the adsense ads are rotated based on their chosen percentage.

Just looking for some suggested approaches. Thanks in advance.

答:
```<code><?php

   $option[0] = 'html option 1';
   $option[1] = 'html option 2';

   echo $option[rand()%count($option)];
?>
</code>```

ContentLicense: CC BY-SA 3.0


问:
java label exporting a blank image
My java code places a image on a label which in the code is label1. When the user hits button b1 it should export the image in a specific size. Right now a image file is exported but it is just a black screen. The image on the label is not being transferred. I want the image on the label to be transferred. </p>

```<code>   JLabel labels = new JLabel("Label 2");
        static JButton b1 = new JButton("First");

        b1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

  BufferedImage scaledButtonImage =
      new BufferedImage(400, 1000, bimg.getType());
          Graphics g1 = scaledButtonImage.createGraphics();
      g1.drawImage(scaledButtonImage, 0, 0, 0, 0, null);
      g1.dispose();

              label2.setIcon(new ImageIcon(bimg));

          try {

              ImageIO.write(scaledButtonImage, "png",file);

          }

            });
    }
</code>```

答:
Right now a image file is exported but it is just a black screen.

```<code>g1.drawImage(scaledButtonImage, 0, 0, 0, 0, null);
</code>```

Read the API for the drawImage(…) method.

You are not specifying the width/height parameters of the image you want to draw, so nothing is begin drawn.

Also, you are drawing the BufferedImage onto itself.

If you want to draw the Image from the label you need code like:

```<code>ImageIcon icon = (ImageIcon)label.getIcon();
g1.drawImage(icon.getImage(), …);
</code>```

Title: java label exporting a blank image

Body:
My java code places a image on a label which in the code is label1. When the user hits button b1 it should export the image in a specific size. Right now a image file is exported but it is just a black screen. The image on the label is not being transferred. I want the image on the label to be transferred.

   JLabel labels = new JLabel("Label 2");
        static JButton b1 = new JButton("First");

        b1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

  BufferedImage scaledButtonImage =
      new BufferedImage(400, 1000, bimg.getType());
          Graphics g1 = scaledButtonImage.createGraphics();
      g1.drawImage(scaledButtonImage, 0, 0, 0, 0, null);
      g1.dispose();

              label2.setIcon(new ImageIcon(bimg));

          try {

              ImageIO.write(scaledButtonImage, "png",file);

          }

            });
    }

Body:
Right now a image file is exported but it is just a black screen.

g1.drawImage(scaledButtonImage, 0, 0, 0, 0, null);

Read the API for the drawImage(…) method.

You are not specifying the width/height parameters of the image you want to draw, so nothing is begin drawn.

Also, you are drawing the BufferedImage onto itself.

If you want to draw the Image from the label you need code like:

ImageIcon icon = (ImageIcon)label.getIcon();
g1.drawImage(icon.getImage(), …);


问:
How to change folder names in python?
I have multiple folders each with the name of a person, with the first name(s) first and the surname last.  I want to change the folder names so that the surname is first followed by a comma and then the first name(s) follow.

As an example, in the folder Test, i have:

```<code>C:/Test/John Smith
C:/Test/Fred Jones
C:/Test/Ben Jack Martin
</code>```

and i want to make this:

```<code>C:/Test/Smith, John
C:/Test/Jones, Fred
C:/Test/Martin, Ben Jack
</code>```

I tried some things with os.rename but i couldn't seem to make it work with the varying name length, and i wasn't sure how to insert the comma into the surname.

Also, some of the folder names are already in the correct form, so i need to skip these folders during the renaming.  I think you can do this by just adding an if, so that if the folder name contains a comma it will continue.

Otherwise, the surname will always be the last word in the folder name.

Thanks for any help you can provide.

答:
An alternative to os.rename is shutil.move(src, dest)

```<code>import shutil
import os
shutil.move("M://source/folder", "M://destination/folder")
os.rename("M://source/folder", "M://destination/folder")
</code>```

Differences:

OS module might fail to move a file if the source and destination path is on different file systems or drive.
  But shutil.move will not fail in this kind of cases.

shutil.move checks if the source and destination path are on the same file system or not. But os.rename does not check, thus it fails sometimes.

After checking the source and destination path, if it is found that they are not in the same file system, shutil.move will copy the file first to the destination. Then it will delete the file from the source file. Thus we can say shutil.move is a smarter method to move a file in Python when the source and destination path are not on the same drive or file system.

shutil.move works on high-level functions, while os.rename works on lower-level functions.

I would also advise using pathlib to manipulate paths:

```<code>from shutil import move
from pathlib import Path

base_path = Path("C:/Test")

for folder in base_path.iterdir():
    if not folder.is_dir() or folder.name.startswith("."):
        continue

    name = folder.name
    new_name = ", ".join(name.split(" "))
    new_folder = folder.parent / new_name

    move(folder, new_folder)

</code>```

Title: How to change folder names in python?

Body:
I have multiple folders each with the name of a person, with the first name(s) first and the surname last.  I want to change the folder names so that the surname is first followed by a comma and then the first name(s) follow.

As an example, in the folder Test, i have:

C:/Test/John Smith
C:/Test/Fred Jones
C:/Test/Ben Jack Martin

and i want to make this:

C:/Test/Smith, John
C:/Test/Jones, Fred
C:/Test/Martin, Ben Jack

I tried some things with os.rename but i couldn't seem to make it work with the varying name length, and i wasn't sure how to insert the comma into the surname.

Also, some of the folder names are already in the correct form, so i need to skip these folders during the renaming.  I think you can do this by just adding an if, so that if the folder name contains a comma it will continue.

Otherwise, the surname will always be the last word in the folder name.

Thanks for any help you can provide.

Body:
An alternative to os.rename is shutil.move(src, dest)

import shutil
import os
shutil.move("M://source/folder", "M://destination/folder")
os.rename("M://source/folder", "M://destination/folder")

Differences:

OS module might fail to move a file if the source and destination path is on different file systems or drive.
  But shutil.move will not fail in this kind of cases.

shutil.move checks if the source and destination path are on the same file system or not. But os.rename does not check, thus it fails sometimes.

After checking the source and destination path, if it is found that they are not in the same file system, shutil.move will copy the file first to the destination. Then it will delete the file from the source file. Thus we can say shutil.move is a smarter method to move a file in Python when the source and destination path are not on the same drive or file system.

shutil.move works on high-level functions, while os.rename works on lower-level functions.

I would also advise using pathlib to manipulate paths:

from shutil import move
from pathlib import Path

base_path = Path("C:/Test")

for folder in base_path.iterdir():
    if not folder.is_dir() or folder.name.startswith("."):
        continue

    name = folder.name
    new_name = ", ".join(name.split(" "))
    new_folder = folder.parent / new_name

    move(folder, new_folder)


问:
Javascript get largest object in array of objects
I want to get the largest object in an array of objects, the code I'm using works fine, but I wonder if there is a better way of doing the same. This is the code I'm using.

data=[
    {group: "a", A: 65, N: 20},
    {group: "b", R: 52},
    {group: "c", N: 20, A: 2, R: 2},
    {group: "d", R: 15, N: 12},
]

len = []
for (var i in data){
    len.push(Object.keys(data[i]).length)
}

for (var i in data){
    if (Object.keys(data[i]).length==Math.max.apply(null, len)){
      subgroups = Object.keys(data[i]).slice(1).sort();
    }
}

console.log(subgroups);```

答:
To sort the whole array seems stupid, one loop is enough using reduce function</p>

```<code>const { element } = data.reduce((agg, element) => {
  const length = Object.keys(v).length
  if (length > agg.length) {
    return { element, length }
  }
  return agg
}, { element: null, length: 0 })
</code>```

Body:
To sort the whole array seems stupid, one loop is enough using reduce function

const { element } = data.reduce((agg, element) => {
  const length = Object.keys(v).length
  if (length > agg.length) {
    return { element, length }
  }
  return agg
}, { element: null, length: 0 })


问:
Enable as a primary App ID option is disable in Sign In with Apple - Apple ID configuration
I am trying to add the "Sign In with Apple" to my existing App ID. After checking the option to enable it, the following popup was shown: with this message:

If you're enabling an App ID for the first time or for a new app, enable the App ID as a primary. You can use primary App IDs on their own or to enable identifiers for related apps and websites through grouping. To enable an App ID for a related app, (for example, an App ID for the iOS version of your Mac app), group it with the existing primary. This will also ensure that users only need to provide consent to share their information with you once for each group of apps and websites.

However, I could not proceed because the Save button is disabled. I could not do anything.

are there any extra configs I missed or are there anyways around to enable an App Id as primary?

答: The UI is confusing, what I did was selecting sign in with apple first then immediately clicking save/continue. Don't click configure yet, save first. Then Click cnfigure and enable primary ID.</p>


问:
Missing tab name and tab names doesn't change on android studio
I have my main acitivty which opens SearchActivity with tabs, I did 3 tabs I see only 2 when I run the app and the tab names dont change from Tab 1, Tab 2 to what I configured.

public class MainActivity extends AppCompatActivity {

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

    //Open search window
    Button button = findViewById(R.id.buttonSearch);
    button.setOnClickListener(new View.OnClickListener() {
        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        @Override
        public void onClick(View v) {
            openSearchActivity();
        }
    });
}

public void openSearchActivity() {
    Intent intent = new Intent(this, SearchActivity.class);
    startActivity(intent);
}
</code>```

}

public class SearchActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
    ViewPager viewPager = findViewById(R.id.view_pager);
    viewPager.setAdapter(sectionsPagerAdapter);
    TabLayout tabs = findViewById(R.id.tabs);
    tabs.setupWithViewPager(viewPager);
    FloatingActionButton fab = findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

public class SectctionPagerAdapter extends FragmentPagerAdapter {
    /**
     * Constructor for {@link FragmentPagerAdapter} that sets the fragment manager for the adapter.
     * This is the equivalent of calling {@link #( FragmentManager , int)} and
     * passing in {@link #BEHAVIOR_SET_USER_VISIBLE_HINT}.
     *
     * <p>Fragments will have {@link Fragment#setUserVisibleHint(boolean)} called whenever the
     * current Fragment changes.</p>
     *
     * @param fm fragment manager that will interact with this adapter
     * @deprecated use {@link #(FragmentManager, int)} with
     * {@link #BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT}
     */
    public SectctionPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }

    /**
     * Return the Fragment associated with a specified position.
     *
     * @param position
     */
    @NonNull
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new BuildingTabOne();
            case 1:
                return new BuildingTabTwo();
            case 2:
                return new BuildingTabThree();
            default:
                return null;
        }
    }

    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "T15";
            case 1:
                return "Y3";
            case 2:
                return "T21";
        }
        return null;
    }

    /**
     * Return the number of tabs available.
     */
    @Override
    public int getCount() {
        return 3;
    }
}
</code>```

}

Example one tab:

```<code>public class BuildingTabTwo extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.building_tab_two, container, false);
        return view;
    }
}
</code>```

what did I do wrong?

Edit: added layout:
Main:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <Button
            android:text="Search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/buttonSearch"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.919"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Search:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
        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=".SearchActivity">

    <com.google.android.material.appbar.AppBarLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:theme="@style/AppTheme.AppBarOverlay">

        <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:minHeight="?actionBarSize"
                android:padding="@dimen/appbar_padding"
                android:text="@string/app_name"
                android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"/>

        <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"/>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:srcCompat="@android:drawable/ic_dialog_email"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Tab layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

</LinearLayout>
</code>```

答:
the tablayout and viewpager must be together. Can you try this code.

It should be something like

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".SearchActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:minHeight="?actionBarSize"
            android:padding="@dimen/appbar_padding"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" />

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary" />
        </androidx.viewpager.widget.ViewPager>
    </com.google.android.material.appbar.AppBarLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

</code>```

Body:
I have my main acitivty which opens SearchActivity with tabs, I did 3 tabs I see only 2 when I run the app and the tab names dont change from Tab 1, Tab 2 to what I configured.

public class MainActivity extends AppCompatActivity {

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

    //Open search window
    Button button = findViewById(R.id.buttonSearch);
    button.setOnClickListener(new View.OnClickListener() {
        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        @Override
        public void onClick(View v) {
            openSearchActivity();
        }
    });
}

public void openSearchActivity() {
    Intent intent = new Intent(this, SearchActivity.class);
    startActivity(intent);
}

}

public class SearchActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
    ViewPager viewPager = findViewById(R.id.view_pager);
    viewPager.setAdapter(sectionsPagerAdapter);
    TabLayout tabs = findViewById(R.id.tabs);
    tabs.setupWithViewPager(viewPager);
    FloatingActionButton fab = findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

public class SectctionPagerAdapter extends FragmentPagerAdapter {
    /**
     * Constructor for {@link FragmentPagerAdapter} that sets the fragment manager for the adapter.
     * This is the equivalent of calling {@link #( FragmentManager , int)} and
     * passing in {@link #BEHAVIOR_SET_USER_VISIBLE_HINT}.
     *
     *
Fragments will have {@link Fragment#setUserVisibleHint(boolean)} called whenever the
     * current Fragment changes.

     *
     * @param fm fragment manager that will interact with this adapter
     * @deprecated use {@link #(FragmentManager, int)} with
     * {@link #BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT}
     */
    public SectctionPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }

    /**
     * Return the Fragment associated with a specified position.
     *
     * @param position
     */
    @NonNull
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new BuildingTabOne();
            case 1:
                return new BuildingTabTwo();
            case 2:
                return new BuildingTabThree();
            default:
                return null;
        }
    }

    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "T15";
            case 1:
                return "Y3";
            case 2:
                return "T21";
        }
        return null;
    }

    /**
     * Return the number of tabs available.
     */
    @Override
    public int getCount() {
        return 3;
    }
}

}

Example one tab:

public class BuildingTabTwo extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.building_tab_two, container, false);
        return view;
    }
}

what did I do wrong?

Edit: added layout:
Main:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <Button
            android:text="Search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/buttonSearch"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.919"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Search:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
        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=".SearchActivity">

    <com.google.android.material.appbar.AppBarLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:theme="@style/AppTheme.AppBarOverlay">

        <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:minHeight="?actionBarSize"
                android:padding="@dimen/appbar_padding"
                android:text="@string/app_name"
                android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"/>

        <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"/>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:srcCompat="@android:drawable/ic_dialog_email"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Tab layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

</LinearLayout>

Body:
the tablayout and viewpager must be together. Can you try this code.

It should be something like

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".SearchActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:minHeight="?actionBarSize"
            android:padding="@dimen/appbar_padding"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" />

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary" />
        </androidx.viewpager.widget.ViewPager>
    </com.google.android.material.appbar.AppBarLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>


问:
Blazor server side extended validation
I want my validation model to be invalid when the entered value for ActionId is not within in array/list of integers

```<code>public class AddTerminalInput
{
    private List<int> actionIds;
    public AddTerminalInput(List<int> actionIds)
    {
        this.actionIds = actionIds;
    }
    [Required(AllowEmptyStrings = false)]
    public string TerminalId { get; set; } = "";
    [Required(AllowEmptyStrings = false)]
    public string TerminalName { get; set; } = "";

    // ActionId should be only valid if the value is within actionIds
    public int ActionId { get; set; } = 1;
}
</code>```

does anybody know how I can achive this?

答: There is a library on nuget for Blazor & FluentValidation, that will do it.</p>

Title: Blazor server side extended validation

Body:
I want my validation model to be invalid when the entered value for ActionId is not within in array/list of integers

public class AddTerminalInput
{
    private List<int> actionIds;
    public AddTerminalInput(List<int> actionIds)
    {
        this.actionIds = actionIds;
    }
    [Required(AllowEmptyStrings = false)]
    public string TerminalId { get; set; } = "";
    [Required(AllowEmptyStrings = false)]
    public string TerminalName { get; set; } = "";

    // ActionId should be only valid if the value is within actionIds
    public int ActionId { get; set; } = 1;
}

does anybody know how I can achive this?


问:
Finding empty directories in Python
All,

What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.

```<code>dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)
</code>```

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.

Thanks,
Adam

答:
Try:

```<code>if not os.listdir(dir):
    print "Empty"
</code>```

or

```<code>if os.listdir(dir) == []:
    print "Empty"
</code>```

Title: Finding empty directories in Python

Body:
All,

What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.

dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.

Thanks,
Adam

Body:
Try:

if not os.listdir(dir):
    print "Empty"

or

if os.listdir(dir) == []:
    print "Empty"


问:
How can I convert a list to string
```<code>data class Movie(
    @SerializedName("movie_name")
    val movieName : String
    @SerializedName("genres")
    val movieGenre : List<String>){}
</code>```

How can I convert a list to string created every object in this data class

答:
You can use additional property in Movie class to convert list to string, e.g. val genre:

```<code>data class Movie(
        @SerializedName("movie_name")
        val movieName: String,
        @SerializedName("genres")
        val movieGenre: List<String>
) {
    val genre: String
        get() = buildString { // builds new string using append() method on each item of movieGenre
            movieGenre.forEach { append(it) }
        }

}
</code>```

Here is how to access it:

```<code>val movie: Movie = getMoviewFromInternet()
val movieGenre: String = movie.genre
</code>```

Title: How can I convert a list to string

Body:
data class Movie(
    @SerializedName("movie_name")
    val movieName : String
    @SerializedName("genres")
    val movieGenre : List<String>){}

How can I convert a list to string created every object in this data class

Body:
You can use additional property in Movie class to convert list to string, e.g. val genre:

data class Movie(
        @SerializedName("movie_name")
        val movieName: String,
        @SerializedName("genres")
        val movieGenre: List<String>
) {
    val genre: String
        get() = buildString { // builds new string using append() method on each item of movieGenre
            movieGenre.forEach { append(it) }
        }

}

Here is how to access it:

val movie: Movie = getMoviewFromInternet()
val movieGenre: String = movie.genre


答:
There is no need of ifs

bit = values[index:index + num_to_take] will run fine

Title: Slicing n points or as many as possible from list


问:
WampServer orange icon
I am having problems with Wamp Server, the icon will never turn green. It is constantly stuck at orange.

I have tried many ways, editing HOSTS file, .config files, disabling IIS, changing SKYPE's port, quitting SKYPE, disabling World Wide Web publishing services etc... And under wamp server icon > Apache > Test port 80, it states that Apache is using that port.

I am running Windows 8 64 bit and Wamp Server 2.4. Any help would be appreciated.

答:
In case that helps anybody I had the same issue with wampserver3.2.0_x64 on Windows 10 Enterprise.

Tried everything from the answers of this thread and nothing helped.

I then installed wampserver3.1.0_x86 instead and got the green light on first launch. I have no explanation but at least the desired end result.

Title: WampServer orange icon


问:
Remove rows in pandas df with index values within a range
I would like to remove all rows in a pandas df that have an index value within 4 counts of the index value of the previous row.

In the pandas df below,

```<code>    A   B
0   1   1
5   5   5
8   9   9
9   10  10
</code>```

Only the row with index value 0 should remain.

Thanks!

Body:
I would like to remove all rows in a pandas df that have an index value within 4 counts of the index value of the previous row.

In the pandas df below,

    A   B
0   1   1
5   5   5
8   9   9
9   10  10

Only the row with index value 0 should remain.

Thanks!

Body:
You can use reset_index, diff and shift:

In [1309]: df
Out[1309]:
    A   B
0   1   1
5   5   5
8   9   9
9  10  10

In [1310]: d = df.reset_index()

In [1313]: df = d[d['index'].diff(1).shift(-1) >=4].drop('index', 1)
In [1314]: df
Out[1313]:
   A  B
0  1  1


问:
In tkinter, it showed "TypeError: not all arguments converted during string formatting"
```<code>def kiir2():
    if sz1.get()%2==0:
        prs1=Label(ablak,text=sz1.get())
        prs1.grid(row=4,column=2)
    elif sz3.get()%2==0:
        prs2=Label(ablak,text=sz3.get())
        prs2.grid(row=4,column=2)
    elif sz5.get()%2==0:
        prs3=Label(ablak,text=sz5.get())
        prs3.grid(row=4,column=2)
</code>```

And I get the error:

```<code>TypeError: not all arguments converted during string formatting
</code>```

How can i fix this?

答:
.get() returns a string. %2 is trying to do string formatting, not a modulo operation. If you're trying to do a modulo operation, you need to convert the value to an int.

```<code>if int(sz1.get())%2 == 0:
   ...
</code>```

A better practice, however, is to do the conversion and the math in separate steps, since the conversion could throw errors due to bad data (user not entering anything, the user entering a non-integer, etc).

```<code>try:
    sz1_value = int(sz1.get())
Except ValueError:
    <code to handle bad user input>
...
if sz1_value % 2 == 0:
    ...
</code>```

Body:
def kiir2():
    if sz1.get()%2==0:
        prs1=Label(ablak,text=sz1.get())
        prs1.grid(row=4,column=2)
    elif sz3.get()%2==0:
        prs2=Label(ablak,text=sz3.get())
        prs2.grid(row=4,column=2)
    elif sz5.get()%2==0:
        prs3=Label(ablak,text=sz5.get())
        prs3.grid(row=4,column=2)

And I get the error:

TypeError: not all arguments converted during string formatting

How can i fix this?

Body:
.get() returns a string. %2 is trying to do string formatting, not a modulo operation. If you're trying to do a modulo operation, you need to convert the value to an int.

if int(sz1.get())%2 == 0:
   ...

A better practice, however, is to do the conversion and the math in separate steps, since the conversion could throw errors due to bad data (user not entering anything, the user entering a non-integer, etc).

try:
    sz1_value = int(sz1.get())
Except ValueError:
    <code to handle bad user input>
...
if sz1_value % 2 == 0:
    ...


问:
Kivy segmentation fault on blitting opencv picture
I am trying to cast video from my external cam, that is captured through some aliexpress EasyCap, to my kivy app. One issue I've faced is that crashes with segmentation fault on trying to

```<code>texture = Texture.create(size=(frame.shape[0], frame.shape[1]))
</code>```

I've found that the problem is on kivy's side. It sometimes can't create NPOT textures. So, I've changed it to POT shape and copied what is possible to another numpy array.

```<code>flipped = cv2.flip(frame, 0)
buf = np.zeros((512, 512, 3), dtype=np.uint8)
for i in range(min(frame.shape[0], 512)):
   for j in range(min(frame.shape[1], 512)):
      buf[i, j] = flipped[i, j]
buf = buf.tostring()
texture = Texture.create(size=(512, 512))
texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
self.texture = texture
</code>```

But it still crashes with the same old segmentation fault on the following line:

```<code>texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
</code>```

If it is relevant, cv2.imshow("image", buf) before buf.tostring() show the image correctly.

Here's the original code:

```<code>from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
import threading
from time import sleep
import numpy as np

class KivyCamera(Image):
   def __init__(self, **kwargs):
      super(KivyCamera, self).__init__(**kwargs)
      self.fps = 30
      self.capture = cv2.VideoCature(0)
      threading.Thread(target=self.update).start()

   def update(self):
      while True:
         ret, frame = self.capture.read()
         if ret:
            buf = cv2.flip(frame, 0).tostring()
            texture = Texture.create(size=(frame.shape[0], frame.shape[1])
            texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
            self.texture = texture
         sleep(1.0 / self.fps)

class CamApp(App):
   def build(self):
         return KivyCamera()

if __name__ == "__main__":
   CamApp().run()
</code>```

答: Not well documented, but I believe the Texture manipulation (specifically the blit_buffer()) must be done on the main thread. Your update() method is being run in another thread, so use Clock.schedule_once() to call a method that does the Texture manipulation (and the self.texture = texture) back in the main thread.

Body:
I am trying to cast video from my external cam, that is captured through some aliexpress EasyCap, to my kivy app. One issue I've faced is that crashes with segmentation fault on trying to

texture = Texture.create(size=(frame.shape[0], frame.shape[1]))

I've found that the problem is on kivy's side. It sometimes can't create NPOT textures. So, I've changed it to POT shape and copied what is possible to another numpy array.

flipped = cv2.flip(frame, 0)
buf = np.zeros((512, 512, 3), dtype=np.uint8)
for i in range(min(frame.shape[0], 512)):
   for j in range(min(frame.shape[1], 512)):
      buf[i, j] = flipped[i, j]
buf = buf.tostring()
texture = Texture.create(size=(512, 512))
texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
self.texture = texture

But it still crashes with the same old segmentation fault on the following line:

texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")

If it is relevant, cv2.imshow("image", buf) before buf.tostring() show the image correctly.

Here's the original code:

from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
import threading
from time import sleep
import numpy as np

class KivyCamera(Image):
   def __init__(self, **kwargs):
      super(KivyCamera, self).__init__(**kwargs)
      self.fps = 30
      self.capture = cv2.VideoCature(0)
      threading.Thread(target=self.update).start()

   def update(self):
      while True:
         ret, frame = self.capture.read()
         if ret:
            buf = cv2.flip(frame, 0).tostring()
            texture = Texture.create(size=(frame.shape[0], frame.shape[1])
            texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
            self.texture = texture
         sleep(1.0 / self.fps)

class CamApp(App):
   def build(self):
         return KivyCamera()

if __name__ == "__main__":
   CamApp().run()


问:
AttributeError: 'str' object has no attribute 'json'
I wrote little script on python 3.7 to receive actual browser version

Here is it:

```<code>import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]
</code>```

Also, json file exists, but it does not matter now.

Received:

```<code>AttributeError: 'str' object has no attribute 'json'.
</code>```

In row

```<code>last_version = repr(res.json()['latest']['client'][browser_name]['version'])
</code>```

Please, tell me what is my mistake?

答: If you are trying to convert res as a json object try json.loads(res) instead of res.json()

Body:
I wrote little script on python 3.7 to receive actual browser version

Here is it:

import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]

Also, json file exists, but it does not matter now.

Received:

AttributeError: 'str' object has no attribute 'json'.

In row

last_version = repr(res.json()['latest']['client'][browser_name]['version'])

Please, tell me what is my mistake?


问:
How to prevent mutation of private structures returned by reference
I have following code:

```<code>struct MyStruct {
    int a;
    int b;
};

class Foo {
public:
    MyStruct const &getValue() {
        return value;
    }

private:
    MyStruct value{10, 20};
};

int main() {
    Foo foo{};
    auto v = foo.getValue();
    v.a = 42; // compiles! it shouldn't!
}
</code>```

I want to return a reference to private member, but don't allow caller to mutate contents of this reference. Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to. Though, declaring return type as MyStruct& const fails with "'const' qualifier may not be applied to a reference". I believe I might be missing something here.

I could have solved that with declaring MyStruct with all const fields, but I want to mutate it myself inside my class — only disallow caller to do so.

How is it possible to do so?

答:
Your wrong assumption is that auto v declares a reference. It doesn't, you get a copy of the MyStruct returned from getValue().

You can check that original object is not mutated:

```<code>int main() {
    Foo foo{};
    auto v = foo.getValue();
    v.a = 42; // compiles! it should!
    std::cout << foo.getValue().a; //prints 10
}
</code>```

Declaring v as reference type wouldn't compile

```<code>int main() {
    Foo foo{};
    auto& v = foo.getValue(); // const is deduced by auto
    v.a = 42; // error
}
</code>```

Body:
I have following code:

struct MyStruct {
    int a;
    int b;
};

class Foo {
public:
    MyStruct const &getValue() {
        return value;
    }

private:
    MyStruct value{10, 20};
};

int main() {
    Foo foo{};
    auto v = foo.getValue();
    v.a = 42; // compiles! it shouldn't!
}

I want to return a reference to private member, but don't allow caller to mutate contents of this reference. Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to. Though, declaring return type as MyStruct& const fails with "'const' qualifier may not be applied to a reference". I believe I might be missing something here.

I could have solved that with declaring MyStruct with all const fields, but I want to mutate it myself inside my class — only disallow caller to do so.

How is it possible to do so?

Body:
Your wrong assumption is that auto v declares a reference. It doesn't, you get a copy of the MyStruct returned from getValue().

You can check that original object is not mutated:

int main() {
    Foo foo{};
    auto v = foo.getValue();
    v.a = 42; // compiles! it should!
    std::cout << foo.getValue().a; //prints 10
}

Declaring v as reference type wouldn't compile

int main() {
    Foo foo{};
    auto& v = foo.getValue(); // const is deduced by auto
    v.a = 42; // error
}


问:
Inserting data to MySQL from file (csv, sql) in PhpStorm
My situation is as follows. I have a remote database, which i can only access via ssh-tunnel. I promptly configured it as a Data Source in PHPStorm and everything works fine. However, i often need to operate moderately large tables (several millions of records), so simply copy-pasting INSERT statements to add data doesn't work.

I tried googling it, search PhpStorm Help, but there is no info at all. Perhaps, some plugin exists for such task, or is there another way of inserting data from files via PHPStorm?

答:
Step by step guide to execute Mysql Script from PhpStrom or any Jet Brain's intelligence IDE

1.Put your MySQL script file in current project directory.

2.Right click and select option Run_{fileName.sql} from Context menu (Tip: you can also select multiple files if you want.)

3.Select appropriate Schema/database name in Target data source/Schema

4.click on Run button. After that execution of operations will going to start.


问:
CameraAccessException Broken pipe while starting camera session
I am getting this CameraAccessException while attempting to create a capture session after the onOpened() Callback from CameraDevice.StateCallback

First the crashlog

```<code>Fatal Exception: android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): endConfigure:537: Camera 1: Error configuring streams: Broken pipe (-32)
       at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:1127)
       at android.hardware.camera2.impl.ICameraDeviceUserWrapper.endConfigure(ICameraDeviceUserWrapper.java:117)
       at android.hardware.camera2.impl.CameraDeviceImpl.configureStreamsChecked(CameraDeviceImpl.java:481)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSessionInternal(CameraDeviceImpl.java:669)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSession(CameraDeviceImpl.java:517)
       at a.b.c.d.MainActivity.startCapturingSession(MainActivity.java:364)
       at a.b.c.d.MainActivity.access$startCapturingSession(MainActivity.java:36)
       at a.b.c.d.MainActivity$stateCallback$1.onOpened(MainActivity.java:90)
       at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:150)
       at android.os.Handler.handleCallback(Handler.java:883)
       at android.os.Handler.dispatchMessage(Handler.java:100)
       at android.os.Looper.loop(Looper.java:237)
       at android.os.HandlerThread.run(HandlerThread.java:67)

Caused by android.os.ServiceSpecificException: endConfigure:537: Camera 1: Error configuring streams: Broken pipe (-32)
       at android.os.Parcel.createException(Parcel.java:2102)
       at android.os.Parcel.readException(Parcel.java:2056)
       at android.os.Parcel.readException(Parcel.java:2004)
       at android.hardware.camera2.ICameraDeviceUser$Stub$Proxy.endConfigure(ICameraDeviceUser.java:742)
       at android.hardware.camera2.impl.ICameraDeviceUserWrapper.endConfigure(ICameraDeviceUserWrapper.java:114)
       at android.hardware.camera2.impl.CameraDeviceImpl.configureStreamsChecked(CameraDeviceImpl.java:481)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSessionInternal(CameraDeviceImpl.java:669)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSession(CameraDeviceImpl.java:517)
       at a.b.c.d.MainActivity.startCapturingSession(MainActivity.java:364)
       at a.b.c.d.MainActivity.access$startCapturingSession(MainActivity.java:36)
       at a.b.c.d.MainActivity$stateCallback$1.onOpened(MainActivity.java:90)
       at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:150)
       at android.os.Handler.handleCallback(Handler.java:883)
       at android.os.Handler.dispatchMessage(Handler.java:100)
       at android.os.Looper.loop(Looper.java:237)
       at android.os.HandlerThread.run(HandlerThread.java:67)
</code>```

The Camera error doc says the camera is in error state. Can this be due to anything being implemented wrongly from the app code?

My app code

```<code>private val stateCallback = object : CameraDevice.StateCallback() {
        override fun onOpened(camera: CameraDevice) {
            cameraDevice = camera
            startCapturingSession()
        }

        override fun onDisconnected(camera: CameraDevice) {
            cameraDevice = null
            camera.close()
        }

        override fun onError(camera: CameraDevice, error: Int) {
            onDisconnected(camera)
        }
    }

@WorkerThread
    private fun startCapturingSession() {

        val prevSurface = previewSurface ?: kotlin.run {
            throw IllegalStateException("Preview Surface is null while starting capture session")
        }

        reader1 = ImageReader.newInstance(
            PREVIEW_WIDTH, PREVIEW_HEIGHT,
            ImageFormat.YUV_420_888, IMAGE_READER_MAX_IMAGES
        )
        reader1!!.setOnImageAvailableListener(analyser, null)
        val surface1 = reader1!!.surface

        reader2 = ImageReader.newInstance(
            PREVIEW_WIDTH, PREVIEW_HEIGHT,
            ImageFormat.YUV_420_888, IMAGE_READER_MAX_IMAGES
        )
        reader2!!.setOnImageAvailableListener(imageAvailableListener, null)
        val surface2 = reader2!!.surface
        val device = cameraDevice
            ?: throw IllegalStateException("Camera Device null while capturing session")

        device.createCaptureSession( // this is line 364 from the crash log
            listOf(surface1, surface2, prevSurface),
            object : CameraCaptureSession.StateCallback() {
                override fun onConfigureFailed(session: CameraCaptureSession) {
                }

                override fun onConfigured(session: CameraCaptureSession) {
                    // more code here
                }
            }, null
        )
    }
</code>```

At the worst case could I catch this and close and repoen the camera?

This does not occur always but successive trials of opening the app was failing.

答:
I was having the same issue and it was due to the aspect ratio of my preview. I implemented the following code to return me the correct preview size for my device. I found that the problem was the value i was passing to the aspect ratio(i was passing the size of the preview), and in some devices the camera crashed while trying to open. I was getting the CameraError(3) broken pipe exception.

private static Size ChooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight,
            int maxWidth, int maxHeight)
        {
            var bigEnough = new List<Size>();
            var notBigEnough = new List<Size>();

            //Test different aspect ratios(4:3, 16:9)
            int w = 4;
            int h = 3;

            foreach(Size option in choices)
            {
                if(option.Width <= maxWidth && option.Height <= maxHeight)
                {
                    if(option.Height == option.Width * h                    / w)
                    {
                        if (option.Width >= textureViewWidth && option.Height >= textureViewHeight)
                        {
                            bigEnough.Add(option);
                        }
                        else
                            notBigEnough.Add(option);
                    }
                }
            }

            if (bigEnough.Count > 0)
                return (Size)Collections.Min(bigEnough, new ComparesSizeByArea());
            else if (notBigEnough.Count > 0)
                return (Size)Collections.Max(notBigEnough, new ComparesSizeByArea());
            else
            {
                return choices[0];
            }
        }```
</div>
</div>
</p>

<p>The ComparesSizesByArea is a aux class with the following method:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> public int Compare(Java.Lang.Object lhs, Java.Lang.Object rhs)
        {
            var lhsSize = (Size)lhs;
            var rhsSize = (Size)rhs;

            return Long.Signum((long)lhsSize.Width * lhsSize.Height - (long)rhsSize.Width * rhsSize.Height);
        }</code>```

On your extended textureView, constraint it to the width also:

 protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        base.OnMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = MeasureSpec.GetSize(widthMeasureSpec);
        int height = MeasureSpec.GetSize(heightMeasureSpec);

        if (ratioWidth == 0 || ratioHeight == 0)
            SetMeasuredDimension(width, height);
        else
        {
            if (width > (float)height * ratioWidth / ratioHeight)
                SetMeasuredDimension(width, width * ratioHeight / ratioWidth);
            else
                SetMeasuredDimension(height * ratioWidth / ratioHeight, height);
        }
    }```

Body:
I am getting this CameraAccessException while attempting to create a capture session after the onOpened() Callback from CameraDevice.StateCallback

First the crashlog

Fatal Exception: android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): endConfigure:537: Camera 1: Error configuring streams: Broken pipe (-32)
       at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:1127)
       at android.hardware.camera2.impl.ICameraDeviceUserWrapper.endConfigure(ICameraDeviceUserWrapper.java:117)
       at android.hardware.camera2.impl.CameraDeviceImpl.configureStreamsChecked(CameraDeviceImpl.java:481)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSessionInternal(CameraDeviceImpl.java:669)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSession(CameraDeviceImpl.java:517)
       at a.b.c.d.MainActivity.startCapturingSession(MainActivity.java:364)
       at a.b.c.d.MainActivity.access$startCapturingSession(MainActivity.java:36)
       at a.b.c.d.MainActivity$stateCallback$1.onOpened(MainActivity.java:90)
       at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:150)
       at android.os.Handler.handleCallback(Handler.java:883)
       at android.os.Handler.dispatchMessage(Handler.java:100)
       at android.os.Looper.loop(Looper.java:237)
       at android.os.HandlerThread.run(HandlerThread.java:67)

Caused by android.os.ServiceSpecificException: endConfigure:537: Camera 1: Error configuring streams: Broken pipe (-32)
       at android.os.Parcel.createException(Parcel.java:2102)
       at android.os.Parcel.readException(Parcel.java:2056)
       at android.os.Parcel.readException(Parcel.java:2004)
       at android.hardware.camera2.ICameraDeviceUser$Stub$Proxy.endConfigure(ICameraDeviceUser.java:742)
       at android.hardware.camera2.impl.ICameraDeviceUserWrapper.endConfigure(ICameraDeviceUserWrapper.java:114)
       at android.hardware.camera2.impl.CameraDeviceImpl.configureStreamsChecked(CameraDeviceImpl.java:481)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSessionInternal(CameraDeviceImpl.java:669)
       at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSession(CameraDeviceImpl.java:517)
       at a.b.c.d.MainActivity.startCapturingSession(MainActivity.java:364)
       at a.b.c.d.MainActivity.access$startCapturingSession(MainActivity.java:36)
       at a.b.c.d.MainActivity$stateCallback$1.onOpened(MainActivity.java:90)
       at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:150)
       at android.os.Handler.handleCallback(Handler.java:883)
       at android.os.Handler.dispatchMessage(Handler.java:100)
       at android.os.Looper.loop(Looper.java:237)
       at android.os.HandlerThread.run(HandlerThread.java:67)

The Camera error doc says the camera is in error state. Can this be due to anything being implemented wrongly from the app code?

My app code

private val stateCallback = object : CameraDevice.StateCallback() {
        override fun onOpened(camera: CameraDevice) {
            cameraDevice = camera
            startCapturingSession()
        }

        override fun onDisconnected(camera: CameraDevice) {
            cameraDevice = null
            camera.close()
        }

        override fun onError(camera: CameraDevice, error: Int) {
            onDisconnected(camera)
        }
    }

@WorkerThread
    private fun startCapturingSession() {

        val prevSurface = previewSurface ?: kotlin.run {
            throw IllegalStateException("Preview Surface is null while starting capture session")
        }

        reader1 = ImageReader.newInstance(
            PREVIEW_WIDTH, PREVIEW_HEIGHT,
            ImageFormat.YUV_420_888, IMAGE_READER_MAX_IMAGES
        )
        reader1!!.setOnImageAvailableListener(analyser, null)
        val surface1 = reader1!!.surface

        reader2 = ImageReader.newInstance(
            PREVIEW_WIDTH, PREVIEW_HEIGHT,
            ImageFormat.YUV_420_888, IMAGE_READER_MAX_IMAGES
        )
        reader2!!.setOnImageAvailableListener(imageAvailableListener, null)
        val surface2 = reader2!!.surface
        val device = cameraDevice
            ?: throw IllegalStateException("Camera Device null while capturing session")

        device.createCaptureSession( // this is line 364 from the crash log
            listOf(surface1, surface2, prevSurface),
            object : CameraCaptureSession.StateCallback() {
                override fun onConfigureFailed(session: CameraCaptureSession) {
                }

                override fun onConfigured(session: CameraCaptureSession) {
                    // more code here
                }
            }, null
        )
    }

At the worst case could I catch this and close and repoen the camera?

This does not occur always but successive trials of opening the app was failing.

Body:
I was having the same issue and it was due to the aspect ratio of my preview. I implemented the following code to return me the correct preview size for my device. I found that the problem was the value i was passing to the aspect ratio(i was passing the size of the preview), and in some devices the camera crashed while trying to open. I was getting the CameraError(3) broken pipe exception.

private static Size ChooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight,
            int maxWidth, int maxHeight)
        {
            var bigEnough = new List<Size>();
            var notBigEnough = new List<Size>();

            //Test different aspect ratios(4:3, 16:9)
            int w = 4;
            int h = 3;

            foreach(Size option in choices)
            {
                if(option.Width <= maxWidth && option.Height <= maxHeight)
                {
                    if(option.Height == option.Width * h                    / w)
                    {
                        if (option.Width >= textureViewWidth && option.Height >= textureViewHeight)
                        {
                            bigEnough.Add(option);
                        }
                        else
                            notBigEnough.Add(option);
                    }
                }
            }

            if (bigEnough.Count > 0)
                return (Size)Collections.Min(bigEnough, new ComparesSizeByArea());
            else if (notBigEnough.Count > 0)
                return (Size)Collections.Max(notBigEnough, new ComparesSizeByArea());
            else
            {
                return choices[0];
            }
        }

The ComparesSizesByArea is a aux class with the following method:

 public int Compare(Java.Lang.Object lhs, Java.Lang.Object rhs)
        {
            var lhsSize = (Size)lhs;
            var rhsSize = (Size)rhs;

            return Long.Signum((long)lhsSize.Width * lhsSize.Height - (long)rhsSize.Width * rhsSize.Height);
        }

On your extended textureView, constraint it to the width also:

 protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        base.OnMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = MeasureSpec.GetSize(widthMeasureSpec);
        int height = MeasureSpec.GetSize(heightMeasureSpec);

        if (ratioWidth == 0 || ratioHeight == 0)
            SetMeasuredDimension(width, height);
        else
        {
            if (width > (float)height * ratioWidth / ratioHeight)
                SetMeasuredDimension(width, width * ratioHeight / ratioWidth);
            else
                SetMeasuredDimension(height * ratioWidth / ratioHeight, height);
        }
    }


问:
Get html from  and attach it to img
I have HTML:

```<code><table id='ansichttable' class='table appels'>
    <thead>
        <tr>
            <th class='bold'>Afbeelding</th>
            <th class="bold">Locatie</th>
            <th class='bold'>Groep</th>
            <th class='bold'>Soort</th>
            <th class='bold'>Bijzonderheden</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a class="img" href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Dubbele Bellefleur</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
        <tr>
            <td><a class="img" href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Dubbele Zoete Aagt</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
        <tr>
            <td><a href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Ellisons Orange</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
    </tbody>
</table>
</code>```

What I am trying to create is that jQuery gets the title from the: td class="titel"
and create at the a href="......" a title tag like this:

```<code><td><a href="images/imagesfruit/boomgaard4.jpg" titel="Ellisons Orange"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
<td valign="top">Tuin</td>
<td valign="top">Appels</td>
<td valign="top" class="titel">Ellisons Orange</td>
<td valign="top">Zoete stevige appel</td>
</code>```

I have tried the following :

```<code>$(document).ready(function(){
 var gettitle = $("td:eq(3)").html();
                 $("td a").attr("title", $('td.titel').text());
</code>```

And:

```<code>$("td a.img").attr("title", $('.titel').html());
</code>```

And:

```<code>$('table').each(function() {
  var title = $(this).find('td.titel').text();
  $(this).find('td a').attr('title', title);
 });
</code>```

All of them are working, but collecting all the titles from the table and attach them to all the images.

What I need is that jQuery collects the title and attach it to the image above the td where it gets the title. What am I doing wrong?

答:
See: http://jsfiddle.net/dP76b/

```<code>$(document).ready(function(){
    $('.table tr').each(function(){
        var titleText = $(this).find('.titel').text();
        $(this).find('a.img img').attr('title', titleText);
    });
});
</code>```

The "Ellisons Orange" image doesn't work because the corresponding a element does not have class="img":

```<code><a href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a>
</code>```

You can either add the class, or change .find('a.img img') to .find('a img').

Title: Get html from <td class"title"> and attach it to img

Body:
I have HTML:

            Afbeelding
            Locatie
            Groep
            Soort
            Bijzonderheden

            Tuin
            Appels
            Dubbele Bellefleur
            Zoete stevige appel

            Tuin
            Appels
            Dubbele Zoete Aagt
            Zoete stevige appel

            Tuin
            Appels
            Ellisons Orange
            Zoete stevige appel

What I am trying to create is that jQuery gets the title from the: td class="titel"
and create at the a href="......" a title tag like this:

Tuin
Appels
Ellisons Orange
Zoete stevige appel

I have tried the following :

$(document).ready(function(){
 var gettitle = $("td:eq(3)").html();
                 $("td a").attr("title", $('td.titel').text());

And:

$("td a.img").attr("title", $('.titel').html());

And:

$('table').each(function() {
  var title = $(this).find('td.titel').text();
  $(this).find('td a').attr('title', title);
 });

All of them are working, but collecting all the titles from the table and attach them to all the images.

What I need is that jQuery collects the title and attach it to the image above the td where it gets the title. What am I doing wrong?

Body:
See: http://jsfiddle.net/dP76b/

$(document).ready(function(){
    $('.table tr').each(function(){
        var titleText = $(this).find('.titel').text();
        $(this).find('a.img img').attr('title', titleText);
    });
});

The "Ellisons Orange" image doesn't work because the corresponding a element does not have class="img":

<a href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a>

You can either add the class, or change .find('a.img img') to .find('a img').


答:
The data you show appears to be more compatible with using a JSON parser.  (But that is not what you asked.)

How can i use strtok?

First, study the patterns of your input data.  Yours is repeatable, makeng use of strtok() viable, but the way it's formatted  will make parsing interesting.

With the input file as you have provided, the delimiters are unfortunate!  For example using the ":" delimiter between the time string segments, and also in front of the second sub-string used for humidity:

```<code>"2014-02-13T06:20:00": "3.0",
              ^  ^   ^
              |  |   |_this would be better as a comma ","
              |__|_____These are fine as is
</code>```

But as long as the input file is actually shaped as you have it, the following code will parse it.

For your question: How can i use strtok?, the following an implementation that illustrates how this may be done.  It uses a combination of nested strtok() and calls to strchr()  to walk through the file, separating each of the items into variables.

```<code>int fsize(FILE *fp);

int main(void)
{
    FILE *fp = fopen("tempm.txt", "r");

    char *value;
    char hr[4];
    char min[4];
    char sec[4];
    char date[12];
    char hum_rate[6];
    char *data;
    char line[100][50];//change if file size changes!
    double num = 0.0;

    char *tok;

    int filesize = fsize(fp);//get file size
    data = calloc(filesize+1, 1);//size the buffer to contain file contents
    if(!data) //failed, exit
    {
        return 0
    }
    fgets(data, filesize+1, fp);//read file int buffer (its one line)

   int i = 0;
    value = strtok(data, ",");//get string segmemts
    while(value)
    {   //separate into data into date-time-hum_rate segments
        strcpy(line[i++], value);//line segments
        value = strtok(NULL, ",");
    }
    //we now have data segments separated
    int count = i;//preserve value of i into count
    for(i=0;i<count;i++)
    {
        value = strtok(line[i], "T");//get date
        if(value)
        {
            tok = strchr(value, '"');
            strcpy(date, tok+1);//consume the extra "
            value = strtok(NULL, ":");//hour
            if(value)
            {
                strcpy(hr, value);
                value = strtok(NULL, ":");//minute
                if(value)
                {
                    strcpy(min, value);//second
                    value = strtok(NULL, ":\"");
                    if(value)
                    {
                        strcpy(sec, value);
                        value = strtok(NULL, ":");//humidity
                        if(value)
                        {
                            tok = strchr(value, '"');//consume the extra "
                            num = strtod(tok+1, NULL);
                            sprintf(hum_rate, "%.1lf", num);
                        }
                    }
                }
            }
        }
        //output to test results:
        printf("%d)\nDate: %s\nTime: %s:%s:%s\nHumidity Rate: %s\n\n", i+1, date, hr, min, sec, hum_rate);
        free(data);
    }

    return 0;
}

int fsize(FILE *fp)
{
    int prev=ftell(fp);
    fseek(fp, 0L, SEEK_END);
    int sz=ftell(fp);
    fseek(fp,prev,SEEK_SET); //go back to where we were
    return sz;
}
</code>```

Title: How can i use strtok?

Body:
{"2014-02-13T06:20:00": "3.0", "2014-02-13T13:50:00": "7.0", "2014-02-13T06:00:00": "2", "2014-02-13T03:00:00": "3", "2014-02-13T13:00:00": "6", "2014-02-13T18:50:00": "4.0", "2014-02-13T13:20:00": "6.0", "2014-02-13T15:00:00": "6", "2014-02-13T08:50:00": "4.0", "2014-02-13T21:50:00": "4.0", "2014-02-13T08:00:00": "3", "2014-02-13T07:50:00": "3.0", "2014-02-13T08:20:00": "4.0", "2014-02-13T21:20:00": "3.0", "2014-02-13T11:50:00": "6.0", "2014-02-13T11:20:00": "6.0", "2014-02-13T17:50:00": "5.0", "2014-02-13T11:00:00": "6", "2014-02-13T05:50:00": "2.0", "2014-02-13T20:50:00": "3.0", "2014-02-13T20:20:00": "4.0", "2014-02-13T16:00:00": "6", "2014-02-13T23:50:00": "2.0", "2014-02-13T21:00:00": "3", "2014-02-13T07:20:00": "3.0", "2014-02-13T03:20:00": "3.0", "2014-02-13T07:00:00": "3", "2014-02-13T15:50:00": "6.0", "2014-02-13T03:50:00": "2.0", "2014-02-13T04:00:00": "2", "2014-02-13T12:00:00": "6", "2014-02-13T04:20:00": "2.0", "2014-02-13T12:20:00": "6.0", "2014-02-13T12:50:00": "6.0", "2014-02-13T22:50:00": "3.0", "2014-02-13T09:00:00": "4", "2014-02-13T09:20:00": "4.0", "2014-02-13T09:50:00": "4.0", "2014-02-13T18:00:00": "5", "2014-02-13T05:20:00": "2.0", "2014-02-13T15:20:00": "6.0", "2014-02-13T00:50:00": "4.0", "2014-02-13T14:50:00": "7.0", "2014-02-13T00:00:00": "4", "2014-02-13T00:20:00": "4.0", "2014-02-13T06:50:00": "3.0", "2014-02-13T22:00:00": "4", "2014-02-13T18:20:00": "5.0", "2014-02-13T02:50:00": "3.0", "2014-02-13T02:20:00": "3.0", "2014-02-13T04:50:00": "2.0", "2014-02-13T02:00:00": "3", "2014-02-13T23:00:00": "3", "2014-02-13T16:50:00": "5.0", "2014-02-13T19:50:00": "4.0", "2014-02-13T19:20:00": "4.0", "2014-02-13T05:00:00": "2", "2014-02-13T19:00:00": "4", "2014-02-13T23:20:00": "3.0", "2014-02-13T14:20:00": "7.0", "2014-02-13T10:20:00": "5.0", "2014-02-13T10:00:00": "4", "2014-02-13T10:50:00": "5.0", "2014-02-13T17:00:00": "5", "2014-02-13T01:00:00": "4", "2014-02-13T17:20:00": "5.0", "2014-02-13T01:20:00": "4.0", "2014-02-13T01:50:00": "4.0", "2014-02-13T22:20:00": "3.0", "2014-02-13T16:20:00 :"6.0"}

I have this text, which represent (for example):
date -> 2014-02-13T06:20:00
humid rate -> 4.0

At first, I want to have as an output date \n humid rate \n date \n humid rate etc. etc.. I've tried to use strtok, but i couldn't do much.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINESIZE 128

int main()
{
    FILE *fp = fopen("tempm.txt", "r");
    char line[LINESIZE];
    char *value;

    while(fgets(line, sizeof(line), fp))
    {
        value = strtok(line, "\" \":");
        printf("\n%s", value);
    }

    return 0;
}

This is the code I've written so far.

Body:
The data you show appears to be more compatible with using a JSON parser.  (But that is not what you asked.)

How can i use strtok?

First, study the patterns of your input data.  Yours is repeatable, makeng use of strtok() viable, but the way it's formatted  will make parsing interesting.

With the input file as you have provided, the delimiters are unfortunate!  For example using the ":" delimiter between the time string segments, and also in front of the second sub-string used for humidity:

"2014-02-13T06:20:00": "3.0",
              ^  ^   ^
              |  |   |_this would be better as a comma ","
              |__|_____These are fine as is

But as long as the input file is actually shaped as you have it, the following code will parse it.

For your question: How can i use strtok?, the following an implementation that illustrates how this may be done.  It uses a combination of nested strtok() and calls to strchr()  to walk through the file, separating each of the items into variables.

int fsize(FILE *fp);

int main(void)
{
    FILE *fp = fopen("tempm.txt", "r");

    char *value;
    char hr[4];
    char min[4];
    char sec[4];
    char date[12];
    char hum_rate[6];
    char *data;
    char line[100][50];//change if file size changes!
    double num = 0.0;

    char *tok;

    int filesize = fsize(fp);//get file size
    data = calloc(filesize+1, 1);//size the buffer to contain file contents
    if(!data) //failed, exit
    {
        return 0
    }
    fgets(data, filesize+1, fp);//read file int buffer (its one line)

   int i = 0;
    value = strtok(data, ",");//get string segmemts
    while(value)
    {   //separate into data into date-time-hum_rate segments
        strcpy(line[i++], value);//line segments
        value = strtok(NULL, ",");
    }
    //we now have data segments separated
    int count = i;//preserve value of i into count
    for(i=0;i<count;i++)
    {
        value = strtok(line[i], "T");//get date
        if(value)
        {
            tok = strchr(value, '"');
            strcpy(date, tok+1);//consume the extra "
            value = strtok(NULL, ":");//hour
            if(value)
            {
                strcpy(hr, value);
                value = strtok(NULL, ":");//minute
                if(value)
                {
                    strcpy(min, value);//second
                    value = strtok(NULL, ":\"");
                    if(value)
                    {
                        strcpy(sec, value);
                        value = strtok(NULL, ":");//humidity
                        if(value)
                        {
                            tok = strchr(value, '"');//consume the extra "
                            num = strtod(tok+1, NULL);
                            sprintf(hum_rate, "%.1lf", num);
                        }
                    }
                }
            }
        }
        //output to test results:
        printf("%d)\nDate: %s\nTime: %s:%s:%s\nHumidity Rate: %s\n\n", i+1, date, hr, min, sec, hum_rate);
        free(data);
    }

    return 0;
}

int fsize(FILE *fp)
{
    int prev=ftell(fp);
    fseek(fp, 0L, SEEK_END);
    int sz=ftell(fp);
    fseek(fp,prev,SEEK_SET); //go back to where we were
    return sz;
}


问:
mPDF pagination problem when using WriteHTML function
I have a dinamically generated HTML content and want to generate a page-numbered PDF using mPDF. The problem is that when the content spans more than one page, the footer is only visible in the last page.

Example:

```<code>$mpdf->AliasNbPages('{PAGETOTAL}');
$mpdf->WriteHTML($content); // $content is dynamic, it can be a series of paragraphs resulting in a 3 or 4, or more, pages long pdf.
$mpdf->setFooter('{PAGENO}/{PAGETOTAL}'); // this only prints a footer in the last page, displaying for example "3/3", but the previous pages do not have footer
</code>```

I want the footer in every page, but i don't know in advance how many pages I will have or where the pagebreaks will be.

Am I doing something wrong?

答:
Try putting setFooter before WriteHTML

So, this way:

```<code>$mpdf->setFooter('{PAGENO}/{PAGETOTAL}');
$mpdf->WriteHTML($content);
</code>```

Body:
I have a dinamically generated HTML content and want to generate a page-numbered PDF using mPDF. The problem is that when the content spans more than one page, the footer is only visible in the last page.

Example:

$mpdf->AliasNbPages('{PAGETOTAL}');
$mpdf->WriteHTML($content); // $content is dynamic, it can be a series of paragraphs resulting in a 3 or 4, or more, pages long pdf.
$mpdf->setFooter('{PAGENO}/{PAGETOTAL}'); // this only prints a footer in the last page, displaying for example "3/3", but the previous pages do not have footer

I want the footer in every page, but i don't know in advance how many pages I will have or where the pagebreaks will be.

Am I doing something wrong?

Body:
Try putting setFooter before WriteHTML

So, this way:

$mpdf->setFooter('{PAGENO}/{PAGETOTAL}');
$mpdf->WriteHTML($content);


问:
Required help in regex
I have created a regex that validate value 10, 10GB.....
I want to correct it to something like it should not take value 10.
regex : "^\d+(\.\d\d?)?\s*(B|[KMGTP]B|%)?$"

regards
NewDev

答:
Just get rid of the ? after the (B|[KMGTP]B|%) bit and it'll work as intended.  Also might want to change the * after \s to ? so it doesn't match "10_____B".  (where _ is space)

```<code>"^\d+(\.\d\d?)?\s?(B|[KMGTP]B|%)$"
</code>```

Title: Required help in regex

Body:
Just get rid of the ? after the (B|[KMGTP]B|%) bit and it'll work as intended.  Also might want to change the * after \s to ? so it doesn't match "10_____B".  (where _ is space)

"^\d+(\.\d\d?)?\s?(B|[KMGTP]B|%)$"


问:
Prevent a TeamCity build configuration to run for certain branches
Is there a way to configure a build configuration in a way that it may run only for certain branches. I'm not only talking about automatic triggers, I also want to prevent users from manually triggering a run for other branches.</p>

答:
To prevent users from manually triggering a build, you need to set user permissions. This can be done under Administration > users/groups > group name/username > roles.

If you want them to only view the project, you can assign the role Project Viewer.
You can also make your own roles with your own set of rules by clicking Administration > roles.


问:
beautifulsoup select method not selecting results as expected
Following the automate the boring stuff tutorial in chapter 11, the I’m Feeling Lucky Google Search project. It's downloading the HTML data correctly seemingly but when I use beautifulsoup to select the result links I get nothing. According to the book it said use soup.select('.r a') and it didn't select anything.

Reading the documentation I tried using differing syntax soup.select('[class~=r]') to hopefully get beautifulsoup to select something but it didn't. I've also tried selecting different classes and it didn't do that either so I assume I'm doing something fundamentally wrong.

```<code>SEARCHVAR = sys.argv[1:]

res = requests.get('http://google.com/search?q=' + ' '.join(SEARCHVAR))
res.raise_for_status()
print('Searching ' + ' '.join(SEARCHVAR[:]) + ' on Google')
soup = bs4.BeautifulSoup(res.text, 'html.parser')
print('Parsing')
linkElems = soup.select('.r a')
print(str(linkElems))
</code>```

I used the print(str(linkElems)) to check what beautifulsoup is selecting but I keep getting nothing, just [].

答:
Replace this:

```<code>linkElems = soup.select('div#main > div > div > div > a')
</code>```

With:

```<code>linkElems = soup.select('div#main > div > div > div > a')
</code>```

Body:
Following the automate the boring stuff tutorial in chapter 11, the I’m Feeling Lucky Google Search project. It's downloading the HTML data correctly seemingly but when I use beautifulsoup to select the result links I get nothing. According to the book it said use soup.select('.r a') and it didn't select anything.

Reading the documentation I tried using differing syntax soup.select('[class~=r]') to hopefully get beautifulsoup to select something but it didn't. I've also tried selecting different classes and it didn't do that either so I assume I'm doing something fundamentally wrong.

SEARCHVAR = sys.argv[1:]

res = requests.get('http://google.com/search?q=' + ' '.join(SEARCHVAR))
res.raise_for_status()
print('Searching ' + ' '.join(SEARCHVAR[:]) + ' on Google')
soup = bs4.BeautifulSoup(res.text, 'html.parser')
print('Parsing')
linkElems = soup.select('.r a')
print(str(linkElems))

I used the print(str(linkElems)) to check what beautifulsoup is selecting but I keep getting nothing, just [].

Body:
Replace this:

linkElems = soup.select('div#main > div > div > div > a')

With:

linkElems = soup.select('div#main > div > div > div > a')


问:
Nuxt.js is not importing font-face properly
I'm using custom font files with Nuxt project. I tried to add font files to /static/fonts and import them using

```<code>  font-family: 'coconregular';
  src: url('fonts/cocon-regular-font.woff2') format('woff2'),
       url('fonts/cocon-regular-font.woff') format('woff');
  font-weight: normal;
  font-style: normal;

}

$cocon: 'coconregular';

.brand-name {
  font-family: $cocon;
}
</code>```

I'm having    '@nuxtjs/style-resources' installed and all other variables and SCSS loading is working totally fine but fonts are not loading.

This is my file structure
files screenshot

I can't find a way to add fonts properly neither i don't know how to check if the font is loaded. There aren't any errors.

What is the correct way for Nuxt and SCSS to load fontfiles?

答:
So i finally figured out good workaround. I don't know if this is good or not, but i separated fonts download from anything else.  Therefore i added another entrypoint to nuxt.config.js to include fonts stylesheet before other stuff.

```<code>css: [
    '@/assets/scss/theme/fonts/stylesheet.css',
    '@/assets/scss/main.scss'
  ],
</code>```

It worked good because My fonts stylesheet for Woff and Woff2 files were generated by font squirrel generator anyway.

Hope this helps you guys

Body:
I'm using custom font files with Nuxt project. I tried to add font files to /static/fonts and import them using

  font-family: 'coconregular';
  src: url('fonts/cocon-regular-font.woff2') format('woff2'),
       url('fonts/cocon-regular-font.woff') format('woff');
  font-weight: normal;
  font-style: normal;

}

$cocon: 'coconregular';

.brand-name {
  font-family: $cocon;
}

I'm having    '@nuxtjs/style-resources' installed and all other variables and SCSS loading is working totally fine but fonts are not loading.

This is my file structure
files screenshot

I can't find a way to add fonts properly neither i don't know how to check if the font is loaded. There aren't any errors.

What is the correct way for Nuxt and SCSS to load fontfiles?

Body:
So i finally figured out good workaround. I don't know if this is good or not, but i separated fonts download from anything else.  Therefore i added another entrypoint to nuxt.config.js to include fonts stylesheet before other stuff.

css: [
    '@/assets/scss/theme/fonts/stylesheet.css',
    '@/assets/scss/main.scss'
  ],

It worked good because My fonts stylesheet for Woff and Woff2 files were generated by font squirrel generator anyway.

Hope this helps you guys


问:
How to import Vensim model to Anylogic PLE?
I have encountered "parsing error! com.anylogic.ui.bad: encountered " ","","" at column X, row Y, was expecting: ..."
The Vensim model is in MDL format and consists of three simple formulas, however, the importer doesn't work. How can I fix the issue?</p>

答:
This is a bug

I just tested models with Vensim 7 and no problem to import, but with vensim 8 it's impossible to import models, and I get your same error.

I will report this problem to AnyLogic.

Response from AnyLogic:

Our converter was written several years ago, and we do not maintain
  compatibility with newer versions of Vensim.They have updated file
  format, and we need to research it, and update our converter. This is
  not a taks with high priority. Vensim 8 support will be added in next
  versions (8.8 or later).


问:
Angular Unit Testing: Observable variable value not updating in the data service
I have a data service that is used by a component.

For example:

BookService:

```<code>...
private book: Book;
private bookSubject = new BehaviorSubject<Book>(this.book);
bookChanged = this.bookSubject.asObservable();
...
</code>```

BookComponent:

```<code>...
book: Book;
ngOnInit() {
  this.bookService.bookChanged.subscribe(
    (book: Book) => this.book = book;
  )
}
...
</code>```

Spec (test file) for the component:

```<code>describe('BookComponent', () => {
  let component: BookComponent;
  let fixture: ComponentFixture<BookComponent>;
  let bookServiceStub: Partial<BookService>;

  bookServiceStub = {
    bookChanged: of({id: 123, name: 'Book 1'})
  };
  beforeEach(async(() => {
    TestBed
      .configureTestingModule({
        declarations: [BookComponent],
        providers: [
          {provide: BookService, useValue: bookServiceStub},
          ...
        ]
      })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };
    bookServiceStub.bookChanged = of(newBook);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.book.id).toBe(newBook.id); // FAILS (still has old value)
      expect(component.book).toBe(newBook); // FAILS (still has old value)
    });
  }));
});

</code>```

So the tests fail because the "book" variable does not update with the new values.

What am I doing wrong here?

NOTE: I actually wanted to test if the subscriptions in the component are working as expected or not!

REASON: I would like to check-in further tests that when the value in service is updated, does the DOM changes automatically or not

答:
Here's the order of what happens:

```<code>  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);

// The component is created now. So, its constructor is run and services instantiated.
// Also, ngOnInit is executed.

// ...

  it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };

// And now you're overwriting bookServiceStub's bookChanged property.
// The problem is, the component doesn't care at this point, it already has a subscription,
// and it's attached to the original bookChanged stream.

    bookServiceStub.bookChanged = of(newBook);

</code>```

If you don't have more tests to run in this suite (or if you don't need different contents of bookChanged in them), you can simply move bookServiceStub.bookChanged = of(newBook) earlier, before the component is created.

Body:
I have a data service that is used by a component.

For example:

BookService:

...
private book: Book;
private bookSubject = new BehaviorSubject<Book>(this.book);
bookChanged = this.bookSubject.asObservable();
...

BookComponent:

...
book: Book;
ngOnInit() {
  this.bookService.bookChanged.subscribe(
    (book: Book) => this.book = book;
  )
}
...

Spec (test file) for the component:

describe('BookComponent', () => {
  let component: BookComponent;
  let fixture: ComponentFixture<BookComponent>;
  let bookServiceStub: Partial<BookService>;

  bookServiceStub = {
    bookChanged: of({id: 123, name: 'Book 1'})
  };
  beforeEach(async(() => {
    TestBed
      .configureTestingModule({
        declarations: [BookComponent],
        providers: [
          {provide: BookService, useValue: bookServiceStub},
          ...
        ]
      })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };
    bookServiceStub.bookChanged = of(newBook);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(component.book.id).toBe(newBook.id); // FAILS (still has old value)
      expect(component.book).toBe(newBook); // FAILS (still has old value)
    });
  }));
});

So the tests fail because the "book" variable does not update with the new values.

What am I doing wrong here?

NOTE: I actually wanted to test if the subscriptions in the component are working as expected or not!

REASON: I would like to check-in further tests that when the value in service is updated, does the DOM changes automatically or not

Body:
Here's the order of what happens:

  beforeEach(() => {
    fixture = TestBed.createComponent(BookComponent);

// The component is created now. So, its constructor is run and services instantiated.
// Also, ngOnInit is executed.

// ...

  it('should change the book with a new one', fakeAsync(() => {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };

// And now you're overwriting bookServiceStub's bookChanged property.
// The problem is, the component doesn't care at this point, it already has a subscription,
// and it's attached to the original bookChanged stream.

    bookServiceStub.bookChanged = of(newBook);

If you don't have more tests to run in this suite (or if you don't need different contents of bookChanged in them), you can simply move bookServiceStub.bookChanged = of(newBook) earlier, before the component is created.


问:
Finding empty directories in Python
All,

What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.

```<code>dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)
</code>```

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.

Thanks,
Adam

答:
```<code>import os

if not os.listdir(dir):
    os.rmdir(dir)
</code>```

LBYL style.

for EAFP, see mouad's answer.

Title: Finding empty directories in Python

Body:
All,

What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.

dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.

Thanks,
Adam

Body:
import os

if not os.listdir(dir):
    os.rmdir(dir)

LBYL style.

for EAFP, see mouad's answer.