问:
Angular Template Cache with Service Worker Issue
I have a gulp setup that puts all my html in template cache for faster access in angular.  I'm trying to add a service worker to my project, using sw-precache, so that it can be used offline.  If I'm connected to the network, everything works fine.  When I go offline, the requests for html resources (that are in the template cache) fail because it seems it is requesting the path from the network.

Is there something I need to add to my sw-precache config in order to have it defer to angular to handle retrieval of html files?

答:
ok, so this is how I solved this. I am using Angular JS 1.6.4 with sw-precache.

I have CacheStorage via service workers, so using service workers I know I am expecting devices to support certain functionality, in my case we know our users will have Android Tablets with Chrome and support is valid.

I am developing a progressive web app with offline functionality.

So, the theory...I have directives which have templateUrls.

Using this post: https://thinkster.io/templatecache-tutorial

I basically have my directive code:

```<code>angular.module('app').directive('location',
['$timeout', 'notify.service', 'user.settings.service', 'log.service',
    function ($timeout, notify, userSettings, log) {
        return {
            restrict: 'EA',
            ... controller etc..,
            templateUrl: '/App/core/directives/location.html'
        }
    }
]);
</code>```

Now, when this app goes offline, the cached instances of the content was not kicking it - annoying.

So, after much procrastinating I got down and dirty.

My solutio is, keep the templateUrl as it is, but overwrite the content via the $templateCache service.

To do this, you append a RUN function with your directive (for clarity). We know the service worker cache representation of our Url files contains the common path, in my case: '/App/core/directives/location.html'.

So, using new technology in the browser, window.caches gives me access to the CacheStorage that the service workers uses, I can then use the API available: https://developer.mozilla.org/en-US/docs/Web/API/Cache

I can then use the match method to find the matching service worker cache content, read that stream of binary and convert to HTML and then tell $templateCache to replace it with the service worker cached value.

So, for completeness (and you can create a common service which replaces the cached values based on templateUrl - which I will be doing for each directive)

```<code>(function () {

    'use strict';

    var templateUrl = '/App/core/directives/location.html';

    // <location on-location='someFunc'></location>
    // provides a form/control to find a location either by GEO location or manual city search
    angular.module('app')
            .run(['$templateCache', function ($templateCache) {
                var cache = window.caches;

                cache.match(templateUrl, { ignoreSearch: true }).then(function (response) {

                    if (response) {
                        response.body.getReader().read().then(function (cachedResponse) {
                            // convert the Uint8Array value to HTML string
                            var content = new TextDecoder('utf-8').decode(cachedResponse.value);
                            $templateCache.put(templateUrl, content);
                            //console.log($templateCache.get(templateUrl)); // debug
                        });
                    }
                });

            }])
    .directive('location',
    ['$timeout', 'notify.service', 'user.settings.service', 'log.service',
        function ($timeout, notify, userSettings, log) {
            return {
                restrict: 'EA',
                ... controller, scope etc...
                templateUrl: templateUrl
            }
        }
    ]);
})();
</code>```

Draw backs...the RUN process is synchronous, so initially they have to hit the site online first...but thats how service worker needs to work anyway, so thats handled in training :)

I expect there to be a better option, but for the time being thats the solution I have, I will be creating a template service for replacing $templateCache values based on the var templateUrl each directive will have, so the code becomes cleaner in each directtive....i considered having a global arr of templates and files, but, just a bit obscure, think its cleaner for each directive

Body:
ok, so this is how I solved this. I am using Angular JS 1.6.4 with sw-precache.

I have CacheStorage via service workers, so using service workers I know I am expecting devices to support certain functionality, in my case we know our users will have Android Tablets with Chrome and support is valid.

I am developing a progressive web app with offline functionality.

So, the theory...I have directives which have templateUrls.

Using this post: https://thinkster.io/templatecache-tutorial

I basically have my directive code:

angular.module('app').directive('location',
['$timeout', 'notify.service', 'user.settings.service', 'log.service',
    function ($timeout, notify, userSettings, log) {
        return {
            restrict: 'EA',
            ... controller etc..,
            templateUrl: '/App/core/directives/location.html'
        }
    }
]);

Now, when this app goes offline, the cached instances of the content was not kicking it - annoying.

So, after much procrastinating I got down and dirty.

My solutio is, keep the templateUrl as it is, but overwrite the content via the $templateCache service.

To do this, you append a RUN function with your directive (for clarity). We know the service worker cache representation of our Url files contains the common path, in my case: '/App/core/directives/location.html'.

So, using new technology in the browser, window.caches gives me access to the CacheStorage that the service workers uses, I can then use the API available: https://developer.mozilla.org/en-US/docs/Web/API/Cache

I can then use the match method to find the matching service worker cache content, read that stream of binary and convert to HTML and then tell $templateCache to replace it with the service worker cached value.

So, for completeness (and you can create a common service which replaces the cached values based on templateUrl - which I will be doing for each directive)

(function () {

    'use strict';

    var templateUrl = '/App/core/directives/location.html';

    // <location on-location='someFunc'></location>
    // provides a form/control to find a location either by GEO location or manual city search
    angular.module('app')
            .run(['$templateCache', function ($templateCache) {
                var cache = window.caches;

                cache.match(templateUrl, { ignoreSearch: true }).then(function (response) {

                    if (response) {
                        response.body.getReader().read().then(function (cachedResponse) {
                            // convert the Uint8Array value to HTML string
                            var content = new TextDecoder('utf-8').decode(cachedResponse.value);
                            $templateCache.put(templateUrl, content);
                            //console.log($templateCache.get(templateUrl)); // debug
                        });
                    }
                });

            }])
    .directive('location',
    ['$timeout', 'notify.service', 'user.settings.service', 'log.service',
        function ($timeout, notify, userSettings, log) {
            return {
                restrict: 'EA',
                ... controller, scope etc...
                templateUrl: templateUrl
            }
        }
    ]);
})();

Draw backs...the RUN process is synchronous, so initially they have to hit the site online first...but thats how service worker needs to work anyway, so thats handled in training :)

I expect there to be a better option, but for the time being thats the solution I have, I will be creating a template service for replacing $templateCache values based on the var templateUrl each directive will have, so the code becomes cleaner in each directtive....i considered having a global arr of templates and files, but, just a bit obscure, think its cleaner for each directive


来源: stackexchange

问:
Retrieving the backcolor in C#
I'm a absolute beginner. Just started to play with C#.
I want to switch the backcolor of a textBox.
If it is red, I want to change it into yellow.

Why is if (textBox1.backcolor = Color.Red) giving an error ?

答:
You must use == , = is for assignment. And not backColor ,correct syntax is BackColor.

```<code>if (textBox1.BackColor == Color.Red)
    textBox1.BackColor  = Color.Yellow;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Retrieving the backcolor in C#

Body:
You must use == , = is for assignment. And not backColor ,correct syntax is BackColor.

if (textBox1.BackColor == Color.Red)
    textBox1.BackColor  = Color.Yellow;


问:
UISearchController search bar overlap first cell when active
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

```<code> -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}
</code>```

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

答:
You can add content inset from the top instead of adding a header.

```<code>  self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
</code>```

and when willDismissSearchController (UISearchController's delegate method) is called, return the insets to 0

```<code>  self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
</code>```

This way, you'll avoid the whitespace when it's not active.

Body:
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

 -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

Body:
You can add content inset from the top instead of adding a header.

  self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

and when willDismissSearchController (UISearchController's delegate method) is called, return the insets to 0

  self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

This way, you'll avoid the whitespace when it's not active.


问:
Heroku API returns 403 in Python only
So I am working on a Python script to communicate with the Heroku API to get dyno information, but it doesn't seem to work in Python. However, with the exact same information, it works fine in cURL:

Works (cURL 7.51.0):

```<code>curl -XGET -H 'Authorization: Bearer <BEARER>' -H 'Accept: application/vnd.heroku+json; version=3' 'https://api.heroku.com/apps/<APP>/dynos/<DYNO>'
</code>```

Fails (Python, both on 2.7.12, 3.5.3, and 3.6.1):

```<code>import json
import requests
callapi = requests.get('https://api.heroku.com/apps/<APP>/dynos/<DYNO>', headers={"Authorization":"Bearer <BEARER>", "Accept":"application/vnd.heroku+json; version=3"})
json = callapi.json()
print(json)
</code>```

...with error:

```<code>{'id': 'forbidden', 'message': 'You do not have access to the app <APP>.'}
</code>```

Where <APP> is my app name, <DYNO> is the dyno name, and <BEARER> is my bearer token.

Any help would be appreciated!

答:
The problem is that requests uses the .netrc file if no auth argument is provided: http://docs.python-requests.org/en/master/user/authentication/?highlight=netrc#netrc-authentication

So requests is using your Heroku credentials (heroku login saves your credentials in that file).

An easy way to fix the issue is expained here: http://docs.python-requests.org/en/master/user/authentication/?highlight=netrc#new-forms-of-authentication

TL;DR: remove the Authorization header and use the auth parameter with a custom class.

This is the implementation I'm using:

```<code>class HerokuBearerAuth(requests.auth.AuthBase):
    def __init__(self, api_key):
        self.api_key = api_key

    def __call__(self, r):
        r.headers.update({'Authorization': 'Bearer {}'.format(self.api_key)})
        return r

myHeaders = {'Accept': 'application/vnd.heroku+json; version=3'}
response = requests.get(myUrl, headers=myHeaders, auth=HerokuBearerAuth(api_key))
</code>```

Title: Heroku API returns 403 in Python only

Body:
So I am working on a Python script to communicate with the Heroku API to get dyno information, but it doesn't seem to work in Python. However, with the exact same information, it works fine in cURL:

Works (cURL 7.51.0):

curl -XGET -H 'Authorization: Bearer <BEARER>' -H 'Accept: application/vnd.heroku+json; version=3' 'https://api.heroku.com/apps/<APP>/dynos/<DYNO>'

Fails (Python, both on 2.7.12, 3.5.3, and 3.6.1):

import json
import requests
callapi = requests.get('https://api.heroku.com/apps/<APP>/dynos/<DYNO>', headers={"Authorization":"Bearer <BEARER>", "Accept":"application/vnd.heroku+json; version=3"})
json = callapi.json()
print(json)

...with error:

{'id': 'forbidden', 'message': 'You do not have access to the app <APP>.'}

Where <APP> is my app name, <DYNO> is the dyno name, and <BEARER> is my bearer token.

Any help would be appreciated!

Body:
The problem is that requests uses the .netrc file if no auth argument is provided: http://docs.python-requests.org/en/master/user/authentication/?highlight=netrc#netrc-authentication

So requests is using your Heroku credentials (heroku login saves your credentials in that file).

An easy way to fix the issue is expained here: http://docs.python-requests.org/en/master/user/authentication/?highlight=netrc#new-forms-of-authentication

TL;DR: remove the Authorization header and use the auth parameter with a custom class.

This is the implementation I'm using:

class HerokuBearerAuth(requests.auth.AuthBase):
    def __init__(self, api_key):
        self.api_key = api_key

    def __call__(self, r):
        r.headers.update({'Authorization': 'Bearer {}'.format(self.api_key)})
        return r

myHeaders = {'Accept': 'application/vnd.heroku+json; version=3'}
response = requests.get(myUrl, headers=myHeaders, auth=HerokuBearerAuth(api_key))


问:
How concat very long clob in pl sql without error
Hi I'm making a new plsql function with this declaration:

```<code>string_result CLOB;
string1 CLOB;
string2 CLOB;
</code>```

In my body I have:

```<code>...
for i in variable
loop
 string_result := string_result || string1 || string2 ;
end loop
...
--send string_result in mail
...
return 1
</code>```

When I execute this function I received:

01489. 00000 -  "result of string concatenation is too long"

Cause:    String concatenation result is more than the maximum size.

Action:   Make sure that the result is less than the maximum size.

答:
You can use DBMS_LOB.CREATETEMPORARY and DBMS_LOB.WRITEAPPEND.

Something like:

```<code>DECLARE
  string_result CLOB;
BEGIN
  DBMS_LOB.CREATETEMPORARY( string_result, TRUE );
  FOR i IN variable LOOP
    DBMS_LOB.WRITEAPPEND( string_result, LENGTH( string1 ), string1 );
    DBMS_LOB.WRITEAPPEND( string_result, LENGTH( string2 ), string2 );
  END LOOP;
  --send string_result in mail
END;
</code>```

Body:
Hi I'm making a new plsql function with this declaration:

string_result CLOB;
string1 CLOB;
string2 CLOB;

In my body I have:

...
for i in variable
loop
 string_result := string_result || string1 || string2 ;
end loop
...
--send string_result in mail
...
return 1

When I execute this function I received:

01489. 00000 -  "result of string concatenation is too long"

Cause:    String concatenation result is more than the maximum size.

Action:   Make sure that the result is less than the maximum size.

Body:
You can use DBMS_LOB.CREATETEMPORARY and DBMS_LOB.WRITEAPPEND.

Something like:

DECLARE
  string_result CLOB;
BEGIN
  DBMS_LOB.CREATETEMPORARY( string_result, TRUE );
  FOR i IN variable LOOP
    DBMS_LOB.WRITEAPPEND( string_result, LENGTH( string1 ), string1 );
    DBMS_LOB.WRITEAPPEND( string_result, LENGTH( string2 ), string2 );
  END LOOP;
  --send string_result in mail
END;


问:
How just get raw with scapy
For a project I use scapy to sniff my network and check some data.
But for seeing each frame, I use .show(), and I just want to see the raw part.

How can I do it?

```<code>packets = sniff('xx.xx.xx.xx')
packets.show()
</code>```

答: packets is a python list of scapy.Packets, not a instance of scapy.Packet. If you want to use show, you need to run that function on an instance of scapy.Packet, i.e. packets[0].show()

Title: How just get raw with scapy

Body:
For a project I use scapy to sniff my network and check some data.
But for seeing each frame, I use .show(), and I just want to see the raw part.

How can I do it?

packets = sniff('xx.xx.xx.xx')
packets.show()


问:
C# Navigate to a different Folder for startupPath
I have an executable in the Solution of which I added, I want to replace the System.Windows.Forms.Application.StartupPath to the executable location. Unfortunately it's continues to navigate to the Bin\debug folder which I don't want, I need to go up an additional level.

```<code>string pintoolpath = System.Windows.Forms.Application.StartupPath.Replace(@"\bin\Debug", "").Replace(@"\bin\Release", "");
</code>```

That's how I'm doing it but it's actually not replacing it at all when printing it to a message box. How would I navigate to say a another folder.

FYI: using the ..\ to navigate up does not currently work as shown below:

```<code>string pintoolpath = System.Windows.Forms.Application.StartupPath.Replace(@"..\\bin\Debug", "").Replace(@"..\\bin\Release", "");
</code>```

答:
I have figured out my answer,

The directly path on the Solution Explorer had characters that were different then the actual path. For example the B in Bin was capitalized in the actual path VS the solution explorer having it as a lower case. once changing these I was able to get the correct path by navigating to the appropriate folder.

```<code>string pintoolpath = System.Windows.Forms.Application.StartupPath.Replace(@"\Bin\debug", "").Replace(@"\Bin\release", "")
</code>```

Thanks Rahul for assisting me.

Body:
I have an executable in the Solution of which I added, I want to replace the System.Windows.Forms.Application.StartupPath to the executable location. Unfortunately it's continues to navigate to the Bin\debug folder which I don't want, I need to go up an additional level.

string pintoolpath = System.Windows.Forms.Application.StartupPath.Replace(@"\bin\Debug", "").Replace(@"\bin\Release", "");

That's how I'm doing it but it's actually not replacing it at all when printing it to a message box. How would I navigate to say a another folder.

FYI: using the ..\ to navigate up does not currently work as shown below:

string pintoolpath = System.Windows.Forms.Application.StartupPath.Replace(@"..\\bin\Debug", "").Replace(@"..\\bin\Release", "");

Body:
I have figured out my answer,

The directly path on the Solution Explorer had characters that were different then the actual path. For example the B in Bin was capitalized in the actual path VS the solution explorer having it as a lower case. once changing these I was able to get the correct path by navigating to the appropriate folder.

string pintoolpath = System.Windows.Forms.Application.StartupPath.Replace(@"\Bin\debug", "").Replace(@"\Bin\release", "")

Thanks Rahul for assisting me.


问:
Reading Datastream sharpDX Error all values are 0
I followed this solution for my project : How to create bitmap from Surface (SharpDX)

I don't have enough reputation to comment so I'm opening a new question here.

My project is basically in Direct 2D, I have a Surface buffer, a swapchain. I want to put my buffer into a datastream and reads it's value to put it into a bitmap and save it on disk ( like a screen capture), but my code won't work since all the bytes values are 0 (which is black) and this doesn't make sense since my image is fully white with a bit of blue.

Here is my code :

```<code>SwapChainDescription description = new SwapChainDescription()
     {
        ModeDescription = new ModeDescription(this.Width, this.Height, new Rational(60, 1), Format.B8G8R8A8_UNorm),
        SampleDescription = new SampleDescription(1, 0),
        Usage = Usage.RenderTargetOutput,
        BufferCount = 1,
        SwapEffect = SwapEffect.Discard,
        IsWindowed = true,
        OutputHandle = this.Handle
     };

     Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, description, out device, out swapChain);

     SharpDX.DXGI.Device dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device>();
     SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice.Adapter;

     SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice);
     d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
     SharpDX.Direct3D11.DeviceContext d3DeviceContext = new SharpDX.Direct3D11.DeviceContext(device);

     properties = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
          96, 96);

     Surface backBuffer = swapChain.GetBackBuffer<Surface>(0);
     d2dTarget = new SharpDX.Direct2D1.Bitmap(d2dContext, backBuffer, properties);

     d2dContext.Target = d2dTarget;

     playerBitmap = this.LoadBitmapFromContentFile(@"C:\Users\ndesjardins\Desktop\wave.png");

     //System.Drawing.Bitmap bitmapCanva = new System.Drawing.Bitmap(1254, 735);

     d2dContext.BeginDraw();
     d2dContext.Clear(SharpDX.Color.White);
     d2dContext.DrawBitmap(playerBitmap, new SharpDX.RectangleF(0, 0, playerBitmap.Size.Width, playerBitmap.Size.Height), 1f, SharpDX.Direct2D1.BitmapInterpolationMode.NearestNeighbor);
     SharpDX.Direct2D1.SolidColorBrush brush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, SharpDX.Color.Green);
     d2dContext.DrawRectangle(new SharpDX.RectangleF(200, 200, 100, 100), brush);
     d2dContext.EndDraw();

     swapChain.Present(1, PresentFlags.None);

     Texture2D backBuffer3D = backBuffer.QueryInterface<SharpDX.Direct3D11.Texture2D>();

     Texture2DDescription desc = backBuffer3D.Description;
     desc.CpuAccessFlags = CpuAccessFlags.Read;
     desc.Usage = ResourceUsage.Staging;
     desc.OptionFlags = ResourceOptionFlags.None;
     desc.BindFlags = BindFlags.None;

     var texture = new Texture2D(device, desc);

     d3DeviceContext.CopyResource(backBuffer3D, texture);

     byte[] data = null;
     using (Surface surface = texture.QueryInterface<Surface>())
     {
        DataStream dataStream;
        var map = surface.Map(SharpDX.DXGI.MapFlags.Read, out dataStream);
        int lines = (int)(dataStream.Length / map.Pitch);
        data = new byte[surface.Description.Width * surface.Description.Height * 4];

        dataStream.Position = 0;
        int dataCounter = 0;
        // width of the surface - 4 bytes per pixel.
        int actualWidth = surface.Description.Width * 4;
        for (int y = 0; y < lines; y++)
        {
           for (int x = 0; x < map.Pitch; x++)
           {
              if (x < actualWidth)
              {
                 data[dataCounter++] = dataStream.Read<byte>();
              }
              else
              {
                 dataStream.Read<byte>();
              }
           }
        }
        dataStream.Dispose();
        surface.Unmap();

        int width = surface.Description.Width;
        int height = surface.Description.Height;
        byte[] bytewidth = BitConverter.GetBytes(width);
        byte[] byteheight = BitConverter.GetBytes(height);

        Array.Copy(bytewidth, 0, data, 0, 4);
        Array.Copy(byteheight, 0, data, 4, 4);

     }
</code>```

Do you guys have any idea why the byte array that is returned at the end is full of 0 since it should be mostly 255? All I did in my backbuffer was to draw a bitmap image and a rectangle form.  Array.Copy is to add the width and height header to the byte array, therefore I could create a bitmap out of it.

答:
I answered in a comment but formatting is horrible so apologies!

https://gamedev.stackexchange.com/a/112978/29920  This looks promising but as you said in reply to mine, this was some time ago and I'm pulling this out of thin air, if it doesn't work either someone with more current knowledge will have to answer or I'll have to grab some source code and try myself.

```<code>SharpDX.Direct2D1.Bitmap dxbmp = new SharpDX.Direct2D1.Bitmap(renderTarget,
new SharpDX.Size2(bmpWidth, bmpHeight), new
BitmapProperties(renderTarget.PixelFormat));
dxbmp.CopyFromMemory(bmpBits, bmpWidth * 4);
</code>```

This looks kind of like what you need.  I'm assuming bmpBits in here is either a byte array or a memory stream either of which could then be saved off or at least give you something to look at to see if you're actually getting pixel data

Body:
I followed this solution for my project : How to create bitmap from Surface (SharpDX)

I don't have enough reputation to comment so I'm opening a new question here.

My project is basically in Direct 2D, I have a Surface buffer, a swapchain. I want to put my buffer into a datastream and reads it's value to put it into a bitmap and save it on disk ( like a screen capture), but my code won't work since all the bytes values are 0 (which is black) and this doesn't make sense since my image is fully white with a bit of blue.

Here is my code :

SwapChainDescription description = new SwapChainDescription()
     {
        ModeDescription = new ModeDescription(this.Width, this.Height, new Rational(60, 1), Format.B8G8R8A8_UNorm),
        SampleDescription = new SampleDescription(1, 0),
        Usage = Usage.RenderTargetOutput,
        BufferCount = 1,
        SwapEffect = SwapEffect.Discard,
        IsWindowed = true,
        OutputHandle = this.Handle
     };

     Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, description, out device, out swapChain);

     SharpDX.DXGI.Device dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device>();
     SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice.Adapter;

     SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice);
     d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
     SharpDX.Direct3D11.DeviceContext d3DeviceContext = new SharpDX.Direct3D11.DeviceContext(device);

     properties = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
          96, 96);

     Surface backBuffer = swapChain.GetBackBuffer<Surface>(0);
     d2dTarget = new SharpDX.Direct2D1.Bitmap(d2dContext, backBuffer, properties);

     d2dContext.Target = d2dTarget;

     playerBitmap = this.LoadBitmapFromContentFile(@"C:\Users\ndesjardins\Desktop\wave.png");

     //System.Drawing.Bitmap bitmapCanva = new System.Drawing.Bitmap(1254, 735);

     d2dContext.BeginDraw();
     d2dContext.Clear(SharpDX.Color.White);
     d2dContext.DrawBitmap(playerBitmap, new SharpDX.RectangleF(0, 0, playerBitmap.Size.Width, playerBitmap.Size.Height), 1f, SharpDX.Direct2D1.BitmapInterpolationMode.NearestNeighbor);
     SharpDX.Direct2D1.SolidColorBrush brush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, SharpDX.Color.Green);
     d2dContext.DrawRectangle(new SharpDX.RectangleF(200, 200, 100, 100), brush);
     d2dContext.EndDraw();

     swapChain.Present(1, PresentFlags.None);

     Texture2D backBuffer3D = backBuffer.QueryInterface<SharpDX.Direct3D11.Texture2D>();

     Texture2DDescription desc = backBuffer3D.Description;
     desc.CpuAccessFlags = CpuAccessFlags.Read;
     desc.Usage = ResourceUsage.Staging;
     desc.OptionFlags = ResourceOptionFlags.None;
     desc.BindFlags = BindFlags.None;

     var texture = new Texture2D(device, desc);

     d3DeviceContext.CopyResource(backBuffer3D, texture);

     byte[] data = null;
     using (Surface surface = texture.QueryInterface<Surface>())
     {
        DataStream dataStream;
        var map = surface.Map(SharpDX.DXGI.MapFlags.Read, out dataStream);
        int lines = (int)(dataStream.Length / map.Pitch);
        data = new byte[surface.Description.Width * surface.Description.Height * 4];

        dataStream.Position = 0;
        int dataCounter = 0;
        // width of the surface - 4 bytes per pixel.
        int actualWidth = surface.Description.Width * 4;
        for (int y = 0; y < lines; y++)
        {
           for (int x = 0; x < map.Pitch; x++)
           {
              if (x < actualWidth)
              {
                 data[dataCounter++] = dataStream.Read<byte>();
              }
              else
              {
                 dataStream.Read<byte>();
              }
           }
        }
        dataStream.Dispose();
        surface.Unmap();

        int width = surface.Description.Width;
        int height = surface.Description.Height;
        byte[] bytewidth = BitConverter.GetBytes(width);
        byte[] byteheight = BitConverter.GetBytes(height);

        Array.Copy(bytewidth, 0, data, 0, 4);
        Array.Copy(byteheight, 0, data, 4, 4);

     }

Do you guys have any idea why the byte array that is returned at the end is full of 0 since it should be mostly 255? All I did in my backbuffer was to draw a bitmap image and a rectangle form.  Array.Copy is to add the width and height header to the byte array, therefore I could create a bitmap out of it.

Body:
I answered in a comment but formatting is horrible so apologies!

https://gamedev.stackexchange.com/a/112978/29920  This looks promising but as you said in reply to mine, this was some time ago and I'm pulling this out of thin air, if it doesn't work either someone with more current knowledge will have to answer or I'll have to grab some source code and try myself.

SharpDX.Direct2D1.Bitmap dxbmp = new SharpDX.Direct2D1.Bitmap(renderTarget,
new SharpDX.Size2(bmpWidth, bmpHeight), new
BitmapProperties(renderTarget.PixelFormat));
dxbmp.CopyFromMemory(bmpBits, bmpWidth * 4);

This looks kind of like what you need.  I'm assuming bmpBits in here is either a byte array or a memory stream either of which could then be saved off or at least give you something to look at to see if you're actually getting pixel data


问:
Python not showing the [matplotlib] window with openCV results
I'm working on OpenCV 2.4.9 . Below is my code -

```<code>import cv2
import numpy as np
from   matplotlib import pyplot as plt

BLUE = [255,0,0]

img1 = cv2.imread( 'sachin.png' )

replicate  = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REPLICATE )
reflect    = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT )
reflect101 = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT_101 )
wrap       = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_WRAP )
constant   = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value = BLUE )

plt.subplot(231), plt.imshow( img1,       'gray' ), plt.title( 'ORIGINAL' )
plt.subplot(232), plt.imshow( replicate,  'gray' ), plt.title( 'REPLICATE')
plt.subplot(233), plt.imshow( reflect,    'gray' ), plt.title( 'REFLECT' )
plt.subplot(234), plt.imshow( reflect101, 'gray' ), plt.title( 'REFLECT_101' )
plt.subplot(235), plt.imshow( wrap,       'gray' ), plt.title( 'WRAP' )
plt.subplot(236), plt.imshow( constant,   'gray' ), plt.title( 'CONSTANT' )

plt.show()
</code>```

When I run the above code I got the following error -

```<code>Traceback (most recent call last):
  File "border.py", line 3, in <module>
    from matplotlib import pyplot as plt
ImportError: No module named matplotlib
</code>```

After googling, I found that Matplotlib module was missing then I installed it from the following commands -
sudo python get-pip.py to install pip. sudo python get-pip.py to install matplotlib.
After when I run the code no error was reported and the code ran successfully but no windows are displayed. Can anyone tell me where I'm going wrong?

答:
I had similar error in some previous program using matplotlib. Installing python-tk package resolved it for me.

```<code>      sudo apt-get install python-tk
</code>```

Hope this works!

Body:
I'm working on OpenCV 2.4.9 . Below is my code -

import cv2
import numpy as np
from   matplotlib import pyplot as plt

BLUE = [255,0,0]

img1 = cv2.imread( 'sachin.png' )

replicate  = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REPLICATE )
reflect    = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT )
reflect101 = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_REFLECT_101 )
wrap       = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_WRAP )
constant   = cv2.copyMakeBorder( img1, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value = BLUE )

plt.subplot(231), plt.imshow( img1,       'gray' ), plt.title( 'ORIGINAL' )
plt.subplot(232), plt.imshow( replicate,  'gray' ), plt.title( 'REPLICATE')
plt.subplot(233), plt.imshow( reflect,    'gray' ), plt.title( 'REFLECT' )
plt.subplot(234), plt.imshow( reflect101, 'gray' ), plt.title( 'REFLECT_101' )
plt.subplot(235), plt.imshow( wrap,       'gray' ), plt.title( 'WRAP' )
plt.subplot(236), plt.imshow( constant,   'gray' ), plt.title( 'CONSTANT' )

plt.show()

When I run the above code I got the following error -

Traceback (most recent call last):
  File "border.py", line 3, in <module>
    from matplotlib import pyplot as plt
ImportError: No module named matplotlib

After googling, I found that Matplotlib module was missing then I installed it from the following commands -
sudo python get-pip.py to install pip. sudo python get-pip.py to install matplotlib.
After when I run the code no error was reported and the code ran successfully but no windows are displayed. Can anyone tell me where I'm going wrong?

Body:
I had similar error in some previous program using matplotlib. Installing python-tk package resolved it for me.

      sudo apt-get install python-tk

Hope this works!


问:
Declaring variables for multiple scripts and best practices
What is the best way to put  variables in python for multiple scripts?

I have the following scripts:

main.py: This script to declare  common variables for one.py, two.py, and three.py. Also takes input from the user in interactive way and from the defined input file.

config.py: This script has all three scripts configurations inputs like ip-adress, ports details. etc.

one.py: I have written this script with class and it take inputs from main.py and config.py.

two.py: I have written this script with class and it take inputs from main.py and config.py.

three.py: I have written this script with class and it take inputs from main.py and config.py.

run.py: This script loads class objects for the one.py, two.py, and three.py and calls the functions defined in them.

main.py

```<code>list1 = []
a = "common for one.py,two.py and three.py"
</code>```

one.py

```<code>import main
main.list1.append("1")
</code>```

two.py

```<code>import main
main.list1.append("2")
</code>```

three.py

```<code>import main
main.list1.append("3")
</code>```

Running script:

run.py

```<code>import main
import one
import two
import three
# start performing
#call  one script functions
#call  two script functions
#call  three script functions
</code>```

I need some suggestions from you.

Am I am doing it in right way?

Will my scripts be easy for future maintenance?

Since I am putting variable list1 in main.py. It will first
appending some value in one.py and then two.py is going to access it.
My doubt is two.py is importing main.py in this case it does not
overwrite with empty list value? I have tested it, and it  works fine.
But I still want to take your suggestions for best practices.

答:
Yes, I think what you're doing is basically OK. I would rename a couple of the scripts to better indicate their roles: I would rename run.py and make it main.py, and make what you called main.py something like common.py. However, for the sake of discussion, I'll use the script names you have in your question.

You don't have to worry about what's in your main.py reinitializing list1 variable every time it's imported. That's because the results of importing  modules are "cached" in sys.modules and the top-level code in them only executes the first time they're imported. If another script imports one of them again, the results of the first time saved in cached version is used. You can think of loaded modules as "singleton" instances of a module class (which in fact they are, see types.ModuleType).

If there's a dependency in your run.py that the modules one, two, and three are imported in a certain order, then I would import them all in your main module, so other scripts don't have to worry about it (the ordering). That way other scripts can just import whichever ones they want to use.

The above is not to say your design couldn't be improved. It looks like you're basically using global variables, which have long been considered a "bad thing" for a number of reasons (see Global Variables Are Bad). To avoid that, the direct use of list1 would need to be replaced with an instance of some new custom class with it's lifetime and access to it handled indirectly via methods defined in the class after explicitly creating an instance of it. This instance would then need to be passed as argument to any function or method that needed use or otherwise do something with or to the instance.

Body:
What is the best way to put  variables in python for multiple scripts?

I have the following scripts:

main.py: This script to declare  common variables for one.py, two.py, and three.py. Also takes input from the user in interactive way and from the defined input file.

config.py: This script has all three scripts configurations inputs like ip-adress, ports details. etc.

one.py: I have written this script with class and it take inputs from main.py and config.py.

two.py: I have written this script with class and it take inputs from main.py and config.py.

three.py: I have written this script with class and it take inputs from main.py and config.py.

run.py: This script loads class objects for the one.py, two.py, and three.py and calls the functions defined in them.

main.py

list1 = []
a = "common for one.py,two.py and three.py"

one.py

import main
main.list1.append("1")

two.py

import main
main.list1.append("2")

three.py

import main
main.list1.append("3")

Running script:

run.py

import main
import one
import two
import three
# start performing
#call  one script functions
#call  two script functions
#call  three script functions

I need some suggestions from you.

Am I am doing it in right way?

Will my scripts be easy for future maintenance?

Since I am putting variable list1 in main.py. It will first
appending some value in one.py and then two.py is going to access it.
My doubt is two.py is importing main.py in this case it does not
overwrite with empty list value? I have tested it, and it  works fine.
But I still want to take your suggestions for best practices.


问:
Issue in importing Polymer dependencies with AngularDart
Resolving dependencies...
Package polymer has no versions that match >=1.0.0 <2.0.0 derived from:
my-app depends on version ^1.0.0
Process finished with exit code 1</p>

答:
Unfortunately package:polymer hasn't been updated in quite since time, so old dependency ranges are likely to blame here. There is a community supported new version of PolymerDart (https://www.dart-polymer.com/) that might work better - but my recommendation is not to mix Polymer and AngularDart in the same application at this time.

Hope that helps!


问:
find_in_set return different value
I have a table with this declaration:

```<code>CREATE TABLE foobar (
  id int(11) NOT NULL AUTO_INCREMENT,
  dow set('q','w','e','r','t','y', 'u') NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT;
</code>```

With those values inside:

```<code> id,   dow
'1', '1,3,6'
'1', '2,4,7'
</code>```

Those query returns different values.

```<code>SELECT dow, FIND_IN_SET('4', dow) FROM (SELECT * from pippo.pluto) as B;

SELECT dow, FIND_IN_SET('4', dow) FROM pippo.pluto as B;
</code>```

The first query returns those results:

```<code>'1,3,6', '0'
'2,4,7', '2'
</code>```

The second query returns those results:

```<code>'1,3,6', '0'
'2,4,7', '4'
</code>```

Why?

Tested against 5.6 and 5.7 mysql version.

Edit:

This behaviour remains the same if I use the mysql views.

```<code>CREATE VIEW selectInner AS SELECT dow, FIND_IN_SET('r', dow) FROM (SELECT * from pippo.foobar) as B;
CREATE VIEW selectDirect AS SELECT dow, FIND_IN_SET('r', dow) FROM pippo.foobar as B;
</code>```

答:
There are two things interacting here:

"If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic." per FIND_IN_SET docs

One of the two queries operates directly on the table, and the second on a derived table.

The behaviour demonstrates this:

When operating directly on the table (where dow refers to the defined column in that table's metadata), FIND_IN_SET returns the index of the entry in the column's definition

When operating on a derived table (where dow refers to a derived column), FIND_IN_SET returns the index of the entry in the derived value

This is clear if you search for e.g. y and u in a column containing q,e,y,u: you'd get 6 and 7 when querying the table directly, where dow is a SET containing q,w,e,r,t,y,u and FIND_IN_SET uses bitwise optimizations; but 3 and 4 when searching the derived table, where dow is the string containing q,e,y,u for that row.

Title: find_in_set return different value

Body:
I have a table with this declaration:

CREATE TABLE foobar (
  id int(11) NOT NULL AUTO_INCREMENT,
  dow set('q','w','e','r','t','y', 'u') NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT;

With those values inside:

 id,   dow
'1', '1,3,6'
'1', '2,4,7'

Those query returns different values.

SELECT dow, FIND_IN_SET('4', dow) FROM (SELECT * from pippo.pluto) as B;

SELECT dow, FIND_IN_SET('4', dow) FROM pippo.pluto as B;

The first query returns those results:

'1,3,6', '0'
'2,4,7', '2'

The second query returns those results:

'1,3,6', '0'
'2,4,7', '4'

Why?

Tested against 5.6 and 5.7 mysql version.

Edit:

This behaviour remains the same if I use the mysql views.

CREATE VIEW selectInner AS SELECT dow, FIND_IN_SET('r', dow) FROM (SELECT * from pippo.foobar) as B;
CREATE VIEW selectDirect AS SELECT dow, FIND_IN_SET('r', dow) FROM pippo.foobar as B;


问:
How do I fix a java.lang.UnsupportedClassVersionError?
I have a simple Java program that consists of two .java files. It runs fine when executed from my IDE (IntelliJ). It also compiles (via the javac utility) just fine. However, when I attempt to run it from the Windows command prompt (using java <<myClassName>>) I get this error:

```<code>Exception in thread "main" java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=RunExport, offset=6
        at java.lang.ClassLoader.defineClassImpl(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:364)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:777)
        at java.net.URLClassLoader.access$400(URLClassLoader.java:96)
        at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1225)
        at java.security.AccessController.doPrivileged(AccessController.java:366)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:660)
        at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:942)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:851)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:827)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:494)
</code>```

I have read various questions and proposed solutions for this error, but I have not been able to solve it. It appears that the version of Java used to compile the code is not recognized as being the same as that of the JRE in which I am running it. I am using jdk1.8.0_91. The javac.exe and java.exe files I am using are both in C:\Program Files\Java\jdk1.8.0_91\bin. This is also the path defined in my Windows PATH environment variable.

答:
This error means you are compiling and running with different, incompatible versions of Java.

Do java -version and javac -version to find out what versions these commands are actually using.

Then, to fix the version, you have three options:

Change which version of Java is used through the Java control panel.

Change which version of Java is used by editing your PATH environment variable. The path to your desired Java version should come before the path to any other Java versions.

If neither of these seems to work, or if this is a one-time use, you can simply specify the full path when running/compiling your program:

```<code>C:\Program Files\Java\jdk1.8.0_91\bin\java.exe
</code>```

This material taken from comments by Carlos Heuberger

Body:
I have a simple Java program that consists of two .java files. It runs fine when executed from my IDE (IntelliJ). It also compiles (via the javac utility) just fine. However, when I attempt to run it from the Windows command prompt (using java <<myClassName>>) I get this error:

Exception in thread "main" java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=RunExport, offset=6
        at java.lang.ClassLoader.defineClassImpl(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:364)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:777)
        at java.net.URLClassLoader.access$400(URLClassLoader.java:96)
        at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1225)
        at java.security.AccessController.doPrivileged(AccessController.java:366)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:660)
        at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:942)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:851)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:827)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:494)

I have read various questions and proposed solutions for this error, but I have not been able to solve it. It appears that the version of Java used to compile the code is not recognized as being the same as that of the JRE in which I am running it. I am using jdk1.8.0_91. The javac.exe and java.exe files I am using are both in C:\Program Files\Java\jdk1.8.0_91\bin. This is also the path defined in my Windows PATH environment variable.

Body:
This error means you are compiling and running with different, incompatible versions of Java.

Do java -version and javac -version to find out what versions these commands are actually using.

Then, to fix the version, you have three options:

Change which version of Java is used through the Java control panel.

Change which version of Java is used by editing your PATH environment variable. The path to your desired Java version should come before the path to any other Java versions.

If neither of these seems to work, or if this is a one-time use, you can simply specify the full path when running/compiling your program:

C:\Program Files\Java\jdk1.8.0_91\bin\java.exe

This material taken from comments by Carlos Heuberger


问:
Bootstrap form input does not allow for editing when clicked
Problem:
My bootstrap form does not allow for editing.

Details:
I am using a bootstrap form within a .thumbnail and the .caption class. I wanted very specific column sizing for each form-group which is why I used a nested grid system. When I click on an input absolutely nothing happens (literally nothing). However, when I connect a jQuery event listener to the input the event does indeed fire. Why does my form appear to be incapable of editing? Thank you in advance!

Web Development Application

    <form class="col-xs-12" method="post">

        First Name

          <input id="first-name" type="text" class="form-control" placeholder="John">

        Last Name

          <input id="last-name" type="text" class="form-control" placeholder="Doe" />

        Email Address

          <input id="apply-email" type="email" class="form-control" placeholder="johnnyappleseed@gmail.com" />

        LinkedIn

          <input id="linked-in" type="text" class="form-control" placeholder="mylinkedIn.com" />

        Portfolio

          <input id="portfolio" type="text" class="form-control" placeholder="mylinkedIn.com" />

        CV

                                Upload <input class="form-control" type="file">

              No file chosen...

          <button type="submit" class="submit-btn col-sm-4 col-sm-offset-8 btn btn-success btn-mini">Submit!</button>

    </form>

```

答:
Web Development Application

    <form class="col-xs-12" method="post">

        First Name

          <input id="first-name" type="text" class="form-control" placeholder="John">

        Last Name

          <input id="last-name" type="text" class="form-control" placeholder="Doe" />

        Email Address

          <input id="apply-email" type="email" class="form-control" placeholder="johnnyappleseed@gmail.com" />

        LinkedIn

          <input id="linked-in" type="text" class="form-control" placeholder="mylinkedIn.com" />

        Portfolio

          <input id="portfolio" type="text" class="form-control" placeholder="mylinkedIn.com" />

        CV

                                Upload <input class="form-control" type="file">

              No file chosen...

          <button type="submit" class="submit-btn col-sm-4 col-sm-offset-8 btn btn-success btn-mini">Submit!</button>

    </form>

```

Your code seems to be working perfectly fine.

Body:
<div class="thumbnail">
  <div class="col-xs-10 col-centered">
    <h3 id="application-type">Web Development Application</h3>
    <hr>
  </div>
  <div class="caption row">
    <form class="col-xs-12" method="post">
      <div class="form-group row">
        <label for="first-name" class="col-sm-3 col-form-label"><strong>First Name</strong></label>
        <div class="col-sm-9">
          <input id="first-name" type="text" class="form-control" placeholder="John">
        </div>
      </div>
      <div class="form-group row">
        <label for="last-name" class="col-sm-3 col-form-label"><strong>Last Name</strong></label>
        <div class="col-sm-9">
          <input id="last-name" type="text" class="form-control" placeholder="Doe" />
        </div>
      </div>
      <div class="form-group row">
        <label for="apply-email" class="col-sm-3 col-form-label"><strong>Email Address</strong></label>
        <div class="col-sm-9">
          <input id="apply-email" type="email" class="form-control" placeholder="johnnyappleseed@gmail.com" />
        </div>
      </div>
      <div class="form-group row">
        <label for="linked-in" class="col-sm-3 col-form-label"><strong>LinkedIn</strong></label>
        <div class="col-sm-9">
          <input id="linked-in" type="text" class="form-control" placeholder="mylinkedIn.com" />
        </div>
      </div>
      <div id="show-portfolio" style="display: none;" class="form-group row">
        <label for="portfolio" class="col-sm-3 col-form-label"><strong>Portfolio</strong></label>
        <div class="col-sm-9">
          <input id="portfolio" type="text" class="form-control" placeholder="mylinkedIn.com" />
        </div>
      </div>
      <div class="form-group row">
        <label for="apply-file-btn" class="col-sm-3 col-form-label"><strong>CV</strong></label>
        <div class="col-sm-9">
          <ul class="file-btn-group">
            <li>
              <span class="btn btn-primary btn-file">
                                Upload <input class="form-control" type="file">
                            </span>
            </li>
            <li class="file-name">
              <span>No file chosen...</span>
            </li>
          </ul>
        </div>
      </div>
      <div class="form-group row">
        <div class="col-sm-12">
          <button type="submit" class="submit-btn col-sm-4 col-sm-offset-8 btn btn-success btn-mini">Submit!</button>
        </div>
      </div>
    </form>
  </div>
</div>

Your code seems to be working perfectly fine.


问:
RecyclerView List not correct displayed ArrayList
I am populating my recyclerView with an arrayList depending on selected item and rest service call. The problem is that at first for the default selected item it gets correctly populated but the moment I choose another item to get its data, things get weird : it gets the list as if I kept the previous item selected, it dosen't get synchronized, I checked that the choice is being passed to the rest webservice to bring back the correct data. Any ideas ?

Here is my code :

```<code>       facturelist=new ArrayList<>();
   Toast.makeText(getActivity().getApplicationContext(),"fac Ond"+ondSel, Toast.LENGTH_SHORT).show();
    apiService = RestService.createService(SolarAPIService.class);
    Call<List<ListFacture>> call = apiService.listFactureStringDate(ondSel);

    call.enqueue(new Callback<List<ListFacture>>() {
        @Override
        public void onResponse(Call<List<ListFacture>> call, retrofit2.Response<List<ListFacture>> response) {
        try {

            for (ListFacture fac : response.body()) {
                facturelist.add(fac);
                factureAdapter.notifyDataSetChanged();

            }
            Collections.sort(facturelist, new Comparator<ListFacture>() {
                public int compare(ListFacture o1, ListFacture o2) {
                    if (o1.getDateDebut() == null || o2.getDateDebut() == null)
                        return 0;
                    return o2.getDateDebut().compareTo(o1.getDateDebut());
                }
            });

            Toast.makeText(getActivity().getApplicationContext(),"facture List"+facturelist.size(), Toast.LENGTH_SHORT).show();
            factureAdapter.notifyDataSetChanged();
            recyclerView.setAdapter(factureAdapter);
            recyclerLay.setVisibility(View.GONE);
            slideDown= AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.slide_up);
            recyclerLay.startAnimation(slideDown);
            recyclerLay.setVisibility(View.VISIBLE);
            progress.setVisibility(View.GONE);
        }catch (NegativeArraySizeException nx){
            progress.setVisibility(View.GONE);
            layoutFactures.setVisibility(View.GONE);
            notFound.setVisibility(View.VISIBLE);
            errorNotFound.setText(R.string.onduleur_alerts_404);
        }
        }

        @Override
        public void onFailure(Call<List<ListFacture>> call, Throwable t) {
       Log.e("Error",t.getMessage());
            Toast.makeText(getActivity().getApplicationContext(),"facture List"+t.getStackTrace(), Toast.LENGTH_SHORT).show();
        }
    });

}
</code>```

It looks as if factureList keeping its previous state.

答:
You are creating new instance for fractureList before new request but you are not changing instance (or its content) in your adapter.

You should change list in your Adapter to the new instance or recreate the adapter from scratch.

Body:
I am populating my recyclerView with an arrayList depending on selected item and rest service call. The problem is that at first for the default selected item it gets correctly populated but the moment I choose another item to get its data, things get weird : it gets the list as if I kept the previous item selected, it dosen't get synchronized, I checked that the choice is being passed to the rest webservice to bring back the correct data. Any ideas ?

Here is my code :

       facturelist=new ArrayList<>();
   Toast.makeText(getActivity().getApplicationContext(),"fac Ond"+ondSel, Toast.LENGTH_SHORT).show();
    apiService = RestService.createService(SolarAPIService.class);
    Call<List<ListFacture>> call = apiService.listFactureStringDate(ondSel);

    call.enqueue(new Callback<List<ListFacture>>() {
        @Override
        public void onResponse(Call<List<ListFacture>> call, retrofit2.Response<List<ListFacture>> response) {
        try {

            for (ListFacture fac : response.body()) {
                facturelist.add(fac);
                factureAdapter.notifyDataSetChanged();

            }
            Collections.sort(facturelist, new Comparator<ListFacture>() {
                public int compare(ListFacture o1, ListFacture o2) {
                    if (o1.getDateDebut() == null || o2.getDateDebut() == null)
                        return 0;
                    return o2.getDateDebut().compareTo(o1.getDateDebut());
                }
            });

            Toast.makeText(getActivity().getApplicationContext(),"facture List"+facturelist.size(), Toast.LENGTH_SHORT).show();
            factureAdapter.notifyDataSetChanged();
            recyclerView.setAdapter(factureAdapter);
            recyclerLay.setVisibility(View.GONE);
            slideDown= AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.slide_up);
            recyclerLay.startAnimation(slideDown);
            recyclerLay.setVisibility(View.VISIBLE);
            progress.setVisibility(View.GONE);
        }catch (NegativeArraySizeException nx){
            progress.setVisibility(View.GONE);
            layoutFactures.setVisibility(View.GONE);
            notFound.setVisibility(View.VISIBLE);
            errorNotFound.setText(R.string.onduleur_alerts_404);
        }
        }

        @Override
        public void onFailure(Call<List<ListFacture>> call, Throwable t) {
       Log.e("Error",t.getMessage());
            Toast.makeText(getActivity().getApplicationContext(),"facture List"+t.getStackTrace(), Toast.LENGTH_SHORT).show();
        }
    });

}

It looks as if factureList keeping its previous state.


问:
How to run Expo test suite
I generated sample expo app, pull the latest https://github.com/expo/test-suite. I run test-suite in the simulator, it shows a spinner which never disappears.

Can you provide me an instruction how to run the tests?

I see some warnings as well while running test-suite.

Warning
Warning: Using unversioned Expo SDK. Do not publish until you set sdkVersion in exp.json
Warning
Warning: 'react' peer depencency missing. Run `npm ls` in /project/test-suite to see full warning.

If there is an issue running your project, please run `npm install` in /project/test-suite and restart.```

Thanks

答:
the repository that you linked is not a "test" suit as you understand it. It is not for testing your app. It exist for the developers of Expo as a tool, to test Expo before new releases of it.

Check out more about unit testing and test driven development;

https://en.wikipedia.org/wiki/Unit_testing

https://en.wikipedia.org/wiki/Development_testing

If your goal is to test your own app in you will need a simulator or a development device;

https://docs.expo.io/versions/v18.0.0/guides/up-and-running.html

Title: How to run Expo test suite

Body:
I generated sample expo app, pull the latest https://github.com/expo/test-suite. I run test-suite in the simulator, it shows a spinner which never disappears.

Can you provide me an instruction how to run the tests?

I see some warnings as well while running test-suite.

Warning
Warning: Using unversioned Expo SDK. Do not publish until you set sdkVersion in exp.json
Warning
Warning: 'react' peer depencency missing. Run `npm ls` in /project/test-suite to see full warning.

If there is an issue running your project, please run `npm install` in /project/test-suite and restart.

Thanks


问:
Unable to cast transparent proxy to type from AppDomain
I'm trying to create an object in an appdomain:

```<code>var type = typeof (CompiledTemplate);
var obj = (CompiledTemplate) domain.CreateInstanceAndUnwrap (
    type.Assembly.FullName, type.FullName);
</code>```

However, I always get the following error:

Unable to cast transparent proxy to type 'Mono.TextTemplating.CompiledTemplate'.

I'm running on .NET 4.0, not Mono, despite what the namespace might suggest :)

As far as I know, this error happens when .NET thinks that the Type & Assembly do not exactly match in the two domains. However, when debugging, the FullName and Location are identical. Only the Assembly.Codebase property differs - in the child AppDomain its extension is uppercased to "DLL" for some reason.

I've tried adding an AssemblyResolve handler to the AppDomain, which uses Assembly.LoadFrom to load the filename explicitly, but the CodeBase's extension still gets uppercased. Since the original assembly was also loaded with Assembly.LoadFrom (via Mono.Addins), the difference between the CodeBase values seems very strange.

Any suggestions for fixing or working around this problem?

答:
Perhaps you can use the dynamic keyword instead of casting it to a specific type:

```<code>var type = typeof (CompiledTemplate);
dynamic obj = domain.CreateInstanceAndUnwrap (
    type.Assembly.FullName, type.FullName);
</code>```

That might at least give you a workaround to the problem.  Of course, the potential drawbacks will be not having compile time checking and/or slower performance.  However, these might be negligible trade-offs depending on your situation.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create an object in an appdomain:

var type = typeof (CompiledTemplate);
var obj = (CompiledTemplate) domain.CreateInstanceAndUnwrap (
    type.Assembly.FullName, type.FullName);

However, I always get the following error:

Unable to cast transparent proxy to type 'Mono.TextTemplating.CompiledTemplate'.

I'm running on .NET 4.0, not Mono, despite what the namespace might suggest :)

As far as I know, this error happens when .NET thinks that the Type & Assembly do not exactly match in the two domains. However, when debugging, the FullName and Location are identical. Only the Assembly.Codebase property differs - in the child AppDomain its extension is uppercased to "DLL" for some reason.

I've tried adding an AssemblyResolve handler to the AppDomain, which uses Assembly.LoadFrom to load the filename explicitly, but the CodeBase's extension still gets uppercased. Since the original assembly was also loaded with Assembly.LoadFrom (via Mono.Addins), the difference between the CodeBase values seems very strange.

Any suggestions for fixing or working around this problem?

Body:
Perhaps you can use the dynamic keyword instead of casting it to a specific type:

var type = typeof (CompiledTemplate);
dynamic obj = domain.CreateInstanceAndUnwrap (
    type.Assembly.FullName, type.FullName);

That might at least give you a workaround to the problem.  Of course, the potential drawbacks will be not having compile time checking and/or slower performance.  However, these might be negligible trade-offs depending on your situation.


问:
How to add multiple rows using "Insert ... ON DUPLICATE KEY UPDATE" using knex
so I've been playing around with knex lately, however I found myself on a situation where I don't know what to do anymore.

so I have this query:

```<code>knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
[
    ['val1', 'hello', 'world'],
    ['val2', 'ohayo', 'minasan'],
]);
</code>```

And for some reasons It throws me an error Expected 2 bindings, saw 3.

I tried making it:

```<code>knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
    ['val1', 'hello', 'world'],
    ['val2', 'ohayo', 'minasan'],
);
</code>```

No error this time, but it only inserts the first array.

I also tried making the values an object:

```<code>[
    {col1: 'val1', col2: 'hello', col3: 'world'},
    {col1: 'val2', col2: 'ohayo', col3: 'minasan'},
]
</code>```

But still no luck.

答:
If you only need to insert a fix number rows at a time, you could try this:

```<code>knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?), (?, ?, ?) ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
    ['val1', 'hello', 'world', 'val2', 'ohayo', 'minasan'],
);
</code>```

If you don't know how many you need to insert at a time, it is possible to write a script that adds (?, ?, ?), as many times as needed.

```<code>var questionMarks = "";
var values = [];
var rows = [
    {col1: 'val1', col2: 'hello', col3: 'world'},
    {col1: 'val2', col2: 'ohayo', col3: 'minasan'},
];
rows.forEach(function(value, index){
    questionMarks += "("
    Object.keys(value).forEach(function(x){
         questionMarks += "?, ";
         values.push(value[x]);
    });
    questionMarks = questionMarks.substr(0, questionMarks.length - 2);
    questionMarks += "), ";
});
questionMarks = questionMarks.substr(0, questionMarks.length - 2); //cut off last unneeded comma and space
knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES " + questionMarks + " ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)", values);
</code>```

Body:
so I've been playing around with knex lately, however I found myself on a situation where I don't know what to do anymore.

so I have this query:

knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
[
    ['val1', 'hello', 'world'],
    ['val2', 'ohayo', 'minasan'],
]);

And for some reasons It throws me an error Expected 2 bindings, saw 3.

I tried making it:

knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
    ['val1', 'hello', 'world'],
    ['val2', 'ohayo', 'minasan'],
);

No error this time, but it only inserts the first array.

I also tried making the values an object:

[
    {col1: 'val1', col2: 'hello', col3: 'world'},
    {col1: 'val2', col2: 'ohayo', col3: 'minasan'},
]

But still no luck.

Body:
If you only need to insert a fix number rows at a time, you could try this:

knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?), (?, ?, ?) ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
    ['val1', 'hello', 'world', 'val2', 'ohayo', 'minasan'],
);

If you don't know how many you need to insert at a time, it is possible to write a script that adds (?, ?, ?), as many times as needed.

var questionMarks = "";
var values = [];
var rows = [
    {col1: 'val1', col2: 'hello', col3: 'world'},
    {col1: 'val2', col2: 'ohayo', col3: 'minasan'},
];
rows.forEach(function(value, index){
    questionMarks += "("
    Object.keys(value).forEach(function(x){
         questionMarks += "?, ";
         values.push(value[x]);
    });
    questionMarks = questionMarks.substr(0, questionMarks.length - 2);
    questionMarks += "), ";
});
questionMarks = questionMarks.substr(0, questionMarks.length - 2); //cut off last unneeded comma and space
knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES " + questionMarks + " ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)", values);


问:
How to create an Xtext wildcard terminal rule for any combination of characters?
I want to write a rule for the following

```<code>INTEGER X;
IF GIBBERISH THEN
    X = 10;
ELSE
    X = 15;
END;
</code>```

In the above program I want to write a terminal rule for any character in GIBBERISH like code('Xfr) or ADEF==DCF+1 something like that.

I wrote a terminal rule

```<code>// GIBBERISH
terminal GIBBERISH: (.)* ;
</code>```

And  I got this error

```<code>The following token definitions can never be matched because prior tokens match the same
input: RULE_ID,RULE_INT,RULE_STRING,RULE_ML_COMMENT,RULE_WS,RULE_ANY_OTHER
</code>```

I also understand why this error message is being showed but anyways I want to override this.

答: Just not extend your grammar from Terminals rule. Remove extend string from grammar head and all these terminals will be removed.</p>

Body:
I want to write a rule for the following

INTEGER X;
IF GIBBERISH THEN
    X = 10;
ELSE
    X = 15;
END;

In the above program I want to write a terminal rule for any character in GIBBERISH like code('Xfr) or ADEF==DCF+1 something like that.

I wrote a terminal rule

// GIBBERISH
terminal GIBBERISH: (.)* ;

And  I got this error

The following token definitions can never be matched because prior tokens match the same
input: RULE_ID,RULE_INT,RULE_STRING,RULE_ML_COMMENT,RULE_WS,RULE_ANY_OTHER

I also understand why this error message is being showed but anyways I want to override this.


问:
Choosing a data structure
Different Data structures are used according to requirement but how would I know which data structure should I use? I just want to know how to choose an appropriate data structure ? Thanks</p>

答:
Not what you are looking for, but it depends.

It depends on the data that you are storing, any constraints on accessing that data, do you need to be able to look things up really fast? Does it need to maintain any kind of sort on the data? Will you be sorting it later?

Even when you choose a data structure (Linked List, Map, Set) there a numerous variants among them that might further drive your decision.

My rule of thumb is this:

Go with the simplest that you can until you know otherwise that you need something more complicated.

Title: Choosing a data structure


问:
how to avoid file name being filtered in HttpServletRequest
My file name is abc#123.pdf which is passed to the server side by concatenating it to the url.

On the server side, I use this line to get the file name. But only get "abc", the string after # is filtered. How can I avoid this?

fileName= request.getParameter(DOCUMENT_NAME);

答:
This occurs because anything after # in URL is considerd as reference part of the URL. You need to encode you query parameters while sending it to server side. If you are using javascript you can do following.

```<code>var myUrl = "http://example.com?documentName=" + encodeURIComponent("abc#123.pdf");
</code>```

On java side after getting the parameter with following code

```<code>encodeFileName = request.getParameter(DOCUMENT_NAME);
</code>```

You can decode the value using URLDecoder .

```<code>String fileName = java.net.URLDecoder.decode(encodeFileName, "UTF-8");
</code>```

Make sure you use encodeURIComponent in javascript, if you use encodeURI it would not encode #.

Body:
This occurs because anything after # in URL is considerd as reference part of the URL. You need to encode you query parameters while sending it to server side. If you are using javascript you can do following.

var myUrl = "http://example.com?documentName=" + encodeURIComponent("abc#123.pdf");

On java side after getting the parameter with following code

encodeFileName = request.getParameter(DOCUMENT_NAME);

You can decode the value using URLDecoder .

String fileName = java.net.URLDecoder.decode(encodeFileName, "UTF-8");

Make sure you use encodeURIComponent in javascript, if you use encodeURI it would not encode #.


问:
Why -NotMatch is not working while using within a PowerShell script?
I have one XML file. I want to search for a string and then delete that line from the file.

Now the problem is that when I run following code from PS console, it works fine - deletes the line which contains "test3". But when I put the same code inside a PS script and run it, it is NOT deleting the intended line. Can you please let me know if I am missing something?

test.txt:

```<code>test1
test2
test3
test4
test5
test6
</code>```

Code:

```<code>$loc = "D:\test.txt"
$msg = "test3"
$newF = Get-Content -Path $loc | where {$_ -notmatch $msg}
$newF
</code>```

I am using PSVersion: 5.1.14393.1358.

答:
-notmatch is designed to work with a regex.  I'd suggest using -notlike in the future.  As others have stated, your limited example is not reproducible.

Doc on -notmatch: Link

Body:
I have one XML file. I want to search for a string and then delete that line from the file.

Now the problem is that when I run following code from PS console, it works fine - deletes the line which contains "test3". But when I put the same code inside a PS script and run it, it is NOT deleting the intended line. Can you please let me know if I am missing something?

test.txt:

test1
test2
test3
test4
test5
test6

Code:

$loc = "D:\test.txt"
$msg = "test3"
$newF = Get-Content -Path $loc | where {$_ -notmatch $msg}
$newF

I am using PSVersion: 5.1.14393.1358.


问:
insert attributes dynamically in html elements in angular
I have to insert a set of attributes to my a component I want to re use...
now different attributes will come as string to me...
say for example I want to insert an element in my component

```<code><input type="text" maxlength="10" placeholder="enter your name"/>
</code>```

then i will get all the attributes as a single string

```<code>attr = 'type="text" maxlength="10" placeholder="enter your name"'
</code>```

in the controller for my component...
and i have to insert that to my conponent  in the html...

i have tried

```<code><input {{attr}}/>
</code>```

and

```<code><input {{jQuery.parseHtml(attr)}}
</code>```

etc..

but it is not working... also, could not find any solutions...
please share any solutions or some links/references helpful for me...

答:
Use binding for each attribute you want to change dynamically

Component:

```<code>typeTxt: string = "text";
maxLengthNum: number = 10;
placeholderString: string ="enter your name";
</code>```

Html:

```<code><input [type]="typeTxt" [maxlength]="maxLengthNum" [placeholder]="placeholderString"/>
</code>```

See the documentation to better understand data binding and deal with the different attribute types (Properties, events, two-way, etc.)

Use the parent tag to dynamically change your template

Component:

```<code>htmlString: string = '<input type="text" maxlength="10" placeholder="enter your name"/>';
</code>```

Html:

```<code><div [innerHTML]="htmlString"></div>
</code>```

Result:

```<code><div>
    <input type="text" maxlength="10" placeholder="enter your name"/>
</div>
</code>```

Body:
I have to insert a set of attributes to my a component I want to re use...
now different attributes will come as string to me...
say for example I want to insert an element in my component

<input type="text" maxlength="10" placeholder="enter your name"/>

then i will get all the attributes as a single string

attr = 'type="text" maxlength="10" placeholder="enter your name"'

in the controller for my component...
and i have to insert that to my conponent  in the html...

i have tried

<input {{attr}}/>

and

<input {{jQuery.parseHtml(attr)}}

etc..

but it is not working... also, could not find any solutions...
please share any solutions or some links/references helpful for me...

Body:
Use binding for each attribute you want to change dynamically

Component:

typeTxt: string = "text";
maxLengthNum: number = 10;
placeholderString: string ="enter your name";

Html:

<input [type]="typeTxt" [maxlength]="maxLengthNum" [placeholder]="placeholderString"/>

See the documentation to better understand data binding and deal with the different attribute types (Properties, events, two-way, etc.)

Use the parent tag to dynamically change your template

Component:

htmlString: string = '<input type="text" maxlength="10" placeholder="enter your name"/>';

Html:

<div [innerHTML]="htmlString"></div>

Result:

<div>
    <input type="text" maxlength="10" placeholder="enter your name"/>
</div>


问:
Find all numbers within square brackets using REGEX
I searched some posts but can't find the right solution for my problem.

I want all numbers that are within [].

I tested the following regex on regex101:

```<code>\\[.\*([0-9]++).*\\] .....    /gU <- Flags
</code>```

Test string:

```<code>Test bla bla [us_image_slider ids="6207,6204,6203,6199,6484,6470" nav="thumbs" img_size="us_img_size_2"] some numbers 232323 [img="344"] and [daas 23344 2333]2323 ( hello 233 )
</code>```

My Regex finds only the first number and not the others within the square brackets :(

Result has to be :
match0 = 6207
match1 = 6204
...

Hope you can help me, thanks.

答:
It doesn't match other digits since you are matching everything .* after first match.

You are looking for something like a positive lookahead:

```<code>\d+(?=[^][]*\])
</code>```

Live demo

Body:
I searched some posts but can't find the right solution for my problem.

I want all numbers that are within [].

I tested the following regex on regex101:

\\[.\*([0-9]++).*\\] .....    /gU <- Flags

Test string:

Test bla bla [us_image_slider ids="6207,6204,6203,6199,6484,6470" nav="thumbs" img_size="us_img_size_2"] some numbers 232323 [img="344"] and [daas 23344 2333]2323 ( hello 233 )

My Regex finds only the first number and not the others within the square brackets :(

Result has to be :
match0 = 6207
match1 = 6204
...

Hope you can help me, thanks.

Body:
It doesn't match other digits since you are matching everything .* after first match.

You are looking for something like a positive lookahead:

\d+(?=[^][]*\])

Live demo


问:
angular2 - FormGroup Validation not triggering
I have a FormGroup inside a form. I need to validate the FormGroup controls when I click the submit button, but it is not triggering. TransactionForm is the form and allocationForm is the FormGroup. I need to validate the FormGroup lone when clicking add button ie. required field validation is not triggering.

component.ts

this.transactionForm = this.fb.group({
  allocationForm: this.fb.group({
    fund: new FormControl(['', Validators.required]),
    amount: new FormControl(['', Validators.required]),
  })
});
```

<h3>html</h3>

<pre class="lang-html prettyprint-override"><code><form novalidate *ngIf="transactionForm" [formGroup]="transactionForm" (ngSubmit)="submitTransaction()">
  <div class="form-group">
    <label for="name">name:</label>
    <input type="text" class="form-control" formControlName="name">
    <br/>
  </div>
  <fieldset formGroupName="allocationForm">
    <div class="form-group row">
      <label for="amount" class="col-lg-4 col-form-label">    {{labels.percent}}</label>
      <div class="col-lg-8">
        <input name="amount" type="number" class="form-control" placeholder="" min="1" step="1" formControlName="amount" required>
        <div class="form-control-feedback" *ngIf="errors.amount">
          errors.amount
        </div>
      </div>
    </div>
    <div class="form-group row">
      <div class="offset-lg-4 col-lg-8">
        <button type="button" class="btn btn-secondary" class="form-control" name="addButton" type="submit">Add</button>
      </div>
    </div>
  </fieldset>
</form>
</code>```

答:
In your code at line

```<code>     <input name="amount" type="number" class="form-control" placeholder="" min="1" step="1" formControlName="amount" required>
</code>```

After this in the div tag you are using wrong condition,
It should be *ngIf="name.errors.<>",
example:
*ngIf="amount.errors.min".
Hope it helps

Body:
I have a FormGroup inside a form. I need to validate the FormGroup controls when I click the submit button, but it is not triggering. TransactionForm is the form and allocationForm is the FormGroup. I need to validate the FormGroup lone when clicking add button ie. required field validation is not triggering.

component.ts

this.transactionForm = this.fb.group({
  allocationForm: this.fb.group({
    fund: new FormControl(['', Validators.required]),
    amount: new FormControl(['', Validators.required]),
  })
});

html

<form novalidate *ngIf="transactionForm" [formGroup]="transactionForm" (ngSubmit)="submitTransaction()">

    name:
    <input type="text" class="form-control" formControlName="name">

  <fieldset formGroupName="allocationForm">

          {{labels.percent}}

        <input name="amount" type="number" class="form-control" placeholder="" min="1" step="1" formControlName="amount" required>

          errors.amount

        <button type="button" class="btn btn-secondary" class="form-control" name="addButton" type="submit">Add</button>

  </fieldset>
</form>

Body:
In your code at line

     <input name="amount" type="number" class="form-control" placeholder="" min="1" step="1" formControlName="amount" required>

After this in the div tag you are using wrong condition,
It should be *ngIf="name.errors.<>",
example:
*ngIf="amount.errors.min".
Hope it helps


问:
Webpatser/Laravel-UUID throwing exception at line 118 despite correct UUID generation
While working on a project, I ran into a problem with the Webpatser Laravel UUID module - it would throw an exception on UUID creation, because the UUIDs generated didn't match its strlen($uuid) = 16 condition. I didn't discover a solution online, so possibly it may be of use to somebody facing a similar issue.

答:
Turns out, both strlen and mb_strlen function oddly when calculating $uuid's length (even though var_dump'ing it returns string(16) as it should, the aforementioned functions provide a value between 11 and 13 during tests.

What I did is change the condition to strlen($uuid) > 16 which still results in correct UUID generation, and doesn't throw (in my opinion) silly exceptions.


问:
Print resultes to file
Can somebody help my with mine code. I want de results of the code printed in a .txt file on my system, but i cat an error and i can't resolve it by my self, please can somebody help me with the code ?

```<code># Importeer bibliotheek voor systeemfuncties.
import sys
import datetime
import time

############
## Part 1 ##
############
#temperatuur uitlezen
# Definieer een array (temp).
temp = {}

sensorids = ["28-0416b07c2dff"]
# loop net zo lang alles sensors af dat in het array hieboven staan.
    for sensor in range(len(sensorids)):
  tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave") #RPi 2,3 met nieuwe kernel.
  # Lees alle dat uit het "bestand" in een variabele.
  text = tfile.read()
  # Sluit het "bestand" nadat we het gelezen hebben.
  tfile.close()
  # We gaan nu de tekst splitsen per nieuwe regel (\n)
  # en we selecteren de 2e regel [1] (1e regel = [0])
  secondline = text.split("\n")[1]
  # Splits de regel in "woorden", er wordt gespleten op de spaties.
  # We selecteren hier het 10 "woord" [9] (tellend vanaf 0)
  temperaturedata = secondline.split(" ")[9]
  # De eerste 2 karakters zijn "t=", deze moeten we weghalen.
  # we maken meteen van de string een integer (nummer).
  temperature = float(temperaturedata[2:])
  # De temperatuurwaarde moeten we delen door 1000 voor de juiste waarde.
  temp[sensor] = temperature / 1000
  #laatste mogelijkheid
  temperatuur2 = temp[sensor]
  # print de gegevens naar de console.
  #print "sensor", sensor, "=", temp[sensor], "graden."
  print temperatuur2

############
## Part 2 ##
############
#waardes wegschrijven naar text bestand
#Open file
file = open("/home/pi/python_prog/_Log/_temp.txt", "a")

#schrijf waarde testbestand [Tijd: Temp]
file.write(time.strftime("%A %d-%m-%Y %H:%M:%S: " ))
file.write(temperatuur2)
file.write('\r\n')

#file.write()

#Sluit File
file.close()
</code>```

It goes wrong in the "part 2" selection, When i run the script i get the following error:

"Traceback (most recent call last):
  File "./python_prog/temp2.py", line 48, in
    file.write(temperatuur2)
TypeError: expected a character buffer object"

Please can you help me!?

答:
```<code>file.write(str(temperatuur2))
</code>```

you should be writing strings to files.

Title: Print resultes to file

Body:
Can somebody help my with mine code. I want de results of the code printed in a .txt file on my system, but i cat an error and i can't resolve it by my self, please can somebody help me with the code ?

# Importeer bibliotheek voor systeemfuncties.
import sys
import datetime
import time

############
## Part 1 ##
############
#temperatuur uitlezen
# Definieer een array (temp).
temp = {}

sensorids = ["28-0416b07c2dff"]
# loop net zo lang alles sensors af dat in het array hieboven staan.
    for sensor in range(len(sensorids)):
  tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave") #RPi 2,3 met nieuwe kernel.
  # Lees alle dat uit het "bestand" in een variabele.
  text = tfile.read()
  # Sluit het "bestand" nadat we het gelezen hebben.
  tfile.close()
  # We gaan nu de tekst splitsen per nieuwe regel (\n)
  # en we selecteren de 2e regel [1] (1e regel = [0])
  secondline = text.split("\n")[1]
  # Splits de regel in "woorden", er wordt gespleten op de spaties.
  # We selecteren hier het 10 "woord" [9] (tellend vanaf 0)
  temperaturedata = secondline.split(" ")[9]
  # De eerste 2 karakters zijn "t=", deze moeten we weghalen.
  # we maken meteen van de string een integer (nummer).
  temperature = float(temperaturedata[2:])
  # De temperatuurwaarde moeten we delen door 1000 voor de juiste waarde.
  temp[sensor] = temperature / 1000
  #laatste mogelijkheid
  temperatuur2 = temp[sensor]
  # print de gegevens naar de console.
  #print "sensor", sensor, "=", temp[sensor], "graden."
  print temperatuur2

############
## Part 2 ##
############
#waardes wegschrijven naar text bestand
#Open file
file = open("/home/pi/python_prog/_Log/_temp.txt", "a")

#schrijf waarde testbestand [Tijd: Temp]
file.write(time.strftime("%A %d-%m-%Y %H:%M:%S: " ))
file.write(temperatuur2)
file.write('\r\n')

#file.write()

#Sluit File
file.close()

It goes wrong in the "part 2" selection, When i run the script i get the following error:

"Traceback (most recent call last):
  File "./python_prog/temp2.py", line 48, in
    file.write(temperatuur2)
TypeError: expected a character buffer object"

Please can you help me!?

Body:
file.write(str(temperatuur2))

you should be writing strings to files.


问:
How can I reduce my Class Name in Zend to call it from any where in application?
I want to follow Zend file naming convention.

I have Object.php file with a class and a function in it.

MyZendProject->application->models->Test->Object.php

```<code>class Model_Test_Object {
   public function test() {
    echo "Test";
   }
}
</code>```

Now I want to access above test function in following file but it is not finding it.

MyZendProject->application->modules->test->controllers->TestController.php

```<code>$testModel = new Model_Test_Object();
$testModel->test();
</code>```

But when I name the class Application_Model_Test_Object in Object.php and call it in TestController like this then it works.

```<code>$testModel = new Application_Model_Test_Object();
$testModel->test();
</code>```

Problem is that I don't want to use Application in class name because it is too long and ugly. Is there any way that I name the class Model_Test_Object and access it anywhere in application without including any file. I have seen somewhere in Botstrap.php to solve this issue but I did not remember it and unable to find it again.

Any help will be appreciated.

Thanks

答:
Try adding this line into your configs/application.ini

autoloaderNamespaces[] = "Models"

Body:
I want to follow Zend file naming convention.

I have Object.php file with a class and a function in it.

MyZendProject->application->models->Test->Object.php

class Model_Test_Object {
   public function test() {
    echo "Test";
   }
}

Now I want to access above test function in following file but it is not finding it.

MyZendProject->application->modules->test->controllers->TestController.php

$testModel = new Model_Test_Object();
$testModel->test();

But when I name the class Application_Model_Test_Object in Object.php and call it in TestController like this then it works.

$testModel = new Application_Model_Test_Object();
$testModel->test();

Problem is that I don't want to use Application in class name because it is too long and ugly. Is there any way that I name the class Model_Test_Object and access it anywhere in application without including any file. I have seen somewhere in Botstrap.php to solve this issue but I did not remember it and unable to find it again.

Any help will be appreciated.

Thanks


问:
My C# grading program keep outputting the same result
I just started C# and was making this very simple C# program to print a grade according to the inputed marks.

Here's my program:

```<code>    class data
{

    int marks;
    public void input()
    {
        Console.WriteLine("Enter your marks");
        marks = Convert.ToInt16(Console.ReadLine());

    }

    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks < 55)
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");

    }
}
}
</code>```

And here's the main:

```<code> class Program
{
    static void Main(string[] args)
    {
        data obj1 = new data();
        obj1.input();
        obj1.output();
        Console.ReadLine();

    }
}
}
</code>```

Problem is it keeps outputting "Distinction" as the grade no matter what input I give. What am I doing wrong?

Edit - Fail marks is below 40

答:
For all marks entry below 75 it makes 2nd condition true, that's why you get distinction every time. Change your output function to this</p>

```<code>    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks >= 65 && marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks >= 55 && marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks >= 40 && marks < 55) // Here 40 is passing marks. You've set up of your own
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");
    }
</code>```

Body:
I just started C# and was making this very simple C# program to print a grade according to the inputed marks.

Here's my program:

    class data
{

    int marks;
    public void input()
    {
        Console.WriteLine("Enter your marks");
        marks = Convert.ToInt16(Console.ReadLine());

    }

    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks < 55)
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");

    }
}
}

And here's the main:

 class Program
{
    static void Main(string[] args)
    {
        data obj1 = new data();
        obj1.input();
        obj1.output();
        Console.ReadLine();

    }
}
}

Problem is it keeps outputting "Distinction" as the grade no matter what input I give. What am I doing wrong?

Edit - Fail marks is below 40

Body:
For all marks entry below 75 it makes 2nd condition true, that's why you get distinction every time. Change your output function to this

    public void output()
    {
        if (marks >= 75)
        {
            Console.WriteLine("Merit");
        }
        else if (marks >= 65 && marks < 75)
        {
            Console.WriteLine("Distiction");
        }
        else if (marks >= 55 && marks < 65)
        {
            Console.WriteLine("Credit");
        }
        else if (marks >= 40 && marks < 55) // Here 40 is passing marks. You've set up of your own
        {
            Console.WriteLine("Pass");
        }
        else Console.WriteLine("Fail");
    }


问:
Is there a way I can read packets from a pcap file into an array?
I am trying to build a new layer using scapy. I want to read a pcap file and store each packet in an array so that I can access all the information inside the packet using the index of the array.</p>

答:
The scapy function that you're looking for is rdpcap

```<code>from scapy.all import *

packets = rdpcap('file.pcap')
packets[0].show()
</code>```

Body:
The scapy function that you're looking for is rdpcap

from scapy.all import *

packets = rdpcap('file.pcap')
packets[0].show()


问:
ScrollViewer makes TextBox widen when typing longer texts, even though HorizontalScrollMode is disabled
I have a Grid inside a ScrollViewer (only vertical scrolling is enabled). I have a TextBox in that Grid, which ColumnSpan is 2, and its HorizontalAlignment is Stretch. Because of the ScrollViewer, if the user starts typing something really long, the TextBox will grow wider and wider, which I would like to avoid, it should be only as wide as the two columns it's spanning across, not widening them too.

I'm not sure how good of a practice would be to set it's MaxWidth to a constant, so I'd like to bind it instead to the two columns's ActualWidths.

In the column definitions:

```<code><ColumnDefinition Width="1.3*" x:Name="grdCol1"/>
<ColumnDefinition Width="1.3*" x:Name="grdCol2"/>
</code>```

The TextBox:

```<code>Width="{Binding ElementName=grdCol1, Path=ActualWidth}"
</code>```

The question is, how could I bind it to grdCol1 + grdCol2's ActualWidth? Or should I even go down this road? Is there a preferred, maybe cleaner way to do so?

答:
Turns out my ScrollViewer was at fault here.

NOT WORKING:

```<code><ScrollViewer
    HorizontalScrollBarVisibility="Hidden"
    HorizontalScrollMode="Disabled"
    VerticalScrollBarVisibility="Auto"
    VerticalScrollMode="Auto">
</code>```

WORKING:

```<code><ScrollViewer
    HorizontalScrollBarVisibility="Disabled"
    HorizontalScrollMode="Disabled"
    VerticalScrollBarVisibility="Auto"
    VerticalScrollMode="Auto">
</code>```

You have to set the HorizontalScrollBarVisibility to Disabled, as Hidden is not enough for this purpose.

Body:
I have a Grid inside a ScrollViewer (only vertical scrolling is enabled). I have a TextBox in that Grid, which ColumnSpan is 2, and its HorizontalAlignment is Stretch. Because of the ScrollViewer, if the user starts typing something really long, the TextBox will grow wider and wider, which I would like to avoid, it should be only as wide as the two columns it's spanning across, not widening them too.

I'm not sure how good of a practice would be to set it's MaxWidth to a constant, so I'd like to bind it instead to the two columns's ActualWidths.

In the column definitions:

<ColumnDefinition Width="1.3*" x:Name="grdCol1"/>
<ColumnDefinition Width="1.3*" x:Name="grdCol2"/>

The TextBox:

Width="{Binding ElementName=grdCol1, Path=ActualWidth}"

The question is, how could I bind it to grdCol1 + grdCol2's ActualWidth? Or should I even go down this road? Is there a preferred, maybe cleaner way to do so?

Body:
Turns out my ScrollViewer was at fault here.

NOT WORKING:

<ScrollViewer
    HorizontalScrollBarVisibility="Hidden"
    HorizontalScrollMode="Disabled"
    VerticalScrollBarVisibility="Auto"
    VerticalScrollMode="Auto">

WORKING:

<ScrollViewer
    HorizontalScrollBarVisibility="Disabled"
    HorizontalScrollMode="Disabled"
    VerticalScrollBarVisibility="Auto"
    VerticalScrollMode="Auto">

You have to set the HorizontalScrollBarVisibility to Disabled, as Hidden is not enough for this purpose.