问:
Xamarin - How to set/change VideoView display preview orientation
I copied a code from here https://developer.xamarin.com/recipes/android/media/video/record_video/, an instruction on making videostream and I am trying to change some part of it.

I already tried to change the output orientation to 90 using SetOrientationHint(90)

But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?

I already tried the rotation in xml and code but the preview became a total black.

This is the code

```<code>[Activity(Label = "App2", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
    string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
    MediaRecorder recorder;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        //Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        var record = FindViewById<Button>(Resource.Id.Record);
        var stop = FindViewById<Button>(Resource.Id.Stop);
        var play = FindViewById<Button>(Resource.Id.Play);
        var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);
        //video.Rotation = 90;

        record.Click += delegate
        {
            if (recorder == null)
                recorder = startRecording(video);
            else
                Toast.MakeText(this, "Now recording", 0).Show();
        };

        stop.Click += delegate
        {
            if (recorder != null)
            {
                stopRecording(recorder);
                recorder = null;
            }
            else
                Toast.MakeText(this, "No video recording", 0).Show();
        };

        play.Click += delegate
        {
            if (path != null)
                playVideo(video);
            else
                Toast.MakeText(this, "No video available", 0).Show();
        };

        //recorder = startRecording(video);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        if (recorder != null)
        {
            recorder.Release();
            recorder.Dispose();
            recorder = null;
        }
    }

    private void playVideo(VideoView video)
    {
        var uri = Android.Net.Uri.Parse(path);
        video.SetVideoURI(uri);
        video.Start();
    }

    private static void stopRecording(MediaRecorder recorder)
    {
        if (recorder != null)
        {
            recorder.Stop();
            recorder.Release();
        }
    }

    private MediaRecorder startRecording(VideoView video)
    {
        MediaRecorder recorder;
        video.StopPlayback();

        //video.Holder.AddCallback(this);
        //video.Holder.SetType(SurfaceType.PushBuffers);

        recorder = new MediaRecorder();
        recorder.SetVideoSource(VideoSource.Camera);
        recorder.SetAudioSource(AudioSource.Mic);
        recorder.SetOutputFormat(OutputFormat.Default);
        recorder.SetVideoEncoder(VideoEncoder.Default);
        recorder.SetAudioEncoder(AudioEncoder.Default);
        recorder.SetOutputFile(path);
        recorder.SetOrientationHint(90);
        recorder.SetPreviewDisplay(video.Holder.Surface);
        if (recorder!=null)
        {
            try
            {
                recorder.Prepare();
                recorder.Start();
            }
            catch (Exception)
            {
                Toast.MakeText(this, "Exception!", 0).Show();
            }
        }
        return recorder;
    }

    public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
    {
        throw new NotImplementedException();
    }

    public void SurfaceCreated(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }

    public void SurfaceDestroyed(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }
}
</code>```

UPDATE

@Elvis Xia's answer helped a lot.

Here is the new code

```<code>[Activity(Label = "App2", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
    string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
    MediaRecorder recorder;
    Android.Hardware.Camera mCamera; //Android.Hardware is used because it will have
                                     //problem with Android.Graphics

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        //Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        var record = FindViewById<Button>(Resource.Id.Record);
        var stop = FindViewById<Button>(Resource.Id.Stop);
        var play = FindViewById<Button>(Resource.Id.Play);
        var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);

        record.Click += delegate
        {
            if (recorder == null)
                recorder = startRecording(video);
            else
                Toast.MakeText(this, "Now recording", 0).Show();
        };

        stop.Click += delegate
        {
            if (recorder != null)
            {
                stopRecording(recorder, mCamera);
                recorder = null;
            }
            else
                Toast.MakeText(this, "No video recording", 0).Show();
        };

        play.Click += delegate
        {
            if (path != null)
                playVideo(video);
            else
                Toast.MakeText(this, "No video available", 0).Show();
        };

        //recorder = startRecording(video);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        if (recorder != null)
        {
            recorder.Release();
            recorder.Dispose();
            recorder = null;
        }
    }

    private void playVideo(VideoView video)
    {
        var uri = Android.Net.Uri.Parse(path);
        video.SetVideoURI(uri);
        video.Start();
    }

    private static void stopRecording(MediaRecorder recorder, Android.Hardware.Camera mCamera)
    {
        if (recorder != null)
        {
            recorder.Stop();
            recorder.Release();
            mCamera.StopPreview();
            mCamera.Release();
        }
    }

    private MediaRecorder startRecording(VideoView video)
    {
        MediaRecorder recorder;
        video.StopPlayback();

        //video.Holder.AddCallback(this);
        //video.Holder.SetType(SurfaceType.PushBuffers);

        recorder = new MediaRecorder();
        mCamera = GetCameraInstance();
        mCamera.SetDisplayOrientation(90);
        mCamera.Unlock();
        recorder.SetCamera(mCamera);
        recorder.SetVideoSource(VideoSource.Camera);
        recorder.SetAudioSource(AudioSource.Mic);
        recorder.SetOutputFormat(OutputFormat.Default);
        recorder.SetVideoEncoder(VideoEncoder.Default);
        recorder.SetAudioEncoder(AudioEncoder.Default);
        recorder.SetOutputFile(path);
        recorder.SetOrientationHint(90);
        recorder.SetPreviewDisplay(video.Holder.Surface);
        if (recorder!=null)
        {
            try
            {
                recorder.Prepare();
                recorder.Start();
            }
            catch (Exception)
            {
                Toast.MakeText(this, "Exception!", 0).Show();
            }
        }
        return recorder;
    }

    public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
    {
        throw new NotImplementedException();
    }

    public void SurfaceCreated(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }

    public void SurfaceDestroyed(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }

    public static Android.Hardware.Camera GetCameraInstance()
    {
        Android.Hardware.Camera c = null;
        try
        {
            c = Android.Hardware.Camera.Open();
        }
        catch (Exception e)
        {

        }
        return c;
    }
}
</code>```

答:
But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?

You need to associate Camera with MediaRecorder after setting the rotation degree:

get an Camera Instacnce through GetCameraInstace:

```<code>public static Camera GetCameraInstance()
{
    Camera c = null;
    try
    {
        c = Camera.Open();
    }
    catch (Exception e)
    {

    }
    return c;
}
</code>```

In MainActivity.cs record button click event, associate the camera with MediaRecorder and set the orientation before mCamera.Unlock:

```<code>Camera mCamera
...

recorder = new MediaRecorder();
mCamera = ClassName.GetCameraInstance(); //ClassName if in different class.
                                         //else just GetCameraInstance();
mCamera.SetDisplayOrientation(90);
mCamera.Unlock();
recorder.SetCamera(mCamera);

recorder.SetVideoSource(VideoSource.Camera);
</code>```

Body:
I copied a code from here https://developer.xamarin.com/recipes/android/media/video/record_video/, an instruction on making videostream and I am trying to change some part of it.

I already tried to change the output orientation to 90 using SetOrientationHint(90)

But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?

I already tried the rotation in xml and code but the preview became a total black.

This is the code

[Activity(Label = "App2", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
    string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
    MediaRecorder recorder;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        //Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        var record = FindViewById<Button>(Resource.Id.Record);
        var stop = FindViewById<Button>(Resource.Id.Stop);
        var play = FindViewById<Button>(Resource.Id.Play);
        var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);
        //video.Rotation = 90;

        record.Click += delegate
        {
            if (recorder == null)
                recorder = startRecording(video);
            else
                Toast.MakeText(this, "Now recording", 0).Show();
        };

        stop.Click += delegate
        {
            if (recorder != null)
            {
                stopRecording(recorder);
                recorder = null;
            }
            else
                Toast.MakeText(this, "No video recording", 0).Show();
        };

        play.Click += delegate
        {
            if (path != null)
                playVideo(video);
            else
                Toast.MakeText(this, "No video available", 0).Show();
        };

        //recorder = startRecording(video);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        if (recorder != null)
        {
            recorder.Release();
            recorder.Dispose();
            recorder = null;
        }
    }

    private void playVideo(VideoView video)
    {
        var uri = Android.Net.Uri.Parse(path);
        video.SetVideoURI(uri);
        video.Start();
    }

    private static void stopRecording(MediaRecorder recorder)
    {
        if (recorder != null)
        {
            recorder.Stop();
            recorder.Release();
        }
    }

    private MediaRecorder startRecording(VideoView video)
    {
        MediaRecorder recorder;
        video.StopPlayback();

        //video.Holder.AddCallback(this);
        //video.Holder.SetType(SurfaceType.PushBuffers);

        recorder = new MediaRecorder();
        recorder.SetVideoSource(VideoSource.Camera);
        recorder.SetAudioSource(AudioSource.Mic);
        recorder.SetOutputFormat(OutputFormat.Default);
        recorder.SetVideoEncoder(VideoEncoder.Default);
        recorder.SetAudioEncoder(AudioEncoder.Default);
        recorder.SetOutputFile(path);
        recorder.SetOrientationHint(90);
        recorder.SetPreviewDisplay(video.Holder.Surface);
        if (recorder!=null)
        {
            try
            {
                recorder.Prepare();
                recorder.Start();
            }
            catch (Exception)
            {
                Toast.MakeText(this, "Exception!", 0).Show();
            }
        }
        return recorder;
    }

    public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
    {
        throw new NotImplementedException();
    }

    public void SurfaceCreated(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }

    public void SurfaceDestroyed(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }
}

UPDATE

@Elvis Xia's answer helped a lot.

Here is the new code

[Activity(Label = "App2", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity, ISurfaceHolderCallback
{
    string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test.mp4";
    MediaRecorder recorder;
    Android.Hardware.Camera mCamera; //Android.Hardware is used because it will have
                                     //problem with Android.Graphics

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        //Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        var record = FindViewById<Button>(Resource.Id.Record);
        var stop = FindViewById<Button>(Resource.Id.Stop);
        var play = FindViewById<Button>(Resource.Id.Play);
        var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);

        record.Click += delegate
        {
            if (recorder == null)
                recorder = startRecording(video);
            else
                Toast.MakeText(this, "Now recording", 0).Show();
        };

        stop.Click += delegate
        {
            if (recorder != null)
            {
                stopRecording(recorder, mCamera);
                recorder = null;
            }
            else
                Toast.MakeText(this, "No video recording", 0).Show();
        };

        play.Click += delegate
        {
            if (path != null)
                playVideo(video);
            else
                Toast.MakeText(this, "No video available", 0).Show();
        };

        //recorder = startRecording(video);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        if (recorder != null)
        {
            recorder.Release();
            recorder.Dispose();
            recorder = null;
        }
    }

    private void playVideo(VideoView video)
    {
        var uri = Android.Net.Uri.Parse(path);
        video.SetVideoURI(uri);
        video.Start();
    }

    private static void stopRecording(MediaRecorder recorder, Android.Hardware.Camera mCamera)
    {
        if (recorder != null)
        {
            recorder.Stop();
            recorder.Release();
            mCamera.StopPreview();
            mCamera.Release();
        }
    }

    private MediaRecorder startRecording(VideoView video)
    {
        MediaRecorder recorder;
        video.StopPlayback();

        //video.Holder.AddCallback(this);
        //video.Holder.SetType(SurfaceType.PushBuffers);

        recorder = new MediaRecorder();
        mCamera = GetCameraInstance();
        mCamera.SetDisplayOrientation(90);
        mCamera.Unlock();
        recorder.SetCamera(mCamera);
        recorder.SetVideoSource(VideoSource.Camera);
        recorder.SetAudioSource(AudioSource.Mic);
        recorder.SetOutputFormat(OutputFormat.Default);
        recorder.SetVideoEncoder(VideoEncoder.Default);
        recorder.SetAudioEncoder(AudioEncoder.Default);
        recorder.SetOutputFile(path);
        recorder.SetOrientationHint(90);
        recorder.SetPreviewDisplay(video.Holder.Surface);
        if (recorder!=null)
        {
            try
            {
                recorder.Prepare();
                recorder.Start();
            }
            catch (Exception)
            {
                Toast.MakeText(this, "Exception!", 0).Show();
            }
        }
        return recorder;
    }

    public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
    {
        throw new NotImplementedException();
    }

    public void SurfaceCreated(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }

    public void SurfaceDestroyed(ISurfaceHolder holder)
    {
        throw new NotImplementedException();
    }

    public static Android.Hardware.Camera GetCameraInstance()
    {
        Android.Hardware.Camera c = null;
        try
        {
            c = Android.Hardware.Camera.Open();
        }
        catch (Exception e)
        {

        }
        return c;
    }
}

Body:
But since this code do not use the Camera class and just a MediaRecorder class. How can I rotate the display preview because it is giving me a +90degrees and landscape preview?

You need to associate Camera with MediaRecorder after setting the rotation degree:

get an Camera Instacnce through GetCameraInstace:

public static Camera GetCameraInstance()
{
    Camera c = null;
    try
    {
        c = Camera.Open();
    }
    catch (Exception e)
    {

    }
    return c;
}

In MainActivity.cs record button click event, associate the camera with MediaRecorder and set the orientation before mCamera.Unlock:

Camera mCamera
...

recorder = new MediaRecorder();
mCamera = ClassName.GetCameraInstance(); //ClassName if in different class.
                                         //else just GetCameraInstance();
mCamera.SetDisplayOrientation(90);
mCamera.Unlock();
recorder.SetCamera(mCamera);

recorder.SetVideoSource(VideoSource.Camera);


来源: stackexchange

问:
Summing properties in an object array Angular
I am fairly new to Angular and Javascript so am in need of some guidance. I am wanting to work out the sum and average of values within an object array. The objects are pushed into the array through input boxes, here is my code so far:

```<code>var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

$scope.newLog = {};

$scope.logs = [
    {project: "",
     phase: "",
     date: "",
     startTime: "",
     intTime: "",
     endTime: "",
     comments: ""}
];

$scope.saveLog = function(){

    //CREATING DELTA TIME
    var newTimeLog = $scope.newLog;
    var begin = (newTimeLog.startTime).getTime();
    var end = (newTimeLog.endTime).getTime();

    var i = newTimeLog.intTime;
    var ii = parseInt(i);
    var intMilisec = ii*60000;

    if( isNaN(begin) )
        {
            return "";
        }

        if (begin < end) {
            var milisecDiff = end - begin;
        }else{
            var milisecDiff = begin - end;
        }

        var minusInt = milisecDiff - intMilisec;

        var milisec = parseInt((minusInt%1000)/100)
            , seconds = parseInt((minusInt/1000)%60)
            , minutes = parseInt((minusInt/(1000*60))%60)
            , hours = parseInt((minusInt/(1000*60*60))%24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        var deltaFormat = hours + " Hours " + minutes + " Minutes";

    newTimeLog["deltaTime"] = deltaFormat;

    $scope.logs.push($scope.newLog);
    $scope.newLog = {};
};

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += $scope.logs[i].intTime;
    }
    return sum;
};

});
</code>```

So the intSum function is where I am having issues - I am wanting to sum the intTime properties for all the objects. So if object1's intTime = 1, object2's intTime = 2, object3's intTime = 3 the intSum should be 6. However what I am getting from the IntSum currently is 123.

Any help would be greatly appreciated!

答:
Try using parseInt when you sum+=:</p>

```<code>$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += parseInt($scope.logs[i].intTime);
    }
    return sum;
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am fairly new to Angular and Javascript so am in need of some guidance. I am wanting to work out the sum and average of values within an object array. The objects are pushed into the array through input boxes, here is my code so far:

var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

$scope.newLog = {};

$scope.logs = [
    {project: "",
     phase: "",
     date: "",
     startTime: "",
     intTime: "",
     endTime: "",
     comments: ""}
];

$scope.saveLog = function(){

    //CREATING DELTA TIME
    var newTimeLog = $scope.newLog;
    var begin = (newTimeLog.startTime).getTime();
    var end = (newTimeLog.endTime).getTime();

    var i = newTimeLog.intTime;
    var ii = parseInt(i);
    var intMilisec = ii*60000;

    if( isNaN(begin) )
        {
            return "";
        }

        if (begin < end) {
            var milisecDiff = end - begin;
        }else{
            var milisecDiff = begin - end;
        }

        var minusInt = milisecDiff - intMilisec;

        var milisec = parseInt((minusInt%1000)/100)
            , seconds = parseInt((minusInt/1000)%60)
            , minutes = parseInt((minusInt/(1000*60))%60)
            , hours = parseInt((minusInt/(1000*60*60))%24);

        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        var deltaFormat = hours + " Hours " + minutes + " Minutes";

    newTimeLog["deltaTime"] = deltaFormat;

    $scope.logs.push($scope.newLog);
    $scope.newLog = {};
};

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += $scope.logs[i].intTime;
    }
    return sum;
};

});

So the intSum function is where I am having issues - I am wanting to sum the intTime properties for all the objects. So if object1's intTime = 1, object2's intTime = 2, object3's intTime = 3 the intSum should be 6. However what I am getting from the IntSum currently is 123.

Any help would be greatly appreciated!

Body:
Try using parseInt when you sum+=:

$scope.intSum = function(){
    var sum = 0;
    for (var i = 0; i < $scope.logs.length; i++){
        sum += parseInt($scope.logs[i].intTime);
    }
    return sum;
};


问:
How to delete an Azure Table after it is copied to another storage using ADF
I have 100 tables which i want to copy to another storage account frequently. After the copy is over, i want to delete the source tables.  I am able to copy entities inside tables to another storage account using ADF Copy Activity. But couldn't figure out a way to delete the source tables after successful copy.

I am using DataFactory .NET API to create pipelines, datasets etc. I thought of Custom Activity as the solution but not sure how to plug this actvity into pipeline through API ?

Any code samples or suggestions are highly appreciated.

答:
As metioned that we could do that with Custom Activity.

but not sure how to plug this actvity into pipeline through API?

We could use the create or update Pipeline API to create or update the pipeline API.

We could get more info about how to use custom activities in an Azure Data from  this tutorials.

The following is the snippet from the tutorials.

1.Create a custom activity .NET Class Library project implements that IDotNetActivity interface

2.Launch Windows Explorer, and navigate to bin\debug or bin\release folder

3.Zip the all of the file under bin\release folder and upload to the azure storage customactivitycontainer

4.Create Azure Storage linked service

5.Create Azure Batch linked service

We could use the create or update Pipeline API to create a pipeline that uses the custom activity

```<code>{
  "name": "ADFTutorialPipelineCustom",
  "properties": {
    "description": "Use custom activity",
    "activities": [
      {
        "Name": "MyDotNetActivity",
        "Type": "DotNetActivity",
        "Inputs": [
          {
            "Name": "InputDataset"
          }
        ],
        "Outputs": [
          {
            "Name": "OutputDataset"
          }
        ],
        "LinkedServiceName": "AzureBatchLinkedService",
        "typeProperties": {
          "AssemblyName": "MyDotNetActivity.dll",
          "EntryPoint": "MyDotNetActivityNS.MyDotNetActivity",
          "PackageLinkedService": "AzureStorageLinkedService",
          "PackageFile": "customactivitycontainer/MyDotNetActivity.zip",
          "extendedProperties": {
            "SliceStart": "$$Text.Format('{0:yyyyMMddHH-mm}', Time.AddMinutes(SliceStart, 0))"
          }
        },
        "Policy": {
          "Concurrency": 2,
          "ExecutionPriorityOrder": "OldestFirst",
          "Retry": 3,
          "Timeout": "00:30:00",
          "Delay": "00:00:00"
        }
      }
    ],
    "start": "2016-11-16T00:00:00Z",
    "end": "2016-11-16T05:00:00Z",
    "isPaused": false
  }
}
</code>```

About how to operate azure storage table please refer to document.

Body:
As metioned that we could do that with Custom Activity.

but not sure how to plug this actvity into pipeline through API?

We could use the create or update Pipeline API to create or update the pipeline API.

We could get more info about how to use custom activities in an Azure Data from  this tutorials.

The following is the snippet from the tutorials.

1.Create a custom activity .NET Class Library project implements that IDotNetActivity interface

2.Launch Windows Explorer, and navigate to bin\debug or bin\release folder

3.Zip the all of the file under bin\release folder and upload to the azure storage customactivitycontainer

4.Create Azure Storage linked service

5.Create Azure Batch linked service

We could use the create or update Pipeline API to create a pipeline that uses the custom activity

{
  "name": "ADFTutorialPipelineCustom",
  "properties": {
    "description": "Use custom activity",
    "activities": [
      {
        "Name": "MyDotNetActivity",
        "Type": "DotNetActivity",
        "Inputs": [
          {
            "Name": "InputDataset"
          }
        ],
        "Outputs": [
          {
            "Name": "OutputDataset"
          }
        ],
        "LinkedServiceName": "AzureBatchLinkedService",
        "typeProperties": {
          "AssemblyName": "MyDotNetActivity.dll",
          "EntryPoint": "MyDotNetActivityNS.MyDotNetActivity",
          "PackageLinkedService": "AzureStorageLinkedService",
          "PackageFile": "customactivitycontainer/MyDotNetActivity.zip",
          "extendedProperties": {
            "SliceStart": "$$Text.Format('{0:yyyyMMddHH-mm}', Time.AddMinutes(SliceStart, 0))"
          }
        },
        "Policy": {
          "Concurrency": 2,
          "ExecutionPriorityOrder": "OldestFirst",
          "Retry": 3,
          "Timeout": "00:30:00",
          "Delay": "00:00:00"
        }
      }
    ],
    "start": "2016-11-16T00:00:00Z",
    "end": "2016-11-16T05:00:00Z",
    "isPaused": false
  }
}

About how to operate azure storage table please refer to document.


问:
Is it a bad idea to start a thread in init method?
I have a class which acts like a Queue in which I am creating a worker thread. This worker thread would be responsible for processing each item from the queue.

Since an instance of this class should always have a worker thread, I am creating and starting the worker thread in the init method itself.

I would like to know if it is a bad practice to do so.

e.g

```<code>class CustomQueue:

    def __init__(self):
        # some initialization
        self.worker = threading.Thread(target=sometarget)
        self.worker.start()
</code>```

答: It is OK, but you will need to add a __del__ method that stops the thread so that the thread doesn't hang around after the CustomQueue object dissapears. This __del__ method will be called when the CustomQueue instance is garbage collected.

Body:
I have a class which acts like a Queue in which I am creating a worker thread. This worker thread would be responsible for processing each item from the queue.

Since an instance of this class should always have a worker thread, I am creating and starting the worker thread in the init method itself.

I would like to know if it is a bad practice to do so.

e.g

class CustomQueue:

    def __init__(self):
        # some initialization
        self.worker = threading.Thread(target=sometarget)
        self.worker.start()


问:
Sharing a struct safely amongst multiple threads
Under Windows/C++, if I have a struct:

```<code>struct ListItem {
    ListItem* next;
    ListItem* prev;
    ...
}
</code>```

together with multiple threads running in both the main process and in several dynamically loaded DLLs, and all of those threads need to share the above struct, how do I stop them stomping on each other? Something like:

```<code>ListItem* list = ...

A

list->next = ...

B
</code>```

What do I put at A and B to prevent no more than one thread at a time running list->next = ...?

答:
There are two main ways.  One, possibly the simplest, is to simply send each thread it's own copy of the data structure.  This way you won't have to use synchronization to protect the data, since no thread shares another thread's data.

But that won't work in a lot of situations.  Sometimes you really do need to share a common data structure.  In which case, you need to protect the data structure with some form of synchronization object.  Boost.Threads provides some cross-platform ones, and I'm sure someone will show you how to use them.  Since you asked specifically about Windows, I'll show you a Windows way.

You can use a CRITICAL_SECTION.  First, you need to initialize the critical section in your main thread, before you kick off your worker threads:

```<code>int main()
{
// ...
  CRITICAL_SECTION cs;
  InitializeCriticalSection(&cs);
// ...
}
</code>```

Then pass the pointer to the cs to each worker thread. (This is left as an excercise.) In each worker thread, enter the cs before working with your data, and leave it when you're done.

```<code>CRITICAL_SECTION* pcs = ...; // passed in from main thread
EnterCriticalSection(pcs); // this will block until the cs is "available"
list->next = ...
LeaveCriticalSection(pcs); // makes the cs available to other threads
</code>```

The above is psudocode, and has much room for improvement.  For example, the critical section should be wrapped in an RAII object so it is automatically destroyed when you're done with it.  Similarly, the locking and unlocking should also be done in an RAII object so that it is always unlocked no matter how you exit your thread function, even in the face of exceptions.

You should note that a CRITICAL_SECTION can only be used by a single process.  If you need to use a mutex-type object across multiple processes (not what you seem to need here), then you need to use a named mutex instead.

ContentLicense: CC BY-SA 2.5

Body:
Under Windows/C++, if I have a struct:

struct ListItem {
    ListItem* next;
    ListItem* prev;
    ...
}

together with multiple threads running in both the main process and in several dynamically loaded DLLs, and all of those threads need to share the above struct, how do I stop them stomping on each other? Something like:

ListItem* list = ...

A

list->next = ...

B

What do I put at A and B to prevent no more than one thread at a time running list->next = ...?

Body:
There are two main ways.  One, possibly the simplest, is to simply send each thread it's own copy of the data structure.  This way you won't have to use synchronization to protect the data, since no thread shares another thread's data.

But that won't work in a lot of situations.  Sometimes you really do need to share a common data structure.  In which case, you need to protect the data structure with some form of synchronization object.  Boost.Threads provides some cross-platform ones, and I'm sure someone will show you how to use them.  Since you asked specifically about Windows, I'll show you a Windows way.

You can use a CRITICAL_SECTION.  First, you need to initialize the critical section in your main thread, before you kick off your worker threads:

int main()
{
// ...
  CRITICAL_SECTION cs;
  InitializeCriticalSection(&cs);
// ...
}

Then pass the pointer to the cs to each worker thread. (This is left as an excercise.) In each worker thread, enter the cs before working with your data, and leave it when you're done.

CRITICAL_SECTION* pcs = ...; // passed in from main thread
EnterCriticalSection(pcs); // this will block until the cs is "available"
list->next = ...
LeaveCriticalSection(pcs); // makes the cs available to other threads

The above is psudocode, and has much room for improvement.  For example, the critical section should be wrapped in an RAII object so it is automatically destroyed when you're done with it.  Similarly, the locking and unlocking should also be done in an RAII object so that it is always unlocked no matter how you exit your thread function, even in the face of exceptions.

You should note that a CRITICAL_SECTION can only be used by a single process.  If you need to use a mutex-type object across multiple processes (not what you seem to need here), then you need to use a named mutex instead.


问:
Stored procedure is working fine. But when use in SSRS report, I hit an error - Divide by zero error encountered
My stored procedure is working fine when run in SQL Server, but I'm getting an
error when I used it in SSRS.

Below is my stored procedure. I can't find where I'm hitting the error.
But I think it must be near the Case statement.

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[proc_rptAveragePricesFleet]
    @ShipManagerID bigint,
    @PeriodFrom DateTime,
    @PeriodTo DateTime
AS
    DECLARE @ExchangeRate decimal(18, 2)
    DECLARE @tblTotalPrice TABLE
                           (
                               ShipID bigint, ShipName varchar(MAX),
                               CategoryGroupDesc varchar(100),
                               ManagerName varchar(50),
                               PriceGram decimal(18, 2),
                               QuantityGr decimal(18, 2),
                               TotalPrice decimal(18, 2)
                           )
    DECLARE @tblAVGPrice TABLE
                         (
                             ShipID bigint, ShipName varchar(MAX),
                             CategoryGroupDesc varchar(100),
                             ManagerName varchar(50),
                             AveragePrice decimal(18, 2),
                             QuantityGr decimal(18, 2)
                         )

BEGIN
    SET NOCOUNT ON;

    SET @ExchangeRate = ISNULL((SELECT TOP 1 ExchangeRate
                                FROM tblExchangeRate ER
                                INNER JOIN dbo.tblOrderInfoHeader OIH ON ER.FromCurrencyID = OIH.OrderCurrencyID
                                INNER JOIN dbo.tblShips S ON OIH.ShipID = S.ShipID
                                INNER JOIN dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
                                WHERE FromCurrencyID = OIH.SupplierCurrencyID
                                  AND ToCurrencyID =  201
                                  AND EffectivityDate <= OIH.OrderDate
                                  AND SM.ShipsManagerOwnerID = @ShipManagerID
                                  AND OIH.DeliveryDate >= @PeriodFrom
                                  AND OIH.DeliveryDate <= @PeriodTo
                                  AND OIH.IsCashOrder = 0
                                  AND OIH.OrderStatusID <> 11
                              ORDER BY EffectivityDate DESC), 1)

    INSERT INTO @tblTotalPrice (ShipID, ShipName, CategoryGroupDesc, ManagerName, PriceGram, QuantityGr, TotalPrice)
        SELECT
            S.ShipID, S.ShipName,
            CG.CategoryGroupDesc,
            SM.ManagerName,
            CASE
                WHEN OIH.OrderCurrencyID = 201
                   THEN SUM(OID.PriceRequestPrice / OID.WeightInGrams)
                ELSE SUM(OID.PriceRequestPrice * @ExchangeRate / OID.WeightInGrams)
            END AS PriceGram,
            SUM(OID.OrderQuantity * OID.WeightInGrams) AS QuantityGr,
            CASE
               WHEN OIH.OrderCurrencyID = 201
                  THEN SUM((OID.PriceRequestPrice / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
               ELSE SUM(((OID.PriceRequestPrice * @ExchangeRate) / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
            END AS TotalPrice
        FROM
            dbo.tblShips S
        INNER JOIN
            dbo.tblOrderInfoHeader OIH ON S.ShipID = OIH.ShipID
        INNER JOIN
            dbo.tblOrderInfoDetail OID ON OIH.OrderInfoHeaderID = OID.OrderInfoHeaderID
        INNER JOIN
            dbo.tblSuppliersProducts SP ON OID.SuppliersProductsID = SP.SuppliersProductsID
        INNER JOIN
            dbo.tblProducts P ON SP.ProductID = P.ProductID
        INNER JOIN
            dbo.tblSubCategory SC ON P.SubCategoryID = SC.SubCategoryID
        INNER JOIN
            dbo.tblCategory C ON SC.CategoryID = C.CategoryID
        INNER JOIN
            dbo.tblCategoryGroup CG ON C.CategoryGroupID = CG.CategoryGroupID
        INNER JOIN
            dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
        WHERE
            (SM.ShipsManagerOwnerID = @ShipManagerID)
            AND OIH.DeliveryDate >= @PeriodFrom
            AND OIH.DeliveryDate <= @PeriodTo
            AND (OIH.IsCashOrder = 0)
            AND (OIH.OrderStatusID <> 11)
       GROUP BY
           S.ShipID, S.ShipName, CG.CategoryGroupDesc, SM.ManagerName, OIH.OrderCurrencyID
       ORDER BY
           CategoryGroupDesc

    INSERT INTO @tblAVGPrice(ShipID, ShipName, CategoryGroupDesc, ManagerName, AveragePrice, QuantityGr)
        SELECT
            ShipID, ShipName,
            CategoryGroupDesc,
            ManagerName,
            SUM(TotalPrice / (QuantityGr / 1000)) as AveragePrice,
            QuantityGr
        FROM
            @tblTotalPrice
        GROUP BY
            ShipID, ShipName,CategoryGroupDesc, ManagerName,  QuantityGr
        ORDER BY
            CategoryGroupDesc

    SELECT
        ShipID, ShipName,
        CategoryGroupDesc,
        ManagerName,
        AveragePrice, QuantityGr
    FROM
        @tblAVGPrice
    GROUP BY
        ShipID, ShipName,CategoryGroupDesc, ManagerName, AveragePrice,  QuantityGr
    ORDER BY
        CategoryGroupDesc
END
</code>```

答:
You have this column in your temp table:

```<code>SUM(OID.OrderQuantity * OID.WeightInGrams) AS QuantityGr
</code>```

Then you use it in this calculation:

```<code>SUM(TotalPrice / (QuantityGr / 1000)) as AveragePrice
</code>```

So if either OrderQuantity or OID.WeightInGrams are ever 0 that would cause the error.

To address your initial question, SSRS doesn't change the behavior of the procedure in any way. So perhaps you were running it with different parameter values when you got the error? Or were you doing other division in the report expressions that could have caused the error? Just some things to look for.

Body:
My stored procedure is working fine when run in SQL Server, but I'm getting an
error when I used it in SSRS.

Below is my stored procedure. I can't find where I'm hitting the error.
But I think it must be near the Case statement.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[proc_rptAveragePricesFleet]
    @ShipManagerID bigint,
    @PeriodFrom DateTime,
    @PeriodTo DateTime
AS
    DECLARE @ExchangeRate decimal(18, 2)
    DECLARE @tblTotalPrice TABLE
                           (
                               ShipID bigint, ShipName varchar(MAX),
                               CategoryGroupDesc varchar(100),
                               ManagerName varchar(50),
                               PriceGram decimal(18, 2),
                               QuantityGr decimal(18, 2),
                               TotalPrice decimal(18, 2)
                           )
    DECLARE @tblAVGPrice TABLE
                         (
                             ShipID bigint, ShipName varchar(MAX),
                             CategoryGroupDesc varchar(100),
                             ManagerName varchar(50),
                             AveragePrice decimal(18, 2),
                             QuantityGr decimal(18, 2)
                         )

BEGIN
    SET NOCOUNT ON;

    SET @ExchangeRate = ISNULL((SELECT TOP 1 ExchangeRate
                                FROM tblExchangeRate ER
                                INNER JOIN dbo.tblOrderInfoHeader OIH ON ER.FromCurrencyID = OIH.OrderCurrencyID
                                INNER JOIN dbo.tblShips S ON OIH.ShipID = S.ShipID
                                INNER JOIN dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
                                WHERE FromCurrencyID = OIH.SupplierCurrencyID
                                  AND ToCurrencyID =  201
                                  AND EffectivityDate <= OIH.OrderDate
                                  AND SM.ShipsManagerOwnerID = @ShipManagerID
                                  AND OIH.DeliveryDate >= @PeriodFrom
                                  AND OIH.DeliveryDate <= @PeriodTo
                                  AND OIH.IsCashOrder = 0
                                  AND OIH.OrderStatusID <> 11
                              ORDER BY EffectivityDate DESC), 1)

    INSERT INTO @tblTotalPrice (ShipID, ShipName, CategoryGroupDesc, ManagerName, PriceGram, QuantityGr, TotalPrice)
        SELECT
            S.ShipID, S.ShipName,
            CG.CategoryGroupDesc,
            SM.ManagerName,
            CASE
                WHEN OIH.OrderCurrencyID = 201
                   THEN SUM(OID.PriceRequestPrice / OID.WeightInGrams)
                ELSE SUM(OID.PriceRequestPrice * @ExchangeRate / OID.WeightInGrams)
            END AS PriceGram,
            SUM(OID.OrderQuantity * OID.WeightInGrams) AS QuantityGr,
            CASE
               WHEN OIH.OrderCurrencyID = 201
                  THEN SUM((OID.PriceRequestPrice / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
               ELSE SUM(((OID.PriceRequestPrice * @ExchangeRate) / OID.WeightInGrams) * (OID.OrderQuantity * OID.WeightInGrams))
            END AS TotalPrice
        FROM
            dbo.tblShips S
        INNER JOIN
            dbo.tblOrderInfoHeader OIH ON S.ShipID = OIH.ShipID
        INNER JOIN
            dbo.tblOrderInfoDetail OID ON OIH.OrderInfoHeaderID = OID.OrderInfoHeaderID
        INNER JOIN
            dbo.tblSuppliersProducts SP ON OID.SuppliersProductsID = SP.SuppliersProductsID
        INNER JOIN
            dbo.tblProducts P ON SP.ProductID = P.ProductID
        INNER JOIN
            dbo.tblSubCategory SC ON P.SubCategoryID = SC.SubCategoryID
        INNER JOIN
            dbo.tblCategory C ON SC.CategoryID = C.CategoryID
        INNER JOIN
            dbo.tblCategoryGroup CG ON C.CategoryGroupID = CG.CategoryGroupID
        INNER JOIN
            dbo.tblShipsManagerOwner SM ON S.ShipsManagerOwnerID = SM.ShipsManagerOwnerID
        WHERE
            (SM.ShipsManagerOwnerID = @ShipManagerID)
            AND OIH.DeliveryDate >= @PeriodFrom
            AND OIH.DeliveryDate <= @PeriodTo
            AND (OIH.IsCashOrder = 0)
            AND (OIH.OrderStatusID <> 11)
       GROUP BY
           S.ShipID, S.ShipName, CG.CategoryGroupDesc, SM.ManagerName, OIH.OrderCurrencyID
       ORDER BY
           CategoryGroupDesc

    INSERT INTO @tblAVGPrice(ShipID, ShipName, CategoryGroupDesc, ManagerName, AveragePrice, QuantityGr)
        SELECT
            ShipID, ShipName,
            CategoryGroupDesc,
            ManagerName,
            SUM(TotalPrice / (QuantityGr / 1000)) as AveragePrice,
            QuantityGr
        FROM
            @tblTotalPrice
        GROUP BY
            ShipID, ShipName,CategoryGroupDesc, ManagerName,  QuantityGr
        ORDER BY
            CategoryGroupDesc

    SELECT
        ShipID, ShipName,
        CategoryGroupDesc,
        ManagerName,
        AveragePrice, QuantityGr
    FROM
        @tblAVGPrice
    GROUP BY
        ShipID, ShipName,CategoryGroupDesc, ManagerName, AveragePrice,  QuantityGr
    ORDER BY
        CategoryGroupDesc
END

Body:
You have this column in your temp table:

SUM(OID.OrderQuantity * OID.WeightInGrams) AS QuantityGr

Then you use it in this calculation:

SUM(TotalPrice / (QuantityGr / 1000)) as AveragePrice

So if either OrderQuantity or OID.WeightInGrams are ever 0 that would cause the error.

To address your initial question, SSRS doesn't change the behavior of the procedure in any way. So perhaps you were running it with different parameter values when you got the error? Or were you doing other division in the report expressions that could have caused the error? Just some things to look for.


问:
Sorting a file based on a field that's not in a fixed position
i am a newbie in unix sort.
I have a set of data..example of lines:
as i tried sort -n command, it is given me this:
it start with 0_0 and the second one is 10_0, how i can make it to start at 0_0 then follow by 1_0 then 2_0 ....9_0...10_0..11_0...19_0...20_0....etc.?

Here is my input:

```<code>reg_0_0/clk
reg_10_0/clk
reg_11_0/clk
reg_12_0/clk
reg_13_0/clk
reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_1_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_2_0/clk
reg_30_0/clk
reg_31_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
s_reg_0_0/clk
s_reg_10_0/clk
s_reg_11_0/clk
s_reg_12_0/clk
s_reg_13_0/clk
s_reg_14_0/clk
s_reg_15_0/clk
s_reg_16_0/clk
s_reg_17_0/clk
s_reg_18_0/clk
s_reg_19_0/clk
s_reg_1_0/clk
s_reg_20_0/clk
s_reg_21_0/clk
s_reg_22_0/clk
s_reg_23_0/clk
s_reg_24_0/clk
s_reg_25_0/clk
s_reg_26_0/clk
s_reg_27_0/clk
s_reg_28_0/clk
s_reg_29_0/clk
s_reg_2_0/clk
s_reg_30_0/clk
s_reg_31_0/clk
s_reg_3_0/clk
s_reg_4_0/clk
s_reg_5_0/clk
s_reg_6_0/clk
s_reg_7_0/clk
s_reg_8_0/clk
s_reg_9_0/clk
</code>```

答:
The sort command on most modern systems is able to select fields and sort a particular field numerically.  For example:

```<code>sort -t _ -k 2 input.txt
</code>```

This would work for the lines that look like reg_1_0.txt.  Of course, it would not work for the lines that contain an extra underscore before the sort field, like s_reg_1_0.txt, where you would need -k 3.

But there are tricks.

```<code>sed 's/[^0-9]*\([0-9]*\)\(.*\)/\1 &/' input.txt | sort -n | cut -d ' ' -f 2-
</code>```

This rewrites the input file so that the sort field is at the beginning of the line. It then sorts numerically, and then removes the first "field" of each line to restore the look of the original content. All using ubiquitous shell tools.

Body:
i am a newbie in unix sort.
I have a set of data..example of lines:
as i tried sort -n command, it is given me this:
it start with 0_0 and the second one is 10_0, how i can make it to start at 0_0 then follow by 1_0 then 2_0 ....9_0...10_0..11_0...19_0...20_0....etc.?

Here is my input:

reg_0_0/clk
reg_10_0/clk
reg_11_0/clk
reg_12_0/clk
reg_13_0/clk
reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_1_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_2_0/clk
reg_30_0/clk
reg_31_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
s_reg_0_0/clk
s_reg_10_0/clk
s_reg_11_0/clk
s_reg_12_0/clk
s_reg_13_0/clk
s_reg_14_0/clk
s_reg_15_0/clk
s_reg_16_0/clk
s_reg_17_0/clk
s_reg_18_0/clk
s_reg_19_0/clk
s_reg_1_0/clk
s_reg_20_0/clk
s_reg_21_0/clk
s_reg_22_0/clk
s_reg_23_0/clk
s_reg_24_0/clk
s_reg_25_0/clk
s_reg_26_0/clk
s_reg_27_0/clk
s_reg_28_0/clk
s_reg_29_0/clk
s_reg_2_0/clk
s_reg_30_0/clk
s_reg_31_0/clk
s_reg_3_0/clk
s_reg_4_0/clk
s_reg_5_0/clk
s_reg_6_0/clk
s_reg_7_0/clk
s_reg_8_0/clk
s_reg_9_0/clk

Body:
The sort command on most modern systems is able to select fields and sort a particular field numerically.  For example:

sort -t _ -k 2 input.txt

This would work for the lines that look like reg_1_0.txt.  Of course, it would not work for the lines that contain an extra underscore before the sort field, like s_reg_1_0.txt, where you would need -k 3.

But there are tricks.

sed 's/[^0-9]*\([0-9]*\)\(.*\)/\1 &/' input.txt | sort -n | cut -d ' ' -f 2-

This rewrites the input file so that the sort field is at the beginning of the line. It then sorts numerically, and then removes the first "field" of each line to restore the look of the original content. All using ubiquitous shell tools.


问:
How to share .sock file between nginx docker and uwsgi docker?
I'm using docker-compose and now have two docker containers - one is a nginx webserver, whereas the other one is ubuntu with Python uwsgi and Flask.

As I know, the best way to connect nginx and uWSGI is done by sharing a *.sock file between them and pass the requests into the file (And that what I do in older projects where I did not use dockers).

I'm wondering how can I share the sock file between the dockers in order to enable the communication between them?

And at all.. I'm wondering if this scenario of two containers - one for nginx and one for the Flask framework and uWSGI - is best practice and right to do.

Thanks

答:
You don't need to share the sock file with different docker container.

The simple solution is share the socket port between dockers.

In the uwsgi file need to add socket=:3000.

```<code>[uwsgi]

master=true
chdir=.
module=flaskapp

harakiri=60

callable=app
thunder-lock=true
socket=:3000
workers=12
threads=4
chmod-socket=666
vacuum=true
die-on-term=true
pidfile=uwsgi.pid

max-requests=5000

post-buffering=65536
post-buffering-bufsize=524288
</code>```

the define the nginx conf. the uwsgi_pass section flask:3000 means  (docker server name):(docker expose port).

```<code>server {
    listen 80;

    charset     utf-8;
    client_max_body_size 20M;

    location / {
        try_files $uri @slack;
    }

    location @slack {
        include uwsgi_params;
        uwsgi_pass flask:3000;
        uwsgi_read_timeout 60s;
        uwsgi_send_timeout 60s;
        uwsgi_connect_timeout 60s;
    }
}
</code>```

In docker-compose file:

```<code>nginx:
    container_name: nginx
    build:
      context: .
      dockerfile: ./Dockerfile-Nginx
    ports:
      - "80:80"
    depends_on:
      - flask

flask:
    tty: true
    container_name: flask
    build:
      context: .
      dockerfile: ./Dockerfile
    expose:
      - "3000"

    command: uwsgi --ini ./uwsgi.ini
</code>```

So just let the docker run one process for each docker container.

Body:
You don't need to share the sock file with different docker container.

The simple solution is share the socket port between dockers.

In the uwsgi file need to add socket=:3000.

[uwsgi]

master=true
chdir=.
module=flaskapp

harakiri=60

callable=app
thunder-lock=true
socket=:3000
workers=12
threads=4
chmod-socket=666
vacuum=true
die-on-term=true
pidfile=uwsgi.pid

max-requests=5000

post-buffering=65536
post-buffering-bufsize=524288

the define the nginx conf. the uwsgi_pass section flask:3000 means  (docker server name):(docker expose port).

server {
    listen 80;

    charset     utf-8;
    client_max_body_size 20M;

    location / {
        try_files $uri @slack;
    }

    location @slack {
        include uwsgi_params;
        uwsgi_pass flask:3000;
        uwsgi_read_timeout 60s;
        uwsgi_send_timeout 60s;
        uwsgi_connect_timeout 60s;
    }
}

In docker-compose file:

nginx:
    container_name: nginx
    build:
      context: .
      dockerfile: ./Dockerfile-Nginx
    ports:
      - "80:80"
    depends_on:
      - flask

flask:
    tty: true
    container_name: flask
    build:
      context: .
      dockerfile: ./Dockerfile
    expose:
      - "3000"

    command: uwsgi --ini ./uwsgi.ini

So just let the docker run one process for each docker container.


问:
UIScrollView how do you constrain a sub view that acts a container to all the other views?
so as you will see below I have a scrollview and I want to add it the the UIViewControllers root view. When I have it constrained to the top, right, bottom, and left I expect to see the red color take up the whole screen. This obviously works, but I want to add a subview to the scrollview that will wrap all the child views. How would I go about doing that?

I have added the view and I have set the same constraints except this time they are set from the wrapper view to the bounds of the UIScrollView, and the blue background color doesn't show anywhere. Also feel free to point out if this is a bad idea, but I thought I could just have it be constrained to the bottom and it will automatically extend the scrollviews content size as needed. This seems to work when I had all the subviews in the scrollview without a wrapper and the last view would extend the content size.

```<code>    scrollView = UIScrollView(frame: view.bounds)

    scrollView?.showsVerticalScrollIndicator = true
    scrollView?.backgroundColor = .red

    scrollView?.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(scrollView!)

    scrollView?.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView?.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    scrollView?.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    scrollView?.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    //setup wrapper view
    let subviewWrapper = UIView()

    subviewWrapper.translatesAutoresizingMaskIntoConstraints = false

    scrollView?.addSubview(subviewWrapper)

    subviewWrapper.backgroundColor = .blue

    subviewWrapper.topAnchor.constraint(equalTo: (scrollView?.topAnchor)!).isActive = true
    subviewWrapper.leftAnchor.constraint(equalTo: (scrollView?.leftAnchor)!).isActive = true
    subviewWrapper.rightAnchor.constraint(equalTo: (scrollView?.rightAnchor)!).isActive = true
    subviewWrapper.bottomAnchor.constraint(equalTo: (scrollView?.bottomAnchor)!).isActive = true
</code>```

答:
Actually this is a very good idea.  I always set up my scrollViews this way.  I usually call the view contentView, but it is the same idea.

You're almost there.  You haven't yet given Auto Layout anything to go on to figure out the size of your subviewWrapper.  The constraints you've set so far pin the subviewWrapper to the edges of the scrollView's content area, but this just establishes the fact that as the subviewWrapper grows, the content size of the scrollView will expand.  Currently your subviewWrapper has 0 width and 0 height which is why you see no blue.

Below are 3 examples of how you might establish the size of your subviewWrapper.

Note: Each of the following examples is completely independent.  Look at each one separately and as you try them, remember to delete the constraints added by the previous example.

Example 1: Make subviewWrapper 1000 x 1000:

Set constraints to make your subviewWrapper 1000 x 1000 and you will see the blue and it will scroll in both directions.

```<code>subviewWrapper.widthAnchor.constraint(equalToConstant: 1000).isActive = true
subviewWrapper.heightAnchor.constraint(equalToConstant: 1000).isActive = true
</code>```

Example 2: Vertical only scrolling with content size 2X of scrollView height:

If you set the width of your subviewWrapper to be equal to the width of the scrollView then it will only scroll vertically.  If you set the height of subviewWrapper to 2X the height of scrollView, then your blue area will be twice the height of the scrollView.

```<code>subviewWrapper.widthAnchor.constraint(equalTo: scrollView!.widthAnchor, multiplier: 1.0).isActive = true
subviewWrapper.heightAnchor.constraint(equalTo: scrollView!.heightAnchor, multiplier: 2.0).isActive = true
</code>```

Example 3: Size of subviewWrapper set by its subviews:

You can also establish the size of your subviewWrapper by adding subviews to it that are fully specified in size and connected in a chain from the top of subviewWrapper to the bottom, and from side to side.  If you do this, Auto Layout will have enough information to compute the size of your subviewWrapper

In this example, I've added a yellow 600 x 600 square to the subviewWrapper and set it 100 points from each edge.  Without having explicitly set a size for subviewWrapper, Auto Layout can figure out that it is 800 x 800.

```<code>let yellowSquare = UIView()

yellowSquare.translatesAutoresizingMaskIntoConstraints = false
yellowSquare.backgroundColor = .yellow
subviewWrapper.addSubview(yellowSquare)

yellowSquare.widthAnchor.constraint(equalToConstant: 600).isActive = true
yellowSquare.heightAnchor.constraint(equalToConstant: 600).isActive = true

yellowSquare.topAnchor.constraint(equalTo: subviewWrapper.topAnchor, constant: 100).isActive = true
yellowSquare.leadingAnchor.constraint(equalTo: subviewWrapper.leadingAnchor, constant: 100).isActive = true
yellowSquare.trailingAnchor.constraint(equalTo: subviewWrapper.trailingAnchor, constant: -100).isActive = true
yellowSquare.bottomAnchor.constraint(equalTo: subviewWrapper.bottomAnchor, constant: -100).isActive = true
</code>```

Body:
so as you will see below I have a scrollview and I want to add it the the UIViewControllers root view. When I have it constrained to the top, right, bottom, and left I expect to see the red color take up the whole screen. This obviously works, but I want to add a subview to the scrollview that will wrap all the child views. How would I go about doing that?

I have added the view and I have set the same constraints except this time they are set from the wrapper view to the bounds of the UIScrollView, and the blue background color doesn't show anywhere. Also feel free to point out if this is a bad idea, but I thought I could just have it be constrained to the bottom and it will automatically extend the scrollviews content size as needed. This seems to work when I had all the subviews in the scrollview without a wrapper and the last view would extend the content size.

    scrollView = UIScrollView(frame: view.bounds)

    scrollView?.showsVerticalScrollIndicator = true
    scrollView?.backgroundColor = .red

    scrollView?.translatesAutoresizingMaskIntoConstraints = false

    view.addSubview(scrollView!)

    scrollView?.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView?.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    scrollView?.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    scrollView?.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    //setup wrapper view
    let subviewWrapper = UIView()

    subviewWrapper.translatesAutoresizingMaskIntoConstraints = false

    scrollView?.addSubview(subviewWrapper)

    subviewWrapper.backgroundColor = .blue

    subviewWrapper.topAnchor.constraint(equalTo: (scrollView?.topAnchor)!).isActive = true
    subviewWrapper.leftAnchor.constraint(equalTo: (scrollView?.leftAnchor)!).isActive = true
    subviewWrapper.rightAnchor.constraint(equalTo: (scrollView?.rightAnchor)!).isActive = true
    subviewWrapper.bottomAnchor.constraint(equalTo: (scrollView?.bottomAnchor)!).isActive = true

Body:
Actually this is a very good idea.  I always set up my scrollViews this way.  I usually call the view contentView, but it is the same idea.

You're almost there.  You haven't yet given Auto Layout anything to go on to figure out the size of your subviewWrapper.  The constraints you've set so far pin the subviewWrapper to the edges of the scrollView's content area, but this just establishes the fact that as the subviewWrapper grows, the content size of the scrollView will expand.  Currently your subviewWrapper has 0 width and 0 height which is why you see no blue.

Below are 3 examples of how you might establish the size of your subviewWrapper.

Note: Each of the following examples is completely independent.  Look at each one separately and as you try them, remember to delete the constraints added by the previous example.

Example 1: Make subviewWrapper 1000 x 1000:

Set constraints to make your subviewWrapper 1000 x 1000 and you will see the blue and it will scroll in both directions.

subviewWrapper.widthAnchor.constraint(equalToConstant: 1000).isActive = true
subviewWrapper.heightAnchor.constraint(equalToConstant: 1000).isActive = true

Example 2: Vertical only scrolling with content size 2X of scrollView height:

If you set the width of your subviewWrapper to be equal to the width of the scrollView then it will only scroll vertically.  If you set the height of subviewWrapper to 2X the height of scrollView, then your blue area will be twice the height of the scrollView.

subviewWrapper.widthAnchor.constraint(equalTo: scrollView!.widthAnchor, multiplier: 1.0).isActive = true
subviewWrapper.heightAnchor.constraint(equalTo: scrollView!.heightAnchor, multiplier: 2.0).isActive = true

Example 3: Size of subviewWrapper set by its subviews:

You can also establish the size of your subviewWrapper by adding subviews to it that are fully specified in size and connected in a chain from the top of subviewWrapper to the bottom, and from side to side.  If you do this, Auto Layout will have enough information to compute the size of your subviewWrapper

In this example, I've added a yellow 600 x 600 square to the subviewWrapper and set it 100 points from each edge.  Without having explicitly set a size for subviewWrapper, Auto Layout can figure out that it is 800 x 800.

let yellowSquare = UIView()

yellowSquare.translatesAutoresizingMaskIntoConstraints = false
yellowSquare.backgroundColor = .yellow
subviewWrapper.addSubview(yellowSquare)

yellowSquare.widthAnchor.constraint(equalToConstant: 600).isActive = true
yellowSquare.heightAnchor.constraint(equalToConstant: 600).isActive = true

yellowSquare.topAnchor.constraint(equalTo: subviewWrapper.topAnchor, constant: 100).isActive = true
yellowSquare.leadingAnchor.constraint(equalTo: subviewWrapper.leadingAnchor, constant: 100).isActive = true
yellowSquare.trailingAnchor.constraint(equalTo: subviewWrapper.trailingAnchor, constant: -100).isActive = true
yellowSquare.bottomAnchor.constraint(equalTo: subviewWrapper.bottomAnchor, constant: -100).isActive = true


问:
OpenCV cannot read ffmpeg videos
I was unable to read video frames in OpenCV (python and c++) after using ffmpeg.

Specifically, I had the following problems:

1) unable to open the video file using VideoCapture.

2) able to open the video file using VideoCapture, but reading zero frames and/or receiving frames of size 0x0 pixels.

I am pasting my solution below, hoping this will help others.

These problems were encountered on Mac OS X Sierra 10.12.5, ffmpeg 3.2.4, Python 2.7.13, g++ 4.2.1

答:
1) OpenCV cannot read as many video formats as ffmpeg. Therefore, it is often possible to play videos in VLC, but not to open them in OpenCV's VideoCapture. Hence, conversion with a tool such as ffmpeg is often required (see next point). One format that worked for me is h.264.

2) OpenCV seemed to require YUV420, whereas ffmpeg used YUV444 by default. Therefore, the following command solved my problems:

ffmpeg -i input.avi -c:v libx264 -vf format=yuv420p output.mp4

Title: OpenCV cannot read ffmpeg videos


问:
Java algorithm to check to detect if all characters in string are unique not working with Hashmap? Is there a better solution using map operators?
I have the following code for detecting if all the characters in a string are unique, return true if unique or false if not. Why do the characters in my map never increment beyond 1?

```<code>public static boolean hasUniqueChars(String word) {
    HashMap<String, Integer> map = new HashMap<>();
    for(int i = 0; i < word.length(); i++) {
        if(map.get(word.charAt(i)) == null) { // this appears to always equal null even though there is data after the first instance of a character is put into it?
            map.put(""+word.charAt(i), 1);
        } else {
            map.put(""+word.charAt(i), (Integer)map.get(""+word.charAt(i))+1);
        }
    }
    Iterator it = map.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        if((Integer)pair.getValue() != 1) {
            return false;
        }
    }
    return true;

}
</code>```

Also is there a more "reactive" way to do this like maybe using map operators for each of the chars to help determine whether there is a duplicate character?

答:
Look closely at your for loop:

```<code>for (int i=0; i < word.length(); i++) {
    if (map.get(word.charAt(i)) == null) {
        map.put("" + word.charAt(i), 1);
    } else {
        map.put("" + word.charAt(i), (Integer)map.get("" + word.charAt(i)) + 1);
    }
}
</code>```

You are checking using word.charAt(i) instead of the concatenated string "" + word.charAt(i).  Try using consistent keys everywhere and your problem might go away:

```<code>if (map.get("" + word.charAt(i)) == null) {
    map.put("" + word.charAt(i), 1);
} else {
    map.put("" + word.charAt(i), (Integer)map.get("" + word.charAt(i)) + 1);
}
</code>```

Here is a demo showing that after making this change your code works as expected:

Rextester

Body:
I have the following code for detecting if all the characters in a string are unique, return true if unique or false if not. Why do the characters in my map never increment beyond 1?

public static boolean hasUniqueChars(String word) {
    HashMap<String, Integer> map = new HashMap<>();
    for(int i = 0; i < word.length(); i++) {
        if(map.get(word.charAt(i)) == null) { // this appears to always equal null even though there is data after the first instance of a character is put into it?
            map.put(""+word.charAt(i), 1);
        } else {
            map.put(""+word.charAt(i), (Integer)map.get(""+word.charAt(i))+1);
        }
    }
    Iterator it = map.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        if((Integer)pair.getValue() != 1) {
            return false;
        }
    }
    return true;

}

Also is there a more "reactive" way to do this like maybe using map operators for each of the chars to help determine whether there is a duplicate character?

Body:
Look closely at your for loop:

for (int i=0; i < word.length(); i++) {
    if (map.get(word.charAt(i)) == null) {
        map.put("" + word.charAt(i), 1);
    } else {
        map.put("" + word.charAt(i), (Integer)map.get("" + word.charAt(i)) + 1);
    }
}

You are checking using word.charAt(i) instead of the concatenated string "" + word.charAt(i).  Try using consistent keys everywhere and your problem might go away:

if (map.get("" + word.charAt(i)) == null) {
    map.put("" + word.charAt(i), 1);
} else {
    map.put("" + word.charAt(i), (Integer)map.get("" + word.charAt(i)) + 1);
}

Here is a demo showing that after making this change your code works as expected:

Rextester


问:
Why are list/comboboxes sometimes empty until form is refreshed?
I am developing a Database in Access 2010, which multiple users access at once (separated frontend/backend). Now that more users are startin to use it, I have stumbled upon a pretty inconsistent problem:
Some users see empty Listboxes/Comboboxes until they close the current form and open it again, or press f5. This doesn't happen to all users, and it doesn't always happen (meaning a user sometimes has this problem and sometimes not).
I have managed to find out, that this only happens to controls that are filled using VBA -if I specify a query in the properties tab, it works normally.

Here is how I fill the controls:

```<code>Dim sQuery As String
Dim rs As DAO.Recordset

sQuery = "SELECT ID, Name FROM Users WHERE ID <> 1"

Set rs = CurrentDB.OpenRecordset (sQuery)
Set listBox.Recordset = rs

Set rs = Nothing
</code>```

While developing, this happened to me a few times and I could get around it using Me.Refresh or Me.Repaint (sometimes one worked, sometimes the other).

Personally I don't find it difficult to just press F5 when I see an emtpy list that should be filled, but as more users are using this, it is quite inconvenient for them.

So is such behaviour normal? Am I missing something when filling the controls? Could it be a problem of computer performance (as in the control is painted before it can be filled)?

答:
I tried everything to fix this issue in Access 2010, but the ListBox remained blank on startup.

Finally in a fit of desperation I tried adding this as the very first item in the Form Load:

Me.Dirty = False

It works!  I don't care how or why but now my ListBox populates itself at startup. Previously it refused to display anything until an explicit event happened, like re-selecting the item in the Combo Box.

Body:
I am developing a Database in Access 2010, which multiple users access at once (separated frontend/backend). Now that more users are startin to use it, I have stumbled upon a pretty inconsistent problem:
Some users see empty Listboxes/Comboboxes until they close the current form and open it again, or press f5. This doesn't happen to all users, and it doesn't always happen (meaning a user sometimes has this problem and sometimes not).
I have managed to find out, that this only happens to controls that are filled using VBA -if I specify a query in the properties tab, it works normally.

Here is how I fill the controls:

Dim sQuery As String
Dim rs As DAO.Recordset

sQuery = "SELECT ID, Name FROM Users WHERE ID <> 1"

Set rs = CurrentDB.OpenRecordset (sQuery)
Set listBox.Recordset = rs

Set rs = Nothing

While developing, this happened to me a few times and I could get around it using Me.Refresh or Me.Repaint (sometimes one worked, sometimes the other).

Personally I don't find it difficult to just press F5 when I see an emtpy list that should be filled, but as more users are using this, it is quite inconvenient for them.

So is such behaviour normal? Am I missing something when filling the controls? Could it be a problem of computer performance (as in the control is painted before it can be filled)?


问:
Equilibrium Index in Python 2.7
I was given a demo task to do in Codility, and I am having some trouble trying to figure out what I'm doing wrong. The task:

Working in Python 2.7 Environment

A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e.

A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].

Sum of zero elements is assumed to be equal to 0. This can happen if P = 0 or if P = N−1.

For example, consider the following array A consisting of N = 8 elements:

```<code>A[0] = -1
A[1] =  3
A[2] = -4
A[3] =  5
A[4] =  1
A[5] = -6
A[6] =  2
A[7] =  1
</code>```

P = 1 is an equilibrium index of this array, because:

```<code>A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]
</code>```

P = 3 is an equilibrium index of this array, because:

```<code>A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]
</code>```

P = 7 is also an equilibrium index, because:

```<code>A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0
</code>```

and there are no elements with indices greater than 7.

P = 8 is not an equilibrium index, because it does not fulfill the condition 0 ≤ P < N.

Write a function:

def solution(A)

that, given a zero-indexed array A consisting of N integers, returns any of its equilibrium indices. The function should return −1 if no equilibrium index exists.

In response I wrote the following:

```<code>def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        while x < length:
            for i in A:
                rightSum = A[1:i-1]
                leftSum = A[i+1:length-2]
                if sum(rightSum) == sum(leftSum):
                    equi.append(i)
                    return equi
                else:
                    return -1
            x += 1
    pass

solution([-1,3,-4,5,1,-6,2,1])
</code>```

When I complied the code, I kept getting -1 for the test list, even though I should be getting equi[1,3,7].

Another question, why do I need the 'pass' keyword at the end of the method?

I should add, I am extremely new to Python coding and coding in general. Any help y'all can provide would be appreciated.

答:
Your logic is sane, but you're tripping over some of the language's syntax.

I've tried my best to help your code while commenting it:

```<code>def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        # while x < length: (removed)
        # When we do for i in A, we're already iterating over each element i of the list A.
        # As such, there's no need for the while loop.
        for i in A:
            # You switched right and left sum; elements at the 'left' are at the beginning of the list
            # I also switched the name of the lists to leftList and rightList, to be more descriptive
            # (a list and a sum are different things)
            # I switched the i that was in the indexes to x. i is the integer on the list we're iterating over;
            # its position on the list, on the other hand, is being counted with x.
            leftList = A[0:x]  # Go from 0, since you want to count the first element.
            # We could also ommit the first index and it would begin from the first element
            rightList = A[x+1:]  # If we ommit the second index, it'll go until the last element
            if sum(leftList) == sum(rightList):
                # I changed equi.append(i) to equi.append(x), because i is the value we're iterating over, while
                # x is the counter (index) of the number being currently evaluated
                equi.append(x)
                # return equi (removed)
                # We don't want to return here. When we call return, the function exits!

            # What this would do is exit the function if the sum of the left list wasn't equal to the sum of the right.
            # This isn't what we want, so we'll just remove this
            # else: (removed)
            #     return -1 (removed)
            x += 1

        # No pass needed; that's another thing entirely, just a nil instruction

        # Now the loop is done, we have appended to equi all the equilibrium values.
        # It's time to exit the function by returning the list of equi values.
        # Since we must return -1 if no equilibrium indices exist, then we have to check for that as well
        if len(equi) == 0:
            return -1
        else:
            return equi

sol = solution([-1, 3, -4, 5, 1, -6, 2, 1])
print(sol)  # [1, 3, 7]
</code>```

There are a couple other minor things that could be improved for readability (variable naming conventions, using enumerate), but for the sake of brevity and simplicity, I've included just what makes it work.

Title: Equilibrium Index in Python 2.7

Body:
I was given a demo task to do in Codility, and I am having some trouble trying to figure out what I'm doing wrong. The task:

Working in Python 2.7 Environment

A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e.

A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].

Sum of zero elements is assumed to be equal to 0. This can happen if P = 0 or if P = N−1.

For example, consider the following array A consisting of N = 8 elements:

A[0] = -1
A[1] =  3
A[2] = -4
A[3] =  5
A[4] =  1
A[5] = -6
A[6] =  2
A[7] =  1

P = 1 is an equilibrium index of this array, because:

A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]

P = 3 is an equilibrium index of this array, because:

A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]

P = 7 is also an equilibrium index, because:

A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0

and there are no elements with indices greater than 7.

P = 8 is not an equilibrium index, because it does not fulfill the condition 0 ≤ P < N.

Write a function:

def solution(A)

that, given a zero-indexed array A consisting of N integers, returns any of its equilibrium indices. The function should return −1 if no equilibrium index exists.

In response I wrote the following:

def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        while x < length:
            for i in A:
                rightSum = A[1:i-1]
                leftSum = A[i+1:length-2]
                if sum(rightSum) == sum(leftSum):
                    equi.append(i)
                    return equi
                else:
                    return -1
            x += 1
    pass

solution([-1,3,-4,5,1,-6,2,1])

When I complied the code, I kept getting -1 for the test list, even though I should be getting equi[1,3,7].

Another question, why do I need the 'pass' keyword at the end of the method?

I should add, I am extremely new to Python coding and coding in general. Any help y'all can provide would be appreciated.

Body:
Your logic is sane, but you're tripping over some of the language's syntax.

I've tried my best to help your code while commenting it:

def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        # while x < length: (removed)
        # When we do for i in A, we're already iterating over each element i of the list A.
        # As such, there's no need for the while loop.
        for i in A:
            # You switched right and left sum; elements at the 'left' are at the beginning of the list
            # I also switched the name of the lists to leftList and rightList, to be more descriptive
            # (a list and a sum are different things)
            # I switched the i that was in the indexes to x. i is the integer on the list we're iterating over;
            # its position on the list, on the other hand, is being counted with x.
            leftList = A[0:x]  # Go from 0, since you want to count the first element.
            # We could also ommit the first index and it would begin from the first element
            rightList = A[x+1:]  # If we ommit the second index, it'll go until the last element
            if sum(leftList) == sum(rightList):
                # I changed equi.append(i) to equi.append(x), because i is the value we're iterating over, while
                # x is the counter (index) of the number being currently evaluated
                equi.append(x)
                # return equi (removed)
                # We don't want to return here. When we call return, the function exits!

            # What this would do is exit the function if the sum of the left list wasn't equal to the sum of the right.
            # This isn't what we want, so we'll just remove this
            # else: (removed)
            #     return -1 (removed)
            x += 1

        # No pass needed; that's another thing entirely, just a nil instruction

        # Now the loop is done, we have appended to equi all the equilibrium values.
        # It's time to exit the function by returning the list of equi values.
        # Since we must return -1 if no equilibrium indices exist, then we have to check for that as well
        if len(equi) == 0:
            return -1
        else:
            return equi

sol = solution([-1, 3, -4, 5, 1, -6, 2, 1])
print(sol)  # [1, 3, 7]

There are a couple other minor things that could be improved for readability (variable naming conventions, using enumerate), but for the sake of brevity and simplicity, I've included just what makes it work.


问:
Good reference + feature/syntax comparison matrix for SQL databases?
I am looking for a reference guide with possibility one or more comparison matrices for various SQL databases. The goal being to be able to see quickly what functions/operators/statements of the SQL standards (yes, plural would be good :) are supported by each and what syntax they use for them.

And then something similar for additional features as well, possibly matching them with equivalent features in other databases.

For instance, I'd like to be able to quickly see if database A, B, C support the LIKE operator and if they all support both the % and _ placeholders.

This Wikipedia comparison of several RDBMS mentioned in similar questions gives some interesting info but not to the extent of the syntactic features and operator support.

Preferably, I'm looking for a reference containing said info for at least the following tables:

Oracle,

PostgreSQL,

DB2,

HSQLDB,

MS SQL,

MySQL.

Haven't managed to find a good consolidated and usable reference for this over the past few days. Thanks.

答: You might find this book very useful: SQL in a Nutshell (by Kline & Hunt, O'Reilly)</p>

ContentLicense: CC BY-SA 4.0


问:
SQL Server Management Studio dark theme for whole program
Is it possible to set the SSMS theme to all dark? I really like the dark theme in Visual Studio and SSMS is built on top of the VS shell. I saw this SQL Server Management Studio Skin / Appearance / Layout, but it is only for the query editor.</p>

答:
Here's the automated way to make it easier to enable SSMS Dark Theme in SQL Server 2014+. It's re-entrant also in case you've already executed it. It will make a backup first just in case you are concerned about recovery. Inspired by this manual guide.

PS CommandLet to Enable Dark SSMS Theme

function EnableDarkSSMSTheme() {
    $ssmsConfig = "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\ssms.pkgundef"
    $fileContent = get-content $ssmsConfig
    Set-Content -path ([System.IO.Path]::ChangeExtension($ssmsConfig, "backup")) -value $fileContent  # backup original file
    $startContext = $fileContent | Select-String "// Remove Dark theme" -context 0, 100 | Select-Object LineNumber, Line -ExpandProperty Context | select-object LineNumber, PostContext # grab start context
    $endContext = $startContext.PostContext | select-string "//" | Select Line, @{Name="LineNumber";Expression={$_.LineNumber + $startContext.LineNumber - 3}} -First 1 # grab end context, offset line # for ending
    for($i = $startContext.LineNumber-1; $i -le $endContext.LineNumber; $i++) { $fileContent[$i] = "//$($fileContent[$i])" } # prefix lines to comment
    Set-Content -path $ssmsConfig -value $fileContent # persist changes
}

EnableDarkSSMSTheme
kill -name ssms
start-process ssms
```

Note: For version upgrades v17.2 to v17.3, the program file configurations get overwritten and you have to re-apply this script.

Body:
Here's the automated way to make it easier to enable SSMS Dark Theme in SQL Server 2014+. It's re-entrant also in case you've already executed it. It will make a backup first just in case you are concerned about recovery. Inspired by this manual guide.

PS CommandLet to Enable Dark SSMS Theme

function EnableDarkSSMSTheme() {
    $ssmsConfig = "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\ssms.pkgundef"
    $fileContent = get-content $ssmsConfig
    Set-Content -path ([System.IO.Path]::ChangeExtension($ssmsConfig, "backup")) -value $fileContent  # backup original file
    $startContext = $fileContent | Select-String "// Remove Dark theme" -context 0, 100 | Select-Object LineNumber, Line -ExpandProperty Context | select-object LineNumber, PostContext # grab start context
    $endContext = $startContext.PostContext | select-string "//" | Select Line, @{Name="LineNumber";Expression={$_.LineNumber + $startContext.LineNumber - 3}} -First 1 # grab end context, offset line # for ending
    for($i = $startContext.LineNumber-1; $i -le $endContext.LineNumber; $i++) { $fileContent[$i] = "//$($fileContent[$i])" } # prefix lines to comment
    Set-Content -path $ssmsConfig -value $fileContent # persist changes
}

EnableDarkSSMSTheme
kill -name ssms
start-process ssms

Note: For version upgrades v17.2 to v17.3, the program file configurations get overwritten and you have to re-apply this script.


问:
Where to find custom Content type related files in Drupal directories?
I have a localhost Drupal 7.x installation on my system. I have just explored with UI and created a custom Content type which defines a form with radio boxes. (Home --> Structure --> Content types --> Add Content Type, and so on.)

I am assuming these custom content types will be stored in local directories of Drupal core. I am not able to figure out where exactly these stay. I am curious to make changes to that file and see if there is any reflection, though I am not sure if it works that way.

答:
Content types are data structure under Drupal so those are not stored in files but in Database.

If you add a field type file as part of a content type you can define where those files will be placed into the field type configuration


问:
CORS in OAuth: Response to preflight request doesn't pass access control check
So I'm trying to implement the OAuth 2 flow, while my webapp is the server that give away authorization code/access token.

Cors error happens when sending the code back to third-party website(zapier in this case):

XMLHttpRequest cannot load https://zapier.com/dashboard/auth/oauth/return/App505CLIAPI/?code=somecode&state=somestate. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://myurl' is therefore not allowed access.

If I manually open a new tab, paste that zapier uri, everything works perfectly.

Seems like a typical CORS issue, but none the popular solutions works for me:

Add Access-Control-Allow-Origin: I'm using this oauth2orize
library, and sending reponse to preflight seems also part of the
library. So I cannot add header.

Using cors: Have tried app.use(cors()) and app.options('*',
cors()) which should apply to all routes, but simply not working.

My webapp sits on a node express server, in front of which there's an nginx proxy server.

Any idea where the problem might be is appreciated.

答:
The issue that error message indicates isn’t caused by the app code running at https://myurl/. Instead it’s just that https://zapier.com/dashboard/auth/… doesn’t seem to support CORS.

Specifically, the response from that https://zapier.com/dashboard/auth/… URL doesn’t include the Access-Control-Allow-Origin response header, so your browser won’t let your frontend JavaScript code access the response.

It seems like that is all intentional on the part of Zapier—they don’t intend for that auth endpoint to be accessed from frontend AJAX/XHR/Fetch code running in a browser. Instead I guess it’s intended that you only access that auth endpoint from your backend code. Or something.

Anyway there is no way from your side that you can fix the fact the response from that Zapier API endpoint doesn’t include Access-Control-Allow-Origin.

And as long as it doesn’t include Access-Control-Allow-Origin, your browser blocks your frontend code from being able to get to the response—and there’s no way to get your browser to behave otherwise as long as your frontend code is trying to hit that API endpoint directly.

So the only solution is to not hit that API endpoint directly from your frontend code but to instead either set up a proxy and change your frontend code to make the request through that, or else just handle it in some other way in your existing backend code, as mentioned above.

The answer at Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not? gives some details on how you can set up a special CORS proxy, if you want to go that route.


问:
Python Pandas DataFrame with only a single number stored?
AzureML's Python Script module requires to return a Pandas DataFrame. I want to return only a value and I do this:

```<code>result=7
dataframe1=pd.DataFrame(numpy.zeros(1))
dataframe1[0][0]=result
</code>```

by which I am able to return just a single value in Azure ML's Python Script module.

What is a proper way to create a pandas DataFrame with a single value?

答:
Following code should work:</p>

```<code>import pandas as pd
def azureml_main(dataframe1 = None, dataframe2 = None):
    result = pd.DataFrame({'mycol': [123]})
    return result,
</code>```

Body:
AzureML's Python Script module requires to return a Pandas DataFrame. I want to return only a value and I do this:

result=7
dataframe1=pd.DataFrame(numpy.zeros(1))
dataframe1[0][0]=result

by which I am able to return just a single value in Azure ML's Python Script module.

What is a proper way to create a pandas DataFrame with a single value?

Body:
Following code should work:

import pandas as pd
def azureml_main(dataframe1 = None, dataframe2 = None):
    result = pd.DataFrame({'mycol': [123]})
    return result,


问:
Is there a way to select on a value attached by .data()?
Background: I'm performing an upgrade on an existing photo gallery plug-in which displays a large image in the center and progressively smaller images off to either side.

So my question is this:  I'm setting some data on each image that gives the image's index, the index of the next image, and the index of the previous image, like so:

```<code>$(this).data('index', i).data('prev', i - 1).data('next', i + 1);
</code>```

Later on, I'd like to be able to select an image based on its index.  I've tried the following, but it doesn't seem to work:

```<code>$('[data-index=' + index + ']');
</code>```

Is there a way to select an element based on a piece of data attached with .data()?

答:
Slightly alternative approach:

Assuming the images are in a series in the HTML, why not just do something like this?

$('#images img').eq(index)

Body:
Background: I'm performing an upgrade on an existing photo gallery plug-in which displays a large image in the center and progressively smaller images off to either side.

So my question is this:  I'm setting some data on each image that gives the image's index, the index of the next image, and the index of the previous image, like so:

$(this).data('index', i).data('prev', i - 1).data('next', i + 1);

Later on, I'd like to be able to select an image based on its index.  I've tried the following, but it doesn't seem to work:

$('[data-index=' + index + ']');

Is there a way to select an element based on a piece of data attached with .data()?


问:
nodejs printing api response on browser
I'm absolute beginner on nodejs or javascript so excuse me for the low level question. I read a few tutorials but couldn't find a way to print out the response on the browser (i'm using ejs) what I can get is I can get it printed on console but I don't have a no clue on how to do it. Could someone direct me to the right way or show me a snippet so i can learn from it?

the way i'm getting the console log result is:

```<code>const express = require('express')
const app = express()
const bcypher = require('blockcypher')
const request = require('request');

app.set('view engine', 'ejs');

request('https://api.blockcypher.com/v1/btc/main/addrs/1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD/balance', function (error, response, data) {
  if (!error && response.statusCode == 200) {
    console.log(data)
  }
})

app.listen(3000, function() {
  console.log('listening on 3000')
})
</code>```

thank you

答:
So as it stands this will not display in any browser as you are not sending the data anywhere. This is your server.js file, so when the server runs, it makes the request and on successful completion, the data is logged in your console.
To send it back to the browser, you would need set it up to serve requests that from the front end. A simple example:</p>

```<code>app.get('/data', function(req, res){
  request('https://api.blockcypher.com/v1/btc/main/addrs/1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD/balance', function (error, response, data) {
    if (!error && response.statusCode == 200) {
      console.log(data)
    }
  })
  res.send('Hello browser, here's my data: ', response.body); //replace with your data here
});
</code>```

Title: nodejs printing api response on browser

Body:
I'm absolute beginner on nodejs or javascript so excuse me for the low level question. I read a few tutorials but couldn't find a way to print out the response on the browser (i'm using ejs) what I can get is I can get it printed on console but I don't have a no clue on how to do it. Could someone direct me to the right way or show me a snippet so i can learn from it?

the way i'm getting the console log result is:

const express = require('express')
const app = express()
const bcypher = require('blockcypher')
const request = require('request');

app.set('view engine', 'ejs');

request('https://api.blockcypher.com/v1/btc/main/addrs/1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD/balance', function (error, response, data) {
  if (!error && response.statusCode == 200) {
    console.log(data)
  }
})

app.listen(3000, function() {
  console.log('listening on 3000')
})

thank you

Body:
So as it stands this will not display in any browser as you are not sending the data anywhere. This is your server.js file, so when the server runs, it makes the request and on successful completion, the data is logged in your console.
To send it back to the browser, you would need set it up to serve requests that from the front end. A simple example:

app.get('/data', function(req, res){
  request('https://api.blockcypher.com/v1/btc/main/addrs/1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD/balance', function (error, response, data) {
    if (!error && response.statusCode == 200) {
      console.log(data)
    }
  })
  res.send('Hello browser, here's my data: ', response.body); //replace with your data here
});


问:
Print between specific ranges - sed or awk
How can we achieve this using sed or awk?

I have now included the text in a code block to make it clear.

The code block part should be printed  -  is the requirement.

LOGIC 1:

The text 'abc' will be our keyword here which will be unique and will only occur within the code block part

So we'll have to search for 'abc' and from that line till the last occurrence of 'abc' all lines should be printed inclusive

LOGIC 2:

Based on page numbers i.e. select text between page 1 and page n again inclusive
Note: 'Page 1' and 'Page 1 - Page n' can come multiple times.

The whole text is a part of a 4GB file which needs to be parsed for similar occurrences.

Apologies for not being clear.

START OF TEXT IN THE FILE:

Xyz       Page: 1

a

b

c

d

e

QWE       Page: 1

e

r

t

y

```<code>asdabc       Page: 1

t

y

u

I

o

ghjabc       Page: 2

e

d

c

b

bnmabc       Page: 3

uia

asd

ads
</code>```

thm       Page: 1

as

das

da

END OF TEXT IN FILE

答:
You may achieve it by using awk,

```<code>awk 'BEGIN{a=0} /.*Page/{if(index($0,"abc")!=0){a=1} else{a=0}} a==1{print}' <Your_File>
</code>```

Output:

```<code>asdabc       Page: 1

t

y

u

I

o

ghjabc       Page: 2

e

d

c

b

bnmabc       Page: 3

uia

asd

ads
</code>```

Here's what I do here,

set the flag 'a' to determine if print or not

find string "Page" in the line, and then check if "abc" in it

start to print lines

print the line until next "Page" show up but no "abc" in it

Body:
How can we achieve this using sed or awk?

I have now included the text in a code block to make it clear.

The code block part should be printed  -  is the requirement.

LOGIC 1:

The text 'abc' will be our keyword here which will be unique and will only occur within the code block part

So we'll have to search for 'abc' and from that line till the last occurrence of 'abc' all lines should be printed inclusive

LOGIC 2:

Based on page numbers i.e. select text between page 1 and page n again inclusive
Note: 'Page 1' and 'Page 1 - Page n' can come multiple times.

The whole text is a part of a 4GB file which needs to be parsed for similar occurrences.

Apologies for not being clear.

START OF TEXT IN THE FILE:

Xyz       Page: 1

a

b

c

d

e

QWE       Page: 1

e

r

t

y

asdabc       Page: 1

t

y

u

I

o

ghjabc       Page: 2

e

d

c

b

bnmabc       Page: 3

uia

asd

ads

thm       Page: 1

as

das

da

END OF TEXT IN FILE

Body:
You may achieve it by using awk,

awk 'BEGIN{a=0} /.*Page/{if(index($0,"abc")!=0){a=1} else{a=0}} a==1{print}' <Your_File>

Output:

asdabc       Page: 1

t

y

u

I

o

ghjabc       Page: 2

e

d

c

b

bnmabc       Page: 3

uia

asd

ads

Here's what I do here,

set the flag 'a' to determine if print or not

find string "Page" in the line, and then check if "abc" in it

start to print lines

print the line until next "Page" show up but no "abc" in it