问:
Threejs 2D Texture array issue when read raw image data
When I Try To execute this example, I see its work fine with current sample, But when I try to put my binary file which is contain continuous 2D frames jpg image was exported from here I got a none detailed image like this:

And this is converter binary code:

```<code><?php
header("Content-type: application/octet-stream");
header('Content-disposition: attachment; filename=head256x256x1092.bin');

$dirs = scandir('512');
unset($dirs[0]);
unset($dirs[1]);
natsort($dirs);
foreach($dirs as $dir):
$fp = fopen('512/'.$dir, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);

endforeach;
?>
~
</code>```

And this is threejs file reader:

```<code>new THREE.FileLoader()
      .setResponseType( 'arraybuffer' )
      .load( 'head256x256x1092.zip', function ( data ) {

        var zip = new JSZip( data );
        var array = zip.files[ 'head256x256x1092.bin' ].asUint8Array();

        var texture = new THREE.DataTexture2DArray( array, 256, 256, 109 );
        texture.format = THREE.RedFormat;
        texture.type = THREE.UnsignedByteType;
        texture.needsUpdate = true;
        var material = new THREE.ShaderMaterial( {
          uniforms: {
            diffuse: { value: texture },
            depth: { value: 0 },
            size: { value: new THREE.Vector2( planeWidth, planeHeight ) }
          },
          vertexShader: document.getElementById( 'vs' ).textContent.trim(),
          fragmentShader: document.getElementById( 'fs' ).textContent.trim()
        } );
        var geometry = new THREE.PlaneBufferGeometry( planeWidth, planeHeight );
        mesh = new THREE.Mesh( geometry, material );
        scene.add( mesh );
      } );
</code>```

答:
DataTexture are arrays of rgb
jpeg files are compressed data, it's not the same.
You can use this function:</p>

```<code>function jpegToBinaryData( $filename ) {
  $data = '';
  $img = imagecreatefromjpeg( $filename );
  for( $y = 0; $y < imagesy( $img ); $y++ ) {
    for( $x = 0; $x < imagesx( $img ); $x++ ) {
        $rgb = imagecolorat( $img, $x, $y );
        $r = ( $rgb >> 16 ) & 0xFF;
        $g = ( $rgb >> 8 ) & 0xFF;
        $b = $rgb & 0xFF;
        $data .= chr( $r ) . chr( $g ) . chr( $b );
    }
  }
  return $data;
}
</code>```

Body:
When I Try To execute this example, I see its work fine with current sample, But when I try to put my binary file which is contain continuous 2D frames jpg image was exported from here I got a none detailed image like this:

And this is converter binary code:

<?php
header("Content-type: application/octet-stream");
header('Content-disposition: attachment; filename=head256x256x1092.bin');

$dirs = scandir('512');
unset($dirs[0]);
unset($dirs[1]);
natsort($dirs);
foreach($dirs as $dir):
$fp = fopen('512/'.$dir, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);

endforeach;
?>
~

And this is threejs file reader:

new THREE.FileLoader()
      .setResponseType( 'arraybuffer' )
      .load( 'head256x256x1092.zip', function ( data ) {

        var zip = new JSZip( data );
        var array = zip.files[ 'head256x256x1092.bin' ].asUint8Array();

        var texture = new THREE.DataTexture2DArray( array, 256, 256, 109 );
        texture.format = THREE.RedFormat;
        texture.type = THREE.UnsignedByteType;
        texture.needsUpdate = true;
        var material = new THREE.ShaderMaterial( {
          uniforms: {
            diffuse: { value: texture },
            depth: { value: 0 },
            size: { value: new THREE.Vector2( planeWidth, planeHeight ) }
          },
          vertexShader: document.getElementById( 'vs' ).textContent.trim(),
          fragmentShader: document.getElementById( 'fs' ).textContent.trim()
        } );
        var geometry = new THREE.PlaneBufferGeometry( planeWidth, planeHeight );
        mesh = new THREE.Mesh( geometry, material );
        scene.add( mesh );
      } );

Body:
DataTexture are arrays of rgb
jpeg files are compressed data, it's not the same.
You can use this function:

function jpegToBinaryData( $filename ) {
  $data = '';
  $img = imagecreatefromjpeg( $filename );
  for( $y = 0; $y < imagesy( $img ); $y++ ) {
    for( $x = 0; $x < imagesx( $img ); $x++ ) {
        $rgb = imagecolorat( $img, $x, $y );
        $r = ( $rgb >> 16 ) & 0xFF;
        $g = ( $rgb >> 8 ) & 0xFF;
        $b = $rgb & 0xFF;
        $data .= chr( $r ) . chr( $g ) . chr( $b );
    }
  }
  return $data;
}


来源: stackexchange

问:
Nth salary in SQL
I'm trying to understand below query, how its working.

```<code>SELECT *
FROM Employee Emp1
WHERE (N-1) = (
               SELECT COUNT(DISTINCT(Emp2.Salary))
               FROM Employee Emp2
               WHERE Emp2.Salary > Emp1.Salary
               )
</code>```

Lets say I have 5 distinct salaries and want to get 3rd largest salary. So Inner query will run first and then outer query ?

I'm getting confused how its being done in sql engine. Curious to know. Becasue if its 3rd largest then 3-1 = 2, so that 2 needs to be matched with inner count as well. How inner count is being operated.

Can anyone explain the how its working .. ?

答:
```<code>SELECT * FROM (SELECT EMP.ID,RANK() OVER (ORDER BY SALARY DESC) AS NOS FROM EMPLOYEE) T WHERE T.NOS=3
</code>```

<p>Then from this select the one with any desired rank. </p>

ContentLicense: CC BY-SA 4.0

Title: Nth salary in SQL

Body:
I'm trying to understand below query, how its working.

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
               SELECT COUNT(DISTINCT(Emp2.Salary))
               FROM Employee Emp2
               WHERE Emp2.Salary > Emp1.Salary
               )

Lets say I have 5 distinct salaries and want to get 3rd largest salary. So Inner query will run first and then outer query ?

I'm getting confused how its being done in sql engine. Curious to know. Becasue if its 3rd largest then 3-1 = 2, so that 2 needs to be matched with inner count as well. How inner count is being operated.

Can anyone explain the how its working .. ?

Body:
SELECT * FROM (SELECT EMP.ID,RANK() OVER (ORDER BY SALARY DESC) AS NOS FROM EMPLOYEE) T WHERE T.NOS=3

Then from this select the one with any desired rank.


问:
Turn off samesite enforcement in chrome version > 80
Now that chrome 80 has implemented the samesite cookie enforcement - is there a way to turn that off?</p>

答:
You can disable this behaviour via chrome://flags. Specifically, you can enter these two into your location bar:

chrome://flags/#same-site-by-default-cookies

chrome://flags/#cookies-without-same-site-must-be-secure

Set both to "Disabled".

However, while this might be useful for dealing with sites that still need to update, I would not expect this to be a long term solution.


问:
Is Perl a good option for heavy text-processing?
I have this web application which needs to do several heavy text processing tasks: removing certain characters, parsing XML files, among others. Some of them involve regular expressions.

The web application has some implementations in Java and others in PHP. Is it worth using Perl or other specific text processing language for such tasks, or is there really no difference with using PHP?

I even thought of using Sed, Awk maybe even some compiled C scripts for processing texts. There's a lot of text to be processed...

答: Perl is THE language for text processsing. It was designed with this in mind.</p>

OwnerDisplayName: Fernando

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy


问:
Fluent NHibernate join for property value
I'm trying to join a table to retreive and set a property on a POCO. Here's the scenario...

*NOTE - An application can belong to many user sessions.

UserSession (Table)

```<code>UserSessionId PK
ApplicationId FK
UserName
</code>```

Application (Table)

```<code>ApplicationId PK
Name
</code>```

UserSession (Poco)

```<code>string UserName get;
string ApplicationName get;
</code>```

I've tried a join like this:

```<code>Join("Application", j => j.Inverse().KeyColumn("ApplicationId").Map(x => x.ApplicationName));
</code>```

However, this uses the primary column of the UserSessionTable for the join column. The part of the query looks like this:

```<code>/**SNIP**/
inner join
 Auditing.UserSession US
     on this_.UserSessionId=US.UserSessionId
left outer join
 Auditing.Application A
     on US.UserSessionId=A.ApplicationId
/**SNIP**/
</code>```

How can i configure nhibernate fluently to use the correct join column from the left table(UserSession)?

答:
Joe unfortunately I don't think you can specify this column.  I believe this is an nhibernate limitation (not FluentNH).  There are workarounds to this.  Here is an article with the same type of question:

Fluent NHibernate join tables in mapping not using primary key

Edit:

Example using your new entity below:

References(x => x.Application, "ApplicationId")

This allows you to specify the column on which you are joining to the Application table.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to join a table to retreive and set a property on a POCO. Here's the scenario...

*NOTE - An application can belong to many user sessions.

UserSession (Table)

UserSessionId PK
ApplicationId FK
UserName

Application (Table)

ApplicationId PK
Name

UserSession (Poco)

string UserName get;
string ApplicationName get;

I've tried a join like this:

Join("Application", j => j.Inverse().KeyColumn("ApplicationId").Map(x => x.ApplicationName));

However, this uses the primary column of the UserSessionTable for the join column. The part of the query looks like this:

/**SNIP**/
inner join
 Auditing.UserSession US
     on this_.UserSessionId=US.UserSessionId
left outer join
 Auditing.Application A
     on US.UserSessionId=A.ApplicationId
/**SNIP**/

How can i configure nhibernate fluently to use the correct join column from the left table(UserSession)?


问:
undefined method `content type=' for nil:nilclass in send_data
I'm writing Unit test rspec for my controller
Here is my code:

report_base_controller.rb

```<code>def send_data_to_report
  params[:user_role_code] = @auth_logic.current_role.code

  report_url = @report_logic.report_url(params)
  res = @request_logic.get(report_url)

  check_request_code(res.code.to_i, params)
  filename = params[:call_docurain_flag].to_i.zero? ? '' : "buildee_v2.#{Constants::REPORT_OUT_TYPE[params[:file_code].to_i]}"

  if params[:file_code].to_i == 2
    send_data(res.body, filename: filename, status: res.code, disposition: 'inline')
  else
    send_data(res.body, filename: filename, status: res.code)
  end
end
</code>```

report_base_controller_spec.rb

```<code>describe "send_data_to_report 【帳票】出面及支払内訳書（請負）" do
  let(:report_setting) { create(:report_setting, report_code: '22',
    unit_code: 1, report_name: '【帳票】出面及支払内訳書（請負）') }

  let(:dummy_auth_logic) { double('dummy_auth_logic') }

  before do
    controller.instance_variable_set(:@auth_logic, dummy_auth_logic)
    controller.instance_variable_set(:@request_logic, dummy_request_logic)
    allow(dummy_auth_logic).to receive_message_chain(:current_role, :code).and_return(Roles::USER_ROLES[:PRIME])
    allow(dummy_report_logic).to receive(:report_url).and_return('')
    allow(dummy_http_response).to receive(:code).and_return(200)
    allow(dummy_http_response).to receive(:body).and_return('abc')
    allow(dummy_request_logic).to receive(:get).and_return(dummy_http_response)
  end
  it "Case 1" do
    expect(controller.send(:send_data_to_report)).to eq(true)
  end
end
</code>```

But when I run the test I received the message

```<code>Failure/Error: send_data(res.body, filename: filename, status: res.code)
NoMethodError:
 #   undefined method `content_type=' for nil:NilClass
 #   ./app/controllers/api/private/reports/report_base_controller.rb:35:in `send_data_to_report'
</code>```

I cannot understand that content_type belongs to which object, so I can't resolve the problem. Please help me to fix this problem. Thanks

答:
content_type is a method from ActionController::Request, and more info can be found here:
https://guides.rubyonrails.org/action_controller_overview.html

I'm not entirely sure how you can fix the error, but the problem is you are trying to mock a very complex rails object, and you are missing certain base variables it requires (content_type,  in this case).

In my experience I generally do an integration test on controllers, specially because RSPEC will handle all the request logic for me. If you choose to keep the unit test route you will have to deeply understand how ActionController works, in order to mock the request variables.

Good luck!

Body:
I'm writing Unit test rspec for my controller
Here is my code:

report_base_controller.rb

def send_data_to_report
  params[:user_role_code] = @auth_logic.current_role.code

  report_url = @report_logic.report_url(params)
  res = @request_logic.get(report_url)

  check_request_code(res.code.to_i, params)
  filename = params[:call_docurain_flag].to_i.zero? ? '' : "buildee_v2.#{Constants::REPORT_OUT_TYPE[params[:file_code].to_i]}"

  if params[:file_code].to_i == 2
    send_data(res.body, filename: filename, status: res.code, disposition: 'inline')
  else
    send_data(res.body, filename: filename, status: res.code)
  end
end

report_base_controller_spec.rb

describe "send_data_to_report 【帳票】出面及支払内訳書（請負）" do
  let(:report_setting) { create(:report_setting, report_code: '22',
    unit_code: 1, report_name: '【帳票】出面及支払内訳書（請負）') }

  let(:dummy_auth_logic) { double('dummy_auth_logic') }

  before do
    controller.instance_variable_set(:@auth_logic, dummy_auth_logic)
    controller.instance_variable_set(:@request_logic, dummy_request_logic)
    allow(dummy_auth_logic).to receive_message_chain(:current_role, :code).and_return(Roles::USER_ROLES[:PRIME])
    allow(dummy_report_logic).to receive(:report_url).and_return('')
    allow(dummy_http_response).to receive(:code).and_return(200)
    allow(dummy_http_response).to receive(:body).and_return('abc')
    allow(dummy_request_logic).to receive(:get).and_return(dummy_http_response)
  end
  it "Case 1" do
    expect(controller.send(:send_data_to_report)).to eq(true)
  end
end

But when I run the test I received the message

Failure/Error: send_data(res.body, filename: filename, status: res.code)
NoMethodError:
 #   undefined method `content_type=' for nil:NilClass
 #   ./app/controllers/api/private/reports/report_base_controller.rb:35:in `send_data_to_report'

I cannot understand that content_type belongs to which object, so I can't resolve the problem. Please help me to fix this problem. Thanks


问:
Should I be using REST or SOAP UI for testing?
I am testing a new webservice that is receiving messages from an application and responding with messages with specific information. The webservice then uses this information to create new messages for downstream systems. I need to know the best way I can test this using the Ready API tool, we just got a pro license. Is it SOAP or REST I need to use. Ideally I want to simply copy my application messages in to the tool, call the webservice and get the response, which I can then check is the correct response for the test </p>

答:
To find your web-service is SOAP or REST.

Please check whether your web service has WSDL to verify it has SOAP web-service, you can get your web-service's WSDL by post-fixing WSDL with your web service url.

Eg: http://{yourservice-url/path1}?WSDL

If your service don't provide WSDL from the above URL, then your web-service is REST.


问:
R: Lubridate outputformat DMY
I was studying the cheat-sheet and other ressources, however I always found examples using lubridatefrom tidyverseputting me the result date into the format Y-M-D

For example having in the raw data the following:

01.06.2016 whhich says First July of 2016 and running:
Date.last.Contact = lubridate::dmy(Date.last.Contact) giving me 2016-06-01

I just want the german format like 01-06-2016. I have to mutate it into date-format to calculate the minimal date od some datarows in my r-script.
I was looking for a parameter where I can specify the output format, however I did not find the hint.

答:
You want

```<code>format(ymd(20200102), "%d.%m.%Y")
</code>```

output:

```<code>"02.01.2020"
</code>```

It is simply about the way you format the output string that is create from the date vector.

Title: R: Lubridate outputformat DMY

Body:
You want

format(ymd(20200102), "%d.%m.%Y")

output:

"02.01.2020"

It is simply about the way you format the output string that is create from the date vector.


问:
How to store & retrieve an object as a value in option of select element?
How to store & retrieve an object as a value for option of select element?</p>

```<code><select>
  <option value = "{}" selected>lorem</option>
</select>
</code>```

答:
This isn't a great pattern to use. You should have the select use some UUID (or a unique ID field from you object) as the value for your select, and use the name or description to display to the user.

Then on form submission, you can use Array.find() to get the object that was selected.

Body:
How to store & retrieve an object as a value for option of select element?

<select>
  <option value = "{}" selected>lorem</option>
</select>


问:
Issue in Adding large numbers in C# with int datatype
I am trying to add five large numbers in C# with int dataType. But the result was not correct. why .net is forcing me cast to long and perform the add to get the correct result.

```<code>using System;
public class Program
{
    public static void Main()
    {
        int i1= 256741038,i2=  623958417,i3=  467905213 ,i4= 714532089,i5=938071625;
        long l1= 256741038,l2=  623958417,l3=  467905213 ,l4= 714532089,l5=938071625;
        long result1=i2+i3+i4+i5;
        long result2=l2+l3+l4+l5;
        long result3=(long)l2+(long)l3+(long)l4+(long)l5;
        Console.WriteLine(result1);
        Console.WriteLine(result2);
        Console.WriteLine(result3);
        }
}
</code>```

答:
int has a maximum value of 2,147,483,647. If you try and make an int that's larger than this (for example, by adding two smaller ints), it will wrap around to being a very large negative number. This is what is happening in result1.

long is much bigger, and has a maximum value of 9,223,372,036,854,775,807. This is large enough to hold the values that you're trying to represent.

Body:
I am trying to add five large numbers in C# with int dataType. But the result was not correct. why .net is forcing me cast to long and perform the add to get the correct result.

using System;
public class Program
{
    public static void Main()
    {
        int i1= 256741038,i2=  623958417,i3=  467905213 ,i4= 714532089,i5=938071625;
        long l1= 256741038,l2=  623958417,l3=  467905213 ,l4= 714532089,l5=938071625;
        long result1=i2+i3+i4+i5;
        long result2=l2+l3+l4+l5;
        long result3=(long)l2+(long)l3+(long)l4+(long)l5;
        Console.WriteLine(result1);
        Console.WriteLine(result2);
        Console.WriteLine(result3);
        }
}


问:
Trying to start with google translate API and using ready()
I have this code:

```<code><script language="javascript" src="http://www.google.com/jsapi"></script>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.js"></script>
<script language="javascript">

 $(document).ready(function() {

 } );
</script>

</head>
<body>
<form onsubmit="return false">

 <input type="button" value="Translate" onclick="gtrans(this.form)" />
 <p id="translation" style="border:1px solid #00f;padding:5px;width:400px">-</p>
</form>
</body>
</code>```

When I add inside ready(){} the line google.load ("language", "1"); the form is not showed, why?

Regards

Javi

答: The $(document).ready() function is executed before the window loads, as soon as the DOM is registered by the browser. So, as Dalen suggests, you should put your code outside the function.

Body:
I have this code:

<form onsubmit="return false">

 <input type="button" value="Translate" onclick="gtrans(this.form)" />

-

</form>

When I add inside ready(){} the line google.load ("language", "1"); the form is not showed, why?

Regards

Javi


问:
Add-Migration while using database in separate Docker container throws an error
I've created dockerized ASP.net Core app with auto-generated identity setup (so I've already had by default entity framework configuration). I've created SQL Server as separate container, here is my docker-compose.yml:

```<code>version: '3.4'

services:
    blazorapp1:
        image: blazorapp1
        build:
            context: .
            dockerfile: Dockerfile
        depends_on:
            - db

    db:
        image: "mcr.microsoft.com/mssql/server"
        environment:
            SA_PASSWORD: "[SOMEPASSWORD]"
            ACCEPT_EULA: "Y"

</code>```

I've tested database configuration: as Visual Studio generated identity setup for me, I could successfully create new users and they were properly stored in memory.

Then I wanted to create new database table:

```<code>public class ApplicationDbContext : IdentityDbContext
{

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<WeightLog> WeightLogs { get; set; }
}
</code>```

To apply those changes, I've used Add-Migration WeightLogger in Package Manager Console.

Here is an output:

```<code>PM> Add-Migration WeightLogger
Build started...
Build succeeded.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: C:\root\.nuget\packages\microsoft.aspnetcore.identity.ui\3.1.1\staticwebassets\V4\
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
</code>```

There are a couple of things I don't understand here. The first error points me to C:\root\.nuget\packages\microsoft.aspnetcore.identity.ui\3.1.1\staticwebassets\V4\ which does not exist. Then there is the second error telling me that ApplicationDbContext can't be created. Link points me to webpage that tells:

When you create a new ASP.NET Core application, this hook is included by default.

So, does this mean I shouldn't need to configure anything? Why it isn't working then? Should I create migrations differently when using Docker container as environment?

答:
I got exactly the same issue and I ended up solving it by deleting the docker-compose project from visual studio and just keep the docker-compose.yaml and manage it through the command line and that solve it.

For those who don't want to remove the docker-compose support for the solution and facing the same issue, I think it is possible to solve it by implementing a design-time interface for the context or using docker ef migrations add command but in all cases, it's an issue that should be reported to Microsoft.

Body:
I've created dockerized ASP.net Core app with auto-generated identity setup (so I've already had by default entity framework configuration). I've created SQL Server as separate container, here is my docker-compose.yml:

version: '3.4'

services:
    blazorapp1:
        image: blazorapp1
        build:
            context: .
            dockerfile: Dockerfile
        depends_on:
            - db

    db:
        image: "mcr.microsoft.com/mssql/server"
        environment:
            SA_PASSWORD: "[SOMEPASSWORD]"
            ACCEPT_EULA: "Y"

I've tested database configuration: as Visual Studio generated identity setup for me, I could successfully create new users and they were properly stored in memory.

Then I wanted to create new database table:

public class ApplicationDbContext : IdentityDbContext
{

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<WeightLog> WeightLogs { get; set; }
}

To apply those changes, I've used Add-Migration WeightLogger in Package Manager Console.

Here is an output:

PM> Add-Migration WeightLogger
Build started...
Build succeeded.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: C:\root\.nuget\packages\microsoft.aspnetcore.identity.ui\3.1.1\staticwebassets\V4\
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

There are a couple of things I don't understand here. The first error points me to C:\root\.nuget\packages\microsoft.aspnetcore.identity.ui\3.1.1\staticwebassets\V4\ which does not exist. Then there is the second error telling me that ApplicationDbContext can't be created. Link points me to webpage that tells:

When you create a new ASP.NET Core application, this hook is included by default.

So, does this mean I shouldn't need to configure anything? Why it isn't working then? Should I create migrations differently when using Docker container as environment?


问:
Explaination for what tensorflow.keras.dataset.minst.load_data() returns
I came across the statement:

```<code>(x_train, y_train), (x_test, y_test) = mnist.load_data()
</code>```

and its corresponding explanation for what it returns:

Returns: 2 tuples: x_train, x_test: uint8 array of grayscale image data with shape (num_samples, 28, 28). y_train, y_test: uint8 array of digit labels (integers in range 0-9) with shape (num_samples,).

My doubt here is that whether x_train, x_test, y_train or y_test is itself a tuple that holds the values (num_sample, 28, 28) and (num_sample) respectively? and the tuple x_train, x_test is actually a tuple of tuple ?

I am new to this topic, so I am sorry if I am asking very silly questions! If anyone out there has an explanation for this, please write back.

答:
From the docs:

tf.keras.datasets.mnist.load_data

Returns:

  Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test).

But this wording is kind of confusing, the actual return type of the function is a tuple of two tuples with two numpy arrays each:

Tuple[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray]]

Body:
I came across the statement:

(x_train, y_train), (x_test, y_test) = mnist.load_data()

and its corresponding explanation for what it returns:

Returns: 2 tuples: x_train, x_test: uint8 array of grayscale image data with shape (num_samples, 28, 28). y_train, y_test: uint8 array of digit labels (integers in range 0-9) with shape (num_samples,).

My doubt here is that whether x_train, x_test, y_train or y_test is itself a tuple that holds the values (num_sample, 28, 28) and (num_sample) respectively? and the tuple x_train, x_test is actually a tuple of tuple ?

I am new to this topic, so I am sorry if I am asking very silly questions! If anyone out there has an explanation for this, please write back.


问:
How can i sort multidimension array with specific name in swift?
In my json result, there is odds array. And inside of it, there will be 8 types of bet. And i want to sort the array by bet type as i want to show.  Eg. first "name": "3Way Result", second another one, third "over/under" etc..

Here is my json result from server.

```<code> {
    "success": true,
    "result": [
        {
            "league_id": 5,
            "localTeam": {"data": {}},
            "visitorTeam": {"data": {}},
            "scores": {},
            "time": {"starting_at": {},},
            "league": {"data": {"coverage": {}}},
            "odds": [
                {
                    "id": 12,
                    "name": "Over/Under",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "Over",
                                            "value": "2.00",
                                            "extra": null,
                                            "probability": "50%",
                                            "dp3": "2.000",
                                            "american": 100,
                                            "handicap": null,
                                            "total": "2.5",
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                        },
                                        {
                                            "label": "Under",
                                            "value": "1.80",
                                            "probability": "55.56%",
                                            "dp3": "1.800",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 1,
                    "name": "3Way Result",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1",
                                            "value": "2.10",
                                            "extra": null,
                                            "probability": "47.62%",
                                            "dp3": "2.100",
                                            "american": 110,

                                        },
                                        {
                                            "label": "X",
                                            "value": "3.30",
                                            "extra": null,
                                            "probability": "30.3%",
                                            "dp3": "3.300",
                                            "american": 229,

                                        },
                                        {
                                            "label": "2",
                                            "value": "3.60",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 975909,
                    "name": "Correct Score",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1:0",
                                            "value": "7.50",
                                            "extra": null,
                                            "probability": "13.33%",
                                            "dp3": "7.500",
                                            "american": 650,
                                            "factional": null,
                                            "handicap": null,
                                            "total": null,
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                            "last_update": {
                                                "date": "2020-02-20 10:59:06.746514",
                                                "timezone_type": 3,
                                                "timezone": "UTC"
                                            }
                                        },
                                        {
                                            "label": "2:0",
                                            "value": "10.00",

                                        },

                                    ]
                                }
                            }
                        ]
                    }
                },

            ],
            "tipsters": 2
        }
    ]
}
</code>```

so it is not alphabetically, datetime or anytype i could access. How could i do ?

Update: I have added model.

```<code>struct BetterMatchResults: APIModel, Codable {
    var success: Bool?
    var result: [BetterMatch]?
}
struct BetterMatch: APIModel, Codable  {
    var id,_id: String?
    var localTeam, visitorTeam: BetterTeam?
    var spId, league_id, seasonID: Int?
    var winningOddsCalculated: Bool?
    var time: BetterTime?
    var league: BetterLeague?
    var createdAt, updatedAt: String?
    var odds: [BetterOdd]!
    var resultID: String?
    var tipsters: Int?
    var stats_url: String?
}

struct BetterLeague : APIModel, Codable {
    var data: LeagueData?
}

struct LeagueData : APIModel, Codable{
    var id: Int?
    var active: Bool?
    //var legacyID, countryID: Int?
    var logo_path: String?
    var name: String?
    //var isCup: Bool?

}

struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// MARK: - Bookmaker
struct BetterBookmaker : APIModel, Codable {
    var data: [BetterBookmakerDatum]?
}

// MARK: - BookmakerDatum
struct BetterBookmakerDatum : APIModel, Codable {
    var id: Int?
    var name: String?
    var odds: BetterOdds?
}

// MARK: - Odds
struct BetterOdds : APIModel, Codable {
    var data: [BetterOddsDatum]?
}

class BetterOddsDatum: APIModel , Codable {

    var label: String?
     //var extra: NSNull?
     //var probability, dp3: String?
     var american: Int?
     //var factional, handicap: NSNull?
     var total: String?
     var winning: Bool?
     var stop: Bool?
     var bookmakerEventID: Int?
    //private var odd: Double
    public var value: String?
    init() {

    }
}
</code>```

答:
First of all, mark result in BetterMatchResults and odds in BetterMatch as var, i.e.

```<code>struct BetterMatchResults: Codable {
    let success: Bool
    var result: [BetterMatch] //here....
}

struct BetterMatch: Codable {
    var odds: [BetterOdd] //here....
    //rest of the parameters...
}
</code>```

Next, while parsing your JSON data, use map(_:) and sorted(by:) to modify the result and odds in the betterMatchResults, i.e.

```<code>do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    var betterMatchResults = try JSONDecoder().decode(BetterMatchResults.self, from: data)

    betterMatchResults.result = betterMatchResults.result.map {(betterMatch) in
        var match = betterMatch
        match.odds =  match.odds.sorted(by: { $0.name < $1.name })
        return match
    }

    //Test the response...
    print(betterMatchResults.result.map({ $0.odds.map({ $0.name }) })) //[["3Way Result", "Correct Score", "Over/Under"]]

} catch {
    print(error)
}
</code>```

Body:
In my json result, there is odds array. And inside of it, there will be 8 types of bet. And i want to sort the array by bet type as i want to show.  Eg. first "name": "3Way Result", second another one, third "over/under" etc..

Here is my json result from server.

 {
    "success": true,
    "result": [
        {
            "league_id": 5,
            "localTeam": {"data": {}},
            "visitorTeam": {"data": {}},
            "scores": {},
            "time": {"starting_at": {},},
            "league": {"data": {"coverage": {}}},
            "odds": [
                {
                    "id": 12,
                    "name": "Over/Under",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "Over",
                                            "value": "2.00",
                                            "extra": null,
                                            "probability": "50%",
                                            "dp3": "2.000",
                                            "american": 100,
                                            "handicap": null,
                                            "total": "2.5",
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                        },
                                        {
                                            "label": "Under",
                                            "value": "1.80",
                                            "probability": "55.56%",
                                            "dp3": "1.800",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 1,
                    "name": "3Way Result",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1",
                                            "value": "2.10",
                                            "extra": null,
                                            "probability": "47.62%",
                                            "dp3": "2.100",
                                            "american": 110,

                                        },
                                        {
                                            "label": "X",
                                            "value": "3.30",
                                            "extra": null,
                                            "probability": "30.3%",
                                            "dp3": "3.300",
                                            "american": 229,

                                        },
                                        {
                                            "label": "2",
                                            "value": "3.60",

                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "id": 975909,
                    "name": "Correct Score",
                    "suspended": false,
                    "bookmaker": {
                        "data": [
                            {
                                "id": 2,
                                "name": "bet365",
                                "odds": {
                                    "data": [
                                        {
                                            "label": "1:0",
                                            "value": "7.50",
                                            "extra": null,
                                            "probability": "13.33%",
                                            "dp3": "7.500",
                                            "american": 650,
                                            "factional": null,
                                            "handicap": null,
                                            "total": null,
                                            "winning": null,
                                            "stop": false,
                                            "bookmaker_event_id": 84922729,
                                            "last_update": {
                                                "date": "2020-02-20 10:59:06.746514",
                                                "timezone_type": 3,
                                                "timezone": "UTC"
                                            }
                                        },
                                        {
                                            "label": "2:0",
                                            "value": "10.00",

                                        },

                                    ]
                                }
                            }
                        ]
                    }
                },

            ],
            "tipsters": 2
        }
    ]
}

so it is not alphabetically, datetime or anytype i could access. How could i do ?

Update: I have added model.

struct BetterMatchResults: APIModel, Codable {
    var success: Bool?
    var result: [BetterMatch]?
}
struct BetterMatch: APIModel, Codable  {
    var id,_id: String?
    var localTeam, visitorTeam: BetterTeam?
    var spId, league_id, seasonID: Int?
    var winningOddsCalculated: Bool?
    var time: BetterTime?
    var league: BetterLeague?
    var createdAt, updatedAt: String?
    var odds: [BetterOdd]!
    var resultID: String?
    var tipsters: Int?
    var stats_url: String?
}

struct BetterLeague : APIModel, Codable {
    var data: LeagueData?
}

struct LeagueData : APIModel, Codable{
    var id: Int?
    var active: Bool?
    //var legacyID, countryID: Int?
    var logo_path: String?
    var name: String?
    //var isCup: Bool?

}

struct BetterOdd : APIModel, Codable {
    var id: Int?
    var name: String?
    var suspended: Bool?
    var bookmaker: BetterBookmaker?
   }

// MARK: - Bookmaker
struct BetterBookmaker : APIModel, Codable {
    var data: [BetterBookmakerDatum]?
}

// MARK: - BookmakerDatum
struct BetterBookmakerDatum : APIModel, Codable {
    var id: Int?
    var name: String?
    var odds: BetterOdds?
}

// MARK: - Odds
struct BetterOdds : APIModel, Codable {
    var data: [BetterOddsDatum]?
}

class BetterOddsDatum: APIModel , Codable {

    var label: String?
     //var extra: NSNull?
     //var probability, dp3: String?
     var american: Int?
     //var factional, handicap: NSNull?
     var total: String?
     var winning: Bool?
     var stop: Bool?
     var bookmakerEventID: Int?
    //private var odd: Double
    public var value: String?
    init() {

    }
}

Body:
First of all, mark result in BetterMatchResults and odds in BetterMatch as var, i.e.

struct BetterMatchResults: Codable {
    let success: Bool
    var result: [BetterMatch] //here....
}

struct BetterMatch: Codable {
    var odds: [BetterOdd] //here....
    //rest of the parameters...
}

Next, while parsing your JSON data, use map(_:) and sorted(by:) to modify the result and odds in the betterMatchResults, i.e.

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    var betterMatchResults = try JSONDecoder().decode(BetterMatchResults.self, from: data)

    betterMatchResults.result = betterMatchResults.result.map {(betterMatch) in
        var match = betterMatch
        match.odds =  match.odds.sorted(by: { $0.name < $1.name })
        return match
    }

    //Test the response...
    print(betterMatchResults.result.map({ $0.odds.map({ $0.name }) })) //[["3Way Result", "Correct Score", "Over/Under"]]

} catch {
    print(error)
}


问:
Fire local push notification on selected date and time in swift
I need to fire push notification on below date and time at 9:00 AM :

```<code>January: 13rd, 18th, 20th, 23rd
</code>```

Please Help!

答:
Here we use Trigger notification:
Calendar: Trigger at a specific date and time. The trigger is created using a date components object which makes it easier for certain repeating intervals. To convert a Date to its date components use the current calendar. For example:

```<code>`// Swift
let date = Date(timeIntervalSinceNow: 3600)
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,],from: date)
//Objective-C
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600];
NSDateComponents *triggerDate = [[NSCalendar currentCalendar]
          components:NSCalendarUnitYear +
          NSCalendarUnitMonth + NSCalendarUnitDay +
          NSCalendarUnitHour + NSCalendarUnitMinute +
          NSCalendarUnitSecond fromDate:date];`
</code>```

To create the trigger from the date components:

```<code>// Swift
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
// Objective-C
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO];
</code>```

To create a trigger that repeats at a certain interval use the correct set of date components. For example, to have the notification repeat daily at the same time we need just the hour, minutes and seconds:

```<code>let triggerDaily = Calendar.current.dateComponents([hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
</code>```

To have it repeat weekly at the same time we also need the weekday:

```<code>let triggerWeekly = Calendar.current.dateComponents([.weekday,hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
</code>```

This is an interesting change from the older notification framework which had a fire date and repeat interval. The date components are more flexible but there is no easy way to fully replicate the fireDate property of the older framework. For example, if I want a daily trigger that starts in 1 week.

please gothrough

UNCalendarNotificationTrigger https://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger

Visit https://useyourloaf.com/blog/local-notifications-with-ios-10/

Body:
I need to fire push notification on below date and time at 9:00 AM :

January: 13rd, 18th, 20th, 23rd

Please Help!

Body:
Here we use Trigger notification:
Calendar: Trigger at a specific date and time. The trigger is created using a date components object which makes it easier for certain repeating intervals. To convert a Date to its date components use the current calendar. For example:

`// Swift
let date = Date(timeIntervalSinceNow: 3600)
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,],from: date)
//Objective-C
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600];
NSDateComponents *triggerDate = [[NSCalendar currentCalendar]
          components:NSCalendarUnitYear +
          NSCalendarUnitMonth + NSCalendarUnitDay +
          NSCalendarUnitHour + NSCalendarUnitMinute +
          NSCalendarUnitSecond fromDate:date];`

To create the trigger from the date components:

// Swift
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
// Objective-C
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO];

To create a trigger that repeats at a certain interval use the correct set of date components. For example, to have the notification repeat daily at the same time we need just the hour, minutes and seconds:

let triggerDaily = Calendar.current.dateComponents([hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

To have it repeat weekly at the same time we also need the weekday:

let triggerWeekly = Calendar.current.dateComponents([.weekday,hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

This is an interesting change from the older notification framework which had a fire date and repeat interval. The date components are more flexible but there is no easy way to fully replicate the fireDate property of the older framework. For example, if I want a daily trigger that starts in 1 week.

please gothrough

UNCalendarNotificationTrigger https://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger

Visit https://useyourloaf.com/blog/local-notifications-with-ios-10/


答:
Because of performance C# (not dotnet) and ANY other langauge that I know use the LARGEST common denominator to do operations. This is COMMON, between them. not the result, which would have to be guessed.

SO, adding 2 int numbers is an int operation that may overflow. Adding an int to long is a long operation. Adding two long is a long operation.

Simple like that. If you know you will overflow, then declare one of the types as longer.

Now, you CAN cast - you COULD also just declare them as long, you know.

C# short/long/int literal format?

shows you all the suffices.

1111 is an int

1111UL is an unsigned long.

So, there is no need to cast if you tell the compiler the correct data type to use in the literal.

Title: Issue in Adding large numbers in C# with int datatype


问:
C++ prevent access to a temporary
I am working on a class that acts like a std::variant, in that, it stores another object using a union along with an error code. Like std::variant, there is a get_if() function that can be used to access to the object in the class. So something like this

```<code>template<typename T>
class result final
{
    ...
    [[nodiscard]] constexpr T const *
    get_if() const noexcept
    {
        if (details::result_type::contains_t == m_which) {
            return &m_t;
        }

        return nullptr;
    }
    ...
};
</code>```

Now... suppose you have a function that returns an object using this class like this:

```<code>[[nodiscard]] static bsl::result<example_implementation>
make(bsl::int32 const answer) noexcept
{
    constexpr bsl::int32 valid_answer{42};

    if (answer == valid_answer) {
        return {bsl::in_place, valid_answer};
    }

    return {bsl::errc_failure, bsl::here()};
}
</code>```

All of this works great. The problem that I cam concerned about is if the user does something like this:

```<code>if (auto const impl = example_implementation::make(valid_answer).get_if()) {
    example_bind_apis_type enforced_impl{*impl};

    if (enforced_impl.member_func_example(valid_answer)) {
        bsl::print("success\n");
    }

    if (!enforced_impl.member_func_example(invalid_answer)) {
        bsl::print("success\n");
    }
}
else {
    bsl::print("failure\n");
}
</code>```

In the example above, the user is creating an example_implementation, and then using get_if() to get a pointer to the object wrapped by the result object. That pointer is then dereferenced and used. ASAN detects that the stack was used after destruction of an object, which is due to the fact that the "if" statement created a temporary result object, and then returned a pointer to something inside that temporary, which is deleted after the call to get_if(). This is similar to an issue with QString that I remember years ago, when people would get a pointer to the C style string inside the QString from a temporary.

Is there a way, in C++ to prevent the user from being able to call get_if() on a temporary like this? I tried reference qualifying get_if(), but that doesn't seem to work as the make function above returns an lvalue, not an rvalue (even though RVO will likely remove the copy). All I want to do is prevent the user from making this mistake accidentally.

Update:
As stated in the comments, make() is returning an rvalue, not an lvalue as I stated above, so a ref qualifier should work.

答:
@Eljay in the comments above figured it out. You need to explicitly delete the rvalue reference qualified version of the function. </p>

```<code>[[nodiscard]] constexpr T *
get_if() &noexcept
{
    if (details::result_type::contains_t == m_which) {
        return &m_t;
    }

    return nullptr;
}

[[nodiscard]] constexpr T * get_if() && noexcept = delete;
</code>```

Title: C++ prevent access to a temporary

Body:
I am working on a class that acts like a std::variant, in that, it stores another object using a union along with an error code. Like std::variant, there is a get_if() function that can be used to access to the object in the class. So something like this

template<typename T>
class result final
{
    ...
    [[nodiscard]] constexpr T const *
    get_if() const noexcept
    {
        if (details::result_type::contains_t == m_which) {
            return &m_t;
        }

        return nullptr;
    }
    ...
};

Now... suppose you have a function that returns an object using this class like this:

[[nodiscard]] static bsl::result<example_implementation>
make(bsl::int32 const answer) noexcept
{
    constexpr bsl::int32 valid_answer{42};

    if (answer == valid_answer) {
        return {bsl::in_place, valid_answer};
    }

    return {bsl::errc_failure, bsl::here()};
}

All of this works great. The problem that I cam concerned about is if the user does something like this:

if (auto const impl = example_implementation::make(valid_answer).get_if()) {
    example_bind_apis_type enforced_impl{*impl};

    if (enforced_impl.member_func_example(valid_answer)) {
        bsl::print("success\n");
    }

    if (!enforced_impl.member_func_example(invalid_answer)) {
        bsl::print("success\n");
    }
}
else {
    bsl::print("failure\n");
}

In the example above, the user is creating an example_implementation, and then using get_if() to get a pointer to the object wrapped by the result object. That pointer is then dereferenced and used. ASAN detects that the stack was used after destruction of an object, which is due to the fact that the "if" statement created a temporary result object, and then returned a pointer to something inside that temporary, which is deleted after the call to get_if(). This is similar to an issue with QString that I remember years ago, when people would get a pointer to the C style string inside the QString from a temporary.

Is there a way, in C++ to prevent the user from being able to call get_if() on a temporary like this? I tried reference qualifying get_if(), but that doesn't seem to work as the make function above returns an lvalue, not an rvalue (even though RVO will likely remove the copy). All I want to do is prevent the user from making this mistake accidentally.

Update:
As stated in the comments, make() is returning an rvalue, not an lvalue as I stated above, so a ref qualifier should work.

Body:
@Eljay in the comments above figured it out. You need to explicitly delete the rvalue reference qualified version of the function.

[[nodiscard]] constexpr T *
get_if() &noexcept
{
    if (details::result_type::contains_t == m_which) {
        return &m_t;
    }

    return nullptr;
}

[[nodiscard]] constexpr T * get_if() && noexcept = delete;


答:
Let's look at the shapes of those objects:

```<code>(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(np.shape(x_train))
print(np.shape(x_test))
print(np.shape(y_train))
print(np.shape(x_test))
</code>```

(60000, 28, 28)

(10000, 28, 28)

(60000,)

(10000,)

You x_* datasets contain respectively 60000 and 10000 matrices of 28*28 pixels encoded as ints between 0 and 255.

Your y_* dataset contain the labels of what number is represented in your corresponding 28*28 pixels matrices.

Title: Explaination for what tensorflow.keras.dataset.minst.load_data() returns

Body:
Let's look at the shapes of those objects:

(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(np.shape(x_train))
print(np.shape(x_test))
print(np.shape(y_train))
print(np.shape(x_test))

(60000, 28, 28)

(10000, 28, 28)

(60000,)

(10000,)

You x_* datasets contain respectively 60000 and 10000 matrices of 28*28 pixels encoded as ints between 0 and 255.

Your y_* dataset contain the labels of what number is represented in your corresponding 28*28 pixels matrices.


问:
TextField with Label over the border at Top-Left position
I need to implement outline textfield with placeholder in my swift project one like the Material UI. I tried googling for the same but could not found anything. Anyone know how to achieve it in swift?
Reference Images:

答:
you can also try this framework SkyFloatingLabelTextField , TextFieldEffects or TweeTextField

https://github.com/Skyscanner/SkyFloatingLabelTextField

https://github.com/oleghnidets/TweeTextField

https://github.com/raulriera/TextFieldEffects


问:
Add view to a cell in a Table View Programmatically
I have a table view with dynamic prototypes that is currently displaying 4 elements programmatically. I assign the cell names through an array (see code below), but I also want to add a small view to the right half of each cell in order to show a small graph next to each label. I can drop in a view in storyboard, but it doesn't extend itself dynamically. Basically I need to find a way to modify this code to add a view inside of each cell and assign a class I have already created to those views.

```<code>    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("LineCell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = oneLine.lineNames[indexPath.row]
    return cell
}
</code>```

This is where I want the views:

Also, how can I make more space between the Carrier, Time, and Battery and the table view?

答:
```<code>var newView = UIView(frame: CGRect(x: 210, y: 10, width: 110, height: 50))
cell.contentView.addSubview(newView)
</code>```

As ashish says, as far i know this will add the subview at the top of the cell. what should i do if i want to add it to the bottom of the cell.

Body:
I have a table view with dynamic prototypes that is currently displaying 4 elements programmatically. I assign the cell names through an array (see code below), but I also want to add a small view to the right half of each cell in order to show a small graph next to each label. I can drop in a view in storyboard, but it doesn't extend itself dynamically. Basically I need to find a way to modify this code to add a view inside of each cell and assign a class I have already created to those views.

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("LineCell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = oneLine.lineNames[indexPath.row]
    return cell
}

This is where I want the views:

Also, how can I make more space between the Carrier, Time, and Battery and the table view?

Body:
var newView = UIView(frame: CGRect(x: 210, y: 10, width: 110, height: 50))
cell.contentView.addSubview(newView)

As ashish says, as far i know this will add the subview at the top of the cell. what should i do if i want to add it to the bottom of the cell.


问:
Spawning an External Editor - how does this work?
What is the typical design for a program (such as a command line utility) to spawn an external editor and read back changes to the file? Many command line utilities do this. For example, svn commit launches an external editor to get the comment if it is run without -c.

Some options I have considered are:

Poll a temp file file, waiting for the timestamp to change, but this would be limited to a single save.

Register with the operating system to be notified of changes to a temp file, but this would would be platform dependent, which I'd like to avoid.

Monitor the spawned process, waiting for it to terminate, but I'm not sure how this would work for editors such as TextMate and TextWrangler that typically have long-lived processes.

Interact with the spawned process by stdin and stdout, but I'm not clear on the details of how/if this could work.

Hopefully the solution is platform independent. For the record my platform is the JVM on OS X.

P.S. Any advice on appropriate tags for this question?

答:
If you launch a process through Java (Runtime.exec), you get a Process object back, which has a waitFor() method that will tell you when the process is complete.

Just run vi or nano or whatever via that, and once it exits, you can read the file.


问:
How to get component instance in data section in vuejs template?
I have a component that has complex rendering logic.
I try to carry out this logic to helper classes, for simplifying.
To do this, in the data section (for reactivity), I create class references as follows:

```<code>export default {
  data: () => ({
    state: new InitialState(this),
    query: new QueryController(this)
  })
}
</code>```

As I understand it, at this point the context of this is not yet defined.
So, I have two questions.

1) Is there a way to pass the this component context in the data section (without lifecycle hooks)?

2) Is the approach with references to external classes of vuejs philosophy contrary?

答:
Component instance is already available when data function runs, this is one of reasons why it has been forced to be a function.

Due to how lexical this works with arrow functions, it's incorrect to use them to access dynamic this. It should be:

```<code>  data() {
    return {
      state: new InitialState(this),
      query: new QueryController(this)
    };
  })
</code>```

The problem with InitialState(this) is that the entire component instance is passed instead of relevant data, this breaks the principle of least privilege.

Despite Vue isn't focused on OOP, there's nothing wrong with using classes. One of possible pitfalls is that classes may not play well with Vue reactivity because it puts restrictions on the implementation. Another pitfall is that classes cannot be serialized to JSON and back without additional measures, this introduces limitations to how application state can be handled.

Body:
I have a component that has complex rendering logic.
I try to carry out this logic to helper classes, for simplifying.
To do this, in the data section (for reactivity), I create class references as follows:

export default {
  data: () => ({
    state: new InitialState(this),
    query: new QueryController(this)
  })
}

As I understand it, at this point the context of this is not yet defined.
So, I have two questions.

1) Is there a way to pass the this component context in the data section (without lifecycle hooks)?

2) Is the approach with references to external classes of vuejs philosophy contrary?

Body:
Component instance is already available when data function runs, this is one of reasons why it has been forced to be a function.

Due to how lexical this works with arrow functions, it's incorrect to use them to access dynamic this. It should be:

  data() {
    return {
      state: new InitialState(this),
      query: new QueryController(this)
    };
  })

The problem with InitialState(this) is that the entire component instance is passed instead of relevant data, this breaks the principle of least privilege.

Despite Vue isn't focused on OOP, there's nothing wrong with using classes. One of possible pitfalls is that classes may not play well with Vue reactivity because it puts restrictions on the implementation. Another pitfall is that classes cannot be serialized to JSON and back without additional measures, this introduces limitations to how application state can be handled.


答:
Using this pod, you can get the same design

Take UIView on Storyboard and set constraints

Make class which is a subclass of UIView and import pods MaterialComponents.MaterialTextFields and MaterialComponents.MaterialTextFields_ColorThemer

class CustomOutlinedTxtField: UIView {

```<code>private var textFieldControllerFloating: MDCTextInputControllerOutlined!
var textField: MDCTextField!

@IBInspectable var placeHolder: String!
@IBInspectable var value: String!
@IBInspectable var primaryColor: UIColor! = .purple

override open func draw(_ rect: CGRect) {
    super.draw(rect)

    textField.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)

}
open override func awakeFromNib() {
    super.awakeFromNib()
    setUpProperty()
}
func setUpProperty() {
    //Change this properties to change the propperties of text
    textField = MDCTextField(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
    textField.placeholder = placeHolder
    textField.text = value

    //Change this properties to change the colors of border around text
    textFieldControllerFloating = MDCTextInputControllerOutlined(textInput: textField)

    textFieldControllerFloating.activeColor = primaryColor
    textFieldControllerFloating.floatingPlaceholderActiveColor = primaryColor
    textFieldControllerFloating.normalColor = UIColor.lightGray
    textFieldControllerFloating.inlinePlaceholderColor = UIColor.lightGray

    //Change this font to make borderRect bigger
    textFieldControllerFloating.inlinePlaceholderFont = UIFont.systemFont(ofSize: 14)
    textFieldControllerFloating.textInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))

    self.addSubview(textField)
}
</code>```

}

Assign that custom class to UIView

Result

Title: TextField with Label over the border at Top-Left position

Body:
I need to implement outline textfield with placeholder in my swift project one like the Material UI. I tried googling for the same but could not found anything. Anyone know how to achieve it in swift?
Reference Images:

Body:
Using this pod, you can get the same design

Take UIView on Storyboard and set constraints

Make class which is a subclass of UIView and import pods MaterialComponents.MaterialTextFields and MaterialComponents.MaterialTextFields_ColorThemer

class CustomOutlinedTxtField: UIView {

private var textFieldControllerFloating: MDCTextInputControllerOutlined!
var textField: MDCTextField!

@IBInspectable var placeHolder: String!
@IBInspectable var value: String!
@IBInspectable var primaryColor: UIColor! = .purple

override open func draw(_ rect: CGRect) {
    super.draw(rect)

    textField.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)

}
open override func awakeFromNib() {
    super.awakeFromNib()
    setUpProperty()
}
func setUpProperty() {
    //Change this properties to change the propperties of text
    textField = MDCTextField(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
    textField.placeholder = placeHolder
    textField.text = value

    //Change this properties to change the colors of border around text
    textFieldControllerFloating = MDCTextInputControllerOutlined(textInput: textField)

    textFieldControllerFloating.activeColor = primaryColor
    textFieldControllerFloating.floatingPlaceholderActiveColor = primaryColor
    textFieldControllerFloating.normalColor = UIColor.lightGray
    textFieldControllerFloating.inlinePlaceholderColor = UIColor.lightGray

    //Change this font to make borderRect bigger
    textFieldControllerFloating.inlinePlaceholderFont = UIFont.systemFont(ofSize: 14)
    textFieldControllerFloating.textInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))

    self.addSubview(textField)
}

}

Assign that custom class to UIView

Result


问:
Force to download dependencies from repository but only for particular package
I am looking for a way to force to download only dependencies from particular package in Gradle (which comes from my company only and changing very often) instead of redownloading everything.

I know how to redownload everything by executing

```<code>./gradlew build --refresh-dependencies
</code>```

or by

```<code>rm -rf $HOME/.gradle/caches/
</code>```

but is there any option to limits dependencies to download? All of them have the same prefix com.company.*

Thanks!

答:
You can not control which dependency to refresh with --refresh-dependencies, it's not designed for that.

You will need specify a rich version for the changing dependencies. Then configure Gradle's caching of dynamic/rich versions to your liking:

```<code>dependencies {
    implementation("com.company:my-library:latest.release")
}

configurations.all {
    resolutionStrategy.cacheChangingModulesFor 0, "seconds"
}
</code>```

Body:
I am looking for a way to force to download only dependencies from particular package in Gradle (which comes from my company only and changing very often) instead of redownloading everything.

I know how to redownload everything by executing

./gradlew build --refresh-dependencies

or by

rm -rf $HOME/.gradle/caches/

but is there any option to limits dependencies to download? All of them have the same prefix com.company.*

Thanks!

Body:
You can not control which dependency to refresh with --refresh-dependencies, it's not designed for that.

You will need specify a rich version for the changing dependencies. Then configure Gradle's caching of dynamic/rich versions to your liking:

dependencies {
    implementation("com.company:my-library:latest.release")
}

configurations.all {
    resolutionStrategy.cacheChangingModulesFor 0, "seconds"
}


问:
Population density within polygons
So, I have some questions regarding the raster package in R. I have a raster with estimated population in each grid point. I also have a shapefile with polygons of regions. I want to find out the coordinates of the neighborhood with the highest population density within each regions. Supose that each neighborhood is a homogeneous square of 5 by 5 grid points.

The following toy example mimics my problem.

```<code>library(raster)
library(maptools)

set.seed(123)

data(wrld_simpl)

wrld_simpl <- st_as_sf(wrld_simpl)
contr_c_am <- wrld_simpl %>%
  filter(SUBREGION ==13) %>%
  filter(FIPS != "MX") %>%
  select(NAME)

# Create a raster of population (sorry for the bad example spatial distribution)
r <- raster(xmn=-180, xmx=180, ymn=-90, ymx=90, res=0.1)
values(r) <- runif(ncell(r), 0, 100)

# keep only raster around the region of interest
r_small <- crop(r, extent(contr_c_am))
plot(r_small)
plot(st_geometry(contr_c_am), add = T)

raster_contr_c_am <- rasterize(contr_c_am, r)

</code>```

raster_contr_c_am is the population grid and the name of the region is saved as an attribute.

Somehow I need to filter only grid points from one region, and probably use some funcion like focal() to find total nearby population.

```<code>focal(raster_contr_c_am, matrix(1,5,5),sum, pad = T, padValue = 0)
</code>```

Then, I need to find which grid point has the highest value within each region, and save it's coordinates.

I hope my explanation is not too confusing,

Thanks for any help!

答:
Here's an example that iterates over the shape defining the region, then uses the raster values within the region and the focal() function to find the maximum.

```<code>library(raster)
library(maptools)
library(sf)
library(dplyr)

set.seed(123)

data(wrld_simpl)

wrld_simpl <- st_as_sf(wrld_simpl)
contr_c_am <- wrld_simpl %>%
    filter(SUBREGION ==13) %>%
    filter(FIPS != "MX") %>%
    select(NAME)

# Create a raster of population (sorry for the bad example spatial distribution)
r <- raster(xmn=-180, xmx=180, ymn=-90, ymx=90, res=0.1)
values(r) <- runif(ncell(r), 0, 100)

# keep only raster around the region of interest
r_small <- crop(r, extent(contr_c_am))
raster_contr_c_am <- rasterize(contr_c_am, r_small)

# function to find the max raster value using focal
# in a region
findMax <- function(region, raster) {
    tt <- trim((mask(raster, region))) # focus on the region
    ff <- focal(tt, w=matrix(1/25,nc=5,nr=5))
    maximumCell <- which.max(ff) # find the maximum cell id
    maximumvalue <- maxValue(ff) # find the maximum value
    maximumx <- xFromCell(ff, maximumCell) # get the coordinates
    maximumy <- yFromCell(ff, maximumCell)
    # return a data frame
    df <- data.frame(maximumx, maximumy, maximumvalue)
    df
}

numberOfShapes <- nrow(contr_c_am)
ll <- lapply(1:numberOfShapes, function(s) findMax(region = contr_c_am[s,], raster = r_small))
merged <- do.call(rbind, ll)
maxpoints <- st_as_sf(merged, coords=c('maximumx', 'maximumy'), crs=crs(contr_c_am))

library(mapview) # optional but nice visualization - select layers to see if things look right
mapview(maxpoints) + mapview(r_small) + mapview(contr_c_am)
</code>```

I've made an sf object so that it can be plotted with the other spatial objects. Using the mapview package, I get this.

Title: Population density within polygons

Body:
So, I have some questions regarding the raster package in R. I have a raster with estimated population in each grid point. I also have a shapefile with polygons of regions. I want to find out the coordinates of the neighborhood with the highest population density within each regions. Supose that each neighborhood is a homogeneous square of 5 by 5 grid points.

The following toy example mimics my problem.

library(raster)
library(maptools)

set.seed(123)

data(wrld_simpl)

wrld_simpl <- st_as_sf(wrld_simpl)
contr_c_am <- wrld_simpl %>%
  filter(SUBREGION ==13) %>%
  filter(FIPS != "MX") %>%
  select(NAME)

# Create a raster of population (sorry for the bad example spatial distribution)
r <- raster(xmn=-180, xmx=180, ymn=-90, ymx=90, res=0.1)
values(r) <- runif(ncell(r), 0, 100)

# keep only raster around the region of interest
r_small <- crop(r, extent(contr_c_am))
plot(r_small)
plot(st_geometry(contr_c_am), add = T)

raster_contr_c_am <- rasterize(contr_c_am, r)

raster_contr_c_am is the population grid and the name of the region is saved as an attribute.

Somehow I need to filter only grid points from one region, and probably use some funcion like focal() to find total nearby population.

focal(raster_contr_c_am, matrix(1,5,5),sum, pad = T, padValue = 0)

Then, I need to find which grid point has the highest value within each region, and save it's coordinates.

I hope my explanation is not too confusing,

Thanks for any help!

Body:
Here's an example that iterates over the shape defining the region, then uses the raster values within the region and the focal() function to find the maximum.

library(raster)
library(maptools)
library(sf)
library(dplyr)

set.seed(123)

data(wrld_simpl)

wrld_simpl <- st_as_sf(wrld_simpl)
contr_c_am <- wrld_simpl %>%
    filter(SUBREGION ==13) %>%
    filter(FIPS != "MX") %>%
    select(NAME)

# Create a raster of population (sorry for the bad example spatial distribution)
r <- raster(xmn=-180, xmx=180, ymn=-90, ymx=90, res=0.1)
values(r) <- runif(ncell(r), 0, 100)

# keep only raster around the region of interest
r_small <- crop(r, extent(contr_c_am))
raster_contr_c_am <- rasterize(contr_c_am, r_small)

# function to find the max raster value using focal
# in a region
findMax <- function(region, raster) {
    tt <- trim((mask(raster, region))) # focus on the region
    ff <- focal(tt, w=matrix(1/25,nc=5,nr=5))
    maximumCell <- which.max(ff) # find the maximum cell id
    maximumvalue <- maxValue(ff) # find the maximum value
    maximumx <- xFromCell(ff, maximumCell) # get the coordinates
    maximumy <- yFromCell(ff, maximumCell)
    # return a data frame
    df <- data.frame(maximumx, maximumy, maximumvalue)
    df
}

numberOfShapes <- nrow(contr_c_am)
ll <- lapply(1:numberOfShapes, function(s) findMax(region = contr_c_am[s,], raster = r_small))
merged <- do.call(rbind, ll)
maxpoints <- st_as_sf(merged, coords=c('maximumx', 'maximumy'), crs=crs(contr_c_am))

library(mapview) # optional but nice visualization - select layers to see if things look right
mapview(maxpoints) + mapview(r_small) + mapview(contr_c_am)

I've made an sf object so that it can be plotted with the other spatial objects. Using the mapview package, I get this.


问:
How do I read a byte from a Slave I2C Device while handling a request from the Master?
I have a Raspberry Pi Zero W acting as a Master in communication with an Arduino Pro Mini acting as a Slave.  I would like for the Master to send commands to the Slave.  However, when I try using commands such as bus.write_byte_data or bus.write_byte from the Master, the Slave only ever seems to receive the value 255.  Here's the code:

Master (in Python):

```<code>import time
import smbus

i2c_ch = 1
bus = smbus.SMBus(i2c_ch)

i2c_address = 20
bus.write_byte_data(i2c_address, 113,111)
val = bus.read_i2c_block_data(i2c_address,12)
bus.write_byte(i2c_address, 123)
print(val)
</code>```

And here's the Slave's requestEvent() (in Arduino C):

```<code>void requestEvent()
{
  byte command = Wire.read();
  Serial.println(command);
  command = Wire.read();
  Serial.println(command);
  command = Wire.read();
  Serial.println(command);
...
}
</code>```

What would be an approach whereby the Slave could receive bytes when being commanded by the Master?

答:
You're probably trying to use a handler created by Wire.onRequest instead of one created by Wire.onReceive.  An onReceive handler will do what you want:

```<code>Wire.onReceive(receieveEvent);
Wire.onRequest(requestEvent);
...
void receieveEvent()
{
  Serial.println("received some data");
  while(0 < Wire.available()) // loop through all but the last
  {
    byte command = Wire.read();
    Serial.println(command);
  }
}
</code>```

PS: LOL you have the same name as me!

Body:
I have a Raspberry Pi Zero W acting as a Master in communication with an Arduino Pro Mini acting as a Slave.  I would like for the Master to send commands to the Slave.  However, when I try using commands such as bus.write_byte_data or bus.write_byte from the Master, the Slave only ever seems to receive the value 255.  Here's the code:

Master (in Python):

import time
import smbus

i2c_ch = 1
bus = smbus.SMBus(i2c_ch)

i2c_address = 20
bus.write_byte_data(i2c_address, 113,111)
val = bus.read_i2c_block_data(i2c_address,12)
bus.write_byte(i2c_address, 123)
print(val)

And here's the Slave's requestEvent() (in Arduino C):

void requestEvent()
{
  byte command = Wire.read();
  Serial.println(command);
  command = Wire.read();
  Serial.println(command);
  command = Wire.read();
  Serial.println(command);
...
}

What would be an approach whereby the Slave could receive bytes when being commanded by the Master?

Body:
You're probably trying to use a handler created by Wire.onRequest instead of one created by Wire.onReceive.  An onReceive handler will do what you want:

Wire.onReceive(receieveEvent);
Wire.onRequest(requestEvent);
...
void receieveEvent()
{
  Serial.println("received some data");
  while(0 < Wire.available()) // loop through all but the last
  {
    byte command = Wire.read();
    Serial.println(command);
  }
}

PS: LOL you have the same name as me!


问:
How do I install the yaml package for my PyCharm Python project?
I'm using PyCharm 2018.2.4 with Python 3.7.  I want to run some seed data so in the Python management console, I tried running my yaml file, which ended in this error

```<code>manage.py@mainpage_project > loaddata seed_data
bash -cl "/Users/davea/Documents/workspace/mainpage_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py loaddata seed_data /Users/davea/Documents/workspace/mainpage_project"
Tracking file by folder pattern:  migrations
/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 52, in <module>
    run_command()
  File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 46, in run_command
    run_module(manage_file, None, '__main__', True)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 205, in run_module
    return _run_module_code(code, init_globals, run_name, mod_spec)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/davea/Documents/workspace/mainpage_project/manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
    self.loaddata(fixture_labels)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 165, in load_label
    ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore,
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 140, in deserialize
    return d(stream_or_string, **options)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 50, in __call__
    raise self.exception
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 70, in register_serializer
    module = importlib.import_module(serializer_module)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 11, in <module>
    import yaml
ModuleNotFoundError: No module named 'yaml'

so then I opened up my Project Interpreter page, selected the "yaml" module and clicked "Install".  However it didn't install and instead gave me this error ...
</code>```

Collecting yaml

```<code>  Could not find a version that satisfies the requirement yaml (from versions: )
No matching distribution found for yaml
</code>```

How do I install Yaml for PyCharm?

答: If you want to install any module through Pycharm not terminal. Refer the screenshot for this:-

Body:
I'm using PyCharm 2018.2.4 with Python 3.7.  I want to run some seed data so in the Python management console, I tried running my yaml file, which ended in this error

manage.py@mainpage_project > loaddata seed_data
bash -cl "/Users/davea/Documents/workspace/mainpage_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py loaddata seed_data /Users/davea/Documents/workspace/mainpage_project"
Tracking file by folder pattern:  migrations
/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 52, in <module>
    run_command()
  File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 46, in run_command
    run_module(manage_file, None, '__main__', True)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 205, in run_module
    return _run_module_code(code, init_globals, run_name, mod_spec)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/davea/Documents/workspace/mainpage_project/manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
    self.loaddata(fixture_labels)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 165, in load_label
    ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore,
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 140, in deserialize
    return d(stream_or_string, **options)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 50, in __call__
    raise self.exception
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 70, in register_serializer
    module = importlib.import_module(serializer_module)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 11, in <module>
    import yaml
ModuleNotFoundError: No module named 'yaml'

so then I opened up my Project Interpreter page, selected the "yaml" module and clicked "Install".  However it didn't install and instead gave me this error ...

Collecting yaml

  Could not find a version that satisfies the requirement yaml (from versions: )
No matching distribution found for yaml

How do I install Yaml for PyCharm?


问:
How to make code wait for okay/cancel button selection?
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

```<code>$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);
</code>```

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

答:
Simply put all code that follows after opening the dialog in a function and call that function from the dialogs callback function for okay / cancel.</p>

```<code>function doTheRest(args) {
    alert(args);
}

// snippet from dialog options
"Okay": function() {
    $(this).dialog("close");
    doTheRest(1);
},

"Cancel": function() {
    $(this).dialog("close");
    doTheRest(0);
}
</code>```

Body:
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("
Users
" + makeDialogTable(users) + "
Owners
" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

Body:
Simply put all code that follows after opening the dialog in a function and call that function from the dialogs callback function for okay / cancel.

function doTheRest(args) {
    alert(args);
}

// snippet from dialog options
"Okay": function() {
    $(this).dialog("close");
    doTheRest(1);
},

"Cancel": function() {
    $(this).dialog("close");
    doTheRest(0);
}


问:
ngClass directive to use with ngFor
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

```<code><ul>
      <li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
    </ul>
income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];
</code>```

答:
It's because the  {{text.text}} contains the full text.
You have to split the "li" like this</p>

```<code><ul>
  <li *ngFor="let income of incomes; let i = index" [ngClass]="'strong'">{{income.text}}{{income.value</li>
</ul>

incomes = [
  {text:'Your Annual Income:*',
    value: '$1,316,422'},
  {text:'Your Monthly Income:'
    value: '$109,702'}
 ];
</code>```

Title: ngClass directive to use with ngFor

Body:
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

{{text.text}}

income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];

Body:
It's because the  {{text.text}} contains the full text.
You have to split the "li" like this

<ul>
  <li *ngFor="let income of incomes; let i = index" [ngClass]="'strong'">{{income.text}}{{income.value</li>
</ul>

incomes = [
  {text:'Your Annual Income:*',
    value: '$1,316,422'},
  {text:'Your Monthly Income:'
    value: '$109,702'}
 ];


答:
This is an optimized version: removed a lot of redundant character classes and groups. Ultimately it would be better to know what the regex is supposed to do.

```<code>\w{15}\x01\d{12}\x01\d{2}.{6}(13[0-5]\d|14([0-2]\d|30))[0-5]\d801.*
</code>```

Edit: based on your new information, you can reduce it further down to:

```<code>\w{15}\x01\d{12}\x01\d{2}.{6}(13[0-5]\d|1400)[0-5]\d801.*
</code>```

Title: Reg Exp optimisation

Body:
I need to optimise the following reg exp so that it executes faster. Can anyone help?

([\d\w]{15}[\x01]\d{12}[\x01]\d{2}(.){6}((13((0[0-9]|([1-4][0-9])|5[0-9]))|14((0[0-9]|([1-2][0-9])|30)))[0-5][0-9])801(?:.*))

Thanks

Body:
This is an optimized version: removed a lot of redundant character classes and groups. Ultimately it would be better to know what the regex is supposed to do.

\w{15}\x01\d{12}\x01\d{2}.{6}(13[0-5]\d|14([0-2]\d|30))[0-5]\d801.*

Edit: based on your new information, you can reduce it further down to:

\w{15}\x01\d{12}\x01\d{2}.{6}(13[0-5]\d|1400)[0-5]\d801.*


问:
Behavior of scanf when reading strings in C
I would like to know what does the compiler do with the whitespaces, newline character when using scanf("%s"). I know that scanf("%s") cannot read whitespaces and newline character.

For example if I enter

```<code>hi          question
</code>```

or

```<code>hi

        question
</code>```

scanf("%s") reads it without problems.

Below is the code that I am referring to

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

int main () {
    char str [2][50];
    scanf("%s", str[0]);
    scanf("%s", str[1]);
    printf("%s\n", str[0]);
    printf("%s\n", str[1]);
    return 0;
}
</code>```

答:
scanf documentation online:

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

source

Body:
I would like to know what does the compiler do with the whitespaces, newline character when using scanf("%s"). I know that scanf("%s") cannot read whitespaces and newline character.

For example if I enter

hi          question

or

hi

        question

scanf("%s") reads it without problems.

Below is the code that I am referring to

#include <stdio.h>

int main () {
    char str [2][50];
    scanf("%s", str[0]);
    scanf("%s", str[1]);
    printf("%s\n", str[0]);
    printf("%s\n", str[1]);
    return 0;
}