问:
CodeIgniter - best place to declare global variable
I just want to use a $variable at several places: not only views and controllers, but also in the routes.php and other configuration files.

I don't want things like: use the Config class to load configuration files; use CI's get_instance, et cetera.

I just want to declare a given $variable (it could be a constant, but I need it as a variable), and use it absolutely everywhere.

In fact... I'd like to know which PHP file in the CI bootstrap is one of the first to be parsed, so I could introduce my global variable there... but not a core/system or inapproriated file, but the "best" suited placement for this simple requirement.

答:
Similar to Spartak answer above but perhaps simpler.

A class in a helper file with a static property and two instance methods that read and write to that static property. No matter how many instances you create, they all write to the single static property.

In one of your custom helper files create a class. Also create a function that returns an instance of that class. The class has a static variable defined and two instance methods, one to read data, one to write data. I did this because I wanted to be able to collect log data from controllers, models, libraries, library models and collect all logging data to send down to browser at one time. I did not want to write to a log file nor save stuff in session. I just wanted to collect an array of what happened on the server during my ajax call and return that array to the browser for processing.

In helper file:

```<code>if (!class_exists('TTILogClass')){
    class TTILogClass{

        public static $logData = array();

        function TTILogClass(){

        }

        public function __call($method, $args){
            if (isset($this->$method)) {
                $func = $this->$method;
                return call_user_func_array($func, $args);
            }
        }

        //write to static $logData
        public function write($text=''){
            //check if $text is an array!
            if(is_array($text)){
                foreach($text as $item){
                    self::$logData[] = $item;
                }
            } else {
                self::$logData[] = $text;
            }
        }

        //read from static $logData
        public function read(){
            return self::$logData;
        }

    }// end class
} //end if

//an "entry" point for other code to get instance of the class above
if(! function_exists('TTILog')){
    function TTILog(){
        return new TTILogClass();

    }
}
</code>```

In any controller, where you might want to output all log entries made by the controller or by a library method called by the controller or by a model function called by the controller:

```<code>function testLogging(){
    $location = $this->file . __FUNCTION__;
    $message = 'Logging from ' . $location;

    //calling a helper function which returns
    //instance of a class called "TTILogClass" in the helper file

    $TTILog = TTILog();

    //the instance method write() appends $message contents
    //to the TTILog class's static $logData array

    $TTILog->write($message);

    // Test model logging as well.The model function has the same two lines above,
    //to create an instance of the helper class TTILog
    //and write some data to its static $logData array

    $this->Tests_model->testLogging();

    //Same thing with a library method call
    $this->customLibrary->testLogging();

    //now output our log data array. Amazing! It all prints out!
    print_r($TTILog->read());
}
</code>```

Prints out:

Logging from controllerName: testLogging

Logging from modelName: testLogging

Logging from customLibrary: testLogging

Body:
Similar to Spartak answer above but perhaps simpler.

A class in a helper file with a static property and two instance methods that read and write to that static property. No matter how many instances you create, they all write to the single static property.

In one of your custom helper files create a class. Also create a function that returns an instance of that class. The class has a static variable defined and two instance methods, one to read data, one to write data. I did this because I wanted to be able to collect log data from controllers, models, libraries, library models and collect all logging data to send down to browser at one time. I did not want to write to a log file nor save stuff in session. I just wanted to collect an array of what happened on the server during my ajax call and return that array to the browser for processing.

In helper file:

if (!class_exists('TTILogClass')){
    class TTILogClass{

        public static $logData = array();

        function TTILogClass(){

        }

        public function __call($method, $args){
            if (isset($this->$method)) {
                $func = $this->$method;
                return call_user_func_array($func, $args);
            }
        }

        //write to static $logData
        public function write($text=''){
            //check if $text is an array!
            if(is_array($text)){
                foreach($text as $item){
                    self::$logData[] = $item;
                }
            } else {
                self::$logData[] = $text;
            }
        }

        //read from static $logData
        public function read(){
            return self::$logData;
        }

    }// end class
} //end if

//an "entry" point for other code to get instance of the class above
if(! function_exists('TTILog')){
    function TTILog(){
        return new TTILogClass();

    }
}

In any controller, where you might want to output all log entries made by the controller or by a library method called by the controller or by a model function called by the controller:

function testLogging(){
    $location = $this->file . __FUNCTION__;
    $message = 'Logging from ' . $location;

    //calling a helper function which returns
    //instance of a class called "TTILogClass" in the helper file

    $TTILog = TTILog();

    //the instance method write() appends $message contents
    //to the TTILog class's static $logData array

    $TTILog->write($message);

    // Test model logging as well.The model function has the same two lines above,
    //to create an instance of the helper class TTILog
    //and write some data to its static $logData array

    $this->Tests_model->testLogging();

    //Same thing with a library method call
    $this->customLibrary->testLogging();

    //now output our log data array. Amazing! It all prints out!
    print_r($TTILog->read());
}

Prints out:

Logging from controllerName: testLogging

Logging from modelName: testLogging

Logging from customLibrary: testLogging


来源: stackexchange

问:
Path-based authorization for microservices in kubernetes
I am tasked with migrating AWS lambda microservices to Kubernetes. For simplicity, there are two service endpoints: /admin and /user where you can GET or POST a request to get something done.

You have to be in admin group (defined in an external authZ provider) to hit /admin endpoint, or otherwise, you get 401. You have to be in user group to have access to /user endpoint.

I will have each endpoint exposed as a service running in a docker container. The question is - what is the correct way to add routing and path-based authorization in Kubernetes?

Like, if I go to /admin in the browser, I need Kubernetes to check if I am in admin group and then route me to admin service; otherwise, it should return 401.

I can write this router myself, but I want to check if there is a built-in solution in Kubernetes for that.

答:
You can explore istio's traffic management. They provide routing based on user identity (https://istio.io/docs/tasks/traffic-management/request-routing/#route-based-on-user-identity). But they do this by finding the user from request header. If you have an admin group then not sure whether this can be used as is.

Sample virtual service:

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
  ...
spec:
  hosts:
  - reviews
  http:
  - match:
    - headers:
        end-user:
          exact: jason
    route:
    - destination:
        host: reviews
        subset: v2
  - route:
    - destination:
        host: reviews
        subset: v1
</code>```

The above service can be accessed from outside the cluster using istio gateway.

ContentLicense: CC BY-SA 4.0

Body:
You can explore istio's traffic management. They provide routing based on user identity (https://istio.io/docs/tasks/traffic-management/request-routing/#route-based-on-user-identity). But they do this by finding the user from request header. If you have an admin group then not sure whether this can be used as is.

Sample virtual service:

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
  ...
spec:
  hosts:
  - reviews
  http:
  - match:
    - headers:
        end-user:
          exact: jason
    route:
    - destination:
        host: reviews
        subset: v2
  - route:
    - destination:
        host: reviews
        subset: v1

The above service can be accessed from outside the cluster using istio gateway.


问:
Lombok: RequiredArgsConstructor is not working
It seems that @RequiredArgsConstructor not working in the code below. Why is it?

```<code>import java.io.Serializable;

import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
public class User implements Serializable {

    private String username;

    /*public User(String username) {
        this.username = username;
    }*/

    private static final long serialVersionUID = 8043545738660721361L;
}
</code>```

I get the error:

```<code>javax.faces.el.EvaluationException: java.lang.Error: Unresolved compilation problem:
    The constructor User(String) is undefined
</code>```

For some reason seems it does work for other domain class in which no constructor defined but instead used the @RequiredArgsConstructor annotation.

答:
Try changing project/module JDK to 1.8.

Project Structure -> Project Settings->Project SDK and Project Language Level

Body:
It seems that @RequiredArgsConstructor not working in the code below. Why is it?

import java.io.Serializable;

import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
public class User implements Serializable {

    private String username;

    /*public User(String username) {
        this.username = username;
    }*/

    private static final long serialVersionUID = 8043545738660721361L;
}

I get the error:

javax.faces.el.EvaluationException: java.lang.Error: Unresolved compilation problem:
    The constructor User(String) is undefined

For some reason seems it does work for other domain class in which no constructor defined but instead used the @RequiredArgsConstructor annotation.


问:
Python: handling a large string value - if statement not working properly?
I have this large string value, about 500 characters called 'strPage6'
I'm looking to see if nth position of this string has the '%' value with an if statement without success.

```<code>#see if 330th character has value '%'
if (strPage6[330:331]=="%"):
   print("330th character is '%' ")
   print(strPage6)
else:
   print("330th character is NOT '%' ")
   print(strPage6)
</code>```

my terminal returns the following value:

```<code>330th character is NOT '%'
b'%'
</code>```

I tried switching the byte string into a plain string with 'decode' with the following result:

```<code>strPage6=strPage.decode('utf-8')
[...]

330th character is NOT '%'
e
</code>```

Basically, I am looking to get the following result:

```<code>330th character is '%'
%
</code>```

Your help is appreciated!

答:
Did you try strPage6[330]==b"%"? – khelwood

does the equation properly

Body:
I have this large string value, about 500 characters called 'strPage6'
I'm looking to see if nth position of this string has the '%' value with an if statement without success.

#see if 330th character has value '%'
if (strPage6[330:331]=="%"):
   print("330th character is '%' ")
   print(strPage6)
else:
   print("330th character is NOT '%' ")
   print(strPage6)

my terminal returns the following value:

330th character is NOT '%'
b'%'

I tried switching the byte string into a plain string with 'decode' with the following result:

strPage6=strPage.decode('utf-8')
[...]

330th character is NOT '%'
e

Basically, I am looking to get the following result:

330th character is '%'
%

Your help is appreciated!


问:
Adding a default header only for POST request
I'm trying a Typed HttpClient as below. I'm looking to find a way to add DefaultRequestHeaders only to my POST request (and not to other requests such GET or PUT). Is there way to achieve this?

Here is my code snippet.

```<code>var builder = services
     .AddHttpClient("MyService", client =>
      {
         client.BaseAddress = configuration.BaseAddress;

         // Need to default header only for "POST" request
         client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue");
      })
      .AddTypedClient<IMyServiceClient, MyServiceRestClient>();
</code>```

I'm trying to find a way where line client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue") is only effective for POST request.

答:
What about a re-usable httpclient that has minimal config and then manage your request by http method specific execution?

For example, consider an async POST method that overrides an internal generic async method that configs the request/response and uses your httpclient to execute.  You could pass in the headers you need and/or set the default headers in this method.

```<code>public async Task<KeyValuePair<HttpResponseMessage, T>> PostAsync<T>(Uri uri, object data, AuthenticationHeaderValue authHeader = null, Dictionary<string, string> headers = null)
{
   return await SendRequestAsync<T, object>(uri.ToString(), data, HttpMethod.Post, authHeader, headers);
}
</code>```

The internal method is as follows:

```<code>private async Task<KeyValuePair<HttpResponseMessage, T>> SendRequestAsync<T, U>(string requestUri, U content, HttpMethod method, AuthenticationHeaderValue authHeader = null, Dictionary<string, string> headers = null)
{
    using (HttpRequestMessage request = new HttpRequestMessage())
    {
        request.Method = method;
        request.RequestUri = new Uri(requestUri, UriKind.Absolute);

        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        if (authHeader != null)
        {
            request.Headers.Authorization = authHeader;
        }

        string requestContent = null;

        if (content != null)
        {
            requestContent = JsonConvert.SerializeObject(content);
            request.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
        }

        if (headers != null)
        {
            foreach (var header in headers)
            {
                if (!request.Headers.Contains(header.Key))
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
        }

        // _client would be a private implementation or injected version of your httpclient
        using (HttpResponseMessage response = await _client.SendAsync(request))
        {
            if (response.IsSuccessStatusCode)
            {
                if (response.Content != null)
                {
                    var rawJson = await response.Content.ReadAsStringAsync();

                    var mappedObj = JsonConvert.DeserializeObject<T>(rawJson);

                    var result = new KeyValuePair<HttpResponseMessage, T>(response, mappedObj);

                    return result;
                }
            }
            else
            {
                // do something else
            }

            return new KeyValuePair<HttpResponseMessage, T>(response, default(T));
        }
    }
}
</code>```

Body:
I'm trying a Typed HttpClient as below. I'm looking to find a way to add DefaultRequestHeaders only to my POST request (and not to other requests such GET or PUT). Is there way to achieve this?

Here is my code snippet.

var builder = services
     .AddHttpClient("MyService", client =>
      {
         client.BaseAddress = configuration.BaseAddress;

         // Need to default header only for "POST" request
         client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue");
      })
      .AddTypedClient<IMyServiceClient, MyServiceRestClient>();

I'm trying to find a way where line client.DefaultRequestHeaders.Add("MyHeader", "MyHeaderValue") is only effective for POST request.

Body:
What about a re-usable httpclient that has minimal config and then manage your request by http method specific execution?

For example, consider an async POST method that overrides an internal generic async method that configs the request/response and uses your httpclient to execute.  You could pass in the headers you need and/or set the default headers in this method.

public async Task<KeyValuePair<HttpResponseMessage, T>> PostAsync<T>(Uri uri, object data, AuthenticationHeaderValue authHeader = null, Dictionary<string, string> headers = null)
{
   return await SendRequestAsync<T, object>(uri.ToString(), data, HttpMethod.Post, authHeader, headers);
}

The internal method is as follows:

private async Task<KeyValuePair<HttpResponseMessage, T>> SendRequestAsync<T, U>(string requestUri, U content, HttpMethod method, AuthenticationHeaderValue authHeader = null, Dictionary<string, string> headers = null)
{
    using (HttpRequestMessage request = new HttpRequestMessage())
    {
        request.Method = method;
        request.RequestUri = new Uri(requestUri, UriKind.Absolute);

        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        if (authHeader != null)
        {
            request.Headers.Authorization = authHeader;
        }

        string requestContent = null;

        if (content != null)
        {
            requestContent = JsonConvert.SerializeObject(content);
            request.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
        }

        if (headers != null)
        {
            foreach (var header in headers)
            {
                if (!request.Headers.Contains(header.Key))
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
        }

        // _client would be a private implementation or injected version of your httpclient
        using (HttpResponseMessage response = await _client.SendAsync(request))
        {
            if (response.IsSuccessStatusCode)
            {
                if (response.Content != null)
                {
                    var rawJson = await response.Content.ReadAsStringAsync();

                    var mappedObj = JsonConvert.DeserializeObject<T>(rawJson);

                    var result = new KeyValuePair<HttpResponseMessage, T>(response, mappedObj);

                    return result;
                }
            }
            else
            {
                // do something else
            }

            return new KeyValuePair<HttpResponseMessage, T>(response, default(T));
        }
    }
}


问:
Repeatedly get values from Postgres, using most recent set
I have a sensor that reads values into a Postgres DB.  I have a main :: IO () function that returns a list of the values in a given table.  (The example below is for a light sensor that returns a Bool for whether the light sensor is exposed to light or not.)

```<code>main :: IO ()
main = do
  conn <- connectPostgreSQL "my connection string here"
  myQuery <- (query_ conn "select sensor1 from lightbool" :: IO [Only String])
  mapM_ print myQuery
  let usefulLightBools = lightBoolConverter myQuery
  mapM_ print usefulLightBools

lightBoolConverter :: [Only String] -> [Bool]
lightBoolConverter = map (lightBoolString2Bool . read . show . fromOnly)

-- TODO change to a Maybe Bool and fix this pattern matching
lightBoolString2Bool :: String -> Bool
lightBoolString2Bool "TRUE" = True
lightBoolString2Bool "FALSE" = False
</code>```

I want to have the script periodically (e.g. every 5 seconds), query the database and store the results in a list.  I want to use the latest value of the list as an input for a function until there is a new value to replace it.

The way I thought to implement this was to compare two lists -- the initially-grabbed list and the potentially-new list -- and take the head of the reverse of the longer list.

```<code>compareLists :: [a] -> [a] -> a
compareLists l1 l2 = head $ reverse $ maximumBy (comparing length) [l1,l2]
</code>```

I am unclear on how to modify my main function to store usefulLightBools, periodically re-run the query, store the new query in a different variable (usefulLightBoolsLatest?), and use my compareLists to get the correct value and store that value in a variable.

Or maybe there is a simpler version where (1) the query is run periodically on some time delay and (2) I do something like this?

```<code>  let usefulLightBools = reverse $ lightBoolConverter myQuery
  myVar <- head usefulLightBools
</code>```

答:
Is something like this good enough?

```<code>import Control.Concurrent
import Control.Monad

main = forever $ do
    bools <- {- ... -}
    print bools
    threadDelay 5000000 -- 5 seconds
</code>```

Query the database, do something neat with the result, wait 5 seconds, rinse, repeat. There are certainly more sophisticated things to do that address shortcomings of this way, but if this meets your needs it definitely has the advantage of being particularly simple.

Body:
I have a sensor that reads values into a Postgres DB.  I have a main :: IO () function that returns a list of the values in a given table.  (The example below is for a light sensor that returns a Bool for whether the light sensor is exposed to light or not.)

main :: IO ()
main = do
  conn <- connectPostgreSQL "my connection string here"
  myQuery <- (query_ conn "select sensor1 from lightbool" :: IO [Only String])
  mapM_ print myQuery
  let usefulLightBools = lightBoolConverter myQuery
  mapM_ print usefulLightBools

lightBoolConverter :: [Only String] -> [Bool]
lightBoolConverter = map (lightBoolString2Bool . read . show . fromOnly)

-- TODO change to a Maybe Bool and fix this pattern matching
lightBoolString2Bool :: String -> Bool
lightBoolString2Bool "TRUE" = True
lightBoolString2Bool "FALSE" = False

I want to have the script periodically (e.g. every 5 seconds), query the database and store the results in a list.  I want to use the latest value of the list as an input for a function until there is a new value to replace it.

The way I thought to implement this was to compare two lists -- the initially-grabbed list and the potentially-new list -- and take the head of the reverse of the longer list.

compareLists :: [a] -> [a] -> a
compareLists l1 l2 = head $ reverse $ maximumBy (comparing length) [l1,l2]

I am unclear on how to modify my main function to store usefulLightBools, periodically re-run the query, store the new query in a different variable (usefulLightBoolsLatest?), and use my compareLists to get the correct value and store that value in a variable.

Or maybe there is a simpler version where (1) the query is run periodically on some time delay and (2) I do something like this?

  let usefulLightBools = reverse $ lightBoolConverter myQuery
  myVar <- head usefulLightBools

Body:
Is something like this good enough?

import Control.Concurrent
import Control.Monad

main = forever $ do
    bools <- {- ... -}
    print bools
    threadDelay 5000000 -- 5 seconds

Query the database, do something neat with the result, wait 5 seconds, rinse, repeat. There are certainly more sophisticated things to do that address shortcomings of this way, but if this meets your needs it definitely has the advantage of being particularly simple.


问:
Laravel table relationship to pivot table
I'm confused on how to get my model setup in laravel with a table that is connected to a pivot table.

Here's the problem

Say I have

```<code>Locations
    id
    name

area_types
    id
    name

area_type_location (Pivot table)
    id
    location_id
    area_type_id

area_test
    id
    area_type_location_id
    clean
    headCount
</code>```

Relationship between the tables are different areas type belongs to different locations.
i.e: beach, 25m pools, kids pools, bbq, etc

area_test is connected to the pivot table because the test has to be generated from area that exists, in this case it is area that is registered under different locations. Thus it has to be tested daily, measured, etc.

I understand the structure between area_types and locations for many to many relationship, however I can't get over my head of how do i structure my area_test model? How do I get the data from locations table -> where are my test?

Should I create a model for my pivot table? Is that a good practice in laravel?

Does anyone has the same use case?

I read about eloquent has many through
 relationship but I understand that it does not mention about getting through pivot table. I don't quite get if my use case is the same.

Thanks

答:
Finally, apparently there are a couple of way to get data from locations table to area_tests

Tried at tinker and it works,

First Option

I need to create a Pivot model for my Pivot table:

```<code>class LocationAreaType extends Pivot{

public function location(){
    return $this->belongsTo(Location::class);
}

public function areaType(){
    return $this->belongsTo(AreaType::class);
}

public function AreaTests(){
    return $this->hasMany(AreaTest::class, 'area_type_location_id');
}
</code>```

}

I can use hasManyThrough relation that I need to create in my Location table

```<code>public function areaTests()
{
    return $this->hasManyThrough(
        AreaTest::class,
        LocationAreaType::class,
        'location_id',
        'area_type_location_id');
}
</code>```

this way I can get the areaTests easily by $location->areaTests, My problem was not determining the area_type_location_id as foreign. You need to determine this, apparently when I extends pivot and use hasMany laravel does not auto recognise the Foreign key by itself.

Second option

Another way to access it is from the relation table, I can define withPivot in the areaTypes() relation then access it like this:

$location->areaType[0]->pivot->areaTests

Since laravel only recognise foreign key from both tables location_id and area_type_id, I have to include the id of the pivot table to get the AreaTest table data

So in the Location model I have to get the column

```<code>public function areaTypes()
{
    // Get the ID of the pivot table to get the poolTests table (connected with ID column)
    return $this->belongsToMany(AreaType::class)
        ->using(AreaTypeLocation::class)
        ->withPivot('id');
}
</code>```

Body:
I'm confused on how to get my model setup in laravel with a table that is connected to a pivot table.

Here's the problem

Say I have

Locations
    id
    name

area_types
    id
    name

area_type_location (Pivot table)
    id
    location_id
    area_type_id

area_test
    id
    area_type_location_id
    clean
    headCount

Relationship between the tables are different areas type belongs to different locations.
i.e: beach, 25m pools, kids pools, bbq, etc

area_test is connected to the pivot table because the test has to be generated from area that exists, in this case it is area that is registered under different locations. Thus it has to be tested daily, measured, etc.

I understand the structure between area_types and locations for many to many relationship, however I can't get over my head of how do i structure my area_test model? How do I get the data from locations table -> where are my test?

Should I create a model for my pivot table? Is that a good practice in laravel?

Does anyone has the same use case?

I read about eloquent has many through
 relationship but I understand that it does not mention about getting through pivot table. I don't quite get if my use case is the same.

Thanks

Body:
Finally, apparently there are a couple of way to get data from locations table to area_tests

Tried at tinker and it works,

First Option

I need to create a Pivot model for my Pivot table:

class LocationAreaType extends Pivot{

public function location(){
    return $this->belongsTo(Location::class);
}

public function areaType(){
    return $this->belongsTo(AreaType::class);
}

public function AreaTests(){
    return $this->hasMany(AreaTest::class, 'area_type_location_id');
}

}

I can use hasManyThrough relation that I need to create in my Location table

public function areaTests()
{
    return $this->hasManyThrough(
        AreaTest::class,
        LocationAreaType::class,
        'location_id',
        'area_type_location_id');
}

this way I can get the areaTests easily by $location->areaTests, My problem was not determining the area_type_location_id as foreign. You need to determine this, apparently when I extends pivot and use hasMany laravel does not auto recognise the Foreign key by itself.

Second option

Another way to access it is from the relation table, I can define withPivot in the areaTypes() relation then access it like this:

$location->areaType[0]->pivot->areaTests

Since laravel only recognise foreign key from both tables location_id and area_type_id, I have to include the id of the pivot table to get the AreaTest table data

So in the Location model I have to get the column

public function areaTypes()
{
    // Get the ID of the pivot table to get the poolTests table (connected with ID column)
    return $this->belongsToMany(AreaType::class)
        ->using(AreaTypeLocation::class)
        ->withPivot('id');
}


问:
How to build a python bot for Teams? How to deploy the same in my PROD server?
I would want to build a bot in python. I would want to to do various rest calls using that bot. Can this be done in Teams and deployed in PROD LINUX server?

I have python bot in slack and that works perfectly fine.

答:
Bots built for Microsoft Teams are made using the Microsoft Bot Framework, which has a Python SDK you can use, or you can use straight REST calls if you prefer. See:

Teams app docs: https://learn.microsoft.com/en-us/microsoftteams/platform/overview

Bot Framework docs: https://learn.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0

For chat bots, it doesn't matter what OS you use to host your service.


问:
Invalid domain name Azure Active directory issue and Migration to Microsoft Graph C# application
I am trying to run below code to get the user details as response from Azure Active Directory  :

```<code>using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AADConsole2
{
    class Program
    {

        private const string aadInstance = "https://login.microsoftonline.com/{0}";
        private const string resource= "https://graph.windows.net";
        private const string GraphServiceObjectId = "XXX";
        private const string TenantId = "XXXXX";
        private const string tenant = "company.onmicrosoft.com";
        private const string ClientId = "XXXX";
        private static string appKey= "XXXXXXXXXXXXXXXX";
        static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, aadInstance, tenant);

        private static HttpClient httpclient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;

        static void Main(string[] args)
        {

            context = new AuthenticationContext(authority);
            credential = new ClientCredential(ClientId, appKey);
            Task<string> token = GetToken();
            token.Wait();
            Console.WriteLine(token.Result);
            Task<string> users = GetUsers(token.Result);
            users.Wait();
            Console.WriteLine(users.Result);
            Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result) {
            //throw new NotImplementedException();
            string users = null;
            string queryString = "test";
</code>```

var uri = "https://graph.windows.net/{your_tenant_name}.onmicrosoft.com/users?api-version=1.6";

```<code>            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpclient.GetAsync(uri);

            if(getResult.Content != null)
            {
                users = await getResult.Content.ReadAsStringAsync();

            }
            return users;

        }

        private static async Task<string> GetToken()
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential);
            token = result.AccessToken;
            return token;

        }
    }
}
</code>```

I am getting below error:

```<code>uMCJ9.FdttazjoKYZWP_SmC5B7Nd3kOF-jRs62WLKYovDA8qMvybLTw8yIUoihp7I00ctJGJHDoEbhbIi0XHp9Ujdq0bNPlG-L5SoE9IFSoxX3ZQOZwSf90b_nDapbHJ8KCHZUnCBOwVnYiTXtpIQfrDVqqENarrIGa_uUbiriomYiB8gVkKWe6PB-I4lsYPEmMNnnpdvIf1eV_CsTmvUA54Ch1Zdip9mxrzRqrUqsx6vUTo0riCmiCxRg7mH2DuMaEPTZuQAMwhrQM_EwNsgx1yX1VsCKkL1Gu7CV_dqW5xxYlE7NEQmorT8W6aySbiBzsUWisJNnaR8RqZzeAUlSVMKBiw
{"odata.error":{"code":"Request_BadRequest","message":{"lang":"en","value":"Invalid domain name in the request url."},"requestId":"01ab745b-8a3f-48cc-9542-0c6abcae8950","date":"2020-02-17T22:41:28"}}
r
</code>```

Also ,help me in getting  tenant name ( it's a name or alphanumeric id ?) ,currently i am just using below tenant name.
private const string tenant = "company.onmicrosoft.com";

I only want to use Microsoft Graph API in this code. Thanks.

答:
i also want to know the whether this code is using Microsoft Graph or
  Azure AD.

This code is using Azure AD Graph API. It works fine if the request uri is correct.You should use your tenant name, not company.onmicrosoft.com, and you must specify the api-version. So the request uri should be

```<code>var uri = "https://graph.windows.net/{your_tenant_name}.onmicrosoft.com/users?api-version=1.6";
</code>```

If the tenant name is wrong, you will encounter Invalid domain name error.

I am not sure whether to use https://graph.microsoft.com or
  https://graph.windows.net.

You can use either one. But the official document strongly recommend that you use Microsoft Graph instead of Azure AD Graph API to access Azure Active Directory (Azure AD) resources.

If you want to use Microsoft Graph API, just change the value of resource and request api url. The resource will be https://graph.microsoft.com. The request api url will be var uri = "https://graph.microsoft.com/v1.0/users";.

Note: Remember to grant your application the correct permissions in Azure portal and grant admin consent.

Body:
I am trying to run below code to get the user details as response from Azure Active Directory  :

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AADConsole2
{
    class Program
    {

        private const string aadInstance = "https://login.microsoftonline.com/{0}";
        private const string resource= "https://graph.windows.net";
        private const string GraphServiceObjectId = "XXX";
        private const string TenantId = "XXXXX";
        private const string tenant = "company.onmicrosoft.com";
        private const string ClientId = "XXXX";
        private static string appKey= "XXXXXXXXXXXXXXXX";
        static string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, aadInstance, tenant);

        private static HttpClient httpclient = new HttpClient();
        private static AuthenticationContext context = null;
        private static ClientCredential credential = null;

        static void Main(string[] args)
        {

            context = new AuthenticationContext(authority);
            credential = new ClientCredential(ClientId, appKey);
            Task<string> token = GetToken();
            token.Wait();
            Console.WriteLine(token.Result);
            Task<string> users = GetUsers(token.Result);
            users.Wait();
            Console.WriteLine(users.Result);
            Console.ReadLine();
        }

        private static async Task<string> GetUsers(string result) {
            //throw new NotImplementedException();
            string users = null;
            string queryString = "test";

var uri = "https://graph.windows.net/{your_tenant_name}.onmicrosoft.com/users?api-version=1.6";

            httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
            var getResult = await httpclient.GetAsync(uri);

            if(getResult.Content != null)
            {
                users = await getResult.Content.ReadAsStringAsync();

            }
            return users;

        }

        private static async Task<string> GetToken()
        {
            AuthenticationResult result = null;
            string token = null;
            result = await context.AcquireTokenAsync(resource, credential);
            token = result.AccessToken;
            return token;

        }
    }
}

I am getting below error:

uMCJ9.FdttazjoKYZWP_SmC5B7Nd3kOF-jRs62WLKYovDA8qMvybLTw8yIUoihp7I00ctJGJHDoEbhbIi0XHp9Ujdq0bNPlG-L5SoE9IFSoxX3ZQOZwSf90b_nDapbHJ8KCHZUnCBOwVnYiTXtpIQfrDVqqENarrIGa_uUbiriomYiB8gVkKWe6PB-I4lsYPEmMNnnpdvIf1eV_CsTmvUA54Ch1Zdip9mxrzRqrUqsx6vUTo0riCmiCxRg7mH2DuMaEPTZuQAMwhrQM_EwNsgx1yX1VsCKkL1Gu7CV_dqW5xxYlE7NEQmorT8W6aySbiBzsUWisJNnaR8RqZzeAUlSVMKBiw
{"odata.error":{"code":"Request_BadRequest","message":{"lang":"en","value":"Invalid domain name in the request url."},"requestId":"01ab745b-8a3f-48cc-9542-0c6abcae8950","date":"2020-02-17T22:41:28"}}
r

Also ,help me in getting  tenant name ( it's a name or alphanumeric id ?) ,currently i am just using below tenant name.
private const string tenant = "company.onmicrosoft.com";

I only want to use Microsoft Graph API in this code. Thanks.

Body:
i also want to know the whether this code is using Microsoft Graph or
  Azure AD.

This code is using Azure AD Graph API. It works fine if the request uri is correct.You should use your tenant name, not company.onmicrosoft.com, and you must specify the api-version. So the request uri should be

var uri = "https://graph.windows.net/{your_tenant_name}.onmicrosoft.com/users?api-version=1.6";

If the tenant name is wrong, you will encounter Invalid domain name error.

I am not sure whether to use https://graph.microsoft.com or
  https://graph.windows.net.

You can use either one. But the official document strongly recommend that you use Microsoft Graph instead of Azure AD Graph API to access Azure Active Directory (Azure AD) resources.

If you want to use Microsoft Graph API, just change the value of resource and request api url. The resource will be https://graph.microsoft.com. The request api url will be var uri = "https://graph.microsoft.com/v1.0/users";.

Note: Remember to grant your application the correct permissions in Azure portal and grant admin consent.


问:
jQuery fullcalendar: how to save dragged and re-sized items
Since yesterday I am looking for a way to save (mysql + php) dragged and re-sized items with jQuery fullcalendar. There are no tutorials and just a few examples. Can someone post his working json.php, json-events.php and external database update scripts? Or guide me to the best explanations, tutorials or examples?

I'm trying to get this fully working

all help much appreciated!

答:
accoring to FullCalendar V4 Documentation - https://fullcalendar.io/docs/eventResize

if you want to save and retrieve start and end date using an acceptable format, use .toISOString()

```<code>var calendar = new Calendar(calendarEl, {
 events: [
   // events here
 ],
 editable: true,
 eventResize: function(info) {
   alert(info.event.title + " end is now " + info.event.end.toISOString());
   if (!confirm("is this okay?")) {
     info.revert();
   }
 }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
accoring to FullCalendar V4 Documentation - https://fullcalendar.io/docs/eventResize

if you want to save and retrieve start and end date using an acceptable format, use .toISOString()

var calendar = new Calendar(calendarEl, {
 events: [
   // events here
 ],
 editable: true,
 eventResize: function(info) {
   alert(info.event.title + " end is now " + info.event.end.toISOString());
   if (!confirm("is this okay?")) {
     info.revert();
   }
 }
});


问:
Tomcat 7 Start up problem in Eclispse for maven project
I m getting this intermittent problem in eclipse, when i try to run a maven project in tomcat

Details are as follows :

Eclipse version : 3.6

Maven version : 2.2.1

Tomcat version : 7

Error log :

```<code>java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
 at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1362)
 at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1208)
 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3712)
 at org.apache.catalina.core.StandardContext.start(StandardContext.java:4216)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
 at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
 at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
 at org.apache.catalina.core.StandardService.start(StandardService.java:448)
 at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
 at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
</code>```

Deleting and Recreating the server solves the problem, but still i would like to know why this error is created.

答: Thanks for your reply. Well my problem was fixed by doing a mvn eclipse:clean eclipse:eclipse

ContentLicense: CC BY-SA 2.5

Body:
I m getting this intermittent problem in eclipse, when i try to run a maven project in tomcat

Details are as follows :

Eclipse version : 3.6

Maven version : 2.2.1

Tomcat version : 7

Error log :

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
 at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1362)
 at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1208)
 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3712)
 at org.apache.catalina.core.StandardContext.start(StandardContext.java:4216)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
 at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
 at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
 at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
 at org.apache.catalina.core.StandardService.start(StandardService.java:448)
 at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
 at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)

Deleting and Recreating the server solves the problem, but still i would like to know why this error is created.


问:
Implementing Bresenham's circle drawing algorithm
I have written an implementation of Bresenham's circle drawing algorithm. This algorithms takes advantage of the highly symmetrical properties of a circle (it only computes points from the 1st octant and draws the other points by taking advantage of symmetry). Therefore I was expecting it to be very fast. The Graphics programming black book, chapter #35 was titled "Bresenham is fast, and fast is good", and though it was about the line drawing algorithm, I could reasonably expect the circle drawing algorithm to also be fast (since the principle is the same).

Here is my java, swing implementation

```<code>public static void drawBresenhamsCircle(int r, double width, double height, Graphics g) {
    int x,y,d;
    y = r;
    x = 0;

    drawPoint(x, y, width, height,g);
    d = (3-2*(int)r);
    while (x <= y) {
        if (d <= 0) {
            d = d + (4*x + 6);
        } else {
            d = d + 4*(x-y) + 10;
            y--;
        }
        x++;

        drawPoint(x, y, width, height,g);

        drawPoint(-x, y, width, height,g);
        drawPoint(x, -y, width, height,g);

        drawPoint(-x, -y, width, height,g);
        drawPoint(y, x, width, height,g);
        drawPoint(-y, x, width, height,g);
        drawPoint(y, -x, width, height,g);

        drawPoint(-y, -x, width, height,g);
    }
}
</code>```

This method uses the following drawPointmethod:

```<code>public static void drawPoint(double x, double y,double width,double height, Graphics g) {
    double nativeX = getNativeX(x, width);
    double nativeY = getNativeY(y, height);
    g.fillRect((int)nativeX, (int)nativeY, 1, 1);
}
</code>```

The two methods getNativeX and getNativeY are used to switch coordinates from originating in the upper left corner of the screen to a system that has it origin in the center of the panel with a more classic axis orientation.

```<code>public static double getNativeX(double newX, double width) {
    return newX + (width/2);
}

public static double getNativeY(double newY, double height) {
    return (height/2) - newY;
}
</code>```

I have also created an implementation of a circle drawing algorithm based on trigonometrical formulaes (x=R*Math.cos(angle)and y= R*Math.sin(angle)) and a third implementation using a call to the standard drawArc method (available on the Graphics object). These additional implementations are for the sole purpose of comparing Bresenham's algorithm to them.

I then created methods to draw a bunch of circles in order to be able to get good measures of the spent time. Here is the method I use to draw a bunch of circles using Bresenham's algorithm

```<code>public static void drawABunchOfBresenhamsCircles(int numOfCircles, double width, double height, Graphics g) {
    double r = 5;
    double step = (300.0-5.0)/numOfCircles;

    for (int i = 1; i <= numOfCircles; i++) {
        drawBresenhamsCircle((int)r, width, height, g);
        r += step;
    }
}
</code>```

Finally I override the paint method of the JPanel I am using, to draw the bunch of circles and to measure the time it took each type to draw. Here is the paint method:

```<code>public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D)g;

    g2D.setColor(Color.RED);

    long trigoStartTime = System.currentTimeMillis();
    drawABunchOfTrigonometricalCircles(1000, this.getWidth(), this.getHeight(), g);
    long trigoEndTime = System.currentTimeMillis();
    long trigoDelta = trigoEndTime - trigoStartTime;

    g2D.setColor(Color.BLUE);

    long bresenHamsStartTime = System.currentTimeMillis();
    drawABunchOfBresenhamsCircles(1000, this.getWidth(), this.getHeight(), g);
    long bresenHamsEndTime = System.currentTimeMillis();
    long bresenDelta = bresenHamsEndTime - bresenHamsStartTime;

    g2D.setColor(Color.GREEN);

    long standardStarTime = System.currentTimeMillis();
    drawABunchOfStandardCircles(1000, this.getWidth(), this.getHeight(),g);
    long standardEndTime = System.currentTimeMillis();
    long standardDelta = standardEndTime - standardStarTime;

    System.out.println("Trigo : " + trigoDelta  + " milliseconds");
    System.out.println("Bresenham :" + bresenDelta +  " milliseconds");
    System.out.println("Standard :" + standardDelta +  " milliseconds");
}
</code>```

Here is the kind of rendering it would generate (drawing 1000 circles of each type)

Unfortunately my Bresenham's implementation is very slow. I took many comparatives measures, and the Bresenham's implementation is not only slower than the Graphics.drawArcbut also slower than the trigonometrical approach. Take a look at the following measures for a various number of circles drawn.

What part of my implementation is more time-consuming? Is there any workaround I could use to improve it? Thanks for helping.

[EDITION]: as requested by @higuaro, here is my trigonometrical algorithm for drawing a circle

```<code>public static void drawTrigonometricalCircle (double r, double width, double height, Graphics g) {

    double x0 = 0;
    double y0 = 0;
    boolean isStart = true;

    for (double angle = 0; angle <= 2*Math.PI; angle = angle + Math.PI/36) {

        double x = r * Math.cos(angle);
        double y = r * Math.sin(angle);

        drawPoint((double)x, y, width, height, g);

        if (!isStart) {
            drawLine(x0,  y0, x, y, width, height, g);
        }

        isStart = false;

        x0 = x;
        y0 = y;
    }
}
</code>```

And the method used to draw a bunch of trigonometrical circles

```<code>public static void drawABunchOfTrigonometricalCircles(int numOfCircles, double width, double height, Graphics g) {

    double r = 5;
    double step = (300.0-5.0)/numOfCircles;

    for (int i = 1; i <= numOfCircles; i++) {
        drawTrigonometricalCircle(r, width, height, g);
        r += step;
    }
}
</code>```

答:
I lately wrote a bresenham circle drawing implemenation myself for a sprite rasterizer and tried to optimize it a bit. I'm not sure if it will be faster or slower than what you did but i think it should have a pretty decent execution time.

Also unfortunately it is written in C++. If i have time tomorrow i might edit my answer with a ported Java version and an example picture for the result but for now you'd have to do it yourself if you want (or someone else who would want to take his time and edit it.)

Bascically, what it does is use the bresenham algorithm to aquire the positions for the outer edges of the circle, then perform the algorithm for 1/8th of the circle and mirror that for the the remaining 7 parts by drawing straight lines from the center to the outer edge.

Color is just an rgba value

Color* createCircleColorArray(const int radius, const Color& color, int& width, int& height) {
  // Draw circle with custom bresenham variation
  int decision = 3 - (2 * radius);
  int center_x = radius;
  int center_y = radius;
  Color* data;

  // Circle is center point plus radius in each direction high/wide
  width = height = 2 * radius + 1;
  data = new Color[width * height];

  // Initialize data array for transparency
  std::fill(data, data + width * height, Color(0.0f, 0.0f, 0.0f, 0.0f));

  // Lambda function just to draw vertical/horizontal straight lines
  auto drawLine = [&data, width, height, color] (int x1, int y1, int x2, int y2) {
    // Vertical
    if (x1 == x2) {
      if (y2 < y1) {
        std::swap(y1, y2);
      }

      for (int x = x1, y = y1; y <= y2; y++) {
        data[(y * width) + x] = color;
      }
    }

    // Horizontal
    if (y1 == y2) {
      if (x2 < x1) {
        std::swap(x1, x2);
      }

      for (int x = x1, y = y1; x <= x2; x++) {
        data[(y * width) + x] = color;
      }
    }
  };

  // Lambda function to draw actual circle split into 8 parts
  auto drawBresenham = [color, drawLine] (int center_x, int center_y, int x, int y) {
    drawLine(center_x + x, center_y + x, center_x + x, center_y + y);
    drawLine(center_x - x, center_y + x, center_x - x, center_y + y);
    drawLine(center_x + x, center_y - x, center_x + x, center_y - y);
    drawLine(center_x - x, center_y - x, center_x - x, center_y - y);
    drawLine(center_x + x, center_y + x, center_x + y, center_y + x);
    drawLine(center_x - x, center_y + x, center_x - y, center_y + x);
    drawLine(center_x + x, center_y - x, center_x + y, center_y - x);
    drawLine(center_x - x, center_y - x, center_x - y, center_y - x);
  };

  for (int x = 0, y = radius; y >= x; x++) {
    drawBresenham(center_x, center_y, x, y);

    if (decision > 0) {
      y--;
      decision += 4 * (x - y) + 10;
    }
    else {
      decision += 4 * x + 6;
    }
  }

  return data;
}
```

//Edit

Oh wow, I just realized how old this question is.

Body:
I have written an implementation of Bresenham's circle drawing algorithm. This algorithms takes advantage of the highly symmetrical properties of a circle (it only computes points from the 1st octant and draws the other points by taking advantage of symmetry). Therefore I was expecting it to be very fast. The Graphics programming black book, chapter #35 was titled "Bresenham is fast, and fast is good", and though it was about the line drawing algorithm, I could reasonably expect the circle drawing algorithm to also be fast (since the principle is the same).

Here is my java, swing implementation

public static void drawBresenhamsCircle(int r, double width, double height, Graphics g) {
    int x,y,d;
    y = r;
    x = 0;

    drawPoint(x, y, width, height,g);
    d = (3-2*(int)r);
    while (x <= y) {
        if (d <= 0) {
            d = d + (4*x + 6);
        } else {
            d = d + 4*(x-y) + 10;
            y--;
        }
        x++;

        drawPoint(x, y, width, height,g);

        drawPoint(-x, y, width, height,g);
        drawPoint(x, -y, width, height,g);

        drawPoint(-x, -y, width, height,g);
        drawPoint(y, x, width, height,g);
        drawPoint(-y, x, width, height,g);
        drawPoint(y, -x, width, height,g);

        drawPoint(-y, -x, width, height,g);
    }
}

This method uses the following drawPointmethod:

public static void drawPoint(double x, double y,double width,double height, Graphics g) {
    double nativeX = getNativeX(x, width);
    double nativeY = getNativeY(y, height);
    g.fillRect((int)nativeX, (int)nativeY, 1, 1);
}

The two methods getNativeX and getNativeY are used to switch coordinates from originating in the upper left corner of the screen to a system that has it origin in the center of the panel with a more classic axis orientation.

public static double getNativeX(double newX, double width) {
    return newX + (width/2);
}

public static double getNativeY(double newY, double height) {
    return (height/2) - newY;
}

I have also created an implementation of a circle drawing algorithm based on trigonometrical formulaes (x=R*Math.cos(angle)and y= R*Math.sin(angle)) and a third implementation using a call to the standard drawArc method (available on the Graphics object). These additional implementations are for the sole purpose of comparing Bresenham's algorithm to them.

I then created methods to draw a bunch of circles in order to be able to get good measures of the spent time. Here is the method I use to draw a bunch of circles using Bresenham's algorithm

public static void drawABunchOfBresenhamsCircles(int numOfCircles, double width, double height, Graphics g) {
    double r = 5;
    double step = (300.0-5.0)/numOfCircles;

    for (int i = 1; i <= numOfCircles; i++) {
        drawBresenhamsCircle((int)r, width, height, g);
        r += step;
    }
}

Finally I override the paint method of the JPanel I am using, to draw the bunch of circles and to measure the time it took each type to draw. Here is the paint method:

public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D)g;

    g2D.setColor(Color.RED);

    long trigoStartTime = System.currentTimeMillis();
    drawABunchOfTrigonometricalCircles(1000, this.getWidth(), this.getHeight(), g);
    long trigoEndTime = System.currentTimeMillis();
    long trigoDelta = trigoEndTime - trigoStartTime;

    g2D.setColor(Color.BLUE);

    long bresenHamsStartTime = System.currentTimeMillis();
    drawABunchOfBresenhamsCircles(1000, this.getWidth(), this.getHeight(), g);
    long bresenHamsEndTime = System.currentTimeMillis();
    long bresenDelta = bresenHamsEndTime - bresenHamsStartTime;

    g2D.setColor(Color.GREEN);

    long standardStarTime = System.currentTimeMillis();
    drawABunchOfStandardCircles(1000, this.getWidth(), this.getHeight(),g);
    long standardEndTime = System.currentTimeMillis();
    long standardDelta = standardEndTime - standardStarTime;

    System.out.println("Trigo : " + trigoDelta  + " milliseconds");
    System.out.println("Bresenham :" + bresenDelta +  " milliseconds");
    System.out.println("Standard :" + standardDelta +  " milliseconds");
}

Here is the kind of rendering it would generate (drawing 1000 circles of each type)

Unfortunately my Bresenham's implementation is very slow. I took many comparatives measures, and the Bresenham's implementation is not only slower than the Graphics.drawArcbut also slower than the trigonometrical approach. Take a look at the following measures for a various number of circles drawn.

What part of my implementation is more time-consuming? Is there any workaround I could use to improve it? Thanks for helping.

[EDITION]: as requested by @higuaro, here is my trigonometrical algorithm for drawing a circle

public static void drawTrigonometricalCircle (double r, double width, double height, Graphics g) {

    double x0 = 0;
    double y0 = 0;
    boolean isStart = true;

    for (double angle = 0; angle <= 2*Math.PI; angle = angle + Math.PI/36) {

        double x = r * Math.cos(angle);
        double y = r * Math.sin(angle);

        drawPoint((double)x, y, width, height, g);

        if (!isStart) {
            drawLine(x0,  y0, x, y, width, height, g);
        }

        isStart = false;

        x0 = x;
        y0 = y;
    }
}

And the method used to draw a bunch of trigonometrical circles

public static void drawABunchOfTrigonometricalCircles(int numOfCircles, double width, double height, Graphics g) {

    double r = 5;
    double step = (300.0-5.0)/numOfCircles;

    for (int i = 1; i <= numOfCircles; i++) {
        drawTrigonometricalCircle(r, width, height, g);
        r += step;
    }
}

Body:
I lately wrote a bresenham circle drawing implemenation myself for a sprite rasterizer and tried to optimize it a bit. I'm not sure if it will be faster or slower than what you did but i think it should have a pretty decent execution time.

Also unfortunately it is written in C++. If i have time tomorrow i might edit my answer with a ported Java version and an example picture for the result but for now you'd have to do it yourself if you want (or someone else who would want to take his time and edit it.)

Bascically, what it does is use the bresenham algorithm to aquire the positions for the outer edges of the circle, then perform the algorithm for 1/8th of the circle and mirror that for the the remaining 7 parts by drawing straight lines from the center to the outer edge.

Color is just an rgba value

Color* createCircleColorArray(const int radius, const Color& color, int& width, int& height) {
  // Draw circle with custom bresenham variation
  int decision = 3 - (2 * radius);
  int center_x = radius;
  int center_y = radius;
  Color* data;

  // Circle is center point plus radius in each direction high/wide
  width = height = 2 * radius + 1;
  data = new Color[width * height];

  // Initialize data array for transparency
  std::fill(data, data + width * height, Color(0.0f, 0.0f, 0.0f, 0.0f));

  // Lambda function just to draw vertical/horizontal straight lines
  auto drawLine = [&data, width, height, color] (int x1, int y1, int x2, int y2) {
    // Vertical
    if (x1 == x2) {
      if (y2 < y1) {
        std::swap(y1, y2);
      }

      for (int x = x1, y = y1; y <= y2; y++) {
        data[(y * width) + x] = color;
      }
    }

    // Horizontal
    if (y1 == y2) {
      if (x2 < x1) {
        std::swap(x1, x2);
      }

      for (int x = x1, y = y1; x <= x2; x++) {
        data[(y * width) + x] = color;
      }
    }
  };

  // Lambda function to draw actual circle split into 8 parts
  auto drawBresenham = [color, drawLine] (int center_x, int center_y, int x, int y) {
    drawLine(center_x + x, center_y + x, center_x + x, center_y + y);
    drawLine(center_x - x, center_y + x, center_x - x, center_y + y);
    drawLine(center_x + x, center_y - x, center_x + x, center_y - y);
    drawLine(center_x - x, center_y - x, center_x - x, center_y - y);
    drawLine(center_x + x, center_y + x, center_x + y, center_y + x);
    drawLine(center_x - x, center_y + x, center_x - y, center_y + x);
    drawLine(center_x + x, center_y - x, center_x + y, center_y - x);
    drawLine(center_x - x, center_y - x, center_x - y, center_y - x);
  };

  for (int x = 0, y = radius; y >= x; x++) {
    drawBresenham(center_x, center_y, x, y);

    if (decision > 0) {
      y--;
      decision += 4 * (x - y) + 10;
    }
    else {
      decision += 4 * x + 6;
    }
  }

  return data;
}

//Edit

Oh wow, I just realized how old this question is.


问:
When the partition key is the primary key, is it possible that 2 different items are saved into the same partition?
When the partition key is the primary key, is it possible that 2 different items are saved into the same partition?

I checked the documents, and it says dynamodb will calculate the hash value of the partition key to decide which partition an item will be save to.
Is it possible that 2 different items have the same hash value?

答:
Items with different partition key may be saved to the same physical partition.
Depends on how many partitions the table has.
How many partitions = max(table size/10gb, (rcu/3000 + wcu/1000))</p>


问:
Should decltype(1, t) be an l-value reference? (Compilers disagree)
Minimal code:

```<code>int t;
static_assert(is_same_v<decltype(1, t), int&>);
</code>```

The above compiles in g++ and clang++ but fails in MSVC. MSVC seems to think:

```<code>int t;
static_assert(is_same_v<decltype(1, t), int>);
</code>```

Which one does the standard specify? I rely on this pattern quite a bit for SFINAE.

答:
Gcc and Clang are correct. 1, t is comma expression,

The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, E2.

The 2nd operand, i.e. t is an lvalue, then decltype would result in T&.

If the argument is any other expression of type T, and

if the value category of expression is lvalue, then decltype yields T&;

From the standard, [expr.comma]/1:

(emphasis mine)

The type and value of the result are the type and value of the right
  operand; the result is of the same value category as its right
  operand,

and [dcl.type.decltype]/1.5

otherwise, if e is an lvalue, decltype(e) is T&, where T is the type
  of e;

BTW: I tried with MSVC here and got the same result with Gcc and Clang.

Body:
Minimal code:

int t;
static_assert(is_same_v<decltype(1, t), int&>);

The above compiles in g++ and clang++ but fails in MSVC. MSVC seems to think:

int t;
static_assert(is_same_v<decltype(1, t), int>);

Which one does the standard specify? I rely on this pattern quite a bit for SFINAE.


问:
MATLAB: 2D DATA TO 3D ! How to?
I have a 34200 x 4 table. This table shows the 30 years monthly amount of pr (precipitation) in some latitudes and longitudes. So the columns are lat, lon, date, and pr. I want to convert it to a 3D matrix that longitude x latitude x month.
I attach my table.
Please tell me how to do it I'm a beginner. If I don't want to convert it based on the month I could but this issue is so complicated for me.
Please look at my table it's only 235 KB I upload it to my DropBox so please click on Open in the top right side and click download.

Here is my image

答:
If A is your data with the 4 columns [34200x4] then you can create a 3-dimensional matrix like this:

```<code>B = zeros(len(A),3)
B(:, 1) = A(:, 1)
B(:, 2) = A(:, 2)
B(:, 3) = A(:, 3)
</code>```

Possibly even:

```<code>B(:,1:3) = A(:, 1:3)
</code>```

Depending how your data is set, you may need to transpose which is:

```<code>B = 'B
</code>```

You can map data over as long as the dimensions match.

You can implement a for loop if you have even more columns or for dynamic data entries.

Title: MATLAB: 2D DATA TO 3D ! How to?

Body:
If A is your data with the 4 columns [34200x4] then you can create a 3-dimensional matrix like this:

B = zeros(len(A),3)
B(:, 1) = A(:, 1)
B(:, 2) = A(:, 2)
B(:, 3) = A(:, 3)

Possibly even:

B(:,1:3) = A(:, 1:3)

Depending how your data is set, you may need to transpose which is:

B = 'B

You can map data over as long as the dimensions match.

You can implement a for loop if you have even more columns or for dynamic data entries.


问:
event year view in fullcalendar v4
I would like to display year view of events in fullcalendar v4. Year view has been added to full calendar until version 2.2.7. Later version does not have this. So, I decided to create year view using custom view . But I did not get where should I add the html part that display year view in the way we want. This is how I create a view. But listYear plugin able to display all events in the year in list form. I would like to display events in calendar display all month on one view. Is it possible to add our own html table to render in calendar?

```<code>views: {
                    Year: {
                           type      : 'listYear',
                           duration  : {
                                        months: 12
                                       },
                           start     :year+'-01-01',
                           end       :(year+1)+'-01-01',
                           buttonText:'year'
                            }
                }
</code>```

```<code>  document.addEventListener('DOMContentLoaded', function() {

                    var year    =<?php echo $year;?>;
                var event   ='<?php echo json_encode($events);?>';
                event=JSON.parse(event);
                //console.log(event);
                //create event Array
                events_array=[];
                for(i=0;i<event.length;i++)
                {
                    //parameter for event Array-https://fullcalendar.io/docs/event-object
                    start_array=event[i]['start'].split(" ");
                    end_array=event[i]['end'].split(" ");

                    if(start_array[1]==='00:00:00')
                    {
                        start   =start_array[0];
                    }
                    else
                    {
                        start   =event[i]['start'];
                    }
                    if(end_array[1]==='00:00:00')
                    {
                        end     =end_array[0];
                    }
                    else
                    {
                        end     =event[i]['end'];
                    }
                    object_data={
                                         id     :event[i]['id'],
                                         title  :event[i]['remark']+'-'+event[i]['title'],
                                         start  :start,
                                         end    :end,
                                         color  :event[i]['color'],
                                    }
                events_array.push(object_data);
                }

    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
      plugins: ['dayGrid','list'],
      header:
                        {
                            left    : 'prev,next today',
                            center  : 'title',
                            //version 2.2.7 able  to show year view.Year view has been implemented until version 2.2.7.
                            //But , we are using 4 to use valid range (limiting the duration).Valid range available from 3.3.0
                            right   : 'Year,dayGridMonth,dayGridWeek,dayGridDay,listMonth'
                        },
            views: {
                        Year: {
                         /* type: 'timelineYear',*/
                          type: 'listYear',
                          duration: { months: 12
                                        /*weeks:1*/ },
                            start:year+'-01-01',
                            end: (year+1)+'-01-01',
                            /*intervalStart: $.fullCalendar.moment(year+'-01-01'),
                            intervalEnd: $.fullCalendar.moment((year+1)+'-01-01'),*/

                          buttonText: 'year'
                                }
                    },
            defaultDate: year+'-01-01',
                        //set the year range limit - fullcalendar.min.js v3.3.0 & above support this
                        validRange: {
                                        start   : year+'-01-01',
                                        end     : (year+1)+'-01-01'
                                    },
                        defaultView : 'dayGridMonth',
                        editable    : false,//disable drag
                        events      : events_array,

                        //from [https://stackoverflow.com/questions/45698134/dayrender-not-properly-working-in-fullcalendar-on-given-dates]
                         dayRender: function (date, cell)
                         {
                            var disabledDates = ["2016-02-10", "2016-02-15"];
                            //$.inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.
                            /*if ($.inArray(date.format("YYYY-MM-DD"), disabledDates) > -1)
                            {
                                cell.css("background-color", "green");
                            }
                            */
                        }

    });

    calendar.render();
  });
</code>```

Thanks in advance

答:
My aim is to use version 3 and above since it support the valid range function and version 3 custom view is quite understandable. So, I had use version 3 to do year view. This year view limited for only one year that consist of 12 months. Declare custom view in fullcalendar instantiation.

views:
                      {
                          CustomView:
                          {
                              type: 'custom',
                          }
                      }

Declare a button year in header for custom year view . Then in customButtons:, define what happen when user click this button.

customButtons:
                      {
                          year:
                          {
                              text:'year',
                               click: function()
                               {
                                  $('#calendar').fullCalendar('changeView', 'CustomView');
                                }
                          }
                      }

Then, get reference(FC) to fullcalendar's root namespace  and class(View) that all views inherit from.

var FC      =$.fullCalendar;
  var View    =FC.View;

Build the view inside render: function() of our class CustomView. Create table containing 12 field (3 columns and 4 rows) and append to fc-view. Then ,arrange each event in object with required informations and add to events_array.events_array contain objects of events. Get next 12 months start from which period month start in array months. Then, loop in months array and instantiate fullcalendar view in each field in that table created by using the id. Id is value from months(ex:'january_2019'). Set the duration one month and pass in the events array. So, each field show the view for one month together with the events. 12 fields shows view for 12 months.

CustomView = View.extend(
                  {
                      render: function()
                      { }}

Register our class with the view system.

FC.views.custom = CustomView;

```<code><?php
require_once('bdd.php');
// information from sql
// $event_2 is events array
// $event_3 are array of earliest event start and latest event end date, chosen period start and end date,
?>
 <html>
  <head>
   <style>
         #container
         {
            width: 100%;
            position: relative;
         }
        #calendar
        {
             width: 900px; /*can be in percentage also.*/
            height: auto;
            margin: 0 auto;
            padding: 10px;
            position: relative;
        }
        td.fc-sun
        {
            background-color: #535450 !important;
        }
    </style>
    <script src="js/jquery.js"></script>
     <script src="js/bootstrap.min.js"></script>
     <script src='js/moment.min.js'></script>
     <script src='v_3/fullcalendar.min.js'></script>
    <link rel="stylesheet" href="v_3/fullcalendar.min.css" />
    <script>
        $(document).ready(function()
        {

            var event       ='<?php echo json_encode($events_2);?>';
            event           =JSON.parse(event);
            limit           ='<?php echo json_encode($events_3);?>';
            limit           =JSON.parse(limit);
            events_array=[];
                for(i=0;i<event.length;i++)
                {
                    //parameter for event Array-https://fullcalendar.io/docs/event-object
                    start_array=event[i]['start'].split(" ");
                    end_array=event[i]['end'].split(" ");

                    if(start_array[1]==='00:00:00')
                    {
                        start   =start_array[0];
                    }
                    else
                    {
                        start   =event[i]['start'];
                    }
                    if(end_array[1]==='00:00:00')
                    {
                        end     =end_array[0];
                    }
                    else
                    {
                        end     =event[i]['end'];
                    }
                    console.log(start+'=>'+end);
                    object_data=
                    {
                        id      :event[i]['id'],
                        title   :event[i]['remark']+'-'+event[i]['title'],
                        start   :start,
                        end :end,
                        color   :event[i]['color'],
                    }
                    events_array.push(object_data);
                }

                $('#calendar').fullCalendar
                ({
                    defaultDate: limit[0]['earliest'],
                    validRange: {
                                        start   : limit[0]['earliest'],
                                        end     : limit[0]['final']
                                    },
                    header      :
                                {
                                    left    :'prev,next,today',
                                    center  :'title',
                                    right   :'year,agendaWeek,month'
                                },

                    events      : events_array,
                    customButtons:
                    {
                        year:
                        {
                            text:'year',
                             click: function()
                             {
                                $('#calendar').fullCalendar('changeView', 'CustomView');
                              }
                        }
                    },
                    views:
                    {
                        CustomView:
                        {
                            type: 'custom',
                        }
                    }
                })

            var view = $('#calendar').fullCalendar('getView');

            //custom view:
            var FC      = $.fullCalendar; //a reference to FullCalendar's root namespace
            var View    =FC.View;  //the class that all views must inherit from
            var CustomView;          //our subclass
            start_year  =limit[0]['earliest'].split("-")[0];
            end_year    =limit[0]['final'].split("-")[0];
            start_month =parseInt(limit[0]['fye_start'].split("-")[1]);

            CustomView = View.extend(
                {
                    render: function()
                    {
                        $('.fc-prev-button').addClass('fc-state-disabled');
                        $('.fc-next-button').addClass('fc-state-disabled');

                        //change the title
                        document.getElementsByClassName("fc-center")[0].getElementsByTagName('h2')[0].innerHTML = start_year;

                        //https://stackoverflow.com/questions/10832179/result-of-getting-next-12-months-in-javascript-is-messed-up
                        var months  =getNext12MonthNamesWithYear(limit[0]['fye_start']);
                        var table   ='<table align="center" style="width:100%">';
                        var m=0;
                        for(i=1;i<=4;i++)
                        {
                            table+='<tr>';
                            for(j=1;j<=3;j++)
                            {
                                table+='<td height="100"><div id="'+months[m]+'"></div></td>';
                                m++;
                            }
                            table+='</tr>';
                        }
                        table+='</table>';
                        $('.fc-view').append(table);
                        for(n=0;n<months.length;n++)
                        {
                            year =months[n].split("_")[1];
                            month=months[n].split("_")[0];
                            //https://stackoverflow.com/questions/13566552/easiest-way-to-convert-month-name-to-month-number-in-js-jan-01/27805696
                            month=getMonthFromString(month);//convert month string to month no

                            //month compulsory to have 2 digit
                            if(month>=10)
                            {
                                c=month;
                            }
                            else
                            {
                                c='0'+month;
                            }

                            $('#'+months[n]).fullCalendar
                            (
                                {
                                    header:
                                    {
                                        left:   '',
                                        center: 'title',
                                        right:  ''
                                    },
                                    events      : events_array,
                                    defaultDate : year+'-'+(c)+'-01',
                                    //set the year range limit - fullcalendar.min.js v3.3.1 & above support this
                                    defaultView:'month',
                                    duration:
                                    {
                                        months: 1
                                    }
                                })
                        }
                    },
                }
            )
            FC.views.custom = CustomView; // register our class with the view system*/
            })

function getNext12MonthNamesWithYear(date)
{
    var now = new Date(date);
    var month = now.getMonth();
    var year = now.getFullYear();

    var names = ['January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'];

    var res = [];
    for (var i = 0; i < 12; ++i)
    {
        res.push(names[month] + '_' + year);
        if (++month === 12)
        {
            month = 0;
            ++year;
        }
    }
    return res;
}
function getMonthFromString(mon)
{
    return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}
    </script>
</head>
<body>
     <div id='calendar'></div>
</body>
</code>```

Looking forward for better solution.

Title: event year view in fullcalendar v4

Body:
I would like to display year view of events in fullcalendar v4. Year view has been added to full calendar until version 2.2.7. Later version does not have this. So, I decided to create year view using custom view . But I did not get where should I add the html part that display year view in the way we want. This is how I create a view. But listYear plugin able to display all events in the year in list form. I would like to display events in calendar display all month on one view. Is it possible to add our own html table to render in calendar?

views: {
                    Year: {
                           type      : 'listYear',
                           duration  : {
                                        months: 12
                                       },
                           start     :year+'-01-01',
                           end       :(year+1)+'-01-01',
                           buttonText:'year'
                            }
                }

  document.addEventListener('DOMContentLoaded', function() {

                    var year    =<?php echo $year;?>;
                var event   ='<?php echo json_encode($events);?>';
                event=JSON.parse(event);
                //console.log(event);
                //create event Array
                events_array=[];
                for(i=0;i<event.length;i++)
                {
                    //parameter for event Array-https://fullcalendar.io/docs/event-object
                    start_array=event[i]['start'].split(" ");
                    end_array=event[i]['end'].split(" ");

                    if(start_array[1]==='00:00:00')
                    {
                        start   =start_array[0];
                    }
                    else
                    {
                        start   =event[i]['start'];
                    }
                    if(end_array[1]==='00:00:00')
                    {
                        end     =end_array[0];
                    }
                    else
                    {
                        end     =event[i]['end'];
                    }
                    object_data={
                                         id     :event[i]['id'],
                                         title  :event[i]['remark']+'-'+event[i]['title'],
                                         start  :start,
                                         end    :end,
                                         color  :event[i]['color'],
                                    }
                events_array.push(object_data);
                }

    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
      plugins: ['dayGrid','list'],
      header:
                        {
                            left    : 'prev,next today',
                            center  : 'title',
                            //version 2.2.7 able  to show year view.Year view has been implemented until version 2.2.7.
                            //But , we are using 4 to use valid range (limiting the duration).Valid range available from 3.3.0
                            right   : 'Year,dayGridMonth,dayGridWeek,dayGridDay,listMonth'
                        },
            views: {
                        Year: {
                         /* type: 'timelineYear',*/
                          type: 'listYear',
                          duration: { months: 12
                                        /*weeks:1*/ },
                            start:year+'-01-01',
                            end: (year+1)+'-01-01',
                            /*intervalStart: $.fullCalendar.moment(year+'-01-01'),
                            intervalEnd: $.fullCalendar.moment((year+1)+'-01-01'),*/

                          buttonText: 'year'
                                }
                    },
            defaultDate: year+'-01-01',
                        //set the year range limit - fullcalendar.min.js v3.3.0 & above support this
                        validRange: {
                                        start   : year+'-01-01',
                                        end     : (year+1)+'-01-01'
                                    },
                        defaultView : 'dayGridMonth',
                        editable    : false,//disable drag
                        events      : events_array,

                        //from [https://stackoverflow.com/questions/45698134/dayrender-not-properly-working-in-fullcalendar-on-given-dates]
                         dayRender: function (date, cell)
                         {
                            var disabledDates = ["2016-02-10", "2016-02-15"];
                            //$.inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.
                            /*if ($.inArray(date.format("YYYY-MM-DD"), disabledDates) > -1)
                            {
                                cell.css("background-color", "green");
                            }
                            */
                        }

    });

    calendar.render();
  });

Thanks in advance

Body:
My aim is to use version 3 and above since it support the valid range function and version 3 custom view is quite understandable. So, I had use version 3 to do year view. This year view limited for only one year that consist of 12 months. Declare custom view in fullcalendar instantiation.

views:
                      {
                          CustomView:
                          {
                              type: 'custom',
                          }
                      }

Declare a button year in header for custom year view . Then in customButtons:, define what happen when user click this button.

customButtons:
                      {
                          year:
                          {
                              text:'year',
                               click: function()
                               {
                                  $('#calendar').fullCalendar('changeView', 'CustomView');
                                }
                          }
                      }

Then, get reference(FC) to fullcalendar's root namespace  and class(View) that all views inherit from.

var FC      =$.fullCalendar;
  var View    =FC.View;

Build the view inside render: function() of our class CustomView. Create table containing 12 field (3 columns and 4 rows) and append to fc-view. Then ,arrange each event in object with required informations and add to events_array.events_array contain objects of events. Get next 12 months start from which period month start in array months. Then, loop in months array and instantiate fullcalendar view in each field in that table created by using the id. Id is value from months(ex:'january_2019'). Set the duration one month and pass in the events array. So, each field show the view for one month together with the events. 12 fields shows view for 12 months.

CustomView = View.extend(
                  {
                      render: function()
                      { }}

Register our class with the view system.

FC.views.custom = CustomView;

<?php
require_once('bdd.php');
// information from sql
// $event_2 is events array
// $event_3 are array of earliest event start and latest event end date, chosen period start and end date,
?>
 <html>
  <head>
   <style>
         #container
         {
            width: 100%;
            position: relative;
         }
        #calendar
        {
             width: 900px; /*can be in percentage also.*/
            height: auto;
            margin: 0 auto;
            padding: 10px;
            position: relative;
        }
        td.fc-sun
        {
            background-color: #535450 !important;
        }
    </style>
    <script src="js/jquery.js"></script>
     <script src="js/bootstrap.min.js"></script>
     <script src='js/moment.min.js'></script>
     <script src='v_3/fullcalendar.min.js'></script>
    <link rel="stylesheet" href="v_3/fullcalendar.min.css" />
    <script>
        $(document).ready(function()
        {

            var event       ='<?php echo json_encode($events_2);?>';
            event           =JSON.parse(event);
            limit           ='<?php echo json_encode($events_3);?>';
            limit           =JSON.parse(limit);
            events_array=[];
                for(i=0;i<event.length;i++)
                {
                    //parameter for event Array-https://fullcalendar.io/docs/event-object
                    start_array=event[i]['start'].split(" ");
                    end_array=event[i]['end'].split(" ");

                    if(start_array[1]==='00:00:00')
                    {
                        start   =start_array[0];
                    }
                    else
                    {
                        start   =event[i]['start'];
                    }
                    if(end_array[1]==='00:00:00')
                    {
                        end     =end_array[0];
                    }
                    else
                    {
                        end     =event[i]['end'];
                    }
                    console.log(start+'=>'+end);
                    object_data=
                    {
                        id      :event[i]['id'],
                        title   :event[i]['remark']+'-'+event[i]['title'],
                        start   :start,
                        end :end,
                        color   :event[i]['color'],
                    }
                    events_array.push(object_data);
                }

                $('#calendar').fullCalendar
                ({
                    defaultDate: limit[0]['earliest'],
                    validRange: {
                                        start   : limit[0]['earliest'],
                                        end     : limit[0]['final']
                                    },
                    header      :
                                {
                                    left    :'prev,next,today',
                                    center  :'title',
                                    right   :'year,agendaWeek,month'
                                },

                    events      : events_array,
                    customButtons:
                    {
                        year:
                        {
                            text:'year',
                             click: function()
                             {
                                $('#calendar').fullCalendar('changeView', 'CustomView');
                              }
                        }
                    },
                    views:
                    {
                        CustomView:
                        {
                            type: 'custom',
                        }
                    }
                })

            var view = $('#calendar').fullCalendar('getView');

            //custom view:
            var FC      = $.fullCalendar; //a reference to FullCalendar's root namespace
            var View    =FC.View;  //the class that all views must inherit from
            var CustomView;          //our subclass
            start_year  =limit[0]['earliest'].split("-")[0];
            end_year    =limit[0]['final'].split("-")[0];
            start_month =parseInt(limit[0]['fye_start'].split("-")[1]);

            CustomView = View.extend(
                {
                    render: function()
                    {
                        $('.fc-prev-button').addClass('fc-state-disabled');
                        $('.fc-next-button').addClass('fc-state-disabled');

                        //change the title
                        document.getElementsByClassName("fc-center")[0].getElementsByTagName('h2')[0].innerHTML = start_year;

                        //https://stackoverflow.com/questions/10832179/result-of-getting-next-12-months-in-javascript-is-messed-up
                        var months  =getNext12MonthNamesWithYear(limit[0]['fye_start']);
                        var table   ='<table align="center" style="width:100%">';
                        var m=0;
                        for(i=1;i<=4;i++)
                        {
                            table+='<tr>';
                            for(j=1;j<=3;j++)
                            {
                                table+='<td height="100"><div id="'+months[m]+'"></div></td>';
                                m++;
                            }
                            table+='</tr>';
                        }
                        table+='</table>';
                        $('.fc-view').append(table);
                        for(n=0;n<months.length;n++)
                        {
                            year =months[n].split("_")[1];
                            month=months[n].split("_")[0];
                            //https://stackoverflow.com/questions/13566552/easiest-way-to-convert-month-name-to-month-number-in-js-jan-01/27805696
                            month=getMonthFromString(month);//convert month string to month no

                            //month compulsory to have 2 digit
                            if(month>=10)
                            {
                                c=month;
                            }
                            else
                            {
                                c='0'+month;
                            }

                            $('#'+months[n]).fullCalendar
                            (
                                {
                                    header:
                                    {
                                        left:   '',
                                        center: 'title',
                                        right:  ''
                                    },
                                    events      : events_array,
                                    defaultDate : year+'-'+(c)+'-01',
                                    //set the year range limit - fullcalendar.min.js v3.3.1 & above support this
                                    defaultView:'month',
                                    duration:
                                    {
                                        months: 1
                                    }
                                })
                        }
                    },
                }
            )
            FC.views.custom = CustomView; // register our class with the view system*/
            })

function getNext12MonthNamesWithYear(date)
{
    var now = new Date(date);
    var month = now.getMonth();
    var year = now.getFullYear();

    var names = ['January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'];

    var res = [];
    for (var i = 0; i < 12; ++i)
    {
        res.push(names[month] + '_' + year);
        if (++month === 12)
        {
            month = 0;
            ++year;
        }
    }
    return res;
}
function getMonthFromString(mon)
{
    return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}
    </script>
</head>
<body>
     <div id='calendar'></div>
</body>

Looking forward for better solution.


问:
Vscode multi-line edit/select on linux mint
I checked other questions/answers. Didn't seem to work out for me.

Back when I was running windows 10, I could simply hold ctrl and select  multiple lines. But since I moved to linux (Linux mint to be precise) that command doesn't seem to work. Also tried:

alt keyed and select. (didn't work)
ctrl+shift+alt while selecting. Didn't work too.

Would appreciate if my question gets answered. Its kinda stressful to edit eaxh line separately.

答:
You can use below key combination to edit multi lines in Visual Studio Code:

Linux: Shift + Alt + Arrow Keys

Mac: Opt + Cmd + Arrow Keys

Windows: Ctrl + Alt + Arrow Keys

Reference


问:
How to supply the Libnet header to Nemesis during installation?
I'm trying to install Nemesis on Fedora 31, but it throws the error below.

How can I supply the Libnet header during installation?

```<code>root@dk:/usr/nembuild/nemesis-1.4$ ./configure
  --with-libnet-includes=/usr/nembuild/Libnet-1.0.2a/include
  --with-libnet-libraries=/usr/nembuild/Libnet-1.0.2a/lib
</code>```

checking arpa/inet.h usability... yes

  checking arpa/inet.h presence... yes

  checking for arpa/inet.h... yes

  checking netinet/in.h usability... yes

  checking netinet/in.h presence... yes

  checking for netinet/in.h... yes

  checking libnet.h usability... no

  checking libnet.h presence... no

  checking for libnet.h... no

ERROR!  Libnet header not found, go get it from

  http://www.packetfactory.net/projects/libnet/

  or use the --with-libnet-* options, if you have it installed

  in unusual place

答:
You could try this (it uses the libnet10-devel package from your Fedora 31):

yum install libnet10-devel

sed -e 's/libnet-config/libnet10-config/g' -e 's/-lnet/-lnet10/g' -i configure

./configure

make

Body:
I'm trying to install Nemesis on Fedora 31, but it throws the error below.

How can I supply the Libnet header during installation?

root@dk:/usr/nembuild/nemesis-1.4$ ./configure
  --with-libnet-includes=/usr/nembuild/Libnet-1.0.2a/include
  --with-libnet-libraries=/usr/nembuild/Libnet-1.0.2a/lib

checking arpa/inet.h usability... yes

  checking arpa/inet.h presence... yes

  checking for arpa/inet.h... yes

  checking netinet/in.h usability... yes

  checking netinet/in.h presence... yes

  checking for netinet/in.h... yes

  checking libnet.h usability... no

  checking libnet.h presence... no

  checking for libnet.h... no

ERROR!  Libnet header not found, go get it from

  http://www.packetfactory.net/projects/libnet/

  or use the --with-libnet-* options, if you have it installed

  in unusual place