问:
How to read data in file which the file inside a file in perl?
I have list2.txt file and inside that file, there are several files like 02x5.txt or 0.3x5.txt etc. Then how to read data inside 02x5.txt file at one time? Inside 02x5.txt, there are height:20, length:5, colour:blue etc.

```<code>inside list2.txt:
02x5.txt
03x5.txt

inside 02x5.txt:
height:20,
length:5,
colour:blue

inside 03x5.txt:
height:25,
length:10,
colour:green
</code>```

```<code>#!/usr/bin/perl
    use strict;
    use warnings;

# Reading a line from a file (or rather from a filehandle)
my $filename = "list2.txt";
    if (open my $data, "<", $filename) {
    while (my $row = <$data>) {
        chomp $row;
        if ($row =~ m/02x5.txt$/ ){
        my $m = $row;
            print "$m\n";
        }
    }
    }
</code>```

How can I read data for height and length from certain txt file?
Thank you

答:
The answer is always to break the problem down into smaller chunks.</p>

```<code>#!/usr/bin/perl

use strict;
use warnings;

my @files = get_list_of_files();

my %data;

foreach my $file (@files) {
  my $file_data = get_data_from_file($file);

  $data{$file} = $file_data;
}

# You now have your data in a hash called %data.
# Do whatever you want with it.

sub get_list_of_files {
  open my $list_fh, '<', 'list2.txt'
    or die $!;

  my @files = <$list_fh>;
  chomp(@files);

  return @files;
}

sub get_data_from_file {
  my ($filename) = @_;

  my $record;

  open my $fh, '<', $filename or die $!;

  while (<$fh>) {
    chomp;
    # Remove trailing comma
    s/,$//;
    my ($key, $value) = split /:/;
    $record->{$key} = $value;
  }

  return $record;
}
</code>```

Body:
I have list2.txt file and inside that file, there are several files like 02x5.txt or 0.3x5.txt etc. Then how to read data inside 02x5.txt file at one time? Inside 02x5.txt, there are height:20, length:5, colour:blue etc.

inside list2.txt:
02x5.txt
03x5.txt

inside 02x5.txt:
height:20,
length:5,
colour:blue

inside 03x5.txt:
height:25,
length:10,
colour:green

#!/usr/bin/perl
    use strict;
    use warnings;

# Reading a line from a file (or rather from a filehandle)
my $filename = "list2.txt";
    if (open my $data, "<", $filename) {
    while (my $row = <$data>) {
        chomp $row;
        if ($row =~ m/02x5.txt$/ ){
        my $m = $row;
            print "$m\n";
        }
    }
    }

How can I read data for height and length from certain txt file?
Thank you

Body:
The answer is always to break the problem down into smaller chunks.

#!/usr/bin/perl

use strict;
use warnings;

my @files = get_list_of_files();

my %data;

foreach my $file (@files) {
  my $file_data = get_data_from_file($file);

  $data{$file} = $file_data;
}

# You now have your data in a hash called %data.
# Do whatever you want with it.

sub get_list_of_files {
  open my $list_fh, '<', 'list2.txt'
    or die $!;

  my @files = <$list_fh>;
  chomp(@files);

  return @files;
}

sub get_data_from_file {
  my ($filename) = @_;

  my $record;

  open my $fh, '<', $filename or die $!;

  while (<$fh>) {
    chomp;
    # Remove trailing comma
    s/,$//;
    my ($key, $value) = split /:/;
    $record->{$key} = $value;
  }

  return $record;
}


来源: stackexchange

问:
Laravel how to add a function from a view to the controller (Business Logic Layer)
I currently have this function in my view:

```<code></tr>
  @foreach ($data as $i )
     <tr>
       <td>
         {{$i->AanvraagID}}
       </td>
       <td>
         {{$i->Status}}
       </td>
       <td>
         {{$i->StartDatum}}
       </td>
       <td>
         {{$i->EindDatum}}
       </td>
       <td>
         {{$i->Leverancier}}
       </td>
       <td>
         {{$i->Product}}
       </td>
       <td>
         {{$i->Validatie}}
       </td>
       <td>
         {{$i->TypeCertificaat}}
       </td>
       <td class="wrong">
            @php
                $date = new DateTime($i->EindDatum);
                $now = new DateTime();

                if($date < $now)  echo  'Certificaat verlopen';

                if ($date < $now && $i->email_send == 0) {

                $user=App\User::find(1);
                $user->notify(new App\Notifications\TaksComplete);

                }
       @endphp
   </td>
</tr>
</code>```

I would like to know if its possible to add this to my controller so my view only has to display the result.

This is my controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        return view('SSL',['data'=>$data]);
    }
}
</code>```

this is my model:

```<code><?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class sslModel extends Model
{
    use Notifiable;

    protected $table='SSL';
    protected $fillable = [
         'email_send',
    ];
}
</code>```

Now the problem is the controller doesn't know stuff like DateTime()

What the function does is if the users has something which is past the current date it will send an email to the user. But now each time the user reloads the page it send the email again. This function is there to stop that but it doesn't work in my view:

```<code>$SSL=App\sslModel::find(1);
$SSL->email_send = 1;
$SSL->save();
</code>```

This does not change the column email_send to 1 from 0 in the table SSL in my database.

Is it possible to add this code to my controller(or model)? and so that the column does update in the database?

my user table migration:

```<code>class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
</code>```

答:
Define a relationship to your User in your SslModel:

<?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use App\User;

class sslModel extends Model
{
    use Notifiable;

    protected $table='SSL';
    protected $fillable = [
         'email_send',
         'userID'
    ];

    protected $hidden = ['userID'];

    public function user() {
        return $this->belongsTo(User::class, "userID", "id");
    }
}
```

<p><strong>See: laravel.com/docs/6.x/eloquent-relationships#updating-belongs-to-relationships</strong> </p>

<p>Write your loop in your controller</p>

<pre class="lang-php prettyprint-override"><code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class sslController extends Controller
{
    public function SSL(){

        $models = \App\sslModel::where('userID', Auth::id())->get();

        foreach($models as $model) {
             if ($model->EindDatum < Carbon::now() && $model->email_send == 0) {
                $model->update(['email_send' => 1]);
                $model->user()->first()->notify(new \App\Notifications\TaksComplete);
             }
        }

        return view('SSL',['data'=>$model]);
    }
}
</code>```

The view:

  @foreach ($data as $i )

         {{$i->AanvraagID}}

         {{$i->Status}}

         {{$i->StartDatum}}

         {{$i->EindDatum}}

         {{$i->Leverancier}}

         {{$i->Product}}

         {{$i->Validatie}}

         {{$i->TypeCertificaat}}

          @if($i->EindDatum < \Carbon::now())
              {{'Certificaat verlopen'}}
          @else
            {{'OK'}}
           @endif

```

See: laravel.com/docs/master/blade#if-statements

[EDIT 1]

Or if you want to do some background processing checkout Laravel Scheduler:
laravel.com/docs/master/scheduling

ContentLicense: CC BY-SA 4.0

Body:
I currently have this function in my view:

  @foreach ($data as $i )

         {{$i->AanvraagID}}

         {{$i->Status}}

         {{$i->StartDatum}}

         {{$i->EindDatum}}

         {{$i->Leverancier}}

         {{$i->Product}}

         {{$i->Validatie}}

         {{$i->TypeCertificaat}}

            @php
                $date = new DateTime($i->EindDatum);
                $now = new DateTime();

                if($date < $now)  echo  'Certificaat verlopen';

                if ($date < $now && $i->email_send == 0) {

                $user=App\User::find(1);
                $user->notify(new App\Notifications\TaksComplete);

                }
       @endphp

I would like to know if its possible to add this to my controller so my view only has to display the result.

This is my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())->get();
        return view('SSL',['data'=>$data]);
    }
}

this is my model:

<?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class sslModel extends Model
{
    use Notifiable;

    protected $table='SSL';
    protected $fillable = [
         'email_send',
    ];
}

Now the problem is the controller doesn't know stuff like DateTime()

What the function does is if the users has something which is past the current date it will send an email to the user. But now each time the user reloads the page it send the email again. This function is there to stop that but it doesn't work in my view:

$SSL=App\sslModel::find(1);
$SSL->email_send = 1;
$SSL->save();

This does not change the column email_send to 1 from 0 in the table SSL in my database.

Is it possible to add this code to my controller(or model)? and so that the column does update in the database?

my user table migration:

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Body:
Define a relationship to your User in your SslModel:

<?php

namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use App\User;

class sslModel extends Model
{
    use Notifiable;

    protected $table='SSL';
    protected $fillable = [
         'email_send',
         'userID'
    ];

    protected $hidden = ['userID'];

    public function user() {
        return $this->belongsTo(User::class, "userID", "id");
    }
}

See: laravel.com/docs/6.x/eloquent-relationships#updating-belongs-to-relationships

Write your loop in your controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class sslController extends Controller
{
    public function SSL(){

        $models = \App\sslModel::where('userID', Auth::id())->get();

        foreach($models as $model) {
             if ($model->EindDatum < Carbon::now() && $model->email_send == 0) {
                $model->update(['email_send' => 1]);
                $model->user()->first()->notify(new \App\Notifications\TaksComplete);
             }
        }

        return view('SSL',['data'=>$model]);
    }
}

The view:

</tr>
  @foreach ($data as $i )
     <tr>
       <td>
         {{$i->AanvraagID}}
       </td>
       <td>
         {{$i->Status}}
       </td>
       <td>
         {{$i->StartDatum}}
       </td>
       <td>
         {{$i->EindDatum}}
       </td>
       <td>
         {{$i->Leverancier}}
       </td>
       <td>
         {{$i->Product}}
       </td>
       <td>
         {{$i->Validatie}}
       </td>
       <td>
         {{$i->TypeCertificaat}}
       </td>
       <td class="wrong">
          @if($i->EindDatum < \Carbon::now())
              {{'Certificaat verlopen'}}
          @else
            {{'OK'}}
           @endif
       </td>
</tr>

See: laravel.com/docs/master/blade#if-statements

[EDIT 1]

Or if you want to do some background processing checkout Laravel Scheduler:
laravel.com/docs/master/scheduling


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
I'd recommend creating a text based game. That really helped me firm up my C++. Doesn't take too long and you can exercise all the features you want. Come up with the game yourself. It is more fun that way.

Another great idea is to write a simple mathematics library, supporting Vectors Matrices etc.
But with todays libraries, that is only of academic use.

OwnerDisplayName: climatewarrior

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: batbrat

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: batbrat


问:
Commit hooks not printing any error message if script exists with code 0
My pre-commit is calling a perl script commit_log.pl.The script is doing so many pre-checks.Now I am trying to send out a mail after commit approval.We are not able to set up post-commit hooks due to some permission issues.So I am trying to call the send mail in the pre-commit script itself.

In my commit_log.pl if the exit code is zero ,even printf is not working.

If exit code is 1 everything is working fine

pre-commit:

```<code>log=`$SVNLOOK log -t "$TXN" "$REPOS"`
author=`$SVNLOOK author -t "$TXN" "$REPOS"`
CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS"`

/usr/bin/perl /isource/svnroot/fgw_ins/hooks/user/commit_log.pl "$log" "$author" "$CHANGED" "$0" 1>&2

if [ "$?" -eq "1" ];
then
        exit 1
else
        exit 0
fi

# if does not match..fail...
exit 1
---------------------------------------------------------------------------------
commit_log.pl
------------------------

}
   else
                {
                        print("Commit approved\n");#this printf itself is not working
                        `python $path/send_mail.py $comment $committed_filepath`;
                        exit 0;
                }
</code>```

答:
I'm not sure where standard output from the pre-commit hook is sent to. According to the SVN book, the standard error is sent back to the client, but only if there is an error (i.e. it exited with a non-zero exit code).

I would try writing to a specific location, rather than to standard output (e.g. /tmp/pre-commit.log for testing purposes).

Also, in general, you probably should avoid as much as possible doing work in the pre-commit script that assumes the commit was successful. The commit may still fail after the pre-commit script runs, such as during the commit itself, which is why the post-commit script exists.

Body:
My pre-commit is calling a perl script commit_log.pl.The script is doing so many pre-checks.Now I am trying to send out a mail after commit approval.We are not able to set up post-commit hooks due to some permission issues.So I am trying to call the send mail in the pre-commit script itself.

In my commit_log.pl if the exit code is zero ,even printf is not working.

If exit code is 1 everything is working fine

pre-commit:

log=`$SVNLOOK log -t "$TXN" "$REPOS"`
author=`$SVNLOOK author -t "$TXN" "$REPOS"`
CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS"`

/usr/bin/perl /isource/svnroot/fgw_ins/hooks/user/commit_log.pl "$log" "$author" "$CHANGED" "$0" 1>&2

if [ "$?" -eq "1" ];
then
        exit 1
else
        exit 0
fi

# if does not match..fail...
exit 1
---------------------------------------------------------------------------------
commit_log.pl
------------------------

}
   else
                {
                        print("Commit approved\n");#this printf itself is not working
                        `python $path/send_mail.py $comment $committed_filepath`;
                        exit 0;
                }


答:
You can try this.

```<code>for lst in time_stamp_list:
    for x,y in zip(lst[1:],lst):
        print(x-y)
</code>```

The above can be written as list comprehension.

```<code>[[x-y for x,y in zip(lst[1:],lst) ] for lst in time_stamp_list]
</code>```

Title: Arranging timestamp according to required condition

Body:
I've list of timestamp values stored in a nested list below.

[[1462692695.0, 1462857370.0, 1463297496.0],

[1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0],

[1455009108.0, 1455218354.0, 1455221295.0],

[1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]

And I want to find the difference between second and first, third and second and so on.. for each of the nested list values.

For example:
The newly created difference list:

[[164675,440126],
 [...,...,...,...],
....]

Body:
You can try this.

for lst in time_stamp_list:
    for x,y in zip(lst[1:],lst):
        print(x-y)

The above can be written as list comprehension.

[[x-y for x,y in zip(lst[1:],lst) ] for lst in time_stamp_list]


问:
BeautifulSoup4 - Concatenating multiple html elements between two different tags for batch processing url
Continuing on my earlier question Python BS4 - Concatenating multiple html elements between two different tags

I want to extend the solution for multiple url.
Consider two url  link1 | link2

The html source code looks like below

```<code><div class="job">

<p><strong>Requisition ID: </strong>223813
<strong>Work Area: </strong>Consulting  and Professional Services
<strong>Expected Travel: </strong>0 - 80%
<strong>Career Status: </strong>Professional
<strong>Employment Type: </strong>Regular Full Time</p>

<p><strong>COMPANY DESCRIPTION</strong>
SAP started in 1972 as a team of five colleagues with a desire to do something new. Together, they changed enterprise software and reinvented how business was done. Today, as a market leader in enterprise application software, we remain true to our roots. That’s why we engineer solutions to fuel innovation, foster equality and spread opportunity for our employees and customers across borders and cultures.</p>

<p>SAP values the entrepreneurial spirit, fostering creativity and building lasting relationships with our employees. We know that a diverse and inclusive workforce keeps us competitive and provides opportunities for all. We believe that together we can transform industries, grow economics, lift up societies and sustain our environment. Because it’s the best-run businesses that make the world run better and improve people’s lives.</p>

.
.
.
.
.
.

<p><strong>WHAT YOU GET FROM US </strong></p>
<p>Success is what you make it. At SAP, we help you make it your own. A career at SAP can open many doors for you. If you’re searching for a company that’s dedicated to your ideas and individual growth, recognizes you for your unique contributions, fills you with a strong sense of purpose, and provides a fun, flexible and inclusive work environment – apply now<em>.</em></p>

</code>```

My Requirement:

Get the section marked as dots in above the code. It is dynamic content & hence can't hardcode any of the section headers. Refer to the 2 links provided above to see the difference in content.

The only static text seems to be
COMPANY DESCRIPTION at the top &
WHAT YOU GET FROM US
 at the bottom.

So I need all the html tags & elemnts after "COMPANY DESCRIPTION" & before "WHAT YOU GET FROM US"

Also observe that the "COMPANY DESCRIPTION" section has 2 para
 in it. I don't want the 2nd para either which starts with
SAP values the entrepreneurial spirit,

答:
Use the css selector to check the text contains "COMPANY DESCRIPTION" and remaining code same.

Code:

```<code>import requests
from bs4 import BeautifulSoup
def scrape_url(url, method='bs4'):
    session = requests.session()
    page = session.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    return soup

urls=['https://jobs.sap.com/job/Kuala-Lumpur-Business-Processes-Consultant-%28FICO%29-Job-14/541909901/','https://jobs.sap.com/job/Mumbai-Senior-Account-Executive-Job-MH/539212101/']

for url in urls:
    print(url)
    soup = scrape_url(url)
    findtag=soup.select_one('p:contains("COMPANY DESCRIPTION")')
    print(findtag.text)
    findnextptag=findtag.find_next_sibling('p')
    for item in findnextptag.find_next_siblings():

         if 'WHAT YOU GET FROM US' in item.text:
             break
         else:
             print(item.text.strip())

    print("======================================")
</code>```

Output:

```<code>https://jobs.sap.com/job/Kuala-Lumpur-Business-Processes-Consultant-%28FICO%29-Job-14/541909901/
COMPANY DESCRIPTION
SAP started in 1972 as a team of five colleagues with a desire to do something new. Together, they changed enterprise software and reinvented how business was done. Today, as a market leader in enterprise application software, we remain true to our roots. That’s why we engineer solutions to fuel innovation, foster equality and spread opportunity for our employees and customers across borders and cultures.
PURPOSE AND OBJECTIVES

To address requirements in the area of Supply Chain Management Extended Warehouse Management solutions, Build competencies at Solution Delivery Center to deliver solutions especially in areas relating to SAP EWM

EXPECTATIONS AND TASKS

Independently handle large implementation projects with focus on Warehouse Management processes such as inbound, outbound and internal processes. RF Device functions and Barcode support experience is desirable
Able to lead EWM discussions, assessments and detail requirement studies with customers
Leading the team that are assigned to, in functional capacity, adding value to the project and to the final deliverables
Be actively involved in the preparation, conception, realization and Go Live of customer implementation projects
Demonstrate the ability to plan, run, and manage blueprint workshops / meetings with internal and external clients
Responsible for defining the scope of a project / opportunities, estimating efforts and project timelines
Participating in RFP discussions and estimating under guidance from a Bid Manager
Providing a creative source of ideas/solutions to address problems
Delivering billable components that meets a customer’s needs
KEY PERFORMANCE INDICATORS

Customer Feedback/customer satisfaction scores
Productive days/utilization as defined by the organization for projects/assessments/etc.
Knowledge Management and creation of effective reusable components
EXPERIENCE REQUIREMENTS

Minimum of 4+ years industry experience and a minimum of 5 to 6 years of SAP EWM experience
Domain knowledge in Supply Chain Management in the areas of Planning, Manufacturing & warehousing processes is a must
Must have strong ERP implementation experience
Experience in SAP Material Flow Systems (MFS) or any other third party automation tools will be desirable
Experience in EWM technical knowledge will be an added advantage
Knowledge on SAP S/4HANA Public Cloud solution and SAP IOT/Leonardo portfolio will be preferred but not mandatory
Good understanding of S/4HANA Order to Cash and Procure to Pay business processes
Good understanding of SAP ACTIVATE implementation methodology
Use of Solution Manager as a part of implementation life cycle is desirable
Good Communication skill in English.

EDUCATION AND QUALIFICATIONS/SKILLS AND COMPETENCIES

Degree in Engineering or IT
SAP Certification in Extended Warehouse Management (EWM) desirable
Minimum 4 to 5 full life cycle SAP EWM implementations
Strong knowledge in SAP SCM Extended Warehouse Management Solutions and S/4HANA Embedded EWM Solution
Good integration knowledge with other components with SAP S/4HANA (WM, SD, MM, PP) and other SAP or Non-SAP legacy applications
Knowledge of SCOR, APICS certification preferable
Strong client-facing experience and well-developed customer focus
Solid oral and written communication skills, with the demonstrated ability to communicate complex technical topics to management and non-technical audiences
Mobility is must – candidate must be ready to travel to project locations (short term and long term)

======================================
https://jobs.sap.com/job/Mumbai-Senior-Account-Executive-Job-MH/539212101/
COMPANY DESCRIPTION
SAP started in 1972 as a team of five colleagues with a desire to do something new. Together, they changed enterprise software and reinvented how business was done. Today, as a market leader in enterprise application software, we remain true to our roots. That’s why we engineer solutions to fuel innovation, foster equality and spread opportunity for our employees and customers across borders and cultures.
Key Areas of Responsibility and Tasks:

The Account Executive’s primary responsibilities include prospecting, qualifying, selling and closing new business to existing and net new customers. The Account Executive brings a Point of View to Customer engagement; uses all resources to solve customer problems with appropriate SAP products.

1.    Account and Customer Relationship Management, Sales and Software License and Cloud Subscription Revenue.

Annual Revenue - Achieve / exceed quota targets.
Sales strategies - Develops effective and specific account plans to ensure revenue target delivery and sustainable growth.   Develop relationships in new and existing customers and leverage to drive strategy through organization.
Trusted advisor - Establishes strong relationships based on knowledge of customer requirements and commitment to value (value of counsel and expertise, the value of solutions, the value of implementation expertise).  Builds a foundation on which to harvest future business opportunities and accurate account information and coaching.
Customer Acumen - Actively understand each customer’s technology footprint, strategic growth plans, technology strategy, and competitive landscape.   Review public information (e.g. new executive appointments, earnings statements, press releases) for the company and its competitors to remain updated on key industry trends and issues impacting the prospect.
Territory and Account Leadership - Lead designated territory, including accounts, account relationships, prospect profiling, and sales cycles.  Encourage all accounts to become SAP references.
Business Planning – Develop and deliver comprehensive business plan to address customer and prospects priorities and pain points.   Utilize VE, benchmarking and ROI data to support the customer’s decision process.

2.    Demand Generation, Pipeline and Opportunity Management

Pipeline planning - Follow a disciplined approach to maintaining a rolling pipeline. Keep pipeline current and moving up the pipeline curve.
Pipeline partnerships – Leverage support organizations including Marketing, Inside sales, Partners and channels to funnel pipeline into the assigned territory.
Leverage SAP Solutions – Be proficient in and bring all SAP offers to bear on sales pursuits including Industry Solutions, LOB solutions (CRM, SCM, HCM, SRM et. al) and technology solutions (Business Analytics, Mobility, Database and Technology, et. al)
Advance and close sales opportunities - through the successful execution of the sales strategy and roadmap.
Support all SAP promotions and events in the territory

3.    Sales Excellence

Sell value.
Maintain White Space analysis and execution of initiatives (up sell and cross sell) on customer base.
Orchestrate resources: deploy appropriate teams to execute winning sales.  Create OneSAP.
Utilize best practice sales models.
Understand SAP’s competition and effectively position solutions against them.
Maintain CRM system with accurate customer and pipeline information.

Experience & Language Requirements

10+ Years of experience in sales of complex business software / IT solutions in Govt/ PSU sector
Proven track record in business application software/ services sales
Experience in the lead role of a team-selling environment. Coordination across multiple internal and external stakeholders and partners.
Demonstrated success with large transactions and lengthy sales campaigns in a fast-paced, consultative and competitive market.
Business level English: Fluent
Local language: Fluent, Business Level
Education:

Bachelor equivalent: yes
======================================
</code>```

Body:
Continuing on my earlier question Python BS4 - Concatenating multiple html elements between two different tags

I want to extend the solution for multiple url.
Consider two url  link1 | link2

The html source code looks like below

Requisition ID: 223813
Work Area: Consulting  and Professional Services
Expected Travel: 0 - 80%
Career Status: Professional
Employment Type: Regular Full Time

COMPANY DESCRIPTION
SAP started in 1972 as a team of five colleagues with a desire to do something new. Together, they changed enterprise software and reinvented how business was done. Today, as a market leader in enterprise application software, we remain true to our roots. That’s why we engineer solutions to fuel innovation, foster equality and spread opportunity for our employees and customers across borders and cultures.

SAP values the entrepreneurial spirit, fostering creativity and building lasting relationships with our employees. We know that a diverse and inclusive workforce keeps us competitive and provides opportunities for all. We believe that together we can transform industries, grow economics, lift up societies and sustain our environment. Because it’s the best-run businesses that make the world run better and improve people’s lives.

.
.
.
.
.
.

WHAT YOU GET FROM US

Success is what you make it. At SAP, we help you make it your own. A career at SAP can open many doors for you. If you’re searching for a company that’s dedicated to your ideas and individual growth, recognizes you for your unique contributions, fills you with a strong sense of purpose, and provides a fun, flexible and inclusive work environment – apply now.

My Requirement:

Get the section marked as dots in above the code. It is dynamic content & hence can't hardcode any of the section headers. Refer to the 2 links provided above to see the difference in content.

The only static text seems to be
COMPANY DESCRIPTION at the top &
WHAT YOU GET FROM US
 at the bottom.

So I need all the html tags & elemnts after "COMPANY DESCRIPTION" & before "WHAT YOU GET FROM US"

Also observe that the "COMPANY DESCRIPTION" section has 2 para
 in it. I don't want the 2nd para either which starts with
SAP values the entrepreneurial spirit,

Body:
Use the css selector to check the text contains "COMPANY DESCRIPTION" and remaining code same.

Code:

import requests
from bs4 import BeautifulSoup
def scrape_url(url, method='bs4'):
    session = requests.session()
    page = session.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    return soup

urls=['https://jobs.sap.com/job/Kuala-Lumpur-Business-Processes-Consultant-%28FICO%29-Job-14/541909901/','https://jobs.sap.com/job/Mumbai-Senior-Account-Executive-Job-MH/539212101/']

for url in urls:
    print(url)
    soup = scrape_url(url)
    findtag=soup.select_one('p:contains("COMPANY DESCRIPTION")')
    print(findtag.text)
    findnextptag=findtag.find_next_sibling('p')
    for item in findnextptag.find_next_siblings():

         if 'WHAT YOU GET FROM US' in item.text:
             break
         else:
             print(item.text.strip())

    print("======================================")

Output:

https://jobs.sap.com/job/Kuala-Lumpur-Business-Processes-Consultant-%28FICO%29-Job-14/541909901/
COMPANY DESCRIPTION
SAP started in 1972 as a team of five colleagues with a desire to do something new. Together, they changed enterprise software and reinvented how business was done. Today, as a market leader in enterprise application software, we remain true to our roots. That’s why we engineer solutions to fuel innovation, foster equality and spread opportunity for our employees and customers across borders and cultures.
PURPOSE AND OBJECTIVES

To address requirements in the area of Supply Chain Management Extended Warehouse Management solutions, Build competencies at Solution Delivery Center to deliver solutions especially in areas relating to SAP EWM

EXPECTATIONS AND TASKS

Independently handle large implementation projects with focus on Warehouse Management processes such as inbound, outbound and internal processes. RF Device functions and Barcode support experience is desirable
Able to lead EWM discussions, assessments and detail requirement studies with customers
Leading the team that are assigned to, in functional capacity, adding value to the project and to the final deliverables
Be actively involved in the preparation, conception, realization and Go Live of customer implementation projects
Demonstrate the ability to plan, run, and manage blueprint workshops / meetings with internal and external clients
Responsible for defining the scope of a project / opportunities, estimating efforts and project timelines
Participating in RFP discussions and estimating under guidance from a Bid Manager
Providing a creative source of ideas/solutions to address problems
Delivering billable components that meets a customer’s needs
KEY PERFORMANCE INDICATORS

Customer Feedback/customer satisfaction scores
Productive days/utilization as defined by the organization for projects/assessments/etc.
Knowledge Management and creation of effective reusable components
EXPERIENCE REQUIREMENTS

Minimum of 4+ years industry experience and a minimum of 5 to 6 years of SAP EWM experience
Domain knowledge in Supply Chain Management in the areas of Planning, Manufacturing & warehousing processes is a must
Must have strong ERP implementation experience
Experience in SAP Material Flow Systems (MFS) or any other third party automation tools will be desirable
Experience in EWM technical knowledge will be an added advantage
Knowledge on SAP S/4HANA Public Cloud solution and SAP IOT/Leonardo portfolio will be preferred but not mandatory
Good understanding of S/4HANA Order to Cash and Procure to Pay business processes
Good understanding of SAP ACTIVATE implementation methodology
Use of Solution Manager as a part of implementation life cycle is desirable
Good Communication skill in English.

EDUCATION AND QUALIFICATIONS/SKILLS AND COMPETENCIES

Degree in Engineering or IT
SAP Certification in Extended Warehouse Management (EWM) desirable
Minimum 4 to 5 full life cycle SAP EWM implementations
Strong knowledge in SAP SCM Extended Warehouse Management Solutions and S/4HANA Embedded EWM Solution
Good integration knowledge with other components with SAP S/4HANA (WM, SD, MM, PP) and other SAP or Non-SAP legacy applications
Knowledge of SCOR, APICS certification preferable
Strong client-facing experience and well-developed customer focus
Solid oral and written communication skills, with the demonstrated ability to communicate complex technical topics to management and non-technical audiences
Mobility is must – candidate must be ready to travel to project locations (short term and long term)

======================================
https://jobs.sap.com/job/Mumbai-Senior-Account-Executive-Job-MH/539212101/
COMPANY DESCRIPTION
SAP started in 1972 as a team of five colleagues with a desire to do something new. Together, they changed enterprise software and reinvented how business was done. Today, as a market leader in enterprise application software, we remain true to our roots. That’s why we engineer solutions to fuel innovation, foster equality and spread opportunity for our employees and customers across borders and cultures.
Key Areas of Responsibility and Tasks:

The Account Executive’s primary responsibilities include prospecting, qualifying, selling and closing new business to existing and net new customers. The Account Executive brings a Point of View to Customer engagement; uses all resources to solve customer problems with appropriate SAP products.

1.    Account and Customer Relationship Management, Sales and Software License and Cloud Subscription Revenue.

Annual Revenue - Achieve / exceed quota targets.
Sales strategies - Develops effective and specific account plans to ensure revenue target delivery and sustainable growth.   Develop relationships in new and existing customers and leverage to drive strategy through organization.
Trusted advisor - Establishes strong relationships based on knowledge of customer requirements and commitment to value (value of counsel and expertise, the value of solutions, the value of implementation expertise).  Builds a foundation on which to harvest future business opportunities and accurate account information and coaching.
Customer Acumen - Actively understand each customer’s technology footprint, strategic growth plans, technology strategy, and competitive landscape.   Review public information (e.g. new executive appointments, earnings statements, press releases) for the company and its competitors to remain updated on key industry trends and issues impacting the prospect.
Territory and Account Leadership - Lead designated territory, including accounts, account relationships, prospect profiling, and sales cycles.  Encourage all accounts to become SAP references.
Business Planning – Develop and deliver comprehensive business plan to address customer and prospects priorities and pain points.   Utilize VE, benchmarking and ROI data to support the customer’s decision process.

2.    Demand Generation, Pipeline and Opportunity Management

Pipeline planning - Follow a disciplined approach to maintaining a rolling pipeline. Keep pipeline current and moving up the pipeline curve.
Pipeline partnerships – Leverage support organizations including Marketing, Inside sales, Partners and channels to funnel pipeline into the assigned territory.
Leverage SAP Solutions – Be proficient in and bring all SAP offers to bear on sales pursuits including Industry Solutions, LOB solutions (CRM, SCM, HCM, SRM et. al) and technology solutions (Business Analytics, Mobility, Database and Technology, et. al)
Advance and close sales opportunities - through the successful execution of the sales strategy and roadmap.
Support all SAP promotions and events in the territory

3.    Sales Excellence

Sell value.
Maintain White Space analysis and execution of initiatives (up sell and cross sell) on customer base.
Orchestrate resources: deploy appropriate teams to execute winning sales.  Create OneSAP.
Utilize best practice sales models.
Understand SAP’s competition and effectively position solutions against them.
Maintain CRM system with accurate customer and pipeline information.

Experience & Language Requirements

10+ Years of experience in sales of complex business software / IT solutions in Govt/ PSU sector
Proven track record in business application software/ services sales
Experience in the lead role of a team-selling environment. Coordination across multiple internal and external stakeholders and partners.
Demonstrated success with large transactions and lengthy sales campaigns in a fast-paced, consultative and competitive market.
Business level English: Fluent
Local language: Fluent, Business Level
Education:

Bachelor equivalent: yes
======================================


问:
Dynamic boostrap card body + image in Vue js ( firestore cloud DB + local image source )
I am trying to create a small Vue js page ( AddItem.vue ) with below data.

```<code>  data (){
      dish_name: null,
      dish_description: null,
      dish_type: null,
      dish_image: null
  }
</code>```

I have a bootstrap form to accept above data and invoke a insertData() method which calls Firestore  Collection.Add() method.

```<code>insertData() {
      db.collection("Items")
        .add({
          dish_type: this.dish_type,
          dish_name: this.dish_name,
          dish_description: this.dish_description,
          dish_image: this.dish_image
        })
        .then(docRef => {
          console.log("Client added: ", docRef.id);
        })
        .catch(error => {
          console.error("Error adding dish: ", error);
        });
    }
</code>```

I would like to copy the image being uploaded from form to
/static/ directory of vue with a name,id, actual image . Is there anyway to do this ?

Also, i would like to list all items later as bootstrap cards with card data from firestore and card image from vue/static folder.

Is Axios JS - a correct way to PUT and GET images files from static folder in Vue ?

Is there any other better way to do this ?

Thank you,

Rahul

答:
Thanks to Brad Traversy & Academind, I used axios to put and get images from a node back-end server ( express js ).

A second approach is to store both data + image in firebase firestore. I was not sure of the performance of second approach and hence wanted to store images in server itself.

I could not make out much time difference between two approaches. To complete my project, I have decided to store data + image in firestore and access with firestore API's.

more info on firestore can be found here - https://firebase.google.com/docs/firestore/quickstart

Body:
I am trying to create a small Vue js page ( AddItem.vue ) with below data.

  data (){
      dish_name: null,
      dish_description: null,
      dish_type: null,
      dish_image: null
  }

I have a bootstrap form to accept above data and invoke a insertData() method which calls Firestore  Collection.Add() method.

insertData() {
      db.collection("Items")
        .add({
          dish_type: this.dish_type,
          dish_name: this.dish_name,
          dish_description: this.dish_description,
          dish_image: this.dish_image
        })
        .then(docRef => {
          console.log("Client added: ", docRef.id);
        })
        .catch(error => {
          console.error("Error adding dish: ", error);
        });
    }

I would like to copy the image being uploaded from form to
/static/ directory of vue with a name,id, actual image . Is there anyway to do this ?

Also, i would like to list all items later as bootstrap cards with card data from firestore and card image from vue/static folder.

Is Axios JS - a correct way to PUT and GET images files from static folder in Vue ?

Is there any other better way to do this ?

Thank you,

Rahul


问:
Selenium IDE Dropdown Menu Selection
I’m brand new to using selenium ide.

I’ve gotten all other parts of my coding to work.

But I’m currently having a problem with getting it to choose an option in a drop down menu.

I have the div class name for the drop down and the
 for the option I’d like to select but nothing I seem to try will work.

答:
I had the same problem and solve it using this algorithm:

```<code>- click on the drop-down list
- wait until list appears
- click on list element
</code>```

or another one:

```<code>- click on the drop-down list
- wait until list appears
- send keys ${ARROW_DOWN} to select element of the list
- send keys ${KEY_ENTER}
</code>```

Title: Selenium IDE Dropdown Menu Selection

Body:
I had the same problem and solve it using this algorithm:

- click on the drop-down list
- wait until list appears
- click on list element

or another one:

- click on the drop-down list
- wait until list appears
- send keys ${ARROW_DOWN} to select element of the list
- send keys ${KEY_ENTER}


问:
How to access and modify style of appending element
After drop, I am appending the child to the container.

My requirement is that I want to append the child at the cursor position. In order to do that, I need to access the style of child which I am appending.

I am doing that as data.style={{...}}. But it is saying as

Cannot set property 'style' of undefined

```<code> drop(event) {
      event.preventDefault();
      var data= event.dataTransfer.getData("Text");
      //data.style={position:"relative"}

      event.target.appendChild(document.getElementById(data));
      console.log(event.clientX)
      data.target.style={
        left : event.clientX + 'px',
        top : event.clientY+ 'px'
      }
</code>```

答:
style of undefined

Because the selector is undefined and it should be because if data is a node then it won't have target property. So, instead you have to do it directly on data:

```<code>data.style={
    left : event.clientX + 'px',
    top : event.clientY+ 'px'
}
</code>```

Or you might want to change your code as:

drop(event) {
  event.preventDefault();
  var data = document.getElementById(event.dataTransfer.getData("Text"));
  //data.style={position:"relative"}
  event.target.appendChild(data);
  console.log(event.clientX)
  data.style = {    // <------------apply styles on "data" node
    left: event.clientX + 'px',
    top: event.clientY + 'px'
  }
}
```

Body:
After drop, I am appending the child to the container.

My requirement is that I want to append the child at the cursor position. In order to do that, I need to access the style of child which I am appending.

I am doing that as data.style={{...}}. But it is saying as

Cannot set property 'style' of undefined

 drop(event) {
      event.preventDefault();
      var data= event.dataTransfer.getData("Text");
      //data.style={position:"relative"}

      event.target.appendChild(document.getElementById(data));
      console.log(event.clientX)
      data.target.style={
        left : event.clientX + 'px',
        top : event.clientY+ 'px'
      }

Body:
style of undefined

Because the selector is undefined and it should be because if data is a node then it won't have target property. So, instead you have to do it directly on data:

data.style={
    left : event.clientX + 'px',
    top : event.clientY+ 'px'
}

Or you might want to change your code as:

drop(event) {
  event.preventDefault();
  var data = document.getElementById(event.dataTransfer.getData("Text"));
  //data.style={position:"relative"}
  event.target.appendChild(data);
  console.log(event.clientX)
  data.style = {    // <------------apply styles on "data" node
    left: event.clientX + 'px',
    top: event.clientY + 'px'
  }
}


问:
How to replace/remove some part of a string
I have a string in which i want to remove some part.

1) below is the string( Encrypted message)

@@_/profiles/c3ed4acd-b3be-487e-81b4-a27643745d^^____User1__@@@^^^ says hello to @@_/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e^^____User2__@@@^^^

I want to get below 2 things from this

a) A string

@User1 says to @User2

2) A json object like

```<code>{
        "c3ed4acd-b3be-487e-81b4-a27643745d":"User1",
        "d3ac3c5a-8a9f-4640-8563-127674d93e":"User2"
}
</code>```

First I tried to get string and used below approach using regex

I have tried it by doing like this

```<code>var str = "@@___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__@@@^^^ says to @@___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__@@@^^^"
var rx = /(^@@___|,@@@^^^)/;  // start with @@___ and end with @@@^^^
var expectedString = str.replace(/(^@@___|,@@@^^^)/g, "");
console.log(expectedString);
</code>```

But this is just replace first occurance of

答:
There are some fundamental problems in your code

you have to escape the ^ character as \^

you don't even use your rx variable

pipe character | means or, not start with and end with

try this:

// a)
var str = "@@___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__@@@^^^ says to @@___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__@@@^^^"
var rx = /@@___([^_]+)__\^\^____([^_]+)__@@@\^\^\^/g;
var expectedString = str.replace(rx, "@$2");
console.log(expectedString);

// b)
var list = {};
while ((m = rx.exec(str)) !== null) {
  if (m.index === rx.lastIndex) {
    rx.lastIndex++;
  }
  list[m[1]] = m[2];
}
console.log(list);
```

Body:
I have a string in which i want to remove some part.

1) below is the string( Encrypted message)

@@_/profiles/c3ed4acd-b3be-487e-81b4-a27643745d^^____User1__@@@^^^ says hello to @@_/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e^^____User2__@@@^^^

I want to get below 2 things from this

a) A string

@User1 says to @User2

2) A json object like

{
        "c3ed4acd-b3be-487e-81b4-a27643745d":"User1",
        "d3ac3c5a-8a9f-4640-8563-127674d93e":"User2"
}

First I tried to get string and used below approach using regex

I have tried it by doing like this

var str = "@@___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__@@@^^^ says to @@___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__@@@^^^"
var rx = /(^@@___|,@@@^^^)/;  // start with @@___ and end with @@@^^^
var expectedString = str.replace(/(^@@___|,@@@^^^)/g, "");
console.log(expectedString);

But this is just replace first occurance of


问:
android how to save captured image into phones gallery
I have two activities. In one activity, I have an ImageView and an camera button.
When I press camera button it goes to other activity where two buttons are there Capture and another is Select button. When I press capture it captures an image. But question is how to save this capture image to gallery. And after pressing the Select button the captured image should display on 1st activity's ImageView.
How can I do that.

答:
try this..

```<code>String path = Environment.getExternalStorageDirectory() + "/CameraImages/example.jpg";
                            File file = new File(path);
                            Uri outputFileUri = Uri.fromFile( file );
                            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
                            intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

                            startActivityForResult( intent, CAPTURE_IMAGE );
</code>```

your image will be save at this location "sdcard/CameraImages/example.jpg"

Body:
try this..

String path = Environment.getExternalStorageDirectory() + "/CameraImages/example.jpg";
                            File file = new File(path);
                            Uri outputFileUri = Uri.fromFile( file );
                            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
                            intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

                            startActivityForResult( intent, CAPTURE_IMAGE );

your image will be save at this location "sdcard/CameraImages/example.jpg"


问:
How to use React.FC<props> type when the children can either be a React node or a function
I have this sample component

```<code>import React, { FC, ReactNode, useMemo } from "react";
import PropTypes from "prop-types";

type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props) {
  const val = useMemo(() => {
    return 1;
  }, []);

  return (
    <div>
      {typeof props.children === "function"
        ? props.children(val)
        : props.children}
    </div>
  );
};

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};

export default Comp;
</code>```

My intent here is that the children prop of the component can either be

a node, which is described as

Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.

a function, (or a "render prop") which simply gets a value from inside the component and returns another node

the point here is to be explicit, that the children can either be the one (node, which is pretty much everything) or the other (which is simply a function)

The problem

I am facing the following issues however with the type check.

if I leave the code as presented here, I get the following error message on the line ? props.children(val)

This expression is not callable.
  Not all constituents of type 'Function | ((x: number) => ReactNode) | (string & {}) | (number & {}) | (false & {}) | (true & {}) | ({} & string) | ({} & number) | ({} & false) | ({} & true) | (((x: number) => ReactNode) & string)

I do not understand this error.

if I change the Props type to be

```<code>type Props = {
  children: (x: number) => ReactNode;
};
</code>```

and rely on React's own type PropsWithChildren
 = P & { children?: ReactNode }; to handle the case where children is not a function, then I get the error

(property) children?: PropTypes.Validator<(x: number) => React.ReactNode>
  Type 'Validator' is not assignable to type 'Validator<(x: number) => ReactNode>'.
    Type 'ReactNodeLike' is not assignable to type '(x: number) => ReactNode'.
      Type 'string' is not assignable to type '(x: number) => ReactNode'.ts(2322)
  Comp.tsx(5, 3): The expected type comes from property 'children' which is declared here on type

on the line children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired

The only solution is to leave the Props type as

```<code>type Props = {
  children: (x: number) => ReactNode;
};
</code>```

and also change the Comp.propTypes to be children: PropTypes.func.isRequired, which is not what I want, since I want to be explicit.

The question

How can I keep the code explicit, as presented at the start of this question, and also not have the type checking throw errors on me?

CodeSandbox link

答:
Another solution which works, and doesn't require to write the Props declaration any differently or rewrite anything else differently, is to strictly define the type of the props parameter, during the component definition, like this

```<code>type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props: Props) { // we strictly define the props type here
  ...
}

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};
</code>```

I am not 100% sure why this makes a difference, my intuition is that we "force" our own Props definition down to the type checker, so we limit the possible scope.

UPDATE

Ever since I asked the original question I eventually settled for the following solution to my problem: I defined my own function component type:

```<code>//global.d.ts

declare module 'react' {
  // Do not arbitrarily pass children down to props.
  // Do not type check actual propTypes because they cannot always map 1:1 with TS types,
  // forcing you to go with PropTypes.any very often, in order for the TS compiler
  // to shut up

  type CFC<P = {}> = CustomFunctionComponent<P>;

  interface CustomFunctionComponent<P = {}> {
    (props: P, context?: any): ReactElement | null;
    propTypes?: { [key: string]: any };
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
  }
}
</code>```

This solution

Allows me to strictly define what is a function component

Does not force any arbitrary children prop into my definition

Does not cross reference any actual Component.propTypes with the TS type Props = {...}. Many times they would not map exactly 1:1, and I was forced to use PropTypes.any which is not what I wanted.

The reason I am keeping the Component.propTypes along with the TS types, is that while TS is very nice during development, PropTypes will actually warn in case of a wrong-type value during runtime, which is useful behaviour when, for example, a field in an API response was supposed to be a number and is now a string. Things like this may happen and it's not something TS can help with.

Further Reading

https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34237
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34237#issuecomment-486374424

Body:
I have this sample component

import React, { FC, ReactNode, useMemo } from "react";
import PropTypes from "prop-types";

type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props) {
  const val = useMemo(() => {
    return 1;
  }, []);

  return (

      {typeof props.children === "function"
        ? props.children(val)
        : props.children}

  );
};

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};

export default Comp;

My intent here is that the children prop of the component can either be

a node, which is described as

Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.

a function, (or a "render prop") which simply gets a value from inside the component and returns another node

the point here is to be explicit, that the children can either be the one (node, which is pretty much everything) or the other (which is simply a function)

The problem

I am facing the following issues however with the type check.

if I leave the code as presented here, I get the following error message on the line ? props.children(val)

This expression is not callable.
  Not all constituents of type 'Function | ((x: number) => ReactNode) | (string & {}) | (number & {}) | (false & {}) | (true & {}) | ({} & string) | ({} & number) | ({} & false) | ({} & true) | (((x: number) => ReactNode) & string)

I do not understand this error.

if I change the Props type to be

type Props = {
  children: (x: number) => ReactNode;
};

and rely on React's own type PropsWithChildren
 = P & { children?: ReactNode }; to handle the case where children is not a function, then I get the error

(property) children?: PropTypes.Validator<(x: number) => React.ReactNode>
  Type 'Validator' is not assignable to type 'Validator<(x: number) => ReactNode>'.
    Type 'ReactNodeLike' is not assignable to type '(x: number) => ReactNode'.
      Type 'string' is not assignable to type '(x: number) => ReactNode'.ts(2322)
  Comp.tsx(5, 3): The expected type comes from property 'children' which is declared here on type

on the line children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired

The only solution is to leave the Props type as

type Props = {
  children: (x: number) => ReactNode;
};

and also change the Comp.propTypes to be children: PropTypes.func.isRequired, which is not what I want, since I want to be explicit.

The question

How can I keep the code explicit, as presented at the start of this question, and also not have the type checking throw errors on me?

CodeSandbox link

Body:
Another solution which works, and doesn't require to write the Props declaration any differently or rewrite anything else differently, is to strictly define the type of the props parameter, during the component definition, like this

type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props: Props) { // we strictly define the props type here
  ...
}

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};

I am not 100% sure why this makes a difference, my intuition is that we "force" our own Props definition down to the type checker, so we limit the possible scope.

UPDATE

Ever since I asked the original question I eventually settled for the following solution to my problem: I defined my own function component type:

//global.d.ts

declare module 'react' {
  // Do not arbitrarily pass children down to props.
  // Do not type check actual propTypes because they cannot always map 1:1 with TS types,
  // forcing you to go with PropTypes.any very often, in order for the TS compiler
  // to shut up

  type CFC<P = {}> = CustomFunctionComponent<P>;

  interface CustomFunctionComponent<P = {}> {
    (props: P, context?: any): ReactElement | null;
    propTypes?: { [key: string]: any };
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
  }
}

This solution

Allows me to strictly define what is a function component

Does not force any arbitrary children prop into my definition

Does not cross reference any actual Component.propTypes with the TS type Props = {...}. Many times they would not map exactly 1:1, and I was forced to use PropTypes.any which is not what I wanted.

The reason I am keeping the Component.propTypes along with the TS types, is that while TS is very nice during development, PropTypes will actually warn in case of a wrong-type value during runtime, which is useful behaviour when, for example, a field in an API response was supposed to be a number and is now a string. Things like this may happen and it's not something TS can help with.

Further Reading

https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34237
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34237#issuecomment-486374424


问:
What property is exposed to outside when using const { }
I follow the example of ngrx store as follows

https://stackblitz.com/edit/angular-multiple-entities-in-same-state?file=src%2Fapp%2Fstate%2Freducers%2Fexample.reducer.ts

There is a code in example.reducer.ts

```<code>export const { selectAll: selectAllCars } = adapterCar.getSelectors();
</code>```

And the outside calls

```<code>export const selectAllCars = createSelector(selectCarState, fromExample.selectAllCars);
</code>```

Not call selectAll

Sorry to ask but I have no idea how to search it. Could you please explain how it works?

答:
It's a destructuring assignment. It's supposed to improve code readibility, but I wonder if it isn't misused here.

```<code>export const { selectAll: selectAllCars } = adapterCar.getSelectors();
</code>```

means the same as

```<code>const carSelectors = adapterCar.getSelectors();
const selectAllCars = carSelectors.selectAll;
export { selectAllCars };
</code>```

Body:
I follow the example of ngrx store as follows

https://stackblitz.com/edit/angular-multiple-entities-in-same-state?file=src%2Fapp%2Fstate%2Freducers%2Fexample.reducer.ts

There is a code in example.reducer.ts

export const { selectAll: selectAllCars } = adapterCar.getSelectors();

And the outside calls

export const selectAllCars = createSelector(selectCarState, fromExample.selectAllCars);

Not call selectAll

Sorry to ask but I have no idea how to search it. Could you please explain how it works?

Body:
It's a destructuring assignment. It's supposed to improve code readibility, but I wonder if it isn't misused here.

export const { selectAll: selectAllCars } = adapterCar.getSelectors();

means the same as

const carSelectors = adapterCar.getSelectors();
const selectAllCars = carSelectors.selectAll;
export { selectAllCars };


问:
Can I log MS Insights calls in a separate thread?
I have console app and i use Microsoft insights, but sending an event or exception is slow so I want send insights on different thread.

```<code>let worker = new Worker(__dirname + '/insights.js');
worker.on('message', (msg) => {
                console.log("First value is: ", msg);

//in worker
let a = 10000000000;
while(a > 1){
    a--;
}
parentPort.postMessage(a);
</code>```

I try use worker thread but it's does not help me. They work synchronously.
For example I create new worker and run loop there

Can I somehow send event into insights in parallel and continue running other code in the mean time?

答:
I change code in index.js  and now i use the following:

```<code>function sendLog(functionName, obj , commandName = ''){
    const cp = require('child_process');
    const subprocess = cp.fork( __dirname + '/insights.js', [], {
        detached: true,
        stdio: [ 'ignore', 'ignore', 'ignore', 'ipc' ]
      });
    subprocess.send({function:functionName, obj: obj, commandName: commandName, UUID : uuid, scriptName: roundCommand});
    subprocess.unref();
}
</code>```

In insights.js i trackEvent. It's work fine, i can send logs in background.
But when in my index.js i execute command whitch run for example App C# console app in whict i againe execute index.js file creating new process:

```<code>var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    RedirectStandardError = true,
                    FileName = "cmd.exe",
                    Arguments = $"/C {PathToCommand} {command} {arguments}",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };
</code>```

the main process will freez... i don't now why, i detach all child processes .... maybe something in how new process execute from C# application and as result child proccess can't detached from parent.... i don't now...

Body:
I have console app and i use Microsoft insights, but sending an event or exception is slow so I want send insights on different thread.

let worker = new Worker(__dirname + '/insights.js');
worker.on('message', (msg) => {
                console.log("First value is: ", msg);

//in worker
let a = 10000000000;
while(a > 1){
    a--;
}
parentPort.postMessage(a);

I try use worker thread but it's does not help me. They work synchronously.
For example I create new worker and run loop there

Can I somehow send event into insights in parallel and continue running other code in the mean time?

Body:
I change code in index.js  and now i use the following:

function sendLog(functionName, obj , commandName = ''){
    const cp = require('child_process');
    const subprocess = cp.fork( __dirname + '/insights.js', [], {
        detached: true,
        stdio: [ 'ignore', 'ignore', 'ignore', 'ipc' ]
      });
    subprocess.send({function:functionName, obj: obj, commandName: commandName, UUID : uuid, scriptName: roundCommand});
    subprocess.unref();
}

In insights.js i trackEvent. It's work fine, i can send logs in background.
But when in my index.js i execute command whitch run for example App C# console app in whict i againe execute index.js file creating new process:

var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    RedirectStandardError = true,
                    FileName = "cmd.exe",
                    Arguments = $"/C {PathToCommand} {command} {arguments}",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };

the main process will freez... i don't now why, i detach all child processes .... maybe something in how new process execute from C# application and as result child proccess can't detached from parent.... i don't now...


问:
Python process for scraping in GCP Compute Engine being suspended for Crypto Mining
I receive this email and my VM instance gets suspended. It is an airflow server that runs multiple processes including one DAG which scrapes of 5k - 10k separate links and extracts body from it - this is done concurrently by 500 different connections which is what I'm suspecting is raising this particular issue. I receive this particular email after 24 hours of running and my VM gets suspended.

```<code>Dear Developer,
We've detected that your Google Cloud Project is engaging in cryptocurrency mining, resulting in the suspension of all project resources displaying this behavior.

This activity violates the Google Cloud Platform Terms of Service or the Terms of Service of the Google API you may be using.

We recommend that you review this activity to determine if it is intended. Cryptocurrency mining is often an indication of the use of fraudulent accounts and payment instruments, and we require verification in order to mine cryptocurrency on our platform.

Therefore if you wish to continue engaging in cryptocurrency mining, you must apply for an Invoiced Billing Account. Additional information is available in the Cloud Security Help Center.

To regain access to your suspended resources please submit an appeal:

Sign in to as the project owner, click Request an appeal below, and fill in the following details:

Possible trigger of this activity
If the behavior is intentional, please provide the Invoiced Billing Account ID
If you believe the project may have been compromised by a third party, describe your concerns
Learn more about policy violations and appeals

If you need further help, reach out to the Google Cloud Platform Community Support Forum. If you have a support package, file a ticket through the Support Center.

You may have received an earlier warning about a possible suspension of resources if this violation wasn't corrected. If you didn't receive a warning before this suspension, it was because the project's behavior was seriously impacting the service of other users.
</code>```

This is the code which I'm suspecting is creating the issue

```<code>out = []
CONNECTIONS = 500
TIMEOUT = 5

def do_request(url):
    try:
        requests.head(url, verify=False, timeout=10, headers=headers)
    except Exception:
        return "", 404

    try:
        res = requests.get(url, verify=False, timeout=10, headers=headers)
        content = extract_content(res.content)
        return content, res.status_code
    except Exception:
        return "", 404

def gen_text_dragnet(article, timeout):
    content, status_code = do_request(article["url"])
    article.update(body=content[:500], status_code=status_code)
    return status_code

def extract_body():
    """
    Processing broken URLs are a huge pain in the ass
    """
    global_init()
    try:
        articles = Article.objects.filter(
            status_code__exists=False)[:5000]
    except Exception as e:
        print(e)
        raise

    print("extracting bodies from {} articles".format(len(articles)))

    with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as executor:
        future_to_url = (executor.submit(gen_text_dragnet, article, TIMEOUT)
                         for article in articles)
        time1 = time.time()
        for future in concurrent.futures.as_completed(future_to_url):
            try:
                data = future.result()
            except Exception as exc:
                data = str(type(exc))
            finally:
                out.append(data)
                print(str(len(out)), end="\r")

        time2 = time.time()

    print(f'Took {time2-time1:.2f} s')
    print(pd.Series(out).value_counts())
</code>```

This has happened multiple times and every time I submit an appeal, I get no response and I have to delete and re-create the instance. That is really annoying and isn't sustainable for the project. What can I do about this?

答:
StackOverflow isn't the right channel to solve issues like this.

The best option for you could be contact Google Cloud Support because they has the possibility to inspect your project and provide you further instructions. If you don't have a support contract yet in such case you could ask for one time courtesy from support.

If you don't wan't to contact support in that way you can try to open a case at Google Issue Tracker under this private component  and provide project name, email and as many details as possible.

Body:
I receive this email and my VM instance gets suspended. It is an airflow server that runs multiple processes including one DAG which scrapes of 5k - 10k separate links and extracts body from it - this is done concurrently by 500 different connections which is what I'm suspecting is raising this particular issue. I receive this particular email after 24 hours of running and my VM gets suspended.

Dear Developer,
We've detected that your Google Cloud Project is engaging in cryptocurrency mining, resulting in the suspension of all project resources displaying this behavior.

This activity violates the Google Cloud Platform Terms of Service or the Terms of Service of the Google API you may be using.

We recommend that you review this activity to determine if it is intended. Cryptocurrency mining is often an indication of the use of fraudulent accounts and payment instruments, and we require verification in order to mine cryptocurrency on our platform.

Therefore if you wish to continue engaging in cryptocurrency mining, you must apply for an Invoiced Billing Account. Additional information is available in the Cloud Security Help Center.

To regain access to your suspended resources please submit an appeal:

Sign in to as the project owner, click Request an appeal below, and fill in the following details:

Possible trigger of this activity
If the behavior is intentional, please provide the Invoiced Billing Account ID
If you believe the project may have been compromised by a third party, describe your concerns
Learn more about policy violations and appeals

If you need further help, reach out to the Google Cloud Platform Community Support Forum. If you have a support package, file a ticket through the Support Center.

You may have received an earlier warning about a possible suspension of resources if this violation wasn't corrected. If you didn't receive a warning before this suspension, it was because the project's behavior was seriously impacting the service of other users.

This is the code which I'm suspecting is creating the issue

out = []
CONNECTIONS = 500
TIMEOUT = 5

def do_request(url):
    try:
        requests.head(url, verify=False, timeout=10, headers=headers)
    except Exception:
        return "", 404

    try:
        res = requests.get(url, verify=False, timeout=10, headers=headers)
        content = extract_content(res.content)
        return content, res.status_code
    except Exception:
        return "", 404

def gen_text_dragnet(article, timeout):
    content, status_code = do_request(article["url"])
    article.update(body=content[:500], status_code=status_code)
    return status_code

def extract_body():
    """
    Processing broken URLs are a huge pain in the ass
    """
    global_init()
    try:
        articles = Article.objects.filter(
            status_code__exists=False)[:5000]
    except Exception as e:
        print(e)
        raise

    print("extracting bodies from {} articles".format(len(articles)))

    with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as executor:
        future_to_url = (executor.submit(gen_text_dragnet, article, TIMEOUT)
                         for article in articles)
        time1 = time.time()
        for future in concurrent.futures.as_completed(future_to_url):
            try:
                data = future.result()
            except Exception as exc:
                data = str(type(exc))
            finally:
                out.append(data)
                print(str(len(out)), end="\r")

        time2 = time.time()

    print(f'Took {time2-time1:.2f} s')
    print(pd.Series(out).value_counts())

This has happened multiple times and every time I submit an appeal, I get no response and I have to delete and re-create the instance. That is really annoying and isn't sustainable for the project. What can I do about this?


问:
Singleton class in Kotlin
I want to know how to create a singleton class in Kotlin, so that my Util class instantiates it only once per app execution. However, when I converted my Java class to kotlin, the code below was generated.

Is this correct?

```<code>companion object {
    private var utilProject: UtilProject? = null

    val instance: UtilProject
        get() {
            if (utilProject == null) utilProject = UtilProject()
            return utilProject!!
        }
}
</code>```

I could find a related question, but it is with parameters, and I am not getting it convert without params.

答:
```<code> class TestMySingleton private constructor() {

   companion object {
        var single = TestMySingleton()

        fun getInstance(): TestMySingleton {
            if (single == null)
                single = TestMySingleton()
            return single
        }
    }

}
</code>```

Title: Singleton class in Kotlin

Body:
I want to know how to create a singleton class in Kotlin, so that my Util class instantiates it only once per app execution. However, when I converted my Java class to kotlin, the code below was generated.

Is this correct?

companion object {
    private var utilProject: UtilProject? = null

    val instance: UtilProject
        get() {
            if (utilProject == null) utilProject = UtilProject()
            return utilProject!!
        }
}

I could find a related question, but it is with parameters, and I am not getting it convert without params.


问:
How to refer to end of grid with implicit grid layout?
I have a HTML document with following fragment

```<code><main>
  <article>A</article>
  <article>B</article>
  <article>C</article>
  <article>D</article>
  <article>E</article>
  <article>F</article>
  <article>G</article>
  <article>H</article>
  <article>I</article>
  <article>J</article>
  <aside>Tall content</aside>
</main>
</code>```

and I would like to put all the articles in left column and strech aside element as sidebar on the right.

I tried following CSS:

```<code>main
{
  display: grid;
  grid-template-columns: 1fr 15rem;
  grid-auto-rows: auto auto;
  gap: 1rem;
}

article
{
  grid-column: 1;
}

aside
{
  grid-column: 2;
  grid-row: 1 / -1;
}
</code>```

However, this does not work. The reason is that the -1 in grid-row refers to end of explicit grid. How to refer to end of implicit or the whole grid?

The list of articles is dynamically generated and I'd prefer not to have to say grid-row: 1 / 11 which would make the example work correctly but requires changing the second number according to content. I'd highly prefer to keep CSS static for all content.

答:
main {
  display: grid;
  gap: 1rem;
  grid-template-columns: 1fr 15em;
  grid-auto-rows: auto auto;
}

article {
  grid-auto-rows: 50px;
}

aside {
  grid-column: 2;
  grid-row: 1 / -1;
}

main>* {
  color: #fff;
  background: #777;
  padding: 1rem;
  border-radius: 0.5rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <article>A</article>
  <article>B</article>
  <article>C</article>
  <article>D</article>
  <article>E</article>
  <article>F</article>
  <article>G</article>
  <article>H</article>
  <article>I</article>
  <article>J</article>
  <article>J</article>
  <article>J</article>
  <article>J</article>
  <article>J</article>
  <div>
    <aside>Tall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall
      contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall content contentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall
      contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall
      contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall
      contentTall contentTall content</aside>
  </div>
</main></code>```

Body:
I have a HTML document with following fragment

A

B

C

D

E

F

G

H

I

J

  Tall content

and I would like to put all the articles in left column and strech aside element as sidebar on the right.

I tried following CSS:

main
{
  display: grid;
  grid-template-columns: 1fr 15rem;
  grid-auto-rows: auto auto;
  gap: 1rem;
}

article
{
  grid-column: 1;
}

aside
{
  grid-column: 2;
  grid-row: 1 / -1;
}

However, this does not work. The reason is that the -1 in grid-row refers to end of explicit grid. How to refer to end of implicit or the whole grid?

The list of articles is dynamically generated and I'd prefer not to have to say grid-row: 1 / 11 which would make the example work correctly but requires changing the second number according to content. I'd highly prefer to keep CSS static for all content.

Body:
main {
  display: grid;
  gap: 1rem;
  grid-template-columns: 1fr 15em;
  grid-auto-rows: auto auto;
}

article {
  grid-auto-rows: 50px;
}

aside {
  grid-column: 2;
  grid-row: 1 / -1;
}

main>* {
  color: #fff;
  background: #777;
  padding: 1rem;
  border-radius: 0.5rem;
}

<main>
  <article>A</article>
  <article>B</article>
  <article>C</article>
  <article>D</article>
  <article>E</article>
  <article>F</article>
  <article>G</article>
  <article>H</article>
  <article>I</article>
  <article>J</article>
  <article>J</article>
  <article>J</article>
  <article>J</article>
  <article>J</article>
  <div>
    <aside>Tall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall
      contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall contentTall content contentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall
      contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall
      contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall contentTall contentTall contentcontentTall
      contentTall contentTall content</aside>
  </div>
</main>


问:
react filtering an object of arrays
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

```<code> this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}
</code>```

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

```<code>var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });
</code>```

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

答:
use Object.keys. In your case like this:
var search = Object.keys(this.state.searchParams).filter(el => {
  // do something
})

Title: react filtering an object of arrays

Body:
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

 this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?


问:
Multi-statement Table Valued Function vs Inline Table Valued Function
A few examples to show, just incase:

Inline Table Valued

```<code>CREATE FUNCTION MyNS.GetUnshippedOrders()
RETURNS TABLE
AS
RETURN SELECT a.SaleId, a.CustomerID, b.Qty
    FROM Sales.Sales a INNER JOIN Sales.SaleDetail b
        ON a.SaleId = b.SaleId
        INNER JOIN Production.Product c ON b.ProductID = c.ProductID
    WHERE a.ShipDate IS NULL
GO
</code>```

Multi Statement Table Valued

```<code>CREATE FUNCTION MyNS.GetLastShipped(@CustomerID INT)
RETURNS @CustomerOrder TABLE
(SaleOrderID    INT         NOT NULL,
CustomerID      INT         NOT NULL,
OrderDate       DATETIME    NOT NULL,
OrderQty        INT         NOT NULL)
AS
BEGIN
    DECLARE @MaxDate DATETIME

    SELECT @MaxDate = MAX(OrderDate)
    FROM Sales.SalesOrderHeader
    WHERE CustomerID = @CustomerID

    INSERT @CustomerOrder
    SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
    FROM Sales.SalesOrderHeader a INNER JOIN Sales.SalesOrderHeader b
        ON a.SalesOrderID = b.SalesOrderID
        INNER JOIN Production.Product c ON b.ProductID = c.ProductID
    WHERE a.OrderDate = @MaxDate
        AND a.CustomerID = @CustomerID
    RETURN
END
GO
</code>```

Is there an advantage to using one type (in-line or multi statement) over the other? Is there certain scenarios when one is better than the other or are the differences purely syntactical? I realise the two example queries are doing different things but is there a reason I would write them in that way?

Reading about them and the advantages/differences haven't really been explained.

答:
Maybe in  a very condensed way.
ITVF ( inline TVF) : more if u are DB person, is kind of parameterized view, take a single SELECT st

MTVF ( Multi-statement TVF): Developer, creates and load a table variable.

Body:
A few examples to show, just incase:

Inline Table Valued

CREATE FUNCTION MyNS.GetUnshippedOrders()
RETURNS TABLE
AS
RETURN SELECT a.SaleId, a.CustomerID, b.Qty
    FROM Sales.Sales a INNER JOIN Sales.SaleDetail b
        ON a.SaleId = b.SaleId
        INNER JOIN Production.Product c ON b.ProductID = c.ProductID
    WHERE a.ShipDate IS NULL
GO

Multi Statement Table Valued

CREATE FUNCTION MyNS.GetLastShipped(@CustomerID INT)
RETURNS @CustomerOrder TABLE
(SaleOrderID    INT         NOT NULL,
CustomerID      INT         NOT NULL,
OrderDate       DATETIME    NOT NULL,
OrderQty        INT         NOT NULL)
AS
BEGIN
    DECLARE @MaxDate DATETIME

    SELECT @MaxDate = MAX(OrderDate)
    FROM Sales.SalesOrderHeader
    WHERE CustomerID = @CustomerID

    INSERT @CustomerOrder
    SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
    FROM Sales.SalesOrderHeader a INNER JOIN Sales.SalesOrderHeader b
        ON a.SalesOrderID = b.SalesOrderID
        INNER JOIN Production.Product c ON b.ProductID = c.ProductID
    WHERE a.OrderDate = @MaxDate
        AND a.CustomerID = @CustomerID
    RETURN
END
GO

Is there an advantage to using one type (in-line or multi statement) over the other? Is there certain scenarios when one is better than the other or are the differences purely syntactical? I realise the two example queries are doing different things but is there a reason I would write them in that way?

Reading about them and the advantages/differences haven't really been explained.


问:
How to perform bilinear interpolation in Python
I would like to perform blinear interpolation using python.

Example gps point for which I want to interpolate height is:

```<code>B = 54.4786674627
L = 17.0470721369
</code>```

using four adjacent points with known coordinates and height values:

```<code>n = [(54.5, 17.041667, 31.993), (54.5, 17.083333, 31.911), (54.458333, 17.041667, 31.945), (54.458333, 17.083333, 31.866)]
</code>```

```<code>z01    z11

     z
z00    z10
</code>```

and here's my primitive attempt:
```<code>import math
z00 = n[0][2]
z01 = n[1][2]
z10 = n[2][2]
z11 = n[3][2]
c = 0.016667 #grid spacing
x0 = 56 #latitude of origin of grid
y0 = 13 #longitude of origin of grid
i = math.floor((L-y0)/c)
j = math.floor((B-x0)/c)
t = (B - x0)/c - j
z0 = (1-t)*z00 + t*z10
z1 = (1-t)*z01 + t*z11
s = (L-y0)/c - i
z = (1-s)*z0 + s*z1
</code>```

where z0 and z1

```<code>z01  z0  z11

     z
z00  z1   z10
</code>```

I get 31.964 but from other software I get 31.961.

Is my script correct?

Can You provide another approach?

2022 Edit:

I would like to thank everyone who, even more than a decade after publication of this question, gives new answers to it.

答:
I suggest the following solution:</p>

```<code>def bilinear_interpolation(x, y, z01, z11, z00, z10):

    def linear_interpolation(x, z0, z1):
        return z0 * x + z1 * (1 - x)

    return linear_interpolation(y, linear_interpolation(x, z01, z11),
                                   linear_interpolation(x, z00, z10))
</code>```

Body:
I would like to perform blinear interpolation using python.

Example gps point for which I want to interpolate height is:

B = 54.4786674627
L = 17.0470721369

using four adjacent points with known coordinates and height values:

n = [(54.5, 17.041667, 31.993), (54.5, 17.083333, 31.911), (54.458333, 17.041667, 31.945), (54.458333, 17.083333, 31.866)]

z01    z11

     z
z00    z10

and here's my primitive attempt:

import math
z00 = n[0][2]
z01 = n[1][2]
z10 = n[2][2]
z11 = n[3][2]
c = 0.016667 #grid spacing
x0 = 56 #latitude of origin of grid
y0 = 13 #longitude of origin of grid
i = math.floor((L-y0)/c)
j = math.floor((B-x0)/c)
t = (B - x0)/c - j
z0 = (1-t)*z00 + t*z10
z1 = (1-t)*z01 + t*z11
s = (L-y0)/c - i
z = (1-s)*z0 + s*z1

where z0 and z1

z01  z0  z11

     z
z00  z1   z10

I get 31.964 but from other software I get 31.961.

Is my script correct?

Can You provide another approach?

2022 Edit:

I would like to thank everyone who, even more than a decade after publication of this question, gives new answers to it.

Body:
I suggest the following solution:

def bilinear_interpolation(x, y, z01, z11, z00, z10):

    def linear_interpolation(x, z0, z1):
        return z0 * x + z1 * (1 - x)

    return linear_interpolation(y, linear_interpolation(x, z01, z11),
                                   linear_interpolation(x, z00, z10))


问:
How to append the child at cursor position in reactjs
I am appending a child after drop in a container.But the data is  not getting appended at the cursor position.How do i do that in reactjs</p>

```<code>

 drop(event) {
      event.preventDefault();
      var data = event.dataTransfer.getData("Text");
      event.target.appendChild(document.getElementById(data));
    }

</code>```

答:
Here is sample codesandbox code for Drag and drop implementation using React.

https://codesandbox.io/s/tender-sanderson-so76x

Hope this helps.

Body:
I am appending a child after drop in a container.But the data is  not getting appended at the cursor position.How do i do that in reactjs

 drop(event) {
      event.preventDefault();
      var data = event.dataTransfer.getData("Text");
      event.target.appendChild(document.getElementById(data));
    }


问:
How to display the activity indicator
After clicking the Login Button in the login screen i need to display a transparent View with activity indicator in the middle(spinning) and after some time that should disappear and the next view should be loaded.

please help me in this aspect

thanks
rizwan

答:
I assume you'll be using ajax for the login and a back-end server side script.

You'll find the "spinning activity indicator" thing in the Apple SDK library Interface Builder as referred to in the comment.

Once your Ajax call has been made - you are waiting for a response. Simply display the activity indicator until you get a response from the server.

Then simply hide it once you have done your processing to load the "next view".

I can't give you an exact answer because your question lacks too much detail.

Title: How to display the activity indicator


问:
How to copy a bundle html file to a document directory in iOS Swift?
I have been trying to save local index.html file to document directory but it does not save to local document directory.

here is my folder structure:

```<code>sampleHtml.xcodeproj
---->sampleHtml
-------->Web_Assets
------------> index.html
---->ViewController.swift
</code>```

Here is the code for saving and checking file path exist is not, if path exist then overwrite it else copy the new one.

```<code>func saveHtmlDoc(){
    let filemgr = FileManager.default
    let docURL = filemgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destPath = docURL.path+"/www/"
    print("des path", destPath)
    let sourcePath = Bundle.main.resourceURL!.appendingPathComponent("Web_Assets").path
    print("sourc", sourcePath.appending("/index.html"))

      //COPY Web_Assets content from Bundle to Documents/www
      do {
          try filemgr.removeItem(atPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }
      do {
          try filemgr.copyItem(atPath:  sourcePath + "/", toPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }

}
</code>```

My issue is how to save index.html file to document directory and check the file path exist are not, if exist overwrite it or copy the new one.

Any help much appreciates it...

答:
I have just done this code in a test project which works.

You should ensure that you are performing checks along the way and ensure that your HTML file is in your Copy resources build phase

```<code>import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        moveHtmlFile()
    }

    private func moveHtmlFile() {
        let fileManager = FileManager.default
        let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        guard let sourcePath = Bundle.main.path(forResource: "index", ofType: "html") else {
            return
        }

        if fileManager.fileExists(atPath: sourcePath) {
            let sourceUrl = URL(fileURLWithPath: sourcePath)
            try? fileManager.createDirectory(atPath: documentsDirectory.appendingPathComponent("www").path,
                                             withIntermediateDirectories: false,
                                             attributes: nil)
            let destination = documentsDirectory.appendingPathComponent("www/index.html", isDirectory: false)
            try? fileManager.copyItem(at: sourceUrl, to: destination)

            if fileManager.fileExists(atPath: destination.path) {
                print("file copied")
            } else {
                print("file copy failed")
            }
        }
    }

}
</code>```

Result:

Body:
I have been trying to save local index.html file to document directory but it does not save to local document directory.

here is my folder structure:

sampleHtml.xcodeproj
---->sampleHtml
-------->Web_Assets
------------> index.html
---->ViewController.swift

Here is the code for saving and checking file path exist is not, if path exist then overwrite it else copy the new one.

func saveHtmlDoc(){
    let filemgr = FileManager.default
    let docURL = filemgr.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destPath = docURL.path+"/www/"
    print("des path", destPath)
    let sourcePath = Bundle.main.resourceURL!.appendingPathComponent("Web_Assets").path
    print("sourc", sourcePath.appending("/index.html"))

      //COPY Web_Assets content from Bundle to Documents/www
      do {
          try filemgr.removeItem(atPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }
      do {
          try filemgr.copyItem(atPath:  sourcePath + "/", toPath: destPath)
      } catch {
          print("Error: \(error.localizedDescription)")
      }

}

My issue is how to save index.html file to document directory and check the file path exist are not, if exist overwrite it or copy the new one.

Any help much appreciates it...

Body:
I have just done this code in a test project which works.

You should ensure that you are performing checks along the way and ensure that your HTML file is in your Copy resources build phase

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        moveHtmlFile()
    }

    private func moveHtmlFile() {
        let fileManager = FileManager.default
        let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        guard let sourcePath = Bundle.main.path(forResource: "index", ofType: "html") else {
            return
        }

        if fileManager.fileExists(atPath: sourcePath) {
            let sourceUrl = URL(fileURLWithPath: sourcePath)
            try? fileManager.createDirectory(atPath: documentsDirectory.appendingPathComponent("www").path,
                                             withIntermediateDirectories: false,
                                             attributes: nil)
            let destination = documentsDirectory.appendingPathComponent("www/index.html", isDirectory: false)
            try? fileManager.copyItem(at: sourceUrl, to: destination)

            if fileManager.fileExists(atPath: destination.path) {
                print("file copied")
            } else {
                print("file copy failed")
            }
        }
    }

}

Result: