问:
Access to merged cells using Ruby-Roo
According to example below: Value is stored only in A1, other cells return nil.
How is possible to get the A1'a value from the others merged cells, or simply check range of the A1 cell?

答:
here is my take, if all merged fields are same as prev - then non-merged fields should become array</p>

```<code>  xlsx = Roo::Excelx.new(__dir__ + "/output.xlsx", { expand_merged_ranges: true })

  parsed = xlsx.sheet(0).parse(headers: true).drop(1)

  parsed_merged = []
    .tap do |parsed_merged|
      parsed.each do |x|
        if parsed_merged.empty?
          parsed_merged << {
            "field_non_merged1" => x["field_non_merged1"],
            "field_merged1"     => [x["field_merged1"]],
            "field_merged2"     => [x["field_merged2"]],
            "field_merged3"     => [x["field_merged3"]],
            "field_merged4"     => [x["field_merged4"]],
            "field_non_merged2" => x["field_non_merged2"],
            "field_non_merged3" => x["field_non_merged3"],
          }
        else
          field_merged1_is_same_as_prev = x["field_non_merged1"] == parsed_merged.last["field_non_merged1"]
          field_merged2_is_same_as_prev = x["field_non_merged2"] == parsed_merged.last["field_non_merged2"]
          field_merged3_is_same_as_prev = x["field_non_merged3"] == parsed_merged.last["field_non_merged3"]

          merged_rows_are_all_same_as_prev = field_non_merged1_is_same_as_prev && field_merged2_is_same_as_prev && field_merged3_is_same_as_prev

          if merged_rows_are_all_same_as_prev
            parsed_merged.last["field_merged1"].push x["field_merged1"]
            parsed_merged.last["field_merged2"].push x["field_merged2"]
            parsed_merged.last["field_merged3"].push x["field_merged3"]
            parsed_merged.last["field_merged4"].push x["field_merged4"]
          else
            parsed_merged << {
              "field_non_merged1" => x["field_non_merged1"],
              "field_merged1"     => [x["field_merged1"]],
              "field_merged2"     => [x["field_merged2"]],
              "field_merged3"     => [x["field_merged3"]],
              "field_merged4"     => [x["field_merged4"]],
              "field_non_merged2" => x["field_non_merged2"],
              "field_non_merged3" => x["field_non_merged3"],
            }
          end
        end
      end
    end
    .map do |x|
      {
        "field_non_merged1" => x["field_non_merged1"],
        "field_merged1"     => x["field_merged1"].compact.uniq,
        "field_merged2"     => x["field_merged2"].compact.uniq,
        "field_merged3"     => x["field_merged3"].compact.uniq,
        "field_merged4"     => x["field_merged4"].compact.uniq,
        "field_non_merged2" => x["field_non_merged2"],
        "field_non_merged3" => x["field_non_merged3"],
      }
    end
</code>```

Title: Access to merged cells using Ruby-Roo

Body:
here is my take, if all merged fields are same as prev - then non-merged fields should become array

  xlsx = Roo::Excelx.new(__dir__ + "/output.xlsx", { expand_merged_ranges: true })

  parsed = xlsx.sheet(0).parse(headers: true).drop(1)

  parsed_merged = []
    .tap do |parsed_merged|
      parsed.each do |x|
        if parsed_merged.empty?
          parsed_merged << {
            "field_non_merged1" => x["field_non_merged1"],
            "field_merged1"     => [x["field_merged1"]],
            "field_merged2"     => [x["field_merged2"]],
            "field_merged3"     => [x["field_merged3"]],
            "field_merged4"     => [x["field_merged4"]],
            "field_non_merged2" => x["field_non_merged2"],
            "field_non_merged3" => x["field_non_merged3"],
          }
        else
          field_merged1_is_same_as_prev = x["field_non_merged1"] == parsed_merged.last["field_non_merged1"]
          field_merged2_is_same_as_prev = x["field_non_merged2"] == parsed_merged.last["field_non_merged2"]
          field_merged3_is_same_as_prev = x["field_non_merged3"] == parsed_merged.last["field_non_merged3"]

          merged_rows_are_all_same_as_prev = field_non_merged1_is_same_as_prev && field_merged2_is_same_as_prev && field_merged3_is_same_as_prev

          if merged_rows_are_all_same_as_prev
            parsed_merged.last["field_merged1"].push x["field_merged1"]
            parsed_merged.last["field_merged2"].push x["field_merged2"]
            parsed_merged.last["field_merged3"].push x["field_merged3"]
            parsed_merged.last["field_merged4"].push x["field_merged4"]
          else
            parsed_merged << {
              "field_non_merged1" => x["field_non_merged1"],
              "field_merged1"     => [x["field_merged1"]],
              "field_merged2"     => [x["field_merged2"]],
              "field_merged3"     => [x["field_merged3"]],
              "field_merged4"     => [x["field_merged4"]],
              "field_non_merged2" => x["field_non_merged2"],
              "field_non_merged3" => x["field_non_merged3"],
            }
          end
        end
      end
    end
    .map do |x|
      {
        "field_non_merged1" => x["field_non_merged1"],
        "field_merged1"     => x["field_merged1"].compact.uniq,
        "field_merged2"     => x["field_merged2"].compact.uniq,
        "field_merged3"     => x["field_merged3"].compact.uniq,
        "field_merged4"     => x["field_merged4"].compact.uniq,
        "field_non_merged2" => x["field_non_merged2"],
        "field_non_merged3" => x["field_non_merged3"],
      }
    end


来源: stackexchange

问:
React JS: Populating a rsuite dropdown from a json object
I'm have this component using the rsuite ui  dropdown component  here is the Component Docs that should populate its elements from the json held in the component state but i keep getting this error any time i try clicking on either of the drop downs.

ERROR:
  VM7492:37 Warning: React DevTools encountered an error: TypeError: Converting circular structure to JSON
      --> starting at object with constructor 'Object'
      |     property '_context' -> object with constructor 'Object'
      --- property 'Provider' closes the circle

the code:

```<code>import React from 'react';
import {SelectPicker } from 'rsuite';

class TimeSelector extends React.Component {
  constructor() {
    super();
    this.state = {
      start_time: [
             {"start_hour":"12:00 AM","start_id":"am-0"},
             {"start_hour":"01:00 AM","start_id":"am-1"},
             {"start_hour":"02:00 AM","start_id":"am-2"},
             {"start_hour":"03:00 AM","start_id":"am-3"},
             {"start_hour":"04:00 AM","start_id":"am-4"},
             {"start_hour":"05:00 AM","start_id":"am-5"},
             {"start_hour":"06:00 AM","start_id":"am-6"},
             {"start_hour":"07:00 AM","start_id":"am-7"},
             {"start_hour":"08:00 AM","start_id":"am-8"},
             {"start_hour":"09:00 AM","start_id":"am-9"},
             {"start_hour":"10:00 AM","start_id":"am-10"},
             {"start_hour":"11:00 AM","start_id":"am-11"},
             {"start_hour":"12:00 PM","start_id":"pm-0"},
             {"start_hour":"1:00 PM","start_id":"pm-1"},
             {"start_hour":"2:00 PM","start_id":"pm-2"},
             {"start_hour":"3:00 PM","start_id":"pm-3"},
             {"start_hour":"4:00 PM","start_id":"pm-4"},
             {"start_hour":"5:00 PM","start_id":"pm-5"},
             {"start_hour":"6:00 PM","start_id":"pm-6"},
             {"start_hour":"7:00 PM","start_id":"pm-7"},
             {"start_hour":"8:00 PM","start_id":"pm-8"},
             {"start_hour":"9:00 PM","start_id":"pm-9"},
             {"start_hour":"10:00 PM","start_id":"pm-10"},
             {"start_hour":"11:00 PM","start_id":"pm-11"},
             {"start_hour":"12:00 PM","start_id":"pm-12"}
      ],
      end_time:[
              {"end_hour":"12:00 AM","end_id":"am-0"},
              {"end_hour":"01:00 AM","end_id":"am-2"},
              {"end_hour":"02:00 AM","end_id":"am-3"},
              {"end_hour":"03:00 AM","end_id":"am-4"},
              {"end_hour":"04:00 AM","end_id":"am-5"},
              {"end_hour":"05:00 AM","end_id":"am-5"},
              {"end_hour":"06:00 AM","end_id":"am-6"},
              {"end_hour":"07:00 AM","end_id":"am-7"},
              {"end_hour":"08:00 AM","end_id":"am-8"},
              {"end_hour":"09:00 AM","end_id":"am-9"},
              {"end_hour":"10:00 AM","end_id":"am-10"},
              {"end_hour":"11:00 AM","end_id":"am-11"},
              {"end_hour":"12:00 PM","end_id":"pm-0"},
              {"end_hour":"1:00 PM","end_id":"pm-1"},
              {"end_hour":"2:00 PM","end_id":"pm-2"},
              {"end_hour":"3:00 PM","end_id":"pm-3"},
              {"end_hour":"4:00 PM","end_id":"pm-4"},
              {"end_hour":"5:00 PM","end_id":"pm-5"},
              {"end_hour":"6:00 PM","end_id":"pm-6"},
              {"end_hour":"7:00 PM","end_id":"pm-7"},
              {"end_hour":"8:00 PM","end_id":"pm-8"},
              {"end_hour":"9:00 PM","end_id":"pm-9"},
              {"end_hour":"10:00 PM","end_id":"pm-10"},
              {"end_hour":"11:00 PM","end_id":"pm-11"},
              {"end_hour":"12:00 PM","end_id":"pm-12"}
      ],
      selectedStartTime:'',
      selectedEndTime:'',
    };

  }

  render() {

    return (
        <div>
            Start Time:
            <SelectPicker
                toggleComponentClass={Button}
                size="md"
                placeholder="12:00 AM"
                data={this.state.start_time}
                labelKey="start_hour"
                valueKey="start_id"
            />
            End Time:
            <SelectPicker
                toggleComponentClass={Button}
                size="md"
                placeholder={this.state.end_time[0].end_hour}
                data={this.state.end_time}
                labelKey="end_hour"
                valueKey="end_id"
            />
        </div>
    );
  }

  componentDidMount() {

  }

}

export default TimeSelector;
</code>```

i have checked the json object seems fine.

答:
That's because you are not passing the data right way. It should be DataItemType array which contains:

```<code>type DataItemType = {
  value: string; // property value is the value of valueKey
  label: React.Node; // property value is the vaue of labelKey
  children?: Array<DataItemType>; // property value is the value of childrenKey
  groupBy?: string;
};
</code>```

You can try passing this:

```<code>data = [
   {label:"12:00 AM", value:"am-0"},
   {label:"01:00 AM", value:"am-1"},
   {label:"02:00 AM", value:"am-2"},
]
</code>```

Hope this work's for you.

ContentLicense: CC BY-SA 4.0

Body:
I'm have this component using the rsuite ui  dropdown component  here is the Component Docs that should populate its elements from the json held in the component state but i keep getting this error any time i try clicking on either of the drop downs.

ERROR:
  VM7492:37 Warning: React DevTools encountered an error: TypeError: Converting circular structure to JSON
      --> starting at object with constructor 'Object'
      |     property '_context' -> object with constructor 'Object'
      --- property 'Provider' closes the circle

the code:

import React from 'react';
import {SelectPicker } from 'rsuite';

class TimeSelector extends React.Component {
  constructor() {
    super();
    this.state = {
      start_time: [
             {"start_hour":"12:00 AM","start_id":"am-0"},
             {"start_hour":"01:00 AM","start_id":"am-1"},
             {"start_hour":"02:00 AM","start_id":"am-2"},
             {"start_hour":"03:00 AM","start_id":"am-3"},
             {"start_hour":"04:00 AM","start_id":"am-4"},
             {"start_hour":"05:00 AM","start_id":"am-5"},
             {"start_hour":"06:00 AM","start_id":"am-6"},
             {"start_hour":"07:00 AM","start_id":"am-7"},
             {"start_hour":"08:00 AM","start_id":"am-8"},
             {"start_hour":"09:00 AM","start_id":"am-9"},
             {"start_hour":"10:00 AM","start_id":"am-10"},
             {"start_hour":"11:00 AM","start_id":"am-11"},
             {"start_hour":"12:00 PM","start_id":"pm-0"},
             {"start_hour":"1:00 PM","start_id":"pm-1"},
             {"start_hour":"2:00 PM","start_id":"pm-2"},
             {"start_hour":"3:00 PM","start_id":"pm-3"},
             {"start_hour":"4:00 PM","start_id":"pm-4"},
             {"start_hour":"5:00 PM","start_id":"pm-5"},
             {"start_hour":"6:00 PM","start_id":"pm-6"},
             {"start_hour":"7:00 PM","start_id":"pm-7"},
             {"start_hour":"8:00 PM","start_id":"pm-8"},
             {"start_hour":"9:00 PM","start_id":"pm-9"},
             {"start_hour":"10:00 PM","start_id":"pm-10"},
             {"start_hour":"11:00 PM","start_id":"pm-11"},
             {"start_hour":"12:00 PM","start_id":"pm-12"}
      ],
      end_time:[
              {"end_hour":"12:00 AM","end_id":"am-0"},
              {"end_hour":"01:00 AM","end_id":"am-2"},
              {"end_hour":"02:00 AM","end_id":"am-3"},
              {"end_hour":"03:00 AM","end_id":"am-4"},
              {"end_hour":"04:00 AM","end_id":"am-5"},
              {"end_hour":"05:00 AM","end_id":"am-5"},
              {"end_hour":"06:00 AM","end_id":"am-6"},
              {"end_hour":"07:00 AM","end_id":"am-7"},
              {"end_hour":"08:00 AM","end_id":"am-8"},
              {"end_hour":"09:00 AM","end_id":"am-9"},
              {"end_hour":"10:00 AM","end_id":"am-10"},
              {"end_hour":"11:00 AM","end_id":"am-11"},
              {"end_hour":"12:00 PM","end_id":"pm-0"},
              {"end_hour":"1:00 PM","end_id":"pm-1"},
              {"end_hour":"2:00 PM","end_id":"pm-2"},
              {"end_hour":"3:00 PM","end_id":"pm-3"},
              {"end_hour":"4:00 PM","end_id":"pm-4"},
              {"end_hour":"5:00 PM","end_id":"pm-5"},
              {"end_hour":"6:00 PM","end_id":"pm-6"},
              {"end_hour":"7:00 PM","end_id":"pm-7"},
              {"end_hour":"8:00 PM","end_id":"pm-8"},
              {"end_hour":"9:00 PM","end_id":"pm-9"},
              {"end_hour":"10:00 PM","end_id":"pm-10"},
              {"end_hour":"11:00 PM","end_id":"pm-11"},
              {"end_hour":"12:00 PM","end_id":"pm-12"}
      ],
      selectedStartTime:'',
      selectedEndTime:'',
    };

  }

  render() {

    return (

            Start Time:
            <SelectPicker
                toggleComponentClass={Button}
                size="md"
                placeholder="12:00 AM"
                data={this.state.start_time}
                labelKey="start_hour"
                valueKey="start_id"
            />
            End Time:
            <SelectPicker
                toggleComponentClass={Button}
                size="md"
                placeholder={this.state.end_time[0].end_hour}
                data={this.state.end_time}
                labelKey="end_hour"
                valueKey="end_id"
            />

    );
  }

  componentDidMount() {

  }

}

export default TimeSelector;

i have checked the json object seems fine.

Body:
That's because you are not passing the data right way. It should be DataItemType array which contains:

type DataItemType = {
  value: string; // property value is the value of valueKey
  label: React.Node; // property value is the vaue of labelKey
  children?: Array<DataItemType>; // property value is the value of childrenKey
  groupBy?: string;
};

You can try passing this:

data = [
   {label:"12:00 AM", value:"am-0"},
   {label:"01:00 AM", value:"am-1"},
   {label:"02:00 AM", value:"am-2"},
]

Hope this work's for you.


问:
C# how to map two section of appsetting and take the unique settings into single class object
I have the following sections in my appsettings. I am using asp.net core webapi application.

```<code>  "security": {
    "instance": "https://login.microsoftonline.com/",
    "domain": "domain.com",
    "tenantId": "tenantid",
    "clientId": "sameclientid"
  },
  "powerBI": {
    "resourceUri": "resourceurl",
    "authorityUri": "authorityurl",
    "extraUrl": "https://api.powerbi.com/",
    "clientId": "sameclientid",
    "clientSecret": "secret"
  }
</code>```

i need to map to single class

```<code>  class MapperClass {
    public string Instance {get;set;}
    public string Domain {get;set;}
    public string TenantId {get;set;}
    public string ClientId {get;set;}
    public string ClientSecret {get;set;}
    public string ExtraUri {get;set;}
  }
</code>```

Is there a way to merge or union the above two section and get it mapped to the final MapperClass?

Thanks

答:
You could just load both sections and merge it in one class on your own.</p>

```<code>var security = settings.GetSection("security") as CustomSection;
var powerBI= settings.GetSection("powerBI") as CustomSection;
MapperClass mapper = new MapperClass();
mapper.Instance = security.Instance;
</code>```

Body:
I have the following sections in my appsettings. I am using asp.net core webapi application.

  "security": {
    "instance": "https://login.microsoftonline.com/",
    "domain": "domain.com",
    "tenantId": "tenantid",
    "clientId": "sameclientid"
  },
  "powerBI": {
    "resourceUri": "resourceurl",
    "authorityUri": "authorityurl",
    "extraUrl": "https://api.powerbi.com/",
    "clientId": "sameclientid",
    "clientSecret": "secret"
  }

i need to map to single class

  class MapperClass {
    public string Instance {get;set;}
    public string Domain {get;set;}
    public string TenantId {get;set;}
    public string ClientId {get;set;}
    public string ClientSecret {get;set;}
    public string ExtraUri {get;set;}
  }

Is there a way to merge or union the above two section and get it mapped to the final MapperClass?

Thanks

Body:
You could just load both sections and merge it in one class on your own.

var security = settings.GetSection("security") as CustomSection;
var powerBI= settings.GetSection("powerBI") as CustomSection;
MapperClass mapper = new MapperClass();
mapper.Instance = security.Instance;


问:
How to set the default value inside a HTML Text box element using Angular Directive . Please refer the below code
Below code works fine for changing innerHTML of "div , heading tags" but not working for textboxes </p>

```<code>@Component({
  selector: 'app-root',
  template: ` <h3 appNamevalidation >Angular 7 Template-Driven Form Validation</h3>
  <input type = "text" [(ngModel)]="model.firstName" #firstName="ngModel" required appNamevalidation
  />`
})

@Directive({
  selector: '[appNamevalidation]'
})

export class NamevalidationDirective {
  constructor(private elem: ElementRef) { }

  ngOnInit() {
    console.log(' inside ngOninIt directive hook');
    this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
    this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
  }
}
</code>```

答:
The ngOnInit hook of your directive gets executed before the binding of your ngModel on your input. You could use another Lifecycle hook like ngAfterViewChecked to make it work:

```<code>export class NamevalidationDirective {
    constructor(private elem: ElementRef) { }

    ngAfterViewChecked() {
        this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
        this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
    }
}
</code>```

Body:
Below code works fine for changing innerHTML of "div , heading tags" but not working for textboxes

@Component({
  selector: 'app-root',
  template: `
Angular 7 Template-Driven Form Validation

  <input type = "text" [(ngModel)]="model.firstName" #firstName="ngModel" required appNamevalidation
  />`
})

@Directive({
  selector: '[appNamevalidation]'
})

export class NamevalidationDirective {
  constructor(private elem: ElementRef) { }

  ngOnInit() {
    console.log(' inside ngOninIt directive hook');
    this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
    this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
  }
}

Body:
The ngOnInit hook of your directive gets executed before the binding of your ngModel on your input. You could use another Lifecycle hook like ngAfterViewChecked to make it work:

export class NamevalidationDirective {
    constructor(private elem: ElementRef) { }

    ngAfterViewChecked() {
        this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
        this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
    }
}


问:
Define default values for function arguments
In the Lua wiki I found a way to define default values for missing arguments:

```<code>function myfunction(a,b,c)
    b = b or 7
    c = c or 5
    print (a,b,c)
end
</code>```

Is that the only way? The PHP style myfunction (a,b=7,c=5) does not seem to work. Not that the Lua way doesn't work, I am just wondering if this is the only way to do it.

答: In my opinion there isn't another way. That's just the Lua mentality: no frills, and except for some syntactic sugar, no redundant ways of doing simple things.</p>

ContentLicense: CC BY-SA 3.0

Body:
In the Lua wiki I found a way to define default values for missing arguments:

function myfunction(a,b,c)
    b = b or 7
    c = c or 5
    print (a,b,c)
end

Is that the only way? The PHP style myfunction (a,b=7,c=5) does not seem to work. Not that the Lua way doesn't work, I am just wondering if this is the only way to do it.


问:
java.io.IOException: unable to create directory: /storage/emulated/0/tokens
I'm trying to hook my Android application up to Google Calendars. I've followed the quick start tutorial, have asked the user for permission to write to external storage, yet I cannot get the code to run without throwing a java.io.IOException.

My code looks like this:

GoogleCalendarModule.kt

```<code>class GoogleCalendarModule {
    var APPLICATION_NAME: String = "Conglobo"
    var JSON_FACTORY: JacksonFactory = JacksonFactory.getDefaultInstance()
    var TOKENS_DIRECTORY_PATH: String = "./tokens"

    var SCOPES: List<String> = Collections.singletonList(CalendarScopes.CALENDAR_READONLY)
    private var CREDENTIALS_FILE_PATH: String = "/credentials.json"

    fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): com.google.api.client.auth.oauth2.Credential? {

        val inputStream: InputStream = this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")

        val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))

        val tokenFolder = File(getExternalStorageDirectory(), File.separator.toString() + TOKENS_DIRECTORY_PATH)
        if (!tokenFolder.exists()) {
            tokenFolder.mkdirs()
        }

        val flow: GoogleAuthorizationCodeFlow = GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(tokenFolder))
            .setAccessType("offline")
            .build();

        val receiver: LocalServerReceiver = LocalServerReceiver.Builder().setPort(8888).build()

        return AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
    }

    fun doSomething() {
        val HTTP_TRANSPORT = NetHttpTransport()
        val service: Calendar = Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build()

        val now = DateTime(System.currentTimeMillis())
        val events: Events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        val items: List<Event> = events.items
        if (items.isEmpty()) {
            println("No events")
        } else {
            println("Upcoming events")
            for(event: Event in items) {
                var start: DateTime = event.start.dateTime
                if(start == null) {
                    start = event.start.date
                }

                print(event.summary)
            }
        }
    }
}
</code>```

Then I check against current permissions in the MainActivity

MainActivity.kt

```<code>class MainActivity: AppCompatActivity(), ITeamFragmentDelegate {

    @Inject
    lateinit var teamInfoModule: TeamInfoModule;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
                print("Permission is granted");
            } else {

                print("Permission is revoked");
                ActivityCompat.requestPermissions(this, Array<String>(1) { Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        GoogleCalendarModule().doSomething()

        setContentView(R.layout.activity_main)
        DaggerServiceModuleComponent.create().inject(this)

        val teamArrayList: ArrayList<Team> = this.teamInfoModule.getAllTeamData()

        for(team: Team in teamArrayList) {
            val bundle = Bundle()
            val teamFragment = TeamFragment()

            bundle.putParcelable("teamData", team)
            teamFragment.arguments = bundle

            supportFragmentManager.beginTransaction()
                .add(R.id.root_container, teamFragment)
                .commitAllowingStateLoss()
        }
    }

    override fun onTeamClicked(fragment: TeamFragment, team: Team) {
        val intent = Intent(this, ViewTeamBacklogActivity::class.java)
        intent.putExtra("teamId", team.id)
        startActivity(intent)
    }
}
</code>```

And I even have the permissions declared in AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluelightlite">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ViewTeamBacklogActivity">

        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

I've searched around S.O and it appears to be a common problem but none of the solutions I've found have worked. Could someone please help?

答:
I don't know if it's useful, but you can try
set your targetSdkVersion Less than 23 ?</p>

Body:
I'm trying to hook my Android application up to Google Calendars. I've followed the quick start tutorial, have asked the user for permission to write to external storage, yet I cannot get the code to run without throwing a java.io.IOException.

My code looks like this:

GoogleCalendarModule.kt

class GoogleCalendarModule {
    var APPLICATION_NAME: String = "Conglobo"
    var JSON_FACTORY: JacksonFactory = JacksonFactory.getDefaultInstance()
    var TOKENS_DIRECTORY_PATH: String = "./tokens"

    var SCOPES: List<String> = Collections.singletonList(CalendarScopes.CALENDAR_READONLY)
    private var CREDENTIALS_FILE_PATH: String = "/credentials.json"

    fun getCredentials(HTTP_TRANSPORT: NetHttpTransport): com.google.api.client.auth.oauth2.Credential? {

        val inputStream: InputStream = this.javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
            ?: throw FileNotFoundException("Resource Not found: $CREDENTIALS_FILE_PATH")

        val clientSecrets: GoogleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))

        val tokenFolder = File(getExternalStorageDirectory(), File.separator.toString() + TOKENS_DIRECTORY_PATH)
        if (!tokenFolder.exists()) {
            tokenFolder.mkdirs()
        }

        val flow: GoogleAuthorizationCodeFlow = GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(tokenFolder))
            .setAccessType("offline")
            .build();

        val receiver: LocalServerReceiver = LocalServerReceiver.Builder().setPort(8888).build()

        return AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
    }

    fun doSomething() {
        val HTTP_TRANSPORT = NetHttpTransport()
        val service: Calendar = Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build()

        val now = DateTime(System.currentTimeMillis())
        val events: Events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute()

        val items: List<Event> = events.items
        if (items.isEmpty()) {
            println("No events")
        } else {
            println("Upcoming events")
            for(event: Event in items) {
                var start: DateTime = event.start.dateTime
                if(start == null) {
                    start = event.start.date
                }

                print(event.summary)
            }
        }
    }
}

Then I check against current permissions in the MainActivity

MainActivity.kt

class MainActivity: AppCompatActivity(), ITeamFragmentDelegate {

    @Inject
    lateinit var teamInfoModule: TeamInfoModule;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
                print("Permission is granted");
            } else {

                print("Permission is revoked");
                ActivityCompat.requestPermissions(this, Array<String>(1) { Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        GoogleCalendarModule().doSomething()

        setContentView(R.layout.activity_main)
        DaggerServiceModuleComponent.create().inject(this)

        val teamArrayList: ArrayList<Team> = this.teamInfoModule.getAllTeamData()

        for(team: Team in teamArrayList) {
            val bundle = Bundle()
            val teamFragment = TeamFragment()

            bundle.putParcelable("teamData", team)
            teamFragment.arguments = bundle

            supportFragmentManager.beginTransaction()
                .add(R.id.root_container, teamFragment)
                .commitAllowingStateLoss()
        }
    }

    override fun onTeamClicked(fragment: TeamFragment, team: Team) {
        val intent = Intent(this, ViewTeamBacklogActivity::class.java)
        intent.putExtra("teamId", team.id)
        startActivity(intent)
    }
}

And I even have the permissions declared in AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluelightlite">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ViewTeamBacklogActivity">

        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I've searched around S.O and it appears to be a common problem but none of the solutions I've found have worked. Could someone please help?


问:
Event data streaming applications with apache kafka in local env and move it to AWS Kafka for pre-prod / prod
Is it possible to develop event data streaming applications with apache kafka locally in my laptop using kafka docker and then deploy the application to AWS msk (kafka) so that cost can be saved by using only for pre-prod and production. </p>

答:
Yes, it is

However, there wouldn't be all that much cost savings because you're effectively paying more for ingress traffic rather than keeping connections within a VPC

The drawback is that it's also not secure and you'll have to port forward your local network's router so that anyone can access your Kafka broker from over the internet, therefore increasing latency as you'd be polling from an upload speed limited by your ISP


问:
How can I draw two contours on an image given a contour distance of 100 pixels between them using python and opencv
What I have tried is drawing the external contour using the following lines

```<code>cnts, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(orig, cnts, -1, (0, 255, 0), 3) # this draws the external contour
</code>```

Referring the below
[![enter image description here][1]][1]

How can I arrive at the answer below?

[![enter image description here][2]][2]

答:
I don't know how it is solved in the links but you can use a blank mask on which you can draw your contour and then use cv2.dilate to expand it using a kernel size of the number of pixels you require between them. Once that is done find contours on the mask and draw the second one onto your original image.

import cv2
import numpy as np

img = cv2.imread('contour.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, cnts, -1, (0, 255, 0), 3)
mask = np.zeros(img.shape[:2], dtype=np.uint8)
cv2.drawContours(mask, cnts, -1, 255, 1)
kernel = np.ones((100, 100), np.uint8)
mask = cv2.dilate(mask, kernel, iterations = 1)
cnts, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, cnts, 1, (255, 0, 0), 3)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```

Body:
What I have tried is drawing the external contour using the following lines

cnts, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(orig, cnts, -1, (0, 255, 0), 3) # this draws the external contour

Referring the below
[![enter image description here][1]][1]

How can I arrive at the answer below?

[![enter image description here][2]][2]


问:
Trying to make a program that checks if a password contains uppercase letter and a number in c
I am trying to make a program that checks whether the password created contains an uppercase letter and a number. Both the for loops execute fine if only one of them is written without the other (one loop works fine if I comment out the other loop), but if I type them both together only the second for loop (that's associated with checking if there is a number or not) works and the other doesn't work.

So with the written code below, if I type a password that does not contain an uppercase letter nor a number I get the "Please make sure that your password contains a number and try again." message only.

Note :

I tried using the assigning the integer i to zero after the first loop and using it in the second loop instead of x but I get the same result.

I am using code::blocks compiler.

Could anyone point out where did I go wrong?

Sorry if the question isn't clear enough this is my first question here in stackoverflow, and thanks in advance.

The code :

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

int main()

{

    char password[25];

    int i;

    int x;

    printf("Create a strong password (must contain an uppercase letter and a number, and must be at least 8 characters) :\n");
    scanf(" %s", password);

    for (i = 0; i <= 25; i++)
    {

        if ( isupper(password[i]) == 1 )
        {
            break;
        }

        if (i == 25)
        {
            printf("\nPlease make sure that your password contains an uppercase letter and try again.\n");
        }

    }

      for (x = 0; x <= 25; x++)
    {

        if (isdigit(password[x]) == 1)
        {
            break;
        }

        if ( x == 25 )
        {
             printf("\nPlease make sure that your password contains a number and try again.\n");
        }

    }

    return 0;
}
</code>```

答:
Here's c++ code that uses regular expressions (with a bit of work this should be do-able in C ?)</p>

```<code>#include <iostream>
#include <iterator>
#include <string>
#include <regex>

int main()
{
    std::string s = "tkfgfff3gf";

    std::regex word_regex("(\[[:upper:]])");

    auto words_begin =
        std::sregex_iterator(s.begin(), s.end(), word_regex);
    auto words_end = std::sregex_iterator();

    int count =std::distance(words_begin, words_end);

    if(count == 0)
    {
        std::cout<<"Please make sure that your password contains an uppercase letter and try again";
    }

    std::regex number_regex("(\[0-9])");

    auto number_begin =
        std::sregex_iterator(s.begin(), s.end(), number_regex);
    auto number_end = std::sregex_iterator();

    count =std::distance(number_begin, number_end);

    if(count == 0)
    {
        std::cout<<"Please make sure that your password contains a number and try again";
    }

    return 0;

}
</code>```

Body:
I am trying to make a program that checks whether the password created contains an uppercase letter and a number. Both the for loops execute fine if only one of them is written without the other (one loop works fine if I comment out the other loop), but if I type them both together only the second for loop (that's associated with checking if there is a number or not) works and the other doesn't work.

So with the written code below, if I type a password that does not contain an uppercase letter nor a number I get the "Please make sure that your password contains a number and try again." message only.

Note :

I tried using the assigning the integer i to zero after the first loop and using it in the second loop instead of x but I get the same result.

I am using code::blocks compiler.

Could anyone point out where did I go wrong?

Sorry if the question isn't clear enough this is my first question here in stackoverflow, and thanks in advance.

The code :

#include <stdio.h>
#include <ctype.h>

int main()

{

    char password[25];

    int i;

    int x;

    printf("Create a strong password (must contain an uppercase letter and a number, and must be at least 8 characters) :\n");
    scanf(" %s", password);

    for (i = 0; i <= 25; i++)
    {

        if ( isupper(password[i]) == 1 )
        {
            break;
        }

        if (i == 25)
        {
            printf("\nPlease make sure that your password contains an uppercase letter and try again.\n");
        }

    }

      for (x = 0; x <= 25; x++)
    {

        if (isdigit(password[x]) == 1)
        {
            break;
        }

        if ( x == 25 )
        {
             printf("\nPlease make sure that your password contains a number and try again.\n");
        }

    }

    return 0;
}

Body:
Here's c++ code that uses regular expressions (with a bit of work this should be do-able in C ?)

#include <iostream>
#include <iterator>
#include <string>
#include <regex>

int main()
{
    std::string s = "tkfgfff3gf";

    std::regex word_regex("(\[[:upper:]])");

    auto words_begin =
        std::sregex_iterator(s.begin(), s.end(), word_regex);
    auto words_end = std::sregex_iterator();

    int count =std::distance(words_begin, words_end);

    if(count == 0)
    {
        std::cout<<"Please make sure that your password contains an uppercase letter and try again";
    }

    std::regex number_regex("(\[0-9])");

    auto number_begin =
        std::sregex_iterator(s.begin(), s.end(), number_regex);
    auto number_end = std::sregex_iterator();

    count =std::distance(number_begin, number_end);

    if(count == 0)
    {
        std::cout<<"Please make sure that your password contains a number and try again";
    }

    return 0;

}


问:
Concatenate hive analog in spark
I have a spark job which create a one result table in Hive and load data from the other tables.
This job is executed every day and generates a lot of file on HDFS.
When I used Hive I make a script: alter table quality_of_service_1 concatenate;

```<code>implicit val spark: SparkSession = SparkSession
    .builder()
    .enableHiveSupport()
    .appName("Test")
    .getOrCreate()

  def build(implicit session: SparkSession, config: Config): Unit = {
    import session.implicits._
    loadData
      .flatMap(Item.buildInternal(_, config))
      .write
      .mode(SaveMode.Overwrite)
      .format("orc")
      .saveAsTable(s"${config.schema}.result_table")
  }
</code>```

Could you please write how to merge this files and where it tunes? Shell script with HDFS, spark or spark session configs.

Config:

```<code>--deploy-mode cluster \
--conf spark.rpc.message.maxSize=300 \
--conf spark.rdd.compress=true \
--conf spark.default.parallelism=1009 \
--conf spark.sql.shuffle.partitions=1009 \
--conf spark.sql.autoBroadcastJoinThreshold=31457280 \
--conf spark.dynamicAllocation.enabled=true \
--conf spark.shuffle.service.enabled=true \
--conf spark.dynamicAllocation.initialExecutors=1200 \
--conf spark.dynamicAllocation.minExecutors=400 \
--conf spark.dynamicAllocation.maxExecutors=1200 \
--conf spark.sql.files.maxPartitionBytes=1073741824 \
--executor-cores 3 \
--executor-memory 7g \
--driver-memory 4g \
</code>```

答:
In spark2, a parameter controls the size of one partition ... thus the number of files when you "save".
So increase the parameter to have less partitions and after less files
For example, a one gigabyte per partition
val maxSplit=1024*1024*1024
spark.conf.set("spark.sql.files.maxPartitionBytes", maxSplit)

Title: Concatenate hive analog in spark

Body:
I have a spark job which create a one result table in Hive and load data from the other tables.
This job is executed every day and generates a lot of file on HDFS.
When I used Hive I make a script: alter table quality_of_service_1 concatenate;

implicit val spark: SparkSession = SparkSession
    .builder()
    .enableHiveSupport()
    .appName("Test")
    .getOrCreate()

  def build(implicit session: SparkSession, config: Config): Unit = {
    import session.implicits._
    loadData
      .flatMap(Item.buildInternal(_, config))
      .write
      .mode(SaveMode.Overwrite)
      .format("orc")
      .saveAsTable(s"${config.schema}.result_table")
  }

Could you please write how to merge this files and where it tunes? Shell script with HDFS, spark or spark session configs.

Config:

--deploy-mode cluster \
--conf spark.rpc.message.maxSize=300 \
--conf spark.rdd.compress=true \
--conf spark.default.parallelism=1009 \
--conf spark.sql.shuffle.partitions=1009 \
--conf spark.sql.autoBroadcastJoinThreshold=31457280 \
--conf spark.dynamicAllocation.enabled=true \
--conf spark.shuffle.service.enabled=true \
--conf spark.dynamicAllocation.initialExecutors=1200 \
--conf spark.dynamicAllocation.minExecutors=400 \
--conf spark.dynamicAllocation.maxExecutors=1200 \
--conf spark.sql.files.maxPartitionBytes=1073741824 \
--executor-cores 3 \
--executor-memory 7g \
--driver-memory 4g \


问:
does DateTime keep itself updated in C#?
I am trying to create a folder based off of the current month/day using DateTime. After i initialize a new DateTime( 2011, 5, 16, 1, 1, 30); will this keep itself updated or reset every time the program is ran?</p>

答: If the code looks like that it will be the same every time.  If you want the the current day use DateTime.Today or DateTime.Now