问:
Removing Middle of Filename
I wish to remove the middle of filenames that look like the following:

```<code>Wm-no-Bis.GAGATTCC-ATAGAGGC.L001.R1.001.fastq.trim.R2.fastq
Pek-no-Bis.GAGATTCC-AGGCGAAG.L001.R1.001.fastq.trim.R1.fastq
</code>```

To Get

```<code>Wm-no-Bis.trim.R2.fastq
Pek-no-Bis.trim.R1.fastq
</code>```

As you can see the beginning and end of the files are slightly variable.
I have attempted to use rename as follows:

```<code>rename 's/.*.*.*.*.*.trim.//g'
Wm-no-Bis.GAGATTCC-ATAGAGGC.L001.R1.001.fastq.trim.R2copy.fastq
</code>```

This removes the entire file name except for the end.
The issue is obviously my lack of understanding how to use wildcards.

Title: Removing Middle of Filename

Body:
I wish to remove the middle of filenames that look like the following:

Wm-no-Bis.GAGATTCC-ATAGAGGC.L001.R1.001.fastq.trim.R2.fastq
Pek-no-Bis.GAGATTCC-AGGCGAAG.L001.R1.001.fastq.trim.R1.fastq

To Get

Wm-no-Bis.trim.R2.fastq
Pek-no-Bis.trim.R1.fastq

As you can see the beginning and end of the files are slightly variable.
I have attempted to use rename as follows:

rename 's/.*.*.*.*.*.trim.//g'
Wm-no-Bis.GAGATTCC-ATAGAGGC.L001.R1.001.fastq.trim.R2copy.fastq

This removes the entire file name except for the end.
The issue is obviously my lack of understanding how to use wildcards.

Body:
try

rename 's/\.\w+-\w+\..{4}\.R.\.\d{3}\.fastq//g'

source


来源: stackexchange

问:
SilverStripe random order for ArrayList()
I know that we can randomly sort a DataList with the following:

```<code>$example = Example::get()->sort('RAND()');
</code>```

But when I try to randomly sort an ArrayList it doesn't work. I can sort an ArrayList by ID DESC, but not with RAND().

Is there a way to make an ArrayList randomly sort its items?

Example:

```<code>public function AllTheKits() {
    $kits = Versioned::get_by_stage('KitsPage', 'Live');
    $kitsArrayList = ArrayList::create();

    foreach ($kits as $kit) {
        if ($kit->MemberID == Member::currentUserID()) {
            $kitsArrayList->push($kit);
        }
    }
    return $kitsArrayList;
}
</code>```

In a page:

```<code>public function getKitsRandom() {
    return $this->AllTheKits()->sort('RAND()');
}
</code>```

This does not work in a template with <% loop KitsRandom %>

答:
Not really. This is the best workaround I can come up with:</p>

```<code>foreach($myArrayList as $item) {
    $item->__Sort = mt_rand();
}

$myArrayList = $myArrayList->sort('__Sort');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know that we can randomly sort a DataList with the following:

$example = Example::get()->sort('RAND()');

But when I try to randomly sort an ArrayList it doesn't work. I can sort an ArrayList by ID DESC, but not with RAND().

Is there a way to make an ArrayList randomly sort its items?

Example:

public function AllTheKits() {
    $kits = Versioned::get_by_stage('KitsPage', 'Live');
    $kitsArrayList = ArrayList::create();

    foreach ($kits as $kit) {
        if ($kit->MemberID == Member::currentUserID()) {
            $kitsArrayList->push($kit);
        }
    }
    return $kitsArrayList;
}

In a page:

public function getKitsRandom() {
    return $this->AllTheKits()->sort('RAND()');
}

This does not work in a template with <% loop KitsRandom %>

Body:
Not really. This is the best workaround I can come up with:

foreach($myArrayList as $item) {
    $item->__Sort = mt_rand();
}

$myArrayList = $myArrayList->sort('__Sort');


问:
What's jQuery’s Data Method? How & Why is it used?
What's jQuery’s Data Method? How & Why is it used?</p>

答:
the jquery data method allows you to store javascript objects or data against any HTML element, for accessing whenever you need it.

from the docs:

The .data() method allows us to attach
  data of any type to DOM elements in a
  way that is safe from circular
  references and therefore from memory
  leaks.

Personally, I use it most to store references to timeouts. For hover menu's that have submenu timeouts that may need cancelling (to stop the fadeout), I store a reference to the timeout, using jQuery.data() on the parent element. This is a handy way of storing this value, without the need for global arrays of timeouts.

ContentLicense: CC BY-SA 2.5


问:
TextView outside of a cardView
i want to swap the functionality of the oldTextView to the TextView with ID nameAgeLabel.

The "nameAgeLabel" is outside of the View view.
It also should change the text dynamically like it does now, depending on the view that is currently loaded.

```<code>public View getView(final int position, View View, ViewGroup parent) {

    Log.d("position:",String.valueOf(position));
    Log.d("laenge user id",String.valueOf(userIds.size()));

    String currentUserId = userIds.get(position);
    LayoutInflater inflater = (LayoutInflater)context.getSystemService
            (Context.LAYOUT_INFLATER_SERVICE);

View view = inflater.inflate(R.layout.content_single_mode_vc, parent, false);

    ImageView imageView = (ImageView) view.findViewById(R.id.offer_image);
    Bitmap image = userImages.get(currentUserId);
    imageView.setImageBitmap(image);

 TextView oldTextView= (TextView) view.findViewById(R.id.textView2);
 oldTextView.setText(userNames.get(currentUserId));
   //works fine

    return view;
}
</code>```

my onCreate looks like this :

```<code>  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_single_mode_vc);
    TextView nameAge = (TextView) findViewById(R.id.nameAgeLabel);

    updateImage();
    //(thats another method)

}
</code>```

acvivity_single_mode_vc.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/swipeLayout"
    android:orientation="vertical"
    android:background="@color/white">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"/>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    />
<com.daprlabs.aaron.swipedeck.SwipeDeck
    android:id="@+id/swipe_deck"
    android:layout_width="match_parent"
    android:layout_height="600dp"
    android:padding="20dp"
    android:layout_marginTop="60dp"
    swipedeck:max_visible="3"
    swipedeck:card_spacing="15dp"
    swipedeck:swipe_enabled="true" >

</com.daprlabs.aaron.swipedeck.SwipeDeck>
<Button
    android:id="@+id/close"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginLeft="20dp"
    android:layout_gravity="bottom"
    android:elevation="1dp"
    android:background="@drawable/close"
    android:backgroundTint="@color/light" />

<Button
    android:id="@+id/check"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginRight="20dp"
    android:layout_gravity="bottom|right"
    android:background="@drawable/check"
    android:backgroundTint="@color/light" />

<TextView

    android:layout_width="match_parent"
    android:padding="20dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="350dp"
    android:id="@+id/nameAgeLabel"
    android:background="@color/separator"
   />
</com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout>
</code>```

content_single_mode_vc.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="4dp"
    card_view:cardUseCompatPadding="true"
    android:layout_margin="8dp"
    android:gravity="center_horizontal"
    android:padding="25dp"
    android:clipChildren="true">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<ImageView
        android:id="@+id/offer_image"
        android:layout_width="match_parent"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:layout_height="200dp"/>
<TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="137dp"
        android:layout_marginStart="137dp"
        android:layout_marginTop="222dp"
        android:id="@+id/textView2"/>

</RelativeLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center">
    <ImageView
        android:layout_weight="1"
        android:id="@+id/left_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/offer_image"
        android:layout_centerHorizontal="true" />
    <ImageView
        android:layout_weight="1"
        android:id="@+id/right_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/offer_image"
        android:layout_centerHorizontal="true" />
    </LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</code>```

So, the main question is where and how do i have to change the textview "nameAge" to get the same result as i do now? In my getView Method doesnt work because

```<code>TextView nameAge= (TextView) view.findViewById(R.id.nameAgeLabel)
</code>```

doesnt include the textView with ID "nameAgeLabel". Doing it in the onCreate doesnt make a lot of sense.
Creating a new view in my getView also doesnt work because i cannot return 2 views, and additionally i get a "android-requestlayout-improperly..:" message.

Thanks a lot.

Edit: class name + constructor

```<code>public class SwipeDeckAdapter extends BaseAdapter {
[...]
public SwipeDeckAdapter(LinkedList<String> data, Context context, LinkedList<String> userIds, Hashtable<String,String> userNames, Hashtable<String,String> userHashtags, Hashtable<String,Bitmap> userImages, Hashtable<String,ArrayList<String>> userAccepted) {
    this.data = data;
    this.context = context;
    this.userIds = userIds;
    this.userNames = userNames;
    this.userHashtags = userHashtags;
    this.userImages = userImages;
    this.userAccepted = userAccepted;
}
}
</code>```

答:
Since your description is incomplete, I try to guess.

Create an Adapter for the SwipeFrameLayout where you pass the TextView from the Activity. Either in the Constructor or a seperate method.

Something like

```<code> public class CustomSwipeDeckAdapter extends SwipeDeckAdapter {

    private AppCompatTextView mNameAgeLabel;

    public SwipeDeckAdapter(List<String> data, Context context, AppCompatTextView textview) {
      mNameAgeLabel = textView;
      […]
    }

    public View getView(final int position, View View, ViewGroup parent) {
      […]
      mNameAgeLabel.setText();
    }
</code>```

Title: TextView outside of a cardView

Body:
i want to swap the functionality of the oldTextView to the TextView with ID nameAgeLabel.

The "nameAgeLabel" is outside of the View view.
It also should change the text dynamically like it does now, depending on the view that is currently loaded.

public View getView(final int position, View View, ViewGroup parent) {

    Log.d("position:",String.valueOf(position));
    Log.d("laenge user id",String.valueOf(userIds.size()));

    String currentUserId = userIds.get(position);
    LayoutInflater inflater = (LayoutInflater)context.getSystemService
            (Context.LAYOUT_INFLATER_SERVICE);

View view = inflater.inflate(R.layout.content_single_mode_vc, parent, false);

    ImageView imageView = (ImageView) view.findViewById(R.id.offer_image);
    Bitmap image = userImages.get(currentUserId);
    imageView.setImageBitmap(image);

 TextView oldTextView= (TextView) view.findViewById(R.id.textView2);
 oldTextView.setText(userNames.get(currentUserId));
   //works fine

    return view;
}

my onCreate looks like this :

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_single_mode_vc);
    TextView nameAge = (TextView) findViewById(R.id.nameAgeLabel);

    updateImage();
    //(thats another method)

}

acvivity_single_mode_vc.xml:

<?xml version="1.0" encoding="utf-8"?>
<com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/swipeLayout"
    android:orientation="vertical"
    android:background="@color/white">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"/>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    />
<com.daprlabs.aaron.swipedeck.SwipeDeck
    android:id="@+id/swipe_deck"
    android:layout_width="match_parent"
    android:layout_height="600dp"
    android:padding="20dp"
    android:layout_marginTop="60dp"
    swipedeck:max_visible="3"
    swipedeck:card_spacing="15dp"
    swipedeck:swipe_enabled="true" >

</com.daprlabs.aaron.swipedeck.SwipeDeck>
<Button
    android:id="@+id/close"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginLeft="20dp"
    android:layout_gravity="bottom"
    android:elevation="1dp"
    android:background="@drawable/close"
    android:backgroundTint="@color/light" />

<Button
    android:id="@+id/check"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_marginBottom="50dp"
    android:layout_marginRight="20dp"
    android:layout_gravity="bottom|right"
    android:background="@drawable/check"
    android:backgroundTint="@color/light" />

<TextView

    android:layout_width="match_parent"
    android:padding="20dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="350dp"
    android:id="@+id/nameAgeLabel"
    android:background="@color/separator"
   />
</com.daprlabs.aaron.swipedeck.layouts.SwipeFrameLayout>

content_single_mode_vc.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="4dp"
    card_view:cardUseCompatPadding="true"
    android:layout_margin="8dp"
    android:gravity="center_horizontal"
    android:padding="25dp"
    android:clipChildren="true">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<ImageView
        android:id="@+id/offer_image"
        android:layout_width="match_parent"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:layout_height="200dp"/>
<TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="137dp"
        android:layout_marginStart="137dp"
        android:layout_marginTop="222dp"
        android:id="@+id/textView2"/>

</RelativeLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center">
    <ImageView
        android:layout_weight="1"
        android:id="@+id/left_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/offer_image"
        android:layout_centerHorizontal="true" />
    <ImageView
        android:layout_weight="1"
        android:id="@+id/right_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/offer_image"
        android:layout_centerHorizontal="true" />
    </LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>

So, the main question is where and how do i have to change the textview "nameAge" to get the same result as i do now? In my getView Method doesnt work because

TextView nameAge= (TextView) view.findViewById(R.id.nameAgeLabel)

doesnt include the textView with ID "nameAgeLabel". Doing it in the onCreate doesnt make a lot of sense.
Creating a new view in my getView also doesnt work because i cannot return 2 views, and additionally i get a "android-requestlayout-improperly..:" message.

Thanks a lot.

Edit: class name + constructor

public class SwipeDeckAdapter extends BaseAdapter {
[...]
public SwipeDeckAdapter(LinkedList<String> data, Context context, LinkedList<String> userIds, Hashtable<String,String> userNames, Hashtable<String,String> userHashtags, Hashtable<String,Bitmap> userImages, Hashtable<String,ArrayList<String>> userAccepted) {
    this.data = data;
    this.context = context;
    this.userIds = userIds;
    this.userNames = userNames;
    this.userHashtags = userHashtags;
    this.userImages = userImages;
    this.userAccepted = userAccepted;
}
}

Body:
Since your description is incomplete, I try to guess.

Create an Adapter for the SwipeFrameLayout where you pass the TextView from the Activity. Either in the Constructor or a seperate method.

Something like

 public class CustomSwipeDeckAdapter extends SwipeDeckAdapter {

    private AppCompatTextView mNameAgeLabel;

    public SwipeDeckAdapter(List<String> data, Context context, AppCompatTextView textview) {
      mNameAgeLabel = textView;
      […]
    }

    public View getView(final int position, View View, ViewGroup parent) {
      […]
      mNameAgeLabel.setText();
    }


问:
How to change the log level for eclipselink in tomcat without code changes?
Sorry, if this is a dup.  Seems like it should be, but I didn't find it.

My logging works fine when I add the following to persistence.xml:

```<code>   <property name="eclipselink.logging.level" value="FINE"/>
   <property name="eclipselink.logging.level.sql" value="FINE"/>
   <property name="eclipselink.logging.logger" value="ServerLogger"/>
</code>```

However, I would like to only turn this logging on occasionally.  Perhaps, turn it on only if there is a issue.

If there way to change this setting at runtime, with no code changes.  Note: I am using Tomcat and I use log4j for my current program logging.

GC_

答:
If you are using ServerLogger, EclipseLink will default to your server's logging mechanism, but only if the ServerPlatform class within EclipseLink supports one.  Tomcat isn't a EE server and so you don't likely have a ServerPlatform class for it, so this is a meaningless property and will default to DefaultLogger which writes to the system.out.  </p>

<p>You can specify java logging, but to specifically integrate with log4J, see the article here </p>

Body:
Sorry, if this is a dup.  Seems like it should be, but I didn't find it.

My logging works fine when I add the following to persistence.xml:

   <property name="eclipselink.logging.level" value="FINE"/>
   <property name="eclipselink.logging.level.sql" value="FINE"/>
   <property name="eclipselink.logging.logger" value="ServerLogger"/>

However, I would like to only turn this logging on occasionally.  Perhaps, turn it on only if there is a issue.

If there way to change this setting at runtime, with no code changes.  Note: I am using Tomcat and I use log4j for my current program logging.

GC_

Body:
If you are using ServerLogger, EclipseLink will default to your server's logging mechanism, but only if the ServerPlatform class within EclipseLink supports one.  Tomcat isn't a EE server and so you don't likely have a ServerPlatform class for it, so this is a meaningless property and will default to DefaultLogger which writes to the system.out.

You can specify java logging, but to specifically integrate with log4J, see the article here


问:
Scrapy Crawler only pulls 19 of 680+ urls
I'm trying to scrape this page:  https://coinmarketcap.com/currencies/views/all/

in td[2] of all the rows is a link.  I am trying to ask scrapy to go to each link in that td, and scrape pages that link represents.  Below is my code:

note: another person was awesome in helping me get this far

```<code>class ToScrapeSpiderXPath(CrawlSpider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]

    rules = (
        Rule(LinkExtractor(restrict_xpaths=('//td[2]/a',)), callback="parse", follow=True),
    )

    def parse(self, response):
        BTC = BTCItem()
        BTC['source'] = str(response.request.url).split("/")[2]
        BTC['asset'] = str(response.request.url).split("/")[4],
        BTC['asset_price'] = response.xpath('//*[@id="quote_price"]/text()').extract(),
        BTC['asset_price_change'] = response.xpath(
            '/html/body/div[2]/div/div[1]/div[3]/div[2]/span[2]/text()').extract(),
        BTC['BTC_price'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[1]/text()').extract(),
        BTC['Prct_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[2]/text()').extract()
        yield (BTC)
</code>```

even tho the table exceeds 600+ links/pages, when I run scrapy crawl coinmarketcap, I only get 19 records.  This means only 19 pages from this list of 600+.  I'm failing to see the issue stopping the scrape.  any help would be greatly appreciated.

Thanks

答:
Your spider goes too deep: with that rule it find and follow links also in the single coin's pages. You can roughly fix the problem adding a DEPTH_LIMIT = 1, but you can for sure find a more elegant solution.
Here the code that works for me (there are other minor adjustment too):</p>

```<code>class ToScrapeSpiderXPath(CrawlSpider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]
    custom_settings = {
        'DEPTH_LIMIT': '1',
    }

    rules = (
        Rule(LinkExtractor(restrict_xpaths=('//td[2]',)),callback="parse_item", follow=True),
    )

    def parse_item(self, response):
        BTC = BTCItem()
        BTC['source'] = str(response.request.url).split("/")[2]
        BTC['asset'] = str(response.request.url).split("/")[4]
        BTC['asset_price'] = response.xpath('//*[@id="quote_price"]/text()').extract()
        BTC['asset_price_change'] = response.xpath(
            '/html/body/div[2]/div/div[1]/div[3]/div[2]/span[2]/text()').extract()
        BTC['BTC_price'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[1]/text()').extract()
        BTC['Prct_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[2]/text()').extract()
        yield (BTC)
</code>```

Body:
I'm trying to scrape this page:  https://coinmarketcap.com/currencies/views/all/

in td[2] of all the rows is a link.  I am trying to ask scrapy to go to each link in that td, and scrape pages that link represents.  Below is my code:

note: another person was awesome in helping me get this far

class ToScrapeSpiderXPath(CrawlSpider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]

    rules = (
        Rule(LinkExtractor(restrict_xpaths=('//td[2]/a',)), callback="parse", follow=True),
    )

    def parse(self, response):
        BTC = BTCItem()
        BTC['source'] = str(response.request.url).split("/")[2]
        BTC['asset'] = str(response.request.url).split("/")[4],
        BTC['asset_price'] = response.xpath('//*[@id="quote_price"]/text()').extract(),
        BTC['asset_price_change'] = response.xpath(
            '/html/body/div[2]/div/div[1]/div[3]/div[2]/span[2]/text()').extract(),
        BTC['BTC_price'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[1]/text()').extract(),
        BTC['Prct_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[2]/text()').extract()
        yield (BTC)

even tho the table exceeds 600+ links/pages, when I run scrapy crawl coinmarketcap, I only get 19 records.  This means only 19 pages from this list of 600+.  I'm failing to see the issue stopping the scrape.  any help would be greatly appreciated.

Thanks

Body:
Your spider goes too deep: with that rule it find and follow links also in the single coin's pages. You can roughly fix the problem adding a DEPTH_LIMIT = 1, but you can for sure find a more elegant solution.
Here the code that works for me (there are other minor adjustment too):

class ToScrapeSpiderXPath(CrawlSpider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]
    custom_settings = {
        'DEPTH_LIMIT': '1',
    }

    rules = (
        Rule(LinkExtractor(restrict_xpaths=('//td[2]',)),callback="parse_item", follow=True),
    )

    def parse_item(self, response):
        BTC = BTCItem()
        BTC['source'] = str(response.request.url).split("/")[2]
        BTC['asset'] = str(response.request.url).split("/")[4]
        BTC['asset_price'] = response.xpath('//*[@id="quote_price"]/text()').extract()
        BTC['asset_price_change'] = response.xpath(
            '/html/body/div[2]/div/div[1]/div[3]/div[2]/span[2]/text()').extract()
        BTC['BTC_price'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[1]/text()').extract()
        BTC['Prct_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[2]/text()').extract()
        yield (BTC)


问:
Grid items who take up the available horizontal space
I have a grid containing 16 grid items.

I want the top row to take 4 grid items, second row 3, third row 2 and fourth row 7. I want each of them to be evenly spaced so that they take up all the available space.

I can to an extent achieve this by specifying a number in grid-template-columns, i.e. 12, and using grid-column-end: span-* on grid items. However this is not adequate for the row in which I want 7 items spaced evenly.

expected behaviour using grid-column-end on grid items (apart from the final row with 7 items, whose last item forces itself into a row not specified in grid-template-columns):

Code snippet of above:

.grid-container {
  display: grid;
  grid-template-columns: repeat(12, 1fr [col]);
  grid-template-rows: repeat(4, 50px [row]);
  grid-gap: 10px;
}

.grid-item {
  border-radius: 5px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tier1 {
  background-color: mediumseagreen;
  grid-column-end: span 3;
}

.tier2 {
  background-color: mediumorchid;
  grid-column-end: span 4;
}

.tier3 {
  background-color: mediumpurple;
  grid-column-end: span 6;
}

.tier4 {
  background-color: mediumvioletred;
  grid-column-end: span 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-item tier1">1</div>
  <div class="grid-item tier1">2</div>
  <div class="grid-item tier1">3</div>
  <div class="grid-item tier1">4</div>
  <div class="grid-item tier2">5</div>
  <div class="grid-item tier2">6</div>
  <div class="grid-item tier2">7</div>
  <div class="grid-item tier3">8</div>
  <div class="grid-item tier3">9</div>
  <div class="grid-item tier4">10</div>
  <div class="grid-item tier4">11</div>
  <div class="grid-item tier4">12</div>
  <div class="grid-item tier4">13</div>
  <div class="grid-item tier4">14</div>
  <div class="grid-item tier4">15</div>
  <div class="grid-item tier4">16</div>
</div></code>```

My idea to solve this is to use auto-fill in the grid-template-columns property, but does not address the separate rows.

auto-fill behaviour:

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 50px);
  grid-template-rows: repeat(4, 50px);
  grid-gap: 10px;
}

.grid-item {
  border-radius: 5px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tier1 {
  background-color: mediumseagreen;
}
  /* grid-column-end: span 3; */

.tier2 {
  background-color: mediumorchid;
  /* grid-column-end: span 4; */
}

.tier3 {
  background-color: mediumpurple;
  /* grid-column-end: span 6; */
}

.tier4 {
  background-color: mediumvioletred;
  /* grid-column-end: span 2; */
}

Code snippet of above:```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-item tier1">1</div>
  <div class="grid-item tier1">2</div>
  <div class="grid-item tier1">3</div>
  <div class="grid-item tier1">4</div>
  <div class="grid-item tier2">5</div>
  <div class="grid-item tier2">6</div>
  <div class="grid-item tier2">7</div>
  <div class="grid-item tier3">8</div>
  <div class="grid-item tier3">9</div>
  <div class="grid-item tier4">10</div>
  <div class="grid-item tier4">11</div>
  <div class="grid-item tier4">12</div>
  <div class="grid-item tier4">13</div>
  <div class="grid-item tier4">14</div>
  <div class="grid-item tier4">15</div>
  <div class="grid-item tier4">16</div>
</div></code>```

Is such a behaviour possible with CSS Grid?

答:
I understand that you are focusing on CSS Grids. But when I read:

I want each of them to be evenly spaced so that they take up all the
  available space.

That sounds to me like CSS Flexbox would be a perfect tool for the job.

Here is an alternative solution with CSS Flexbox:

.grid-container {
display: flex;
flex-flow: row wrap;
justify-content: space-between;
width: 460px;
}

.grid-item {
display: block;
height: 60px;
line-height: 60px;
color: rgb(255, 255, 255);
text-align: center;
font-size: 22px;
font-weight: bold;
border-radius: 9px;
margin: 4px;
}

.tier1 {
flex: 1 1 calc((100% - (2 * 4px * 4)) / 4); /* 4 blocks */
background-color: mediumseagreen;
}

.tier2 {
flex: 1 1 calc((100% - (2 * 4px * 3)) / 3); /* 3 blocks */
background-color: mediumorchid;
}

.tier3 {
flex: 1 1 calc((100% - (2 * 4px * 2)) / 2); /* 2 blocks */
background-color: mediumpurple;
}

.tier4 {
flex: 1 1 calc((100% - (2 * 4px * 7)) / 7); /* 7 blocks */
background-color: mediumvioletred;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-item tier1">1</div>
  <div class="grid-item tier1">2</div>
  <div class="grid-item tier1">3</div>
  <div class="grid-item tier1">4</div>
  <div class="grid-item tier2">5</div>
  <div class="grid-item tier2">6</div>
  <div class="grid-item tier2">7</div>
  <div class="grid-item tier3">8</div>
  <div class="grid-item tier3">9</div>
  <div class="grid-item tier4">10</div>
  <div class="grid-item tier4">11</div>
  <div class="grid-item tier4">12</div>
  <div class="grid-item tier4">13</div>
  <div class="grid-item tier4">14</div>
  <div class="grid-item tier4">15</div>
  <div class="grid-item tier4">16</div>
</div></code>```

Body:
I have a grid containing 16 grid items.

I want the top row to take 4 grid items, second row 3, third row 2 and fourth row 7. I want each of them to be evenly spaced so that they take up all the available space.

I can to an extent achieve this by specifying a number in grid-template-columns, i.e. 12, and using grid-column-end: span-* on grid items. However this is not adequate for the row in which I want 7 items spaced evenly.

expected behaviour using grid-column-end on grid items (apart from the final row with 7 items, whose last item forces itself into a row not specified in grid-template-columns):

Code snippet of above:

.grid-container {
  display: grid;
  grid-template-columns: repeat(12, 1fr [col]);
  grid-template-rows: repeat(4, 50px [row]);
  grid-gap: 10px;
}

.grid-item {
  border-radius: 5px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tier1 {
  background-color: mediumseagreen;
  grid-column-end: span 3;
}

.tier2 {
  background-color: mediumorchid;
  grid-column-end: span 4;
}

.tier3 {
  background-color: mediumpurple;
  grid-column-end: span 6;
}

.tier4 {
  background-color: mediumvioletred;
  grid-column-end: span 2;
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

My idea to solve this is to use auto-fill in the grid-template-columns property, but does not address the separate rows.

auto-fill behaviour:

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 50px);
  grid-template-rows: repeat(4, 50px);
  grid-gap: 10px;
}

.grid-item {
  border-radius: 5px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tier1 {
  background-color: mediumseagreen;
}
  /* grid-column-end: span 3; */

.tier2 {
  background-color: mediumorchid;
  /* grid-column-end: span 4; */
}

.tier3 {
  background-color: mediumpurple;
  /* grid-column-end: span 6; */
}

.tier4 {
  background-color: mediumvioletred;
  /* grid-column-end: span 2; */
}

Code snippet of above:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Is such a behaviour possible with CSS Grid?

Body:
I understand that you are focusing on CSS Grids. But when I read:

I want each of them to be evenly spaced so that they take up all the
  available space.

That sounds to me like CSS Flexbox would be a perfect tool for the job.

Here is an alternative solution with CSS Flexbox:

.grid-container {
display: flex;
flex-flow: row wrap;
justify-content: space-between;
width: 460px;
}

.grid-item {
display: block;
height: 60px;
line-height: 60px;
color: rgb(255, 255, 255);
text-align: center;
font-size: 22px;
font-weight: bold;
border-radius: 9px;
margin: 4px;
}

.tier1 {
flex: 1 1 calc((100% - (2 * 4px * 4)) / 4); /* 4 blocks */
background-color: mediumseagreen;
}

.tier2 {
flex: 1 1 calc((100% - (2 * 4px * 3)) / 3); /* 3 blocks */
background-color: mediumorchid;
}

.tier3 {
flex: 1 1 calc((100% - (2 * 4px * 2)) / 2); /* 2 blocks */
background-color: mediumpurple;
}

.tier4 {
flex: 1 1 calc((100% - (2 * 4px * 7)) / 7); /* 7 blocks */
background-color: mediumvioletred;
}

<div class="grid-container">
  <div class="grid-item tier1">1</div>
  <div class="grid-item tier1">2</div>
  <div class="grid-item tier1">3</div>
  <div class="grid-item tier1">4</div>
  <div class="grid-item tier2">5</div>
  <div class="grid-item tier2">6</div>
  <div class="grid-item tier2">7</div>
  <div class="grid-item tier3">8</div>
  <div class="grid-item tier3">9</div>
  <div class="grid-item tier4">10</div>
  <div class="grid-item tier4">11</div>
  <div class="grid-item tier4">12</div>
  <div class="grid-item tier4">13</div>
  <div class="grid-item tier4">14</div>
  <div class="grid-item tier4">15</div>
  <div class="grid-item tier4">16</div>
</div>


问:
C++ <-> C# Named Pipe Communication
Implementing IPC on windows using named pipes.

C# named pipe server and C++ named pipe client.
Losing the first character when sending data from the C++ client to the C# server.

For example, if "This is a test message" is sent from the C++ client, the server will receive "his is a test message". Below is revelant code.

C++ Client Code

```<code>    success = WriteFile(
    pipe,
    guiMsg,
    PIPE_BUFFER_SIZE,
    &bytesWritten,
    NULL);
</code>```

C# server code

```<code>main()
    {
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream(@"ZVMonitorPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

        StreamString ss = new StreamString(pipeServer);
        ...
        ...
        string input = ss.ReadString();
        Console.WriteLine(input);
        ...
        ...
    }

public class StreamString
    {
        private Stream ioStream;
        private UnicodeEncoding streamEncoding;

        public StreamString(Stream ioStream)
        {
            this.ioStream = ioStream;
            streamEncoding = new UnicodeEncoding();
        }

        public string ReadString()
        {
            int len = 0;

            len = ioStream.ReadByte() * 64;
            len += ioStream.ReadByte();
            byte[] inBuffer = new byte[len];
            ioStream.Read(inBuffer, 0, len);

            return streamEncoding.GetString(inBuffer);
        }
...
...
...
    }
</code>```

What am I missing?

答:
The IO looks functional. You’ve forgot WaitForConnection in the server, and you’re ignoring all return codes, e.g. each ReadByte() can return you -1 instead of the data.

Very likely, the problem is the code that prepares the buffer to send, which you haven't included in your question.

```<code>        len = ioStream.ReadByte() * 64;
        len += ioStream.ReadByte();
</code>```

This is very unorthodox way to send/receive buffer length.

If you want 16 bit length value before each message, read two bytes to the array, call BitConverter.ToUInt16 to make them into a number, and don’t forget to apply same conventions on the C++ side.

Title: C++ <-> C# Named Pipe Communication

Body:
Implementing IPC on windows using named pipes.

C# named pipe server and C++ named pipe client.
Losing the first character when sending data from the C++ client to the C# server.

For example, if "This is a test message" is sent from the C++ client, the server will receive "his is a test message". Below is revelant code.

C++ Client Code

    success = WriteFile(
    pipe,
    guiMsg,
    PIPE_BUFFER_SIZE,
    &bytesWritten,
    NULL);

C# server code

main()
    {
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream(@"ZVMonitorPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

        StreamString ss = new StreamString(pipeServer);
        ...
        ...
        string input = ss.ReadString();
        Console.WriteLine(input);
        ...
        ...
    }

public class StreamString
    {
        private Stream ioStream;
        private UnicodeEncoding streamEncoding;

        public StreamString(Stream ioStream)
        {
            this.ioStream = ioStream;
            streamEncoding = new UnicodeEncoding();
        }

        public string ReadString()
        {
            int len = 0;

            len = ioStream.ReadByte() * 64;
            len += ioStream.ReadByte();
            byte[] inBuffer = new byte[len];
            ioStream.Read(inBuffer, 0, len);

            return streamEncoding.GetString(inBuffer);
        }
...
...
...
    }

What am I missing?

Body:
The IO looks functional. You’ve forgot WaitForConnection in the server, and you’re ignoring all return codes, e.g. each ReadByte() can return you -1 instead of the data.

Very likely, the problem is the code that prepares the buffer to send, which you haven't included in your question.

        len = ioStream.ReadByte() * 64;
        len += ioStream.ReadByte();

This is very unorthodox way to send/receive buffer length.

If you want 16 bit length value before each message, read two bytes to the array, call BitConverter.ToUInt16 to make them into a number, and don’t forget to apply same conventions on the C++ side.


问:
Why does this HashSet code snippet behave this way?
Given the following code:

```<code>public class NewClass {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Orange", "Pineapple", "Banana", "Banana");
        Set<String> fruitsSet = new HashSet<>();

        for (String fruit : fruits) {
            fruitsSet.add(fruit);
        }

        for (String fruit : fruitsSet) {
            System.out.println(fruit);
        }
    }
}
</code>```

Every time I run the code, the order of the elements is the same, eliminating the duplicate item Banana, as is typical of HashSet implementation:

```<code>Banana
Pineapple
Orange
</code>```

My question is, why is the order the same every time, since the specification says "It makes no guarantees as to the iteration order of the set" (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)

答:
The iteration order in a hash set is determined by the way the hash function transforms each element to create it's hashCode.
So for a specific string you'll get a specific hashCode and he will be placed in a specific cell of the Set.

No guarantees means that adding Orange , Pineapple and Banana will not guarantee that order while iterating.

Also, it leaves space for future implementations for HashSet by not committing to certain limitations ( such as ordering).

Body:
Given the following code:

public class NewClass {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Orange", "Pineapple", "Banana", "Banana");
        Set<String> fruitsSet = new HashSet<>();

        for (String fruit : fruits) {
            fruitsSet.add(fruit);
        }

        for (String fruit : fruitsSet) {
            System.out.println(fruit);
        }
    }
}

Every time I run the code, the order of the elements is the same, eliminating the duplicate item Banana, as is typical of HashSet implementation:

Banana
Pineapple
Orange

My question is, why is the order the same every time, since the specification says "It makes no guarantees as to the iteration order of the set" (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)


问:
Multicolored points in plot
I'd like to add points that are multicoloured dots, with one half in blue for ex. and one half in red. If possible, I'd like to be able to do it with more than 2 colors, for example 4 quarters, each with a color.
Is that at all possible?

I know I can superimpose several dots of different sizes, each with a color, resulting in a concentric multicolored dot. But this is not what I am after.

For context, I am using these points for cities in a map.
Here is a small example, with each city having a unicolored dot. But I would like each city to have a dot that has two halves, each one with a color.

```<code>require(ggmap);

citiesnames=c("Madrid","Toledo","Valencia","Granada")

cities=str_c(citiesnames,"Spain",sep=", ");
geo=geocode(cities);
lon=geo$lon;
lat=geo$lat;
coord=mapproject(lon, lat,proj="mercator");

map("world","Spain",fill=T,col="ivory",proj="mercator");

points(coord$x[1], coord$y[1], pch=16, cex=1.2, col="black")
points(coord$x[2],coord$y[2], pch=16, cex=1.2, col="red")
points(coord$x[3], coord$y[3], pch=16, cex=1.2, col="blue")
points(coord$x[4], coord$y[4], pch=16, cex=1.2, col="green4")
</code>```

Any help greatly appreciated.

答:
As I mentioned in the comments you can refer to this post for doing what you want. For documentation purposes I add an answer which resolve the issue:

You can add two half circles (pie charts) to your graph using these two functions:

```<code>  upper.half.circle <- function(x,y,r,nsteps=100,...){
    rs <- seq(0,pi,len=nsteps)
    xc <- x+r*cos(rs)
    yc <- y+r*sin(rs)
    polygon(xc,yc,...)
  }

  lower.half.circle <- function(x,y,r,nsteps=100,...){
    rs <- seq(0,pi,len=nsteps)
    xc <- x-r*cos(rs)
    yc <- y-r*sin(rs)
    polygon(xc,yc,...)
  }
</code>```

Later when you are piloting you should set asp = 1 to get the half-circles.

```<code>   plot(1, type="n",axes=F,xlab="", ylab="",xlim=c(0,200),ylim=c(0,200), asp = 1)
   upper.half.circle(15,170,10,nsteps=1000,col='red')
   lower.half.circle(15,170,10,nsteps=1000,col='blue')
</code>```

Here's the result of this code:

You can later edit the fictions for getting quarters or whatever you need.

Title: Multicolored points in plot

Body:
I'd like to add points that are multicoloured dots, with one half in blue for ex. and one half in red. If possible, I'd like to be able to do it with more than 2 colors, for example 4 quarters, each with a color.
Is that at all possible?

I know I can superimpose several dots of different sizes, each with a color, resulting in a concentric multicolored dot. But this is not what I am after.

For context, I am using these points for cities in a map.
Here is a small example, with each city having a unicolored dot. But I would like each city to have a dot that has two halves, each one with a color.

require(ggmap);

citiesnames=c("Madrid","Toledo","Valencia","Granada")

cities=str_c(citiesnames,"Spain",sep=", ");
geo=geocode(cities);
lon=geo$lon;
lat=geo$lat;
coord=mapproject(lon, lat,proj="mercator");

map("world","Spain",fill=T,col="ivory",proj="mercator");

points(coord$x[1], coord$y[1], pch=16, cex=1.2, col="black")
points(coord$x[2],coord$y[2], pch=16, cex=1.2, col="red")
points(coord$x[3], coord$y[3], pch=16, cex=1.2, col="blue")
points(coord$x[4], coord$y[4], pch=16, cex=1.2, col="green4")

Any help greatly appreciated.

Body:
As I mentioned in the comments you can refer to this post for doing what you want. For documentation purposes I add an answer which resolve the issue:

You can add two half circles (pie charts) to your graph using these two functions:

  upper.half.circle <- function(x,y,r,nsteps=100,...){
    rs <- seq(0,pi,len=nsteps)
    xc <- x+r*cos(rs)
    yc <- y+r*sin(rs)
    polygon(xc,yc,...)
  }

  lower.half.circle <- function(x,y,r,nsteps=100,...){
    rs <- seq(0,pi,len=nsteps)
    xc <- x-r*cos(rs)
    yc <- y-r*sin(rs)
    polygon(xc,yc,...)
  }

Later when you are piloting you should set asp = 1 to get the half-circles.

   plot(1, type="n",axes=F,xlab="", ylab="",xlim=c(0,200),ylim=c(0,200), asp = 1)
   upper.half.circle(15,170,10,nsteps=1000,col='red')
   lower.half.circle(15,170,10,nsteps=1000,col='blue')

Here's the result of this code:

You can later edit the fictions for getting quarters or whatever you need.


问:
Realm - Can't use object after having been deleted
I have a video player in my app. There is a list of videos in a collection view. If you tap on one of the cells, a new view controller appears to play the selected video. Also, you can cycle through all of the videos from the collection view in this new view controller because the entire list is passed.

The problem is:
When the user is in the PlayerVC, they can unfavorite a Video. If they do this, I delete the Video object from Realm. However, this causes a:

Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'

Basically, if a user is watching a video in PlayerVC and he unfavorites a video, I want them to still be able to watch the video for the time being. But when they leave the PlayerVC, the collection view in FavoritesVC should be updated and not show that Video any more.

When I delete a Video object I use Realm's delete method.

This is my code to hold a list of Video objects:

```<code>/// Model class that manages the ordering of `Video` objects.
final class FavoriteList: Object {
    // MARK: - Properties

    /// `objectId` is set to a static value so that only
    /// one `FavoriteList` object could be saved into Realm.
    dynamic var objectId = 0

    let videos = List<Video>()

    // MARK: - Realm Meta Information

    override class func primaryKey() -> String? {
        return "objectId"
    }
}
</code>```

This is my Video class which has an isFavorite property:

```<code>final class Video: Object {
    // MARK: - Properties

    dynamic var title = ""
    dynamic var descriptionText = ""
    dynamic var date = ""
    dynamic var videoId = ""
    dynamic var category = ""
    dynamic var duration = 0
    dynamic var fullURL = ""
    dynamic var creatorSite = ""
    dynamic var creatorName = ""
    dynamic var creatorURL = ""

    // MARK: FileManager Properties (Files are stored on disk for `Video` object).

    /*
        These are file names (e.g., myFile.mp4, myFile.jpg)
    */
    dynamic var previewLocalFileName: String?
    dynamic var stitchedImageLocalFileName: String?
    dynamic var placeholderLocalFileName: String?

    /*
        These are partial paths (e.g., bundleID/Feed/myFile.mp4,     bundleID/Favorites/myFile.mp4)
        They are used to build the full path/URL at runtime.
    */
    dynamic var previewLocalFilePath: String?
    dynamic var stitchedImageLocalFilePath: String?
    dynamic var placeholderLocalFilePath: String?

    // Other code...
}
</code>```

This is my code to show the Video objects in a collection view (Note: I use RealmCollectionChange to update the collection view for deleting  and inserting cells):

```<code>/// This view controller has a `collectioView` to show the favorites.
class FavoriteCollectionViewController: UIViewController {
    // MARK: Properties

    let favoriteList: FavoriteList = {
        let realm = try! Realm()
        return realm.objects(FavoriteList.self).first!
    }()

    // Realm notification token to update collection view.
    var notificationToken: NotificationToken?

    // MARK: Collection View

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return favoriteList.videos.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FavoritesCollectionViewCell.reuseIdentifier, for: indexPath) as! FavoritesCollectionViewCell
        cell.video = favoriteList.videos[indexPath.item]

        return cell
    }

    // I pass this lst forward to the PlayerVC
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let playerVC = self.storyboard?.instantiateViewController(withIdentifier: "PlayerViewController") as? PlayerViewController {
            // I pass the videos here.
            playerVC.videos = favoriteList.videos
            self.parent?.present(playerVC, animated: true, completion: nil)
        }
    }

    // MARK: Realm Notifications

    func updateUI(with changes: RealmCollectionChange<List<Video>>) {
        // This is code to update the collection view.
    }
}
</code>```

Finally, this is the code to allow the user to play and cycle between all Video objects:

```<code>/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// This `videos` is passed from `FavoriteCollectionViewController`
    var videos = List<Video>()

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        let realm = try! Realm()
        try! realm.write {
            let videoToDelete = videos[currentIndexInVideosList] /// Get the video that is currently playing
            realm.delete(videoToDelete)
        }
    }
}
</code>```

Ultimately I want the Video object that is unfavorited to be completely deleted from Realm. Just not sure how/when to do it in this case.

Any thoughts?

Update 1

An option to solve this is to:

Make an unmanaged copy of the Video copy, and use that one to power the UI of the view controller.

The way I see this possibly working is this:

The PlayerVC will receive two List, the original one saved in Realm and a copy of this List to power the UI. Let's call the lists favoriteList and copyList.

So inside of the didToggleStarButton we would do something like this:

Code:

```<code>/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// A button to allow the user to favorite and unfavorite a `Video`
    @IBOutlet weak var starButton: UIButton!

    /// This is passed from `FavoriteCollectionViewController`
    var favoriteList: FavoriteList!

    /// A copy of the `FavoriteList` videos to power the UI.
    var copiedList: List<Video>!

    var currentIndexOfVideoInCopiedList: Int!

    override func viewDidLoad() {
        super viewDidLoad()

        // Make a copy of the favoriteList to power the UI.
        var copiedVideos = [Video]()

        for video in favoriteList.videos {
            let unmanagedVideo = Video(value: video)
            copiedVideos.append(unmanagedVideo)
        }

        self.copiedList.append(copiedVideos)
    }

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        // Do the unfavoriting and favoriting here.

        // An example of unfavoriting:
        let realm = try! Realm()
        try! realm.write {
            let videoToDeleteFromFavoriteList = favoriteList.videos[currentIndexOfVideoInCopiedList] /// Get the video that is currently playing
            realm.delete(videoToDeleteFromOriginalList)
        }

        // Update star button to a new image depending on if the `Video` is favorited or not.
        starButton.isSelected = //... update based on if the `Video` in the `FavoriteList` or not.
    }
}
</code>```

Any thoughts?

答:
This one is definitely tricky for a number of architectural reasons.

You're right in that you could simply remove the object from the FavoriteList.videos and then properly delete it from Realm when going to dismiss the controller, but you're right that if the user clicks the home button, or the app crashes before then, you'll end up with a headless video object. You would need to be able to make sure you can track that.

There's a couple of things you might be able to consider.

Add an isDeleted property to the Video class. When the user unfavorites the video, remove the Video object from FavoriteList.videos, set that property to true, but leave it in Realm. Later on (either when the app quits or the view controller is dismissed), you can then do a general query for all objects where isDeleted is true and delete them then (This solves the headless problem).

Since your architecture requires a view controller relying on a model that could be deleted from under it, depending on how much information you're using from that Video object, it might be safer to make an unmanaged copy of the Video copy, and use that one to power the UI of the view controller. You can create a new copy of an existing Realm object by doing let unmanagedVideo = Video(value: video).

Body:
I have a video player in my app. There is a list of videos in a collection view. If you tap on one of the cells, a new view controller appears to play the selected video. Also, you can cycle through all of the videos from the collection view in this new view controller because the entire list is passed.

The problem is:
When the user is in the PlayerVC, they can unfavorite a Video. If they do this, I delete the Video object from Realm. However, this causes a:

Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'

Basically, if a user is watching a video in PlayerVC and he unfavorites a video, I want them to still be able to watch the video for the time being. But when they leave the PlayerVC, the collection view in FavoritesVC should be updated and not show that Video any more.

When I delete a Video object I use Realm's delete method.

This is my code to hold a list of Video objects:

/// Model class that manages the ordering of `Video` objects.
final class FavoriteList: Object {
    // MARK: - Properties

    /// `objectId` is set to a static value so that only
    /// one `FavoriteList` object could be saved into Realm.
    dynamic var objectId = 0

    let videos = List<Video>()

    // MARK: - Realm Meta Information

    override class func primaryKey() -> String? {
        return "objectId"
    }
}

This is my Video class which has an isFavorite property:

final class Video: Object {
    // MARK: - Properties

    dynamic var title = ""
    dynamic var descriptionText = ""
    dynamic var date = ""
    dynamic var videoId = ""
    dynamic var category = ""
    dynamic var duration = 0
    dynamic var fullURL = ""
    dynamic var creatorSite = ""
    dynamic var creatorName = ""
    dynamic var creatorURL = ""

    // MARK: FileManager Properties (Files are stored on disk for `Video` object).

    /*
        These are file names (e.g., myFile.mp4, myFile.jpg)
    */
    dynamic var previewLocalFileName: String?
    dynamic var stitchedImageLocalFileName: String?
    dynamic var placeholderLocalFileName: String?

    /*
        These are partial paths (e.g., bundleID/Feed/myFile.mp4,     bundleID/Favorites/myFile.mp4)
        They are used to build the full path/URL at runtime.
    */
    dynamic var previewLocalFilePath: String?
    dynamic var stitchedImageLocalFilePath: String?
    dynamic var placeholderLocalFilePath: String?

    // Other code...
}

This is my code to show the Video objects in a collection view (Note: I use RealmCollectionChange to update the collection view for deleting  and inserting cells):

/// This view controller has a `collectioView` to show the favorites.
class FavoriteCollectionViewController: UIViewController {
    // MARK: Properties

    let favoriteList: FavoriteList = {
        let realm = try! Realm()
        return realm.objects(FavoriteList.self).first!
    }()

    // Realm notification token to update collection view.
    var notificationToken: NotificationToken?

    // MARK: Collection View

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return favoriteList.videos.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FavoritesCollectionViewCell.reuseIdentifier, for: indexPath) as! FavoritesCollectionViewCell
        cell.video = favoriteList.videos[indexPath.item]

        return cell
    }

    // I pass this lst forward to the PlayerVC
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let playerVC = self.storyboard?.instantiateViewController(withIdentifier: "PlayerViewController") as? PlayerViewController {
            // I pass the videos here.
            playerVC.videos = favoriteList.videos
            self.parent?.present(playerVC, animated: true, completion: nil)
        }
    }

    // MARK: Realm Notifications

    func updateUI(with changes: RealmCollectionChange<List<Video>>) {
        // This is code to update the collection view.
    }
}

Finally, this is the code to allow the user to play and cycle between all Video objects:

/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// This `videos` is passed from `FavoriteCollectionViewController`
    var videos = List<Video>()

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        let realm = try! Realm()
        try! realm.write {
            let videoToDelete = videos[currentIndexInVideosList] /// Get the video that is currently playing
            realm.delete(videoToDelete)
        }
    }
}

Ultimately I want the Video object that is unfavorited to be completely deleted from Realm. Just not sure how/when to do it in this case.

Any thoughts?

Update 1

An option to solve this is to:

Make an unmanaged copy of the Video copy, and use that one to power the UI of the view controller.

The way I see this possibly working is this:

The PlayerVC will receive two List, the original one saved in Realm and a copy of this List to power the UI. Let's call the lists favoriteList and copyList.

So inside of the didToggleStarButton we would do something like this:

Code:

/// This view controller uses `AVFoundation` to play the videos from `FavoriteCollectionViewController`.
class PlayerViewControllerr: UIViewController {

    /// A button to allow the user to favorite and unfavorite a `Video`
    @IBOutlet weak var starButton: UIButton!

    /// This is passed from `FavoriteCollectionViewController`
    var favoriteList: FavoriteList!

    /// A copy of the `FavoriteList` videos to power the UI.
    var copiedList: List<Video>!

    var currentIndexOfVideoInCopiedList: Int!

    override func viewDidLoad() {
        super viewDidLoad()

        // Make a copy of the favoriteList to power the UI.
        var copiedVideos = [Video]()

        for video in favoriteList.videos {
            let unmanagedVideo = Video(value: video)
            copiedVideos.append(unmanagedVideo)
        }

        self.copiedList.append(copiedVideos)
    }

    // HELP: The app crashes here if I unfavorite a `Video`.
    @IBAction func didToggleStarButton(_ sender: UIButton) {
        // Do the unfavoriting and favoriting here.

        // An example of unfavoriting:
        let realm = try! Realm()
        try! realm.write {
            let videoToDeleteFromFavoriteList = favoriteList.videos[currentIndexOfVideoInCopiedList] /// Get the video that is currently playing
            realm.delete(videoToDeleteFromOriginalList)
        }

        // Update star button to a new image depending on if the `Video` is favorited or not.
        starButton.isSelected = //... update based on if the `Video` in the `FavoriteList` or not.
    }
}

Any thoughts?


问:
R Leaflet Offline Tiles within Shiny
Is it possible to load offline/local leaflet map tiles within a Shiny app? I am able to load the tiles in an interactive R session as shown here, but I now want to try and load them for use in a Shiny app. Here's an example of what I have so far. I'm thinking it has something to do with Shiny running through an IP and port and needing to load the tiles through an IP and port as well. I've tried a few things to change IPs and ports (making them the same) as explained here but haven't figured out anything that works. I can also get it to work using online tiles, but I need it to work with local map tiles.</p>

```<code>library(shiny)
library(leaflet)
library(RColorBrewer)
library(RgoogleMaps)

options(shiny.port = 8000)

  (bwi <- getGeoCode("BWI;MD"))

df <- as.data.frame(rbind(bwi))
df$col <- c("orange")
df$name <- c("BWI")

icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = df$col
)
#################################################################################

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,
                style = "padding: 8px; background: #FFFFEE; opacity:.9",
    checkboxInput("markers", "Show Markers?", TRUE)
  )
)
#################################################################################

server <- function(input, output, session) {

  output$map <- renderLeaflet({
    leaflet() %>%
      addTiles(urlTemplate = "http:/localhost:8000/C:/Users/OTAD USER/Documents/mapTiles/ESRIWorldTopoMap/{z}_{x}_{y}.png") %>%
      setView(lat = bwi[1], lng = bwi[2], zoom = 8)
  })

  observe({
    proxy <- leafletProxy("map", data = df)

    # Remove/show any markers
    proxy %>% clearMarkers()
    if (input$markers) {
      proxy %>% addAwesomeMarkers(lat = df$lat, lng = df$lon,
                                  icon = icons, label = df$name)
    }
  })
}

#Put the ui and server together and run
runApp(shinyApp(ui = ui,
         server = server), launch.browser=TRUE
)
</code>```

答:
1- You have to authorize shiny to serve tiles in that folder by providing an "alias" on the ressource with addResourcePath

2- then use that alias as the base URL in addTiles

```<code>server <- function(input, output, session) {
    addResourcePath("mytiles", "C:/Users/OTAD USER/Documents/mapTiles/ESRIWorldTopoMap")
    output$map <- renderLeaflet({
      leaflet() %>%
        addTiles(urlTemplate = "/mytiles/{z}_{x}_{y}.png") %>%
        setView(lat = bwi[1], lng = bwi[2], zoom = 8)
    })
...
</code>```

Title: R Leaflet Offline Tiles within Shiny

Body:
Is it possible to load offline/local leaflet map tiles within a Shiny app? I am able to load the tiles in an interactive R session as shown here, but I now want to try and load them for use in a Shiny app. Here's an example of what I have so far. I'm thinking it has something to do with Shiny running through an IP and port and needing to load the tiles through an IP and port as well. I've tried a few things to change IPs and ports (making them the same) as explained here but haven't figured out anything that works. I can also get it to work using online tiles, but I need it to work with local map tiles.

library(shiny)
library(leaflet)
library(RColorBrewer)
library(RgoogleMaps)

options(shiny.port = 8000)

  (bwi <- getGeoCode("BWI;MD"))

df <- as.data.frame(rbind(bwi))
df$col <- c("orange")
df$name <- c("BWI")

icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = df$col
)
#################################################################################

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,
                style = "padding: 8px; background: #FFFFEE; opacity:.9",
    checkboxInput("markers", "Show Markers?", TRUE)
  )
)
#################################################################################

server <- function(input, output, session) {

  output$map <- renderLeaflet({
    leaflet() %>%
      addTiles(urlTemplate = "http:/localhost:8000/C:/Users/OTAD USER/Documents/mapTiles/ESRIWorldTopoMap/{z}_{x}_{y}.png") %>%
      setView(lat = bwi[1], lng = bwi[2], zoom = 8)
  })

  observe({
    proxy <- leafletProxy("map", data = df)

    # Remove/show any markers
    proxy %>% clearMarkers()
    if (input$markers) {
      proxy %>% addAwesomeMarkers(lat = df$lat, lng = df$lon,
                                  icon = icons, label = df$name)
    }
  })
}

#Put the ui and server together and run
runApp(shinyApp(ui = ui,
         server = server), launch.browser=TRUE
)

Body:
1- You have to authorize shiny to serve tiles in that folder by providing an "alias" on the ressource with addResourcePath

2- then use that alias as the base URL in addTiles

server <- function(input, output, session) {
    addResourcePath("mytiles", "C:/Users/OTAD USER/Documents/mapTiles/ESRIWorldTopoMap")
    output$map <- renderLeaflet({
      leaflet() %>%
        addTiles(urlTemplate = "/mytiles/{z}_{x}_{y}.png") %>%
        setView(lat = bwi[1], lng = bwi[2], zoom = 8)
    })
...


答:
You can use this rename command:

```<code>rename -n 's/^([^.]+).*(\.trim\..*)$/$1$2/' *.fastq
</code>```

When you're happy with output then remove -n option (dry-run)

Title: Removing Middle of Filename

Body:
I wish to remove the middle of filenames that look like the following:

Wm-no-Bis.GAGATTCC-ATAGAGGC.L001.R1.001.fastq.trim.R2.fastq
Pek-no-Bis.GAGATTCC-AGGCGAAG.L001.R1.001.fastq.trim.R1.fastq

To Get

Wm-no-Bis.trim.R2.fastq
Pek-no-Bis.trim.R1.fastq

As you can see the beginning and end of the files are slightly variable.
I have attempted to use rename as follows:

rename 's/.*.*.*.*.*.trim.//g'
Wm-no-Bis.GAGATTCC-ATAGAGGC.L001.R1.001.fastq.trim.R2copy.fastq

This removes the entire file name except for the end.
The issue is obviously my lack of understanding how to use wildcards.

Body:
You can use this rename command:

rename -n 's/^([^.]+).*(\.trim\..*)$/$1$2/' *.fastq

When you're happy with output then remove -n option (dry-run)


问:
Swift, ios 10 UIButton Border
I was developing in Swift 3 and I had a little problem with a UIButton. I will try to explain my problem. First I created my UIButton:

```<code>let Button: UIButton = {
    let button = UIButton(type: .system)
    button.setBackgroundImage(UIImage(named: "button"), for: .normal)
    button.layer.borderWidth = 2
    button.layer.borderColor = UIColor(red: 0, green: 0, blue: 80/255, alpha: 1).cgColor
    button.layer.cornerRadius = 10
    //button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()
</code>```

After in the viewDidLoad I implemented the action:

```<code>  button.addTarget(self, action: #selector(buttonUnpressed), for: .touchUpInside)
</code>```

In which "favButtonPressed" is a function with no importance
The problem is when I touch the button the border doesn't get unhighlighted as the image or the text does. It is a detail of little importance but quite annoying.

I have tried changing the alpha value when pressed and re-change it but the problem is i dont know how to animate it to make the animation for 2 seconds (the next line of code doesnt work, it does change the color but not during 2 seconds):

```<code>func buttonUnpressed(){
    UIButton.animate(withDuration: 2, animations: {
        self.button.layer.borderColor = UIColor(red: 0, green: 0, blue: 80/255, alpha: 1).cgColor
    })
}
</code>```

The question; is there any way of adding the border to the UIButton "total behavior" of highlighting and unhighlighting when pressed?

Excuse me for my english if there are some expression or gramatical faults.

EDIT
I tried with this function:

```<code> func buttonUnpressed(){
    button.alpha = 0.2
    UIButton.animate(withDuration: 1) {
        self.button.alpha = 1
    }
    button.layer.borderColor = UIColor(red: 0, green: 0, blue: 80/255, alpha: 1).cgColor
}
</code>```

there is a weird highlight of the image but now it works more or less.

答:
I did find the final answer.
Thanks to krotov who tried to help!</p>

```<code> class BorderButton: UIButton {

 override init(frame: CGRect){
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

var colorPast: Bool = true

override var isHighlighted: Bool {
    didSet {
        if isHighlighted && colorPast {
            borderDissapear(highlighted: isHighlighted)
            colorPast = false
        } else if !isHighlighted && !colorPast {
            borderDissapear(highlighted: isHighlighted)
            colorPast = true
        }
    }
}

func borderDissapear (highlighted: Bool) {
    let animation = CABasicAnimation(keyPath: "borderColor")
    animation.duration = 0.1
    animation.autoreverses = false
    animation.repeatCount = 1
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    if highlighted {
        animation.fromValue = self.layer.borderColor?.copy(alpha: 1)
        animation.toValue = self.layer.borderColor?.copy(alpha: 0.3)
    } else if !highlighted {
        animation.fromValue = self.layer.borderColor?.copy(alpha: 0.3)
        animation.toValue = self.layer.borderColor?.copy(alpha: 1)
    }
    self.layer.add(animation, forKey: "borderColor")
}
}
</code>```

Title: Swift, ios 10 UIButton Border

Body:
I was developing in Swift 3 and I had a little problem with a UIButton. I will try to explain my problem. First I created my UIButton:

let Button: UIButton = {
    let button = UIButton(type: .system)
    button.setBackgroundImage(UIImage(named: "button"), for: .normal)
    button.layer.borderWidth = 2
    button.layer.borderColor = UIColor(red: 0, green: 0, blue: 80/255, alpha: 1).cgColor
    button.layer.cornerRadius = 10
    //button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

After in the viewDidLoad I implemented the action:

  button.addTarget(self, action: #selector(buttonUnpressed), for: .touchUpInside)

In which "favButtonPressed" is a function with no importance
The problem is when I touch the button the border doesn't get unhighlighted as the image or the text does. It is a detail of little importance but quite annoying.

I have tried changing the alpha value when pressed and re-change it but the problem is i dont know how to animate it to make the animation for 2 seconds (the next line of code doesnt work, it does change the color but not during 2 seconds):

func buttonUnpressed(){
    UIButton.animate(withDuration: 2, animations: {
        self.button.layer.borderColor = UIColor(red: 0, green: 0, blue: 80/255, alpha: 1).cgColor
    })
}

The question; is there any way of adding the border to the UIButton "total behavior" of highlighting and unhighlighting when pressed?

Excuse me for my english if there are some expression or gramatical faults.

EDIT
I tried with this function:

 func buttonUnpressed(){
    button.alpha = 0.2
    UIButton.animate(withDuration: 1) {
        self.button.alpha = 1
    }
    button.layer.borderColor = UIColor(red: 0, green: 0, blue: 80/255, alpha: 1).cgColor
}

there is a weird highlight of the image but now it works more or less.

Body:
I did find the final answer.
Thanks to krotov who tried to help!

 class BorderButton: UIButton {

 override init(frame: CGRect){
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

var colorPast: Bool = true

override var isHighlighted: Bool {
    didSet {
        if isHighlighted && colorPast {
            borderDissapear(highlighted: isHighlighted)
            colorPast = false
        } else if !isHighlighted && !colorPast {
            borderDissapear(highlighted: isHighlighted)
            colorPast = true
        }
    }
}

func borderDissapear (highlighted: Bool) {
    let animation = CABasicAnimation(keyPath: "borderColor")
    animation.duration = 0.1
    animation.autoreverses = false
    animation.repeatCount = 1
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    if highlighted {
        animation.fromValue = self.layer.borderColor?.copy(alpha: 1)
        animation.toValue = self.layer.borderColor?.copy(alpha: 0.3)
    } else if !highlighted {
        animation.fromValue = self.layer.borderColor?.copy(alpha: 0.3)
        animation.toValue = self.layer.borderColor?.copy(alpha: 1)
    }
    self.layer.add(animation, forKey: "borderColor")
}
}


问:
Service error: Spreadsheets using isblank()
I have a big problem since 2 days, my functiun doesn't work anymore :/
"Service error: Spreadsheets" at "if (cell.isBlank())"

```<code>    function miseEnForme(){
  var classeur = SpreadsheetApp.getActive();
  var feuilleAdm = classeur.getSheetByName("SuiviAdministratif");

  var lastRow;
  for (var row = 3; row < 1000; row++) {
    var cell=feuilleAdm.getRange(row,3);
    if (cell.isBlank()) {
      lastRow =row;
      break;
    }
  }

  for (var i =3; i<lastRow;i++){
   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="RS" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RP" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RD")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("red");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="C")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("#00ff00");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="O")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("white");
  }
}
</code>```

Is it my fault or Google have change something?
How to solve the problem?

Thanks

答:
Checkout this link.  I'm guessing that there's nothing wrong with the code.  It's just that Google Servers are trying to entice you into using a more batch oriented approach.  For example you could get all of your data with one call to var datA=sheet.getDataRange().getValues(); and then you would have all of your data in a 2 dimensional array.  It would be easier for Google servers to handle your process and it would perform much better for you. I'll take a copy of your code and see if I can simplify it for you.  Perhaps you could give me an idea of what your data looks like.

I haven't tested this code.  If you can share some of your data with me I'll be glad to do so.  This should be pretty close though.  I tried to follow the same basic approach that you were using so you could figure out what's happening a little easier.

```<code>function miseEnForme()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sht = ss.getSheetByName("SuiviAdministratif");
  var datrng = sht.getDataRange();
  var datA = datrng.getValues();//datA is a 2 dimensional array starts at zero
  var lastCol = datrng.getLastColumn();

  for(var i=2;i<datA.length;i++)
  {
    if(datA[1][i] == ("RS" || "RP" || "RD"))
    {
      sht.getRange(i+1,1,1,lastCol).setBackground('#ff0000');
    }
    if(datA[1][i] == "C")
    {
      sht.getRange(i+1,1,1,lastCol).setBackground('#00ff00');
    }
    if(datA[1][i] == "O")
    {
      sht.getRange(i+1,1,1,lastCol).setBackground('#ffffff');
    }
  }
}
</code>```

Body:
I have a big problem since 2 days, my functiun doesn't work anymore :/
"Service error: Spreadsheets" at "if (cell.isBlank())"

    function miseEnForme(){
  var classeur = SpreadsheetApp.getActive();
  var feuilleAdm = classeur.getSheetByName("SuiviAdministratif");

  var lastRow;
  for (var row = 3; row < 1000; row++) {
    var cell=feuilleAdm.getRange(row,3);
    if (cell.isBlank()) {
      lastRow =row;
      break;
    }
  }

  for (var i =3; i<lastRow;i++){
   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="RS" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RP" || feuilleAdm.getRange("B"+i).getDisplayValue()=="RD")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("red");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="C")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("#00ff00");

   if (feuilleAdm.getRange("B"+i).getDisplayValue()=="O")
     feuilleAdm.getRange("SuiviAdministratif!A"+i+":AB"+i).setBackground("white");
  }
}

Is it my fault or Google have change something?
How to solve the problem?

Thanks

Body:
Checkout this link.  I'm guessing that there's nothing wrong with the code.  It's just that Google Servers are trying to entice you into using a more batch oriented approach.  For example you could get all of your data with one call to var datA=sheet.getDataRange().getValues(); and then you would have all of your data in a 2 dimensional array.  It would be easier for Google servers to handle your process and it would perform much better for you. I'll take a copy of your code and see if I can simplify it for you.  Perhaps you could give me an idea of what your data looks like.

I haven't tested this code.  If you can share some of your data with me I'll be glad to do so.  This should be pretty close though.  I tried to follow the same basic approach that you were using so you could figure out what's happening a little easier.

function miseEnForme()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sht = ss.getSheetByName("SuiviAdministratif");
  var datrng = sht.getDataRange();
  var datA = datrng.getValues();//datA is a 2 dimensional array starts at zero
  var lastCol = datrng.getLastColumn();

  for(var i=2;i<datA.length;i++)
  {
    if(datA[1][i] == ("RS" || "RP" || "RD"))
    {
      sht.getRange(i+1,1,1,lastCol).setBackground('#ff0000');
    }
    if(datA[1][i] == "C")
    {
      sht.getRange(i+1,1,1,lastCol).setBackground('#00ff00');
    }
    if(datA[1][i] == "O")
    {
      sht.getRange(i+1,1,1,lastCol).setBackground('#ffffff');
    }
  }
}


问:
Audio being played over a stream is jittering/stuttering
I will briefly go over all the elements of my app:

I have an application that records audio to an AVAudioPCMBuffer. This buffer is then converted to NSData and then to [UInt8]. It is then streamed over an OutputStream. On another device, this data is received using an InputStream. Then it is converted to NSData, and back to an AVAudioPCMBuffer. This buffer is then played.

The issue is that the audio is very jittery and you can't make out voices, only that the audio gets louder or quieter depending on if the other person is talking.

When scheduling the buffer:

```<code>self.peerAudioPlayer.scheduleBuffer(audioBuffer, completionHandler: nil)
</code>```

I have delayed playing this audio for a few seconds and then played it, hoping that this would make the audio clearer, however it did not help. My best guess is that the buffer I'm creating is somehow cutting off some of the audio. So I will show you my relevant code:

Here is how I record audio:

```<code>    localInput?.installTap(onBus: 1, bufferSize: 4096, format: localInputFormat) {
        (buffer, when) -> Void in

        let data = self.audioBufferToNSData(PCMBuffer: buffer)
        let output = self.outputStream!.write(data.bytes.assumingMemoryBound(to: UInt8.self), maxLength: data.length)
    }
</code>```

audioBufferToNSData is just a method which converts AVAudioPCMBuffer to NSData and here it is:

```<code>func audioBufferToNSData(PCMBuffer: AVAudioPCMBuffer) -> NSData {
    let channelCount = 1  // given PCMBuffer channel count is 1
    let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: channelCount)
    let data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameCapacity * PCMBuffer.format.streamDescription.pointee.mBytesPerFrame))

    return data
}
</code>```

I'm wondering if the issue could be at the method above. Possibly when I calculate the length of the NSData object, maybe I am cutting off part of the audio.

On the receiving end I have this:

```<code>    case Stream.Event.hasBytesAvailable:
        DispatchQueue.global().async {
            var tempBuffer: [UInt8] = .init(repeating: 0, count: 17640)
            let length = self.inputStream!.read(&tempBuffer, maxLength: tempBuffer.count)

            self.testBufferCount += length
            self.testBuffer.append(contentsOf: tempBuffer)

            if (self.testBufferCount >= 17640) {

                let data = NSData.init(bytes: &self.testBuffer, length: self.testBufferCount)
                let audioBuffer = self.dataToPCMBuffer(data: data)

                self.peerAudioPlayer.scheduleBuffer(audioBuffer, completionHandler: nil)

                self.testBuffer.removeAll()
                self.testBufferCount = 0
            }
        }
</code>```

The reason I check for 17640 is because the data being sent is exactly 17640 bytes, so I need to get all of this data before I play it.

Furthermore, the dataToPCMBuffer method just converts NSData to an AVAudioPCMBuffer so that it can be played. Here is that method:

```<code>func dataToPCMBuffer(data: NSData) -> AVAudioPCMBuffer {
    let audioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 1, interleaved: false)  // given NSData audio format
    let audioBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: UInt32(data.length) / audioFormat.streamDescription.pointee.mBytesPerFrame)
    audioBuffer.frameLength = audioBuffer.frameCapacity
    let channels = UnsafeBufferPointer(start: audioBuffer.floatChannelData, count: Int(audioBuffer.format.channelCount))
    data.getBytes(UnsafeMutableRawPointer(channels[0]) , length: data.length)
    return audioBuffer
}
</code>```

Thank you in advance!

答:
I think that in audioBufferToNSData you should use frameLength instead of frameCapacity.

let data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameLength * PCMBuffer.format.streamDescription.pointee.mBytesPerFrame))

PCMBuffer.frameCapacity -> how much can be stored
PCMBuffer.frameLength -> how much of PCMBuffer.frameCapacity is actual valid data

Body:
I will briefly go over all the elements of my app:

I have an application that records audio to an AVAudioPCMBuffer. This buffer is then converted to NSData and then to [UInt8]. It is then streamed over an OutputStream. On another device, this data is received using an InputStream. Then it is converted to NSData, and back to an AVAudioPCMBuffer. This buffer is then played.

The issue is that the audio is very jittery and you can't make out voices, only that the audio gets louder or quieter depending on if the other person is talking.

When scheduling the buffer:

self.peerAudioPlayer.scheduleBuffer(audioBuffer, completionHandler: nil)

I have delayed playing this audio for a few seconds and then played it, hoping that this would make the audio clearer, however it did not help. My best guess is that the buffer I'm creating is somehow cutting off some of the audio. So I will show you my relevant code:

Here is how I record audio:

    localInput?.installTap(onBus: 1, bufferSize: 4096, format: localInputFormat) {
        (buffer, when) -> Void in

        let data = self.audioBufferToNSData(PCMBuffer: buffer)
        let output = self.outputStream!.write(data.bytes.assumingMemoryBound(to: UInt8.self), maxLength: data.length)
    }

audioBufferToNSData is just a method which converts AVAudioPCMBuffer to NSData and here it is:

func audioBufferToNSData(PCMBuffer: AVAudioPCMBuffer) -> NSData {
    let channelCount = 1  // given PCMBuffer channel count is 1
    let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: channelCount)
    let data = NSData(bytes: channels[0], length:Int(PCMBuffer.frameCapacity * PCMBuffer.format.streamDescription.pointee.mBytesPerFrame))

    return data
}

I'm wondering if the issue could be at the method above. Possibly when I calculate the length of the NSData object, maybe I am cutting off part of the audio.

On the receiving end I have this:

    case Stream.Event.hasBytesAvailable:
        DispatchQueue.global().async {
            var tempBuffer: [UInt8] = .init(repeating: 0, count: 17640)
            let length = self.inputStream!.read(&tempBuffer, maxLength: tempBuffer.count)

            self.testBufferCount += length
            self.testBuffer.append(contentsOf: tempBuffer)

            if (self.testBufferCount >= 17640) {

                let data = NSData.init(bytes: &self.testBuffer, length: self.testBufferCount)
                let audioBuffer = self.dataToPCMBuffer(data: data)

                self.peerAudioPlayer.scheduleBuffer(audioBuffer, completionHandler: nil)

                self.testBuffer.removeAll()
                self.testBufferCount = 0
            }
        }

The reason I check for 17640 is because the data being sent is exactly 17640 bytes, so I need to get all of this data before I play it.

Furthermore, the dataToPCMBuffer method just converts NSData to an AVAudioPCMBuffer so that it can be played. Here is that method:

func dataToPCMBuffer(data: NSData) -> AVAudioPCMBuffer {
    let audioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 1, interleaved: false)  // given NSData audio format
    let audioBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: UInt32(data.length) / audioFormat.streamDescription.pointee.mBytesPerFrame)
    audioBuffer.frameLength = audioBuffer.frameCapacity
    let channels = UnsafeBufferPointer(start: audioBuffer.floatChannelData, count: Int(audioBuffer.format.channelCount))
    data.getBytes(UnsafeMutableRawPointer(channels[0]) , length: data.length)
    return audioBuffer
}

Thank you in advance!


问:
How to add page list in asp.net core MVC application?
I want to add page list in asp.net core MVC application so only 10 result will appear in the first page, to see more result I wanna add next option .I searched  but didn't found any solution for this operation.
There is NuGet package for asp.net but not for  asp.net core application.

PagedList

X.PagedList  (This is forked from PageList)

答:
If you'd rather not use jQuery and a bunch of UI-layer scripts that users will be able to read, you can modify your controller and actions to use pagination.

See the link below for a tutorial on adding Sorting, Filtering and Paging to a list view.

https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page

I'm using this in a company project, and while it can be a bit cumbersome at first, once you get the hang of it it's easy to replicate the functionality in other pages.

ContentLicense: CC BY-SA 4.0


问:
Opening Files for Edit
I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
    }
    return 0;
}
</code>```

答:
You could use the errno to get a hint as to what is going wrong:</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h> /* new */

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
        printf("Errno = %d\n, errno) ; /* new */
    }
    return 0;
}
</code>```

Title: Opening Files for Edit

Body:
I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives.

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
    }
    return 0;
}

Body:
You could use the errno to get a hint as to what is going wrong:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h> /* new */

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
        printf("Errno = %d\n, errno) ; /* new */
    }
    return 0;
}