问:
How can I keep all my navbar icons in one row when viewing from a mobile device in React?
I am making a pretty simple bottomnav for a project I am working on, and I am having difficulty with the view in mobile mode. From standard desktop, I have a pretty simple, bottomnav with 4 icons, however when I inspect the page in mobile view, it only shows you either the first, or the first and 2nd icon. all of my styling for this component is:

```<code>/* Place the navbar at the bottom of the page, and make it stick */
.navbar {
    background-color: rgb(75, 90, 72);
    overflow: hidden;
    position: absolute;
    bottom: 0;
    min-width:800px;
    height:64px;
    /* width: 100%; */
  }
  .navCont {
      text-align: center;
      position: fixed;
    bottom: 0;
    width: 100%;
  }
  .navButton {
      margin-left:10vh;
      margin-right:10vh;
      min-width:10px;
  }
  .navButtonLeft {
    margin-left:10vh;
    margin-right:10vh;
    min-width:10px;
}

  /* Style the links inside the navigation bar */
  .navbar a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
  }

  /* Change the color of links on hover */
  .navbar a:hover {
    background-color: #ddd;
    color: black;
  }

  /* Add a color to the active/current link */
  .navbar a.active {
    background-color: #4CAF50;
    color: white;
  }

  img {
    width:32px;
    height: auto;
    float:left;
    margin-bottom: 20px;
  }

@media screen and (max-width: 100px) {
  .navbar {
    display: inline-block;
    height:64px;
  }
  .navCont {
    display: flex;
    align-content: space-between;
  }
  .navButton,
  .navButtonLeft {

    padding: none;
    display: inline-block;
  }
  img {
    display: inline-block;

  }
}
</code>```

Any advice or tips would be greatly appreciated!

edit: Here is the component i am working with.

```<code>import React from "react";
import home from "./home.png"
import post from "./post.png"
import profile from "./profile.png"
import search from "./search.png"

import "./Footer.css";

class Footer extends React.Component {
    render() {
        return (
            <div class="navCont">
                <div class="navbar">
                    <a href="/"class="navButtonLeft"><img src={home} alt="home icon"/> </a>
                    <a href="Profile"class="navButton"><img src={profile} alt="home icon"/> </a>
                    <a href="Post"class="navButton"><img src={post} style={{width:"44px", height: "auto"}} alt="home icon"/> </a>
                    <a href="Search"class="navButton"><img src={search} style={{width:"44px", height: "auto"}} alt="home icon"/> </a>
                </div>

            </div>
        );
    }
}
export default Footer;
</code>```

答:
I've revamped your css to use flexbox for laying out the icons in a row; got rid of all the floats and some other rules that seemed unnecessary. I'm not sure this does exactly what you're trying to do (since I don't know exactly what you're trying to do) but I think this is at least a better starting point.

.navCont {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  background-color: rgb(75, 90, 72);
}

.navbar {
  height: 64px;
  display: flex;
  justify-content: center;
}

/* Style the links inside the navigation bar */
.navbar > * {
  flex: 0 0 auto;
  padding: 14px 16px;
}

/* Change the color of links on hover */
.navbar a:hover {
  background-color: #ddd;
  color: black;
}

img {
  width: 32px;
  max-width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navCont">
  <div class="navbar">

      <img src="https://via.placeholder.com/64x64.png/fff/000/?text=A" />

      <img src="https://via.placeholder.com/64x64.png/fff/000?text=B" />

      <img src="https://via.placeholder.com/64x64.png/fff/000?text=C" />

      <img src="https://via.placeholder.com/64x64.png/fff/000?text=D" />

  </div>
</div></code>```

Body:
I am making a pretty simple bottomnav for a project I am working on, and I am having difficulty with the view in mobile mode. From standard desktop, I have a pretty simple, bottomnav with 4 icons, however when I inspect the page in mobile view, it only shows you either the first, or the first and 2nd icon. all of my styling for this component is:

/* Place the navbar at the bottom of the page, and make it stick */
.navbar {
    background-color: rgb(75, 90, 72);
    overflow: hidden;
    position: absolute;
    bottom: 0;
    min-width:800px;
    height:64px;
    /* width: 100%; */
  }
  .navCont {
      text-align: center;
      position: fixed;
    bottom: 0;
    width: 100%;
  }
  .navButton {
      margin-left:10vh;
      margin-right:10vh;
      min-width:10px;
  }
  .navButtonLeft {
    margin-left:10vh;
    margin-right:10vh;
    min-width:10px;
}

  /* Style the links inside the navigation bar */
  .navbar a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
  }

  /* Change the color of links on hover */
  .navbar a:hover {
    background-color: #ddd;
    color: black;
  }

  /* Add a color to the active/current link */
  .navbar a.active {
    background-color: #4CAF50;
    color: white;
  }

  img {
    width:32px;
    height: auto;
    float:left;
    margin-bottom: 20px;
  }

@media screen and (max-width: 100px) {
  .navbar {
    display: inline-block;
    height:64px;
  }
  .navCont {
    display: flex;
    align-content: space-between;
  }
  .navButton,
  .navButtonLeft {

    padding: none;
    display: inline-block;
  }
  img {
    display: inline-block;

  }
}

Any advice or tips would be greatly appreciated!

edit: Here is the component i am working with.

import React from "react";
import home from "./home.png"
import post from "./post.png"
import profile from "./profile.png"
import search from "./search.png"

import "./Footer.css";

class Footer extends React.Component {
    render() {
        return (

        );
    }
}
export default Footer;

Body:
I've revamped your css to use flexbox for laying out the icons in a row; got rid of all the floats and some other rules that seemed unnecessary. I'm not sure this does exactly what you're trying to do (since I don't know exactly what you're trying to do) but I think this is at least a better starting point.

.navCont {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  background-color: rgb(75, 90, 72);
}

.navbar {
  height: 64px;
  display: flex;
  justify-content: center;
}

/* Style the links inside the navigation bar */
.navbar > * {
  flex: 0 0 auto;
  padding: 14px 16px;
}

/* Change the color of links on hover */
.navbar a:hover {
  background-color: #ddd;
  color: black;
}

img {
  width: 32px;
  max-width: 100%;
  height: auto;
}

<div class="navCont">
  <div class="navbar">
    <a href="/" class="navButton">
      <img src="https://via.placeholder.com/64x64.png/fff/000/?text=A" />
    </a>
    <a href="Profile" class="navButton">
      <img src="https://via.placeholder.com/64x64.png/fff/000?text=B" />
    </a>
    <a href="Post" class="navButton">
      <img src="https://via.placeholder.com/64x64.png/fff/000?text=C" />
    </a>
    <a href="Search" class="navButton">
      <img src="https://via.placeholder.com/64x64.png/fff/000?text=D" />
    </a>
  </div>
</div>


来源: stackexchange

问:
invariant violation: requirenativecomponent: "rncamera" was not found in the uimanager
In react native I want to add a barcode scanner and take a picture on my app  but I am running  in to the following error:

invariant violation: requirenativecomponent: "rncamera" was not found
  in the uimanager.

When barcode component view opens.

```<code>react-native-camera 3.3.0
react-native sdk-32 (expo)
</code>```

答: you will most likely have to eject to native code out of expo because any third party package that asks you to run the command "react-native link" as part of the setup process is strictly to be used with pure react native app. hope that helps</p>

ContentLicense: CC BY-SA 4.0

Body:
In react native I want to add a barcode scanner and take a picture on my app  but I am running  in to the following error:

invariant violation: requirenativecomponent: "rncamera" was not found
  in the uimanager.

When barcode component view opens.

react-native-camera 3.3.0
react-native sdk-32 (expo)


问:
Work item access for non visual-studio users
We're using TFS for source control and are trialling using the TFS work item tracking. I am trying to find out, is it possible for people who don't have visual studio installed to access, create and edit work items via a browser based user interface?

Our technical support team need to be able to use work items. TFS work items won't be suitable for our company if the support team and project managers can't get sufficient access.

I'm not familiar with how the licensing works either. If there is a way for non visual studio users to use TFS work items, will they need a license?

答: There should be a web interface, both a website and a SharePoint portal that gets installed with TFS. The portal will let you get to the documents and view some reports. The website will let you work with the documents, the source control, work items, and bug reporting.</p>

OwnerDisplayName: Scott Langham

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Scott Langham


问:
SSAS DAX query.... how to show totals against attribute values that match calc conditions
In our companies cubes we regularly use the CALCULATION function for our measures.  We also regularly come across the scenario where even though we apply a filter in the CALCULATION the returned total shows the same value across multiple rows instead of the rows where the condition is met.

The below screen shot is an example.

Where we want the total to only be display against the Row where the Attribute = "Y"

The CALCULATION

```<code>=
CALCULATE (
    DISTINCTCOUNT ( 'Sales'[Transaction_Header_ID] ),
    'Sales'[Is_Named_Sale] = "Y",
    'Member'[Member_Has_Email_Flag] = "Y"
)
</code>```

I am fairly new to DAX and still don't understand how when you use filters in a calculation this can occur. The result we are after is more like

```<code>Member_Has_Email_Flag Total

Y                     249239

N
</code>```

If anyone can explain this it would be greatly appreciated.

Cheers

答:
Think what happens in the report cell where 'Member'[Member_Has_Email_Flag] is "N".

From the report, we are getting a filter 'Member'[Member_Has_Email_Flag] = "N". Then, inside CALCULATE function, you are overriding this filter with "Y". So, you formula ignores filters coming from the report, and replaces them with "Y", giving you the same number regardless of the external filter. That's how CALCULATE works - it modifies external filters by replacing them with the filters you provide inside the function.

To fix the the problem, use KEEPFILTERS function:

```<code>=
CALCULATE (
    DISTINCTCOUNT ( 'Sales'[Transaction_Header_ID] ),
    'Sales'[Is_Named_Sale] = "Y",
    KEEPFILTERS('Member'[Member_Has_Email_Flag] = "Y")
)
</code>```

Here, you tell CALCULATE to keep the external filter ('N") and combine it with the new filter ("Y"). Since there are no records where this field is simultaneously Y and N, the formula will now return blank.

Body:
In our companies cubes we regularly use the CALCULATION function for our measures.  We also regularly come across the scenario where even though we apply a filter in the CALCULATION the returned total shows the same value across multiple rows instead of the rows where the condition is met.

The below screen shot is an example.

Where we want the total to only be display against the Row where the Attribute = "Y"

The CALCULATION

=
CALCULATE (
    DISTINCTCOUNT ( 'Sales'[Transaction_Header_ID] ),
    'Sales'[Is_Named_Sale] = "Y",
    'Member'[Member_Has_Email_Flag] = "Y"
)

I am fairly new to DAX and still don't understand how when you use filters in a calculation this can occur. The result we are after is more like

Member_Has_Email_Flag Total

Y                     249239

N

If anyone can explain this it would be greatly appreciated.

Cheers

Body:
Think what happens in the report cell where 'Member'[Member_Has_Email_Flag] is "N".

From the report, we are getting a filter 'Member'[Member_Has_Email_Flag] = "N". Then, inside CALCULATE function, you are overriding this filter with "Y". So, you formula ignores filters coming from the report, and replaces them with "Y", giving you the same number regardless of the external filter. That's how CALCULATE works - it modifies external filters by replacing them with the filters you provide inside the function.

To fix the the problem, use KEEPFILTERS function:

=
CALCULATE (
    DISTINCTCOUNT ( 'Sales'[Transaction_Header_ID] ),
    'Sales'[Is_Named_Sale] = "Y",
    KEEPFILTERS('Member'[Member_Has_Email_Flag] = "Y")
)

Here, you tell CALCULATE to keep the external filter ('N") and combine it with the new filter ("Y"). Since there are no records where this field is simultaneously Y and N, the formula will now return blank.


问:
How to clear/avoid FFImageLoading's caching in list item image
I am using FFImageLoading instead of Image in my project for more advanced features like placeholders. In my project, there is a list of images needs to show. So I am using a listview for the same.

```<code><ListView x:Name="membersList" ItemTapped="Handle_ItemTappedMember" HorizontalOptions="FillAndExpand" HasUnevenRows="true" SeparatorVisibility="None" BackgroundColor="#EEEEEE" Grid.Row="0" Grid.Column="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout Orientation="Horizontal" Padding="5,5,5,5" HeightRequest="75" Margin="10,5,10,5" BackgroundColor="White" HorizontalOptions="FillAndExpand">
                                <ffimageloading:CachedImage Source="{Binding imageUrl}" x:Name="patImage" WidthRequest="60" HeightRequest="60" Aspect="AspectFill" VerticalOptions="Center">
                                    <ffimageloading:CachedImage.Transformations>
                                        <fftransformations:CircleTransformation />
                                    </ffimageloading:CachedImage.Transformations>
                                </ffimageloading:CachedImage>
                                <StackLayout Spacing="3" Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand">
                                    <Label FontAttributes="Bold" FontSize="14" TextColor="#212121" Text="{Binding FullName}" />
                                    <Label FontSize="12" TextColor="#212121" Text="{Binding Relation}" />
                                    <Label FontSize="12" TextColor="#212121" Text="{Binding Pat_ID}" />
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

My problem is that I don't want to use Caching techniques here since my image from server may be changed without change the URL.

I know how to clear a single image view's cache with FFImageLoading

```<code>await CachedImage.InvalidateCache(Image.Source, CacheType.All, true);
</code>```

But how to achieve this in ListView? I am using Binding property to load images here.

答:
await not working without async so I added the async method for clean cache.   </p>

```<code>private string mImageUrl { get; set; }
public string imageUrl
{
get{
     return mImageUrl;
   };
set{
     mImageUrl = value;
     cleanCache();

   };
}

private async void cleanCache()
{
   await CachedImage.InvalidateCache(ImageURL, CacheType.All, true);
}
</code>```

Body:
I am using FFImageLoading instead of Image in my project for more advanced features like placeholders. In my project, there is a list of images needs to show. So I am using a listview for the same.

<ListView x:Name="membersList" ItemTapped="Handle_ItemTappedMember" HorizontalOptions="FillAndExpand" HasUnevenRows="true" SeparatorVisibility="None" BackgroundColor="#EEEEEE" Grid.Row="0" Grid.Column="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout Orientation="Horizontal" Padding="5,5,5,5" HeightRequest="75" Margin="10,5,10,5" BackgroundColor="White" HorizontalOptions="FillAndExpand">
                                <ffimageloading:CachedImage Source="{Binding imageUrl}" x:Name="patImage" WidthRequest="60" HeightRequest="60" Aspect="AspectFill" VerticalOptions="Center">
                                    <ffimageloading:CachedImage.Transformations>
                                        <fftransformations:CircleTransformation />
                                    </ffimageloading:CachedImage.Transformations>
                                </ffimageloading:CachedImage>
                                <StackLayout Spacing="3" Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand">

                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

My problem is that I don't want to use Caching techniques here since my image from server may be changed without change the URL.

I know how to clear a single image view's cache with FFImageLoading

await CachedImage.InvalidateCache(Image.Source, CacheType.All, true);

But how to achieve this in ListView? I am using Binding property to load images here.

Body:
await not working without async so I added the async method for clean cache.

private string mImageUrl { get; set; }
public string imageUrl
{
get{
     return mImageUrl;
   };
set{
     mImageUrl = value;
     cleanCache();

   };
}

private async void cleanCache()
{
   await CachedImage.InvalidateCache(ImageURL, CacheType.All, true);
}


问:
Send Mail/Task/Appointment with Redemption
I am trying to programmatically send a Mail/Task/Appointment to a user and I have the problem, that every time I send them the first one will get stuck in my outbox... It seems that the first one sent to Outlook has no/looses its sent-date and will stay forever in my outbox.

Here is the code for example "sending a task notification"

```<code>using (MapiSession session = new MapiSession())
{
    var item = session.CreateItem(Outlook.OlItemType.olTaskItem) as RDOTaskItem;
    [..]
    try
    {
        item.Subject = "SUBJECT";
        item.Body = "BODY;

        item.StartDate = DateTime.Now;
        item.DueDate = DateTime.Now;

        item.Recipients.Add("test@mail.com");
        item.Recipients.Add("test2@mail.com");

        item.Recipients.ResolveAll();
        item.Assign();
        item.Save();
        item.Send();
    }
    [..]
}
</code>```

Thanks in advance.

答:
So I am not really shure what is the problem so far...
If all receivers are other persons then myself this should work...

Here is my code for sendig a TaskItem

```<code>private void NotifyByTask(OutlookNotificationTypes notificationType)
{
    Application app = new Application();
    var item = app.CreateItem(OlItemType.olTaskItem) as TaskItem;

    try
    {
        item.Subject = this.Subject;
        item.Body = this.Body;

        if (this.Start != DateTime.MinValue)
        {
            item.StartDate = this.Start;
            item.ReminderSet = true;
            item.ReminderPlaySound = true;
            item.ReminderTime = this.Start.AddMinutes(-5);
        }
        if (this.End != DateTime.MinValue)
        {
            item.DueDate = this.End;
        }
        item.PercentComplete = this.PercentComplete;

        StringBuilder categories = new StringBuilder();
        foreach (String category in this.Categories)
        {
            categories.Append(category);
        }
        item.Categories = categories.ToString();

        bool sendingToMyself = false;
        if (this.NotificationType == OutlookNotificationTypes.TaskRequest)
        {
            // this will add all recipients and checks if Receiver is yourself
            sendingToMyself = item.AddRecipients(this.Recipients, OlMailRecipientType.olTo);
        }
        if (this.NotificationType == OutlookNotificationTypes.TaskRequest
            && (!sendingToMyself))
        {
            item.Recipients.ResolveAll();
            item.Assign();
            item.Save();
            item.Send();
        }
        else
        {
            item.Save();

            //insert element
            if (this.ItemSaved != null)
            {
                Microsoft.Office.Interop.Outlook.MAPIFolder folder =
                                item.Parent as Microsoft.Office.Interop.Outlook.MAPIFolder;

            if (folder != null)
            {
                try
                {
                    String storeId = folder.StoreID;
                    String entryId = item.EntryID;
                    this.ItemSaved(storeId, entryId);
                }
                finally
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
                }
            }
        }
    }
}
finally
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
}
}
</code>```

Body:
I am trying to programmatically send a Mail/Task/Appointment to a user and I have the problem, that every time I send them the first one will get stuck in my outbox... It seems that the first one sent to Outlook has no/looses its sent-date and will stay forever in my outbox.

Here is the code for example "sending a task notification"

using (MapiSession session = new MapiSession())
{
    var item = session.CreateItem(Outlook.OlItemType.olTaskItem) as RDOTaskItem;
    [..]
    try
    {
        item.Subject = "SUBJECT";
        item.Body = "BODY;

        item.StartDate = DateTime.Now;
        item.DueDate = DateTime.Now;

        item.Recipients.Add("test@mail.com");
        item.Recipients.Add("test2@mail.com");

        item.Recipients.ResolveAll();
        item.Assign();
        item.Save();
        item.Send();
    }
    [..]
}

Thanks in advance.

Body:
So I am not really shure what is the problem so far...
If all receivers are other persons then myself this should work...

Here is my code for sendig a TaskItem

private void NotifyByTask(OutlookNotificationTypes notificationType)
{
    Application app = new Application();
    var item = app.CreateItem(OlItemType.olTaskItem) as TaskItem;

    try
    {
        item.Subject = this.Subject;
        item.Body = this.Body;

        if (this.Start != DateTime.MinValue)
        {
            item.StartDate = this.Start;
            item.ReminderSet = true;
            item.ReminderPlaySound = true;
            item.ReminderTime = this.Start.AddMinutes(-5);
        }
        if (this.End != DateTime.MinValue)
        {
            item.DueDate = this.End;
        }
        item.PercentComplete = this.PercentComplete;

        StringBuilder categories = new StringBuilder();
        foreach (String category in this.Categories)
        {
            categories.Append(category);
        }
        item.Categories = categories.ToString();

        bool sendingToMyself = false;
        if (this.NotificationType == OutlookNotificationTypes.TaskRequest)
        {
            // this will add all recipients and checks if Receiver is yourself
            sendingToMyself = item.AddRecipients(this.Recipients, OlMailRecipientType.olTo);
        }
        if (this.NotificationType == OutlookNotificationTypes.TaskRequest
            && (!sendingToMyself))
        {
            item.Recipients.ResolveAll();
            item.Assign();
            item.Save();
            item.Send();
        }
        else
        {
            item.Save();

            //insert element
            if (this.ItemSaved != null)
            {
                Microsoft.Office.Interop.Outlook.MAPIFolder folder =
                                item.Parent as Microsoft.Office.Interop.Outlook.MAPIFolder;

            if (folder != null)
            {
                try
                {
                    String storeId = folder.StoreID;
                    String entryId = item.EntryID;
                    this.ItemSaved(storeId, entryId);
                }
                finally
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
                }
            }
        }
    }
}
finally
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
}
}


问:
log X amount not in a loop
I'm using Javascript trying to log the same string multiple times. Is there a way to do this without iterating through a loop? When I try it with a loop it logs the string 4 times adding to it each time.

I want to log the string once, but with all four items in it.

For example, I want:

```<code>0000
</code>```

and not:

```<code>0
00
000
0000
</code>```

Here's what I've tried:

var string = ''

function zero(x) {
  for (i = 0; i <= 3; i++) {
    console.log(string += x)
  }
}

zero('0')```

Is it possible to skip logging the first three outputs and just log 0000 on one line?

答:
One more way to do the same.

function zero(x, n) {
  console.log(x.repeat(n));
}

zero("0", 4);```

Title: log X amount not in a loop

Body:
I'm using Javascript trying to log the same string multiple times. Is there a way to do this without iterating through a loop? When I try it with a loop it logs the string 4 times adding to it each time.

I want to log the string once, but with all four items in it.

For example, I want:

0000

and not:

0
00
000
0000

Here's what I've tried:

var string = ''

function zero(x) {
  for (i = 0; i <= 3; i++) {
    console.log(string += x)
  }
}

zero('0')

Is it possible to skip logging the first three outputs and just log 0000 on one line?


问:
flutter - make dynamic mark event in calendar plugin
I want to mark the event once every 4 days.

example today is the 1st, mark the event will be available on the 5th, 10th, 15th, 20th, 25th, 30th, etc.

if today is the 3rd, the event will be available on the 8th, 13th, 18th, etc.

how does that function work?

I use this calendar plugin

https://pub.dev/packages/flutter_calendar_carousel

Following is the function to mark event manually:

```<code>EventList<Event> _markedDateMap = new EventList<Event>();

   build(){
       _calendarCarouselNoHeader = CalendarCarousel<Event>(
       ...
       markedDatesMap: _markedDateMap,
       ...
       ),
    }

 @override
  void initState() {

     _markedDateMap.add(
         new DateTime(2020, 2, 26),
        new Event(
         date: new DateTime(2020, 2, 26),
         title: 'Event 5',
         icon: _eventIcon,
         ));

     _markedDateMap.add(
         new DateTime(2020, 2, 26),
        new Event(
         date: new DateTime(2020, 2, 26),
         title: 'Event 5',
         icon: _eventIcon,
         ));

    super.initState();
}
</code>```

Any anwser will appreciated.

答:
You can copy paste run full code below

working demo show when pass start date time with

```<code>addMarker(DateTime(2020, 2, 01));
addMarker(DateTime(2020, 2, 03));
</code>```

code snippet

```<code>addMarker(DateTime startEventDateTime) {

    var eventDateTime = startEventDateTime;

    for(int i=0; i<5; i++) {
      if(eventDateTime.day == 1) {
        eventDateTime = eventDateTime.add(Duration(days: (4)));
      } else {
        eventDateTime = eventDateTime.add(Duration(days: (5)));
      }
      print(eventDateTime.toLocal());
      _markedDateMap.add(
          eventDateTime,
          Event(
            date: eventDateTime,
            title: 'Event $i',
            icon: _eventIcon,
          ));

    }
  }
</code>```

working demo

full code

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

import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
    show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:intl/intl.dart' show DateFormat;

void main() => runApp( MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      title: 'dooboolab flutter calendar',
      theme:  ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  MyHomePage(title: 'Flutter Calendar Carousel Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  DateTime _currentDate = DateTime(2020, 2, 17);
  DateTime _currentDate2 = DateTime(2020, 2, 17);
  String _currentMonth = DateFormat.yMMM().format(DateTime(2020, 2, 17));
  DateTime _targetDateTime = DateTime(2020, 2, 17);
//  List<DateTime> _markedDate = [DateTime(2018, 9, 20), DateTime(2018, 10, 11)];
  static Widget _eventIcon =  Container(
    decoration:  BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(1000)),
        border: Border.all(color: Colors.blue, width: 2.0)),
    child:  Icon(
      Icons.person,
      color: Colors.amber,
    ),
  );

  EventList<Event> _markedDateMap = EventList<Event>();
  CalendarCarousel _calendarCarousel, _calendarCarouselNoHeader;

  @override
  void initState() {
   addMarker(DateTime(2020, 2, 03));
    super.initState();
  }

  addMarker(DateTime startEventDateTime) {

    var eventDateTime = startEventDateTime;

    for(int i=0; i<5; i++) {
      if(eventDateTime.day == 1) {
        eventDateTime = eventDateTime.add(Duration(days: (4)));
      } else {
        eventDateTime = eventDateTime.add(Duration(days: (5)));
      }
      print(eventDateTime.toLocal());
      _markedDateMap.add(
          eventDateTime,
          Event(
            date: eventDateTime,
            title: 'Event $i',
            icon: _eventIcon,
          ));

    }
  }

  @override
  Widget build(BuildContext context) {
    /// Example with custom icon
    _calendarCarousel = CalendarCarousel<Event>(
      onDayPressed: (DateTime date, List<Event> events) {
        this.setState(() => _currentDate = date);
        events.forEach((event) => print(event.title));
      },
      weekendTextStyle: TextStyle(
        color: Colors.red,
      ),
      thisMonthDayBorderColor: Colors.grey,
//          weekDays: null, /// for pass null when you do not want to render weekDays
      headerText: 'Custom Header',
//          markedDates: _markedDate,
      weekFormat: true,
      markedDatesMap: _markedDateMap,
      height: 200.0,
      selectedDateTime: _currentDate2,
      showIconBehindDayText: true,
//          daysHaveCircularBorder: false, /// null for not rendering any border, true for circular border, false for rectangular border
      customGridViewPhysics: NeverScrollableScrollPhysics(),
      markedDateShowIcon: true,
      markedDateIconMaxShown: 2,
      selectedDayTextStyle: TextStyle(
        color: Colors.yellow,
      ),
      todayTextStyle: TextStyle(
        color: Colors.blue,
      ),
      markedDateIconBuilder: (event) {
        return event.icon;
      },
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      todayButtonColor: Colors.transparent,
      todayBorderColor: Colors.green,
      markedDateMoreShowTotal:
      false, // null for not showing hidden events indicator
//          markedDateIconMargin: 9,
//          markedDateIconOffset: 3,
    );

    /// Example Calendar Carousel without header and custom prev & next button
    _calendarCarouselNoHeader = CalendarCarousel<Event>(
      todayBorderColor: Colors.green,
      onDayPressed: (DateTime date, List<Event> events) {
        this.setState(() => _currentDate2 = date);
        events.forEach((event) => print(event.title));
      },
      daysHaveCircularBorder: true,
      showOnlyCurrentMonthDate: false,
      weekendTextStyle: TextStyle(
        color: Colors.red,
      ),
      thisMonthDayBorderColor: Colors.grey,
      weekFormat: false,
//      firstDayOfWeek: 4,
      markedDatesMap: _markedDateMap,
      height: 420.0,
      selectedDateTime: _currentDate2,
      targetDateTime: _targetDateTime,
      customGridViewPhysics: NeverScrollableScrollPhysics(),
      markedDateCustomShapeBorder: CircleBorder(
          side: BorderSide(color: Colors.yellow)
      ),
      markedDateCustomTextStyle: TextStyle(
        fontSize: 18,
        color: Colors.blue,
      ),
      showHeader: false,
      // markedDateIconBuilder: (event) {
      //   return Container(
      //     color: Colors.blue,
      //   );
      // },
      todayTextStyle: TextStyle(
        color: Colors.blue,
      ),
      todayButtonColor: Colors.yellow,
      selectedDayTextStyle: TextStyle(
        color: Colors.yellow,
      ),
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      prevDaysTextStyle: TextStyle(
        fontSize: 16,
        color: Colors.pinkAccent,
      ),
      inactiveDaysTextStyle: TextStyle(
        color: Colors.tealAccent,
        fontSize: 16,
      ),
      onCalendarChanged: (DateTime date) {
        this.setState(() {
          _targetDateTime = date;
          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
        });
      },
      onDayLongPressed: (DateTime date) {
        print('long pressed date $date');
      },
    );

    return  Scaffold(
        appBar:  AppBar(
          title:  Text(widget.title),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              //custom icon
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.0),
                child: _calendarCarousel,
              ), // This trailing comma makes auto-formatting nicer for build methods.
              //custom icon without header
              Container(
                margin: EdgeInsets.only(
                  top: 30.0,
                  bottom: 16.0,
                  left: 16.0,
                  right: 16.0,
                ),
                child:  Row(
                  children: <Widget>[
                    Expanded(
                        child: Text(
                          _currentMonth,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 24.0,
                          ),
                        )),
                    FlatButton(
                      child: Text('PREV'),
                      onPressed: () {
                        setState(() {
                          _targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month -1);
                          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
                        });
                      },
                    ),
                    FlatButton(
                      child: Text('NEXT'),
                      onPressed: () {
                        setState(() {
                          _targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month +1);
                          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
                        });
                      },
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.0),
                child: _calendarCarouselNoHeader,
              ), //
            ],
          ),
        ));
  }
}
</code>```

Body:
I want to mark the event once every 4 days.

example today is the 1st, mark the event will be available on the 5th, 10th, 15th, 20th, 25th, 30th, etc.

if today is the 3rd, the event will be available on the 8th, 13th, 18th, etc.

how does that function work?

I use this calendar plugin

https://pub.dev/packages/flutter_calendar_carousel

Following is the function to mark event manually:

EventList<Event> _markedDateMap = new EventList<Event>();

   build(){
       _calendarCarouselNoHeader = CalendarCarousel<Event>(
       ...
       markedDatesMap: _markedDateMap,
       ...
       ),
    }

 @override
  void initState() {

     _markedDateMap.add(
         new DateTime(2020, 2, 26),
        new Event(
         date: new DateTime(2020, 2, 26),
         title: 'Event 5',
         icon: _eventIcon,
         ));

     _markedDateMap.add(
         new DateTime(2020, 2, 26),
        new Event(
         date: new DateTime(2020, 2, 26),
         title: 'Event 5',
         icon: _eventIcon,
         ));

    super.initState();
}

Any anwser will appreciated.

Body:
You can copy paste run full code below

working demo show when pass start date time with

addMarker(DateTime(2020, 2, 01));
addMarker(DateTime(2020, 2, 03));

code snippet

addMarker(DateTime startEventDateTime) {

    var eventDateTime = startEventDateTime;

    for(int i=0; i<5; i++) {
      if(eventDateTime.day == 1) {
        eventDateTime = eventDateTime.add(Duration(days: (4)));
      } else {
        eventDateTime = eventDateTime.add(Duration(days: (5)));
      }
      print(eventDateTime.toLocal());
      _markedDateMap.add(
          eventDateTime,
          Event(
            date: eventDateTime,
            title: 'Event $i',
            icon: _eventIcon,
          ));

    }
  }

working demo

full code

import 'package:flutter/material.dart';

import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
    show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:intl/intl.dart' show DateFormat;

void main() => runApp( MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      title: 'dooboolab flutter calendar',
      theme:  ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  MyHomePage(title: 'Flutter Calendar Carousel Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  DateTime _currentDate = DateTime(2020, 2, 17);
  DateTime _currentDate2 = DateTime(2020, 2, 17);
  String _currentMonth = DateFormat.yMMM().format(DateTime(2020, 2, 17));
  DateTime _targetDateTime = DateTime(2020, 2, 17);
//  List<DateTime> _markedDate = [DateTime(2018, 9, 20), DateTime(2018, 10, 11)];
  static Widget _eventIcon =  Container(
    decoration:  BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(1000)),
        border: Border.all(color: Colors.blue, width: 2.0)),
    child:  Icon(
      Icons.person,
      color: Colors.amber,
    ),
  );

  EventList<Event> _markedDateMap = EventList<Event>();
  CalendarCarousel _calendarCarousel, _calendarCarouselNoHeader;

  @override
  void initState() {
   addMarker(DateTime(2020, 2, 03));
    super.initState();
  }

  addMarker(DateTime startEventDateTime) {

    var eventDateTime = startEventDateTime;

    for(int i=0; i<5; i++) {
      if(eventDateTime.day == 1) {
        eventDateTime = eventDateTime.add(Duration(days: (4)));
      } else {
        eventDateTime = eventDateTime.add(Duration(days: (5)));
      }
      print(eventDateTime.toLocal());
      _markedDateMap.add(
          eventDateTime,
          Event(
            date: eventDateTime,
            title: 'Event $i',
            icon: _eventIcon,
          ));

    }
  }

  @override
  Widget build(BuildContext context) {
    /// Example with custom icon
    _calendarCarousel = CalendarCarousel<Event>(
      onDayPressed: (DateTime date, List<Event> events) {
        this.setState(() => _currentDate = date);
        events.forEach((event) => print(event.title));
      },
      weekendTextStyle: TextStyle(
        color: Colors.red,
      ),
      thisMonthDayBorderColor: Colors.grey,
//          weekDays: null, /// for pass null when you do not want to render weekDays
      headerText: 'Custom Header',
//          markedDates: _markedDate,
      weekFormat: true,
      markedDatesMap: _markedDateMap,
      height: 200.0,
      selectedDateTime: _currentDate2,
      showIconBehindDayText: true,
//          daysHaveCircularBorder: false, /// null for not rendering any border, true for circular border, false for rectangular border
      customGridViewPhysics: NeverScrollableScrollPhysics(),
      markedDateShowIcon: true,
      markedDateIconMaxShown: 2,
      selectedDayTextStyle: TextStyle(
        color: Colors.yellow,
      ),
      todayTextStyle: TextStyle(
        color: Colors.blue,
      ),
      markedDateIconBuilder: (event) {
        return event.icon;
      },
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      todayButtonColor: Colors.transparent,
      todayBorderColor: Colors.green,
      markedDateMoreShowTotal:
      false, // null for not showing hidden events indicator
//          markedDateIconMargin: 9,
//          markedDateIconOffset: 3,
    );

    /// Example Calendar Carousel without header and custom prev & next button
    _calendarCarouselNoHeader = CalendarCarousel<Event>(
      todayBorderColor: Colors.green,
      onDayPressed: (DateTime date, List<Event> events) {
        this.setState(() => _currentDate2 = date);
        events.forEach((event) => print(event.title));
      },
      daysHaveCircularBorder: true,
      showOnlyCurrentMonthDate: false,
      weekendTextStyle: TextStyle(
        color: Colors.red,
      ),
      thisMonthDayBorderColor: Colors.grey,
      weekFormat: false,
//      firstDayOfWeek: 4,
      markedDatesMap: _markedDateMap,
      height: 420.0,
      selectedDateTime: _currentDate2,
      targetDateTime: _targetDateTime,
      customGridViewPhysics: NeverScrollableScrollPhysics(),
      markedDateCustomShapeBorder: CircleBorder(
          side: BorderSide(color: Colors.yellow)
      ),
      markedDateCustomTextStyle: TextStyle(
        fontSize: 18,
        color: Colors.blue,
      ),
      showHeader: false,
      // markedDateIconBuilder: (event) {
      //   return Container(
      //     color: Colors.blue,
      //   );
      // },
      todayTextStyle: TextStyle(
        color: Colors.blue,
      ),
      todayButtonColor: Colors.yellow,
      selectedDayTextStyle: TextStyle(
        color: Colors.yellow,
      ),
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      prevDaysTextStyle: TextStyle(
        fontSize: 16,
        color: Colors.pinkAccent,
      ),
      inactiveDaysTextStyle: TextStyle(
        color: Colors.tealAccent,
        fontSize: 16,
      ),
      onCalendarChanged: (DateTime date) {
        this.setState(() {
          _targetDateTime = date;
          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
        });
      },
      onDayLongPressed: (DateTime date) {
        print('long pressed date $date');
      },
    );

    return  Scaffold(
        appBar:  AppBar(
          title:  Text(widget.title),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              //custom icon
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.0),
                child: _calendarCarousel,
              ), // This trailing comma makes auto-formatting nicer for build methods.
              //custom icon without header
              Container(
                margin: EdgeInsets.only(
                  top: 30.0,
                  bottom: 16.0,
                  left: 16.0,
                  right: 16.0,
                ),
                child:  Row(
                  children: <Widget>[
                    Expanded(
                        child: Text(
                          _currentMonth,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 24.0,
                          ),
                        )),
                    FlatButton(
                      child: Text('PREV'),
                      onPressed: () {
                        setState(() {
                          _targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month -1);
                          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
                        });
                      },
                    ),
                    FlatButton(
                      child: Text('NEXT'),
                      onPressed: () {
                        setState(() {
                          _targetDateTime = DateTime(_targetDateTime.year, _targetDateTime.month +1);
                          _currentMonth = DateFormat.yMMM().format(_targetDateTime);
                        });
                      },
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.0),
                child: _calendarCarouselNoHeader,
              ), //
            ],
          ),
        ));
  }
}


问:
How to wire/connect multiple sensors to Arduino
I would like to connect two sensors to Arduino Mega, but I don't how to connect the pins.
My two sensors have 0-5V Signals, each with a positive and minus cable.
Should I connect the positive cable to each A-X pin of arduino (e.g. A0 and A1) and connect both negative cables to the same Arduino GND pin?

Would this way mix analoge and digital GND? I read that both should be kept separated. How to achieve this.

UPDATE:

Sensor Specification:
http://www.optris.com/optris-ctlaser-3m

Outputs / analog:  0-5/10 V

Output impedances: mV min. 100 kΩ load impedance

Power supply: 8-36 V DC
Current draw: max. 160 mA

答: you can use common ground line for all the sensors which saves your ground pins</p>

ContentLicense: CC BY-SA 3.0


问:
Get current dispatch queue?
I have a method which should support being called from any queue, and should expect to.

It runs some code in a background thread itself, and then uses dispatch_get_main_queue when it returns a value to its block argument.

I don't want it to force it onto the main queue if it wasn't when it entered the method. Is there a way to get a pointer to the current dispatch queue?

答:
Based on Oleg Barinov answer

Details

Swift 5.1, Xcode 11.3.1

Solution

```<code>import Foundation

// MARK: private functionality

extension DispatchQueue {

    private struct QueueReference { weak var queue: DispatchQueue? }

    private static let key: DispatchSpecificKey<QueueReference> = {
        let key = DispatchSpecificKey<QueueReference>()
        setupSystemQueuesDetection(key: key)
        return key
    }()

    private static func _registerDetection(of queues: [DispatchQueue], key: DispatchSpecificKey<QueueReference>) {
        queues.forEach { $0.setSpecific(key: key, value: QueueReference(queue: $0)) }
    }

    private static func setupSystemQueuesDetection(key: DispatchSpecificKey<QueueReference>) {
        let queues: [DispatchQueue] = [
                                        .main,
                                        .global(qos: .background),
                                        .global(qos: .default),
                                        .global(qos: .unspecified),
                                        .global(qos: .userInitiated),
                                        .global(qos: .userInteractive),
                                        .global(qos: .utility)
                                    ]
        _registerDetection(of: queues, key: key)
    }
}

// MARK: public functionality

extension DispatchQueue {
    static func registerDetection(of queue: DispatchQueue) {
        _registerDetection(of: [queue], key: key)
    }

    static var currentQueueLabel: String? { current?.label }
    static var current: DispatchQueue? { getSpecific(key: key)?.queue }
}
</code>```

Usage

Detect system queue

```<code>DispatchQueue.currentQueueLabel
DispatchQueue.current
DispatchQueue.global(qos: .default) == DispatchQueue.current
DispatchQueue.main === DispatchQueue.current
</code>```

Detect custom queue

```<code>let queue = DispatchQueue(label: "queue-sample")
DispatchQueue.registerDetection(of: queue)
if DispatchQueue.current == queue { ... }
</code>```

Sample

```<code>func subTest(queue: DispatchQueue) {
    queue.async {
        print("--------------------------------------------------------")
        print("queue label: \(DispatchQueue.currentQueueLabel ?? "nil")")
        print("print DispatchQueue.current: \(String(describing: DispatchQueue.current))")
        print("print queue == DispatchQueue.current: \(queue == DispatchQueue.current)")
        print("print queue === DispatchQueue.current: \(queue === DispatchQueue.current)")
        print("DispatchQueue.main == DispatchQueue.current: \(DispatchQueue.main == DispatchQueue.current)\n")
    }
}

func test() {
    subTest(queue: DispatchQueue.main)
    sleep(1)
    subTest(queue: DispatchQueue.global(qos: .default))
    sleep(1)
    subTest(queue: DispatchQueue.global(qos: .utility))
    sleep(1)

    let queue = DispatchQueue(label: "queue-sample")
    DispatchQueue.registerDetection(of: queue)
    subTest(queue: queue)
    sleep(1)
}

test()
DispatchQueue.global(qos: .default).async {
    test()
}
</code>```

Sample Output

```<code>--------------------------------------------------------
queue label: com.apple.root.default-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.default-qos[0x7fff89eb47c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: com.apple.root.utility-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.utility-qos[0x7fff89eb46c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: queue-sample
print DispatchQueue.current: Optional(<OS_dispatch_queue_serial: queue-sample[0x600000275780] = { xref = 7, ref = 3, sref = 2, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x0060002500000b01, enqueued, max qos 5, draining on 0xb03, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: com.apple.main-thread
print DispatchQueue.current: Optional(<OS_dispatch_queue_main: com.apple.main-thread[0x7fff89eb43c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x001ffe9000000300, dirty, in-flight = 0, thread = 0x303 }>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: true

--------------------------------------------------------
queue label: com.apple.main-thread
print DispatchQueue.current: Optional(<OS_dispatch_queue_main: com.apple.main-thread[0x7fff89eb43c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x001ffe9000000300, dirty, in-flight = 0, thread = 0x303 }>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: true

--------------------------------------------------------
queue label: com.apple.root.default-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.default-qos[0x7fff89eb47c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: com.apple.root.utility-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.utility-qos[0x7fff89eb46c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: queue-sample
print DispatchQueue.current: Optional(<OS_dispatch_queue_serial: queue-sample[0x60000027a280] = { xref = 7, ref = 3, sref = 2, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x0060002500000b01, enqueued, max qos 5, draining on 0xb03, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false
</code>```

Title: Get current dispatch queue?

Body:
Based on Oleg Barinov answer

Details

Swift 5.1, Xcode 11.3.1

Solution

import Foundation

// MARK: private functionality

extension DispatchQueue {

    private struct QueueReference { weak var queue: DispatchQueue? }

    private static let key: DispatchSpecificKey<QueueReference> = {
        let key = DispatchSpecificKey<QueueReference>()
        setupSystemQueuesDetection(key: key)
        return key
    }()

    private static func _registerDetection(of queues: [DispatchQueue], key: DispatchSpecificKey<QueueReference>) {
        queues.forEach { $0.setSpecific(key: key, value: QueueReference(queue: $0)) }
    }

    private static func setupSystemQueuesDetection(key: DispatchSpecificKey<QueueReference>) {
        let queues: [DispatchQueue] = [
                                        .main,
                                        .global(qos: .background),
                                        .global(qos: .default),
                                        .global(qos: .unspecified),
                                        .global(qos: .userInitiated),
                                        .global(qos: .userInteractive),
                                        .global(qos: .utility)
                                    ]
        _registerDetection(of: queues, key: key)
    }
}

// MARK: public functionality

extension DispatchQueue {
    static func registerDetection(of queue: DispatchQueue) {
        _registerDetection(of: [queue], key: key)
    }

    static var currentQueueLabel: String? { current?.label }
    static var current: DispatchQueue? { getSpecific(key: key)?.queue }
}

Usage

Detect system queue

DispatchQueue.currentQueueLabel
DispatchQueue.current
DispatchQueue.global(qos: .default) == DispatchQueue.current
DispatchQueue.main === DispatchQueue.current

Detect custom queue

let queue = DispatchQueue(label: "queue-sample")
DispatchQueue.registerDetection(of: queue)
if DispatchQueue.current == queue { ... }

Sample

func subTest(queue: DispatchQueue) {
    queue.async {
        print("--------------------------------------------------------")
        print("queue label: \(DispatchQueue.currentQueueLabel ?? "nil")")
        print("print DispatchQueue.current: \(String(describing: DispatchQueue.current))")
        print("print queue == DispatchQueue.current: \(queue == DispatchQueue.current)")
        print("print queue === DispatchQueue.current: \(queue === DispatchQueue.current)")
        print("DispatchQueue.main == DispatchQueue.current: \(DispatchQueue.main == DispatchQueue.current)\n")
    }
}

func test() {
    subTest(queue: DispatchQueue.main)
    sleep(1)
    subTest(queue: DispatchQueue.global(qos: .default))
    sleep(1)
    subTest(queue: DispatchQueue.global(qos: .utility))
    sleep(1)

    let queue = DispatchQueue(label: "queue-sample")
    DispatchQueue.registerDetection(of: queue)
    subTest(queue: queue)
    sleep(1)
}

test()
DispatchQueue.global(qos: .default).async {
    test()
}

Sample Output

--------------------------------------------------------
queue label: com.apple.root.default-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.default-qos[0x7fff89eb47c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: com.apple.root.utility-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.utility-qos[0x7fff89eb46c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: queue-sample
print DispatchQueue.current: Optional(<OS_dispatch_queue_serial: queue-sample[0x600000275780] = { xref = 7, ref = 3, sref = 2, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x0060002500000b01, enqueued, max qos 5, draining on 0xb03, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: com.apple.main-thread
print DispatchQueue.current: Optional(<OS_dispatch_queue_main: com.apple.main-thread[0x7fff89eb43c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x001ffe9000000300, dirty, in-flight = 0, thread = 0x303 }>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: true

--------------------------------------------------------
queue label: com.apple.main-thread
print DispatchQueue.current: Optional(<OS_dispatch_queue_main: com.apple.main-thread[0x7fff89eb43c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x001ffe9000000300, dirty, in-flight = 0, thread = 0x303 }>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: true

--------------------------------------------------------
queue label: com.apple.root.default-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.default-qos[0x7fff89eb47c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: com.apple.root.utility-qos
print DispatchQueue.current: Optional(<OS_dispatch_queue_global: com.apple.root.utility-qos[0x7fff89eb46c0] = { xref = -2147483648, ref = -2147483648, sref = 1, target = [0x0], width = 0xfff, state = 0x0060000000000000, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false

--------------------------------------------------------
queue label: queue-sample
print DispatchQueue.current: Optional(<OS_dispatch_queue_serial: queue-sample[0x60000027a280] = { xref = 7, ref = 3, sref = 2, target = com.apple.root.default-qos.overcommit[0x7fff89eb4840], width = 0x1, state = 0x0060002500000b01, enqueued, max qos 5, draining on 0xb03, in-barrier}>)
print queue == DispatchQueue.current: true
print queue === DispatchQueue.current: true
DispatchQueue.main == DispatchQueue.current: false


问:
Java regex split on whitespace /not preceded
I would like to split  a string:"x=   2-3   y=3 z=   this,   that"
I would split this up on one or more whitespaces, that are not preceded by a '=' or a ','
meaning group one: "x=   2-3"
              two: "y=3"
              three: "z=   this,   that"
I have an expression that kinda does it but its only good if = or , has only one whitespace after it.

```<code>(?<![,=])\\s+
</code>```

答:
This one splits on white space followed by some non-white space then =: "\\s+(?=[^=\\s]+=)":

```<code>jshell> "x=   2-3   y=3 z=   this,   that".split("\\s+(?=[^=\\s]+=)")
$10 ==> String[3] { "x=   2-3", "y=3", "z=   this,   that" }
</code>```

Body:
I would like to split  a string:"x=   2-3   y=3 z=   this,   that"
I would split this up on one or more whitespaces, that are not preceded by a '=' or a ','
meaning group one: "x=   2-3"
              two: "y=3"
              three: "z=   this,   that"
I have an expression that kinda does it but its only good if = or , has only one whitespace after it.

(?<![,=])\\s+

Body:
This one splits on white space followed by some non-white space then =: "\\s+(?=[^=\\s]+=)":

jshell> "x=   2-3   y=3 z=   this,   that".split("\\s+(?=[^=\\s]+=)")
$10 ==> String[3] { "x=   2-3", "y=3", "z=   this,   that" }


问:
Can't install Rasa on Ubuntu 18.04 + Python 3.7.5?
I have succeed to install Rasa NLU on my Win 10 with python 3.7 but couldn't do this on Ubuntu 18.04.
Please help.

Here is the error I get:

```<code>pip3 install rasa-x --extra-index-url https://pypi.rasa.com/simple
</code>```

Could not find a version that satisfies the requirement
  tensorflow~=1.15.0 (from rasa~=1.5.1->rasa-x) (from versions:
  1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 2.0.0a0, 2.0.0b0, 2.0.0b1) No matching distribution found for tensorflow~=1.15.0 (from rasa~=1.5.1->rasa-x)

Please advise what is the difference to my Win10 machine?
Please advise how can I install it.

答:
I had followed these following steps and it's working fine for me for ubuntu 18.04 + Python3

Firstly create directory name of your choice and get inside of it

```<code>mkdir rasaprojects #directory name of your choice in place of rasaprojects

cd rasaprojects   #get inside that directory
</code>```

Now create virtual environment of python3

```<code>virtualenv rasaenv -p python3 #write your environment name instead of rasaenv
</code>```

Now activate the environment

```<code>source rasaenv/bin/activate
</code>```

Now you are good to go with rasa installation

```<code>pip3 install rasa
</code>```

Body:
I have succeed to install Rasa NLU on my Win 10 with python 3.7 but couldn't do this on Ubuntu 18.04.
Please help.

Here is the error I get:

pip3 install rasa-x --extra-index-url https://pypi.rasa.com/simple

Could not find a version that satisfies the requirement
  tensorflow~=1.15.0 (from rasa~=1.5.1->rasa-x) (from versions:
  1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 2.0.0a0, 2.0.0b0, 2.0.0b1) No matching distribution found for tensorflow~=1.15.0 (from rasa~=1.5.1->rasa-x)

Please advise what is the difference to my Win10 machine?
Please advise how can I install it.

Body:
I had followed these following steps and it's working fine for me for ubuntu 18.04 + Python3

Firstly create directory name of your choice and get inside of it

mkdir rasaprojects #directory name of your choice in place of rasaprojects

cd rasaprojects   #get inside that directory

Now create virtual environment of python3

virtualenv rasaenv -p python3 #write your environment name instead of rasaenv

Now activate the environment

source rasaenv/bin/activate

Now you are good to go with rasa installation

pip3 install rasa


问:
Get the first element from the file path
I have the vector in a data frame

```<code>c("E:\\\\My Network Places.old.dat", "E:\\\\pagefile.sys", "E:\\\\Press_Dly_Diff_G_91.rbc",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\Dantz", "E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000083.rdb",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000561.rdb"
)
</code>```

In the above the length of file paths vary from just 1 to 5.  I am trying to get each level of the file path into a column in the data frame.  I tried with the first part using the following:

```<code>library(stringr)
df1$PF <- strsplit(df1$File.Name, "\\\\"))
df1$PFolder <- df1$PF[[1]][3]
</code>```

But I am getting only the first My Network Places.old.dat for all the rows in the data frame.  How do I split the path into multiple columns based on \\ separator and save it into separate columns within the data frame.  The desired output looks like this:

```<code>File.Name         FilePath1         FilePath2       FilePath3
</code>```

The above character vector is in File.Name in the data frame.

答:
We can use cSplit from splitstackshape

```<code>splitstackshape::cSplit(df, "path", "\\\\+", fixed = FALSE)

#   path_1                    path_2     path_3              path_4                path_5       path_6
#1:     E: My Network Places.old.dat       <NA>                <NA>                  <NA>         <NA>
#2:     E:              pagefile.sys       <NA>                <NA>                  <NA>         <NA>
#3:     E:   Press_Dly_Diff_G_91.rbc       <NA>                <NA>                  <NA>         <NA>
#4:     E:       TV_Press_Dly_Diff_A Retrospect               Dantz                  <NA>         <NA>
#5:     E:       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000083.rdb
#6:     E:       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000561.rdb
</code>```

Or if you already know how many columns the data will be expanded we can also use separate.

```<code>tidyr::separate(df, path, into = paste0('path', 1:6), sep = "\\\\+", fill = 'right')
</code>```

data

```<code>df <- data.frame(path = x, stringsAsFactors = FALSE)
</code>```

Body:
I have the vector in a data frame

c("E:\\\\My Network Places.old.dat", "E:\\\\pagefile.sys", "E:\\\\Press_Dly_Diff_G_91.rbc",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\Dantz", "E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000083.rdb",
"E:\\\\TV_Press_Dly_Diff_A\\Retrospect\\TV_Press_Dly_Diff_A\\1-TV_Press_Dly_Diff_A\\AA000561.rdb"
)

In the above the length of file paths vary from just 1 to 5.  I am trying to get each level of the file path into a column in the data frame.  I tried with the first part using the following:

library(stringr)
df1$PF <- strsplit(df1$File.Name, "\\\\"))
df1$PFolder <- df1$PF[[1]][3]

But I am getting only the first My Network Places.old.dat for all the rows in the data frame.  How do I split the path into multiple columns based on \\ separator and save it into separate columns within the data frame.  The desired output looks like this:

File.Name         FilePath1         FilePath2       FilePath3

The above character vector is in File.Name in the data frame.

Body:
We can use cSplit from splitstackshape

splitstackshape::cSplit(df, "path", "\\\\+", fixed = FALSE)

#   path_1                    path_2     path_3              path_4                path_5       path_6
#1:     E: My Network Places.old.dat       <NA>                <NA>                  <NA>         <NA>
#2:     E:              pagefile.sys       <NA>                <NA>                  <NA>         <NA>
#3:     E:   Press_Dly_Diff_G_91.rbc       <NA>                <NA>                  <NA>         <NA>
#4:     E:       TV_Press_Dly_Diff_A Retrospect               Dantz                  <NA>         <NA>
#5:     E:       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000083.rdb
#6:     E:       TV_Press_Dly_Diff_A Retrospect TV_Press_Dly_Diff_A 1-TV_Press_Dly_Diff_A AA000561.rdb

Or if you already know how many columns the data will be expanded we can also use separate.

tidyr::separate(df, path, into = paste0('path', 1:6), sep = "\\\\+", fill = 'right')

data

df <- data.frame(path = x, stringsAsFactors = FALSE)


问:
Azure cosmos db bulk import
Is bulk import available for Azure cosmos db(Mongo db API)?
I want to import large dataset set which is available in a json file to Azure cosmos for Mongo DB.
I tried importing using mongoimport and Java mongo APIs but it took a long time and timed out in the end.

Any suggestions on how to import it directly from my file to cosmos db?

PS: https://learn.microsoft.com/en-us/azure/cosmos-db/bulk-executor-java --- says bulk executor is not available for cosmos's mongo db yet.

答:
Bulk executor library is not available for cosmos db Mongo Api:

Cosmos db migration tool is not available for cosmos db Mongo Api as well:

As workaround,please get an idea of Azure Data Factory Copy Activity which supports transfer data from a file into cosmos db Mongo api sink. The source file could be from Azure Blob Storage or File System on-premise even.

Title: Azure cosmos db bulk import