问:
CakePHP - Is it possible to use Containable behaviour with the read() method?
I'm new with CakePHP and can't figure out how to call the read() method of a model class with a Containable behaviour. I can do the following with find()

```<code>$this->T->find('all', array (
    'contain' => array (
        'C',
        'L' => array (
            'fields' => array ('L.id, L.time'),
            'I' => array (
                'fields' => array ('I.id','I.time'),
                'J.name',
                'J.id'
            )
        )
    )
);
</code>```

That works just as I expected, but I don't want to get all instances of T, but instead the one with id = $id so I can pass it to the 'view' View. but the array passed to find doesn't work when doing

```<code>$this->T->read(
array (
        'contain' => array (
            'C',
            'L' => array (
                'fields' => array ('L.id, L.time'),
                'I' => array (
                    'fields' => array ('I.id','I.time'),
                    'J.name',
                    'J.id'
                )
            )
        )
, $id)
</code>```

Is there any way to do this?

答:
You can set also before the read() call:</p>

```<code>$this->T->id = $id;
$this->T->contain(array(...));
$this->T->read();
</code>```

Body:
I'm new with CakePHP and can't figure out how to call the read() method of a model class with a Containable behaviour. I can do the following with find()

$this->T->find('all', array (
    'contain' => array (
        'C',
        'L' => array (
            'fields' => array ('L.id, L.time'),
            'I' => array (
                'fields' => array ('I.id','I.time'),
                'J.name',
                'J.id'
            )
        )
    )
);

That works just as I expected, but I don't want to get all instances of T, but instead the one with id = $id so I can pass it to the 'view' View. but the array passed to find doesn't work when doing

$this->T->read(
array (
        'contain' => array (
            'C',
            'L' => array (
                'fields' => array ('L.id, L.time'),
                'I' => array (
                    'fields' => array ('I.id','I.time'),
                    'J.name',
                    'J.id'
                )
            )
        )
, $id)

Is there any way to do this?

Body:
You can set also before the read() call:

$this->T->id = $id;
$this->T->contain(array(...));
$this->T->read();


来源: stackexchange

问:
Paginating a List in React
Probably a silly question but can't seem to figure it out on my own. Let's say I have a long list of items displayed on the page. I simply want to paginate it into pages of e.g. 5 items per page. To avoid reinventing the wheel, looked up a couple of libraries and react-js-pagination seems to do what I need. But for the life of me I can't figure it out.
What I have tried per the simplified example below:

Put <Pagination /> and my list in the same div.

Gave my list items a class of page-item per the API docs.

No luck. I added a parent of
 and/or put my items in
 tags. Even gave the parent
 a class of "pagination". Nothing. The only difference I am able to achieve is all items appearing in the same line like you see in the screenshot. Anything you figure out I am missing is appreciated.

```<code>import 'react-toastify/dist/ReactToastify.css';
import Pagination from "react-js-pagination";
import 'bootstrap/dist/css/bootstrap.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            activePage: 1
        }
    }

    handlePageChange(pageNumber) {
        this.setState({activePage: pageNumber});
    }

    render() {
        return (
            <div>
                <ul className="pagination">
                    <li className="page-item">1</li>
                    <li className="page-item">2</li>
                    <li className="page-item">3</li>
                    <li className="page-item">4</li>
                    <li className="page-item">5</li>
                    <li className="page-item">6</li>
                    <li className="page-item">7</li>
                    <li className="page-item">8</li>
                    <li className="page-item">9</li>
                    <li className="page-item">10</li>
                    <li className="page-item">11</li>
                </ul>
                <Pagination
                    activePage={this.state.activePage}
                    itemsCountPerPage={2}
                    totalItemsCount={11}
                    pageRangeDisplayed={5}
                    onChange={this.handlePageChange.bind(this)}
                    itemClass="page-item"
                    linkClass="page-link"
                />
            </div>
        );
    }
}

export default App;
</code>```

Result so far:

答:
The paginator and the displayed content are two differents things and are managed separatly. Your pagination is ok, but on each onChange event, you need to get x elements from your array of data or API or whatever, x being your pageSize (I guess it's itemsCountPerPage here). The retrieved elements are x elements, starting at the index x * pageIndex, pageIndex being the current page (1, 2 3, etc., named pageRangeDisplayed here is think).

So you need to do the maths around your apginator, it does not include it.

ContentLicense: CC BY-SA 4.0

Title: Paginating a List in React

Body:
Probably a silly question but can't seem to figure it out on my own. Let's say I have a long list of items displayed on the page. I simply want to paginate it into pages of e.g. 5 items per page. To avoid reinventing the wheel, looked up a couple of libraries and react-js-pagination seems to do what I need. But for the life of me I can't figure it out.
What I have tried per the simplified example below:

Put <Pagination /> and my list in the same div.

Gave my list items a class of page-item per the API docs.

No luck. I added a parent of
 and/or put my items in
 tags. Even gave the parent
 a class of "pagination". Nothing. The only difference I am able to achieve is all items appearing in the same line like you see in the screenshot. Anything you figure out I am missing is appreciated.

import 'react-toastify/dist/ReactToastify.css';
import Pagination from "react-js-pagination";
import 'bootstrap/dist/css/bootstrap.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            activePage: 1
        }
    }

    handlePageChange(pageNumber) {
        this.setState({activePage: pageNumber});
    }

    render() {
        return (

1

2

3

4

5

6

7

8

9

10

11

                <Pagination
                    activePage={this.state.activePage}
                    itemsCountPerPage={2}
                    totalItemsCount={11}
                    pageRangeDisplayed={5}
                    onChange={this.handlePageChange.bind(this)}
                    itemClass="page-item"
                    linkClass="page-link"
                />

        );
    }
}

export default App;

Result so far:


答:
Your code is almost good, just make range count backwards:

```<code>for i in range(len(list1)-2,-1,-1):
    if (list1[i] == list1[i+1]) and (list1[i] == 'STRING'):
        list1.remove(list1[i])
</code>```

Why you got problem when removing items with your code when removed reversed is because the list got shorter while you were iterating over it and thus removed wrong items.

For example if your list was:

```<code>a = [1,2,3,4]
</code>```

when you remove something on i(which for example equals 2) then your list will be:

```<code>a = [1,2,4]
</code>```

now look what is on the i=2+1 position. Yes, it is out of range!

So, for the future, if you do a mass deletion in a list according to some condition, then do it always starting with the last item and going backwards.

Title: How to remove one of two consecutive duplicate strings in list?

Body:
I have a list that has duplicated 'STRING' elements and looks like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', 'STRING', '90', '84', '82', '85', '86', 'STRING', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', 'STRING', '86', '89', '88', '66', '70', 'STRING', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

One of every two consecuitive 'STRING' elements has to be in its place. I need to remove every second of the consecutive STRINGelements. And the list should look like this:

a = ['32', '55', '74', '58', 'STRING', 'STRING','56', '53', '51', '59', '49', '45', '45', '43', '62', '57', '53', '52', '49', '50', '47', '63', 'STRING', '90', '84', '82', '85', '86', 'STRING', '78', '88', '81', '88', '88', '73', '88', '81', '92', '129', '115', '105', '94', '91', '85', '79', '74', '69', '55', 'STRING', '86', '89', '88', '66', '70', 'STRING', '75', '73', '86', '75', '65', '57', '69', '59', '55']

This is what I tried:

    for i in reversed(range(len(a)-1)):
        if (list1[i] == list1[i-1]) & (list1[i] == 'STRING'):
            list1.remove(list1[i-1])

but it doesn't work. When it's not reversed I get the IndexError.

Body:
Your code is almost good, just make range count backwards:

for i in range(len(list1)-2,-1,-1):
    if (list1[i] == list1[i+1]) and (list1[i] == 'STRING'):
        list1.remove(list1[i])

Why you got problem when removing items with your code when removed reversed is because the list got shorter while you were iterating over it and thus removed wrong items.

For example if your list was:

a = [1,2,3,4]

when you remove something on i(which for example equals 2) then your list will be:

a = [1,2,4]

now look what is on the i=2+1 position. Yes, it is out of range!

So, for the future, if you do a mass deletion in a list according to some condition, then do it always starting with the last item and going backwards.


问:
How to make countdown start every eight hours?
I wonder how to make countdown start every 8 hours? for example
the puzzle starts at 10 pm next is 6 am, and next 2 pm.

I have javascript like this

```

and how to make that countDown date every 8 hours? like 10 pm, 6 am and 2 pm? Thank you.

答:
Try to evaluate the starting countdown time by current time, then set the start of countdown time to that time.

Something like:

```<code>var countDownDate = new Date("May 31, 2020 22:00:00");
var currentHour = countDownDate.getHours();
// 10 pm to 6 am
if(currentHour >= 22 && currentHour < 6) {
    // set countdown startTime to 10 pm
    countDownDate.setHours(22);
}
// 6 am to 2 pm
else if(currentHour >= 6 && currentHour < 14) {
    // set countdown startTime to 6 am
    countDownDate.setHours(6);
} else {
    // set countdown startTime to 2 pm
    countDownDate.setHours(14);
}

</code>```

Body:
I wonder how to make countdown start every 8 hours? for example
the puzzle starts at 10 pm next is 6 am, and next 2 pm.

I have javascript like this

and how to make that countDown date every 8 hours? like 10 pm, 6 am and 2 pm? Thank you.

Body:
Try to evaluate the starting countdown time by current time, then set the start of countdown time to that time.

Something like:

var countDownDate = new Date("May 31, 2020 22:00:00");
var currentHour = countDownDate.getHours();
// 10 pm to 6 am
if(currentHour >= 22 && currentHour < 6) {
    // set countdown startTime to 10 pm
    countDownDate.setHours(22);
}
// 6 am to 2 pm
else if(currentHour >= 6 && currentHour < 14) {
    // set countdown startTime to 6 am
    countDownDate.setHours(6);
} else {
    // set countdown startTime to 2 pm
    countDownDate.setHours(14);
}


问:
How can I update the record in sharepoint 2010 using linq
I am unable to update the record in SharePoint 2010 using new linq feature.
follwoing in my code please review it.</p>

```<code>  AbsentTrackingSystemEntitiesDataContext ctx = new AbsentTrackingSystemEntitiesDataContext(spWeb.Url);
                ctx.ObjectTrackingEnabled = true;
                HolidaysItem Holidayobj = GetHolidays(HolidayID, ctx); // get the specific record to be update.
                if (Holidayobj != null)
                {
                    Holidayobj.Title = "test";
                    Holidayobj.HolidayDate = DateTime.Today;
                    Holidayobj.Description = "test holiday";
                    ctx.Holidays.Attach(Holidayobj);
                    // or ctx.Holidays.Attach(Holidayobj, true); not working in 2010
                    ctx.SubmitChanges();
                  }
</code>```

答:
This is not required at all.
ctx.Holidays.Attach(Holidayobj);

ctx.SubmitChanges(); is all you need

ContentLicense: CC BY-SA 2.5

Body:
I am unable to update the record in SharePoint 2010 using new linq feature.
follwoing in my code please review it.

  AbsentTrackingSystemEntitiesDataContext ctx = new AbsentTrackingSystemEntitiesDataContext(spWeb.Url);
                ctx.ObjectTrackingEnabled = true;
                HolidaysItem Holidayobj = GetHolidays(HolidayID, ctx); // get the specific record to be update.
                if (Holidayobj != null)
                {
                    Holidayobj.Title = "test";
                    Holidayobj.HolidayDate = DateTime.Today;
                    Holidayobj.Description = "test holiday";
                    ctx.Holidays.Attach(Holidayobj);
                    // or ctx.Holidays.Attach(Holidayobj, true); not working in 2010
                    ctx.SubmitChanges();
                  }

ContentLicense: CC BY-SA 3.0


问:
angular ng-autocomplete doesn't work whit [(ngModel)] and name together
i'm using angular 8, installed ng-autocomplete, it works like this:

HTML:

```<code><div class="field">
       <label class="label">Nombre del condominio:</label>
        <div class="control">
          <div class="input is-small is-fullwidth">

            <ng-autocomplete

              [(ngModel)]="condos.conName"
              [data]="condominiums"
              [searchKeyword]="keyword"
              (selected)='selectEvent($event)'
              (inputChanged)='onChangeSearch($event)'
              (inputFocused)='onFocused($event)'
              (inputCleared)='onCleared()'
              [itemTemplate]="itemTemplate"
              [notFoundTemplate]="notFoundTemplate">
            </ng-autocomplete>

            <ng-template #itemTemplate let-item>
              <a [innerHTML]="item.conName"></a>
            </ng-template>

            <ng-template #notFoundTemplate let-notFound>
              <div [innerHTML]="notFound"></div>
            </ng-template>
          </div>
        </div>
      </div>
</code>```

But send me an error in ng-autocomplete:

ERROR Error: If ngModel is used within a form tag, either the name
  attribute must be set or the form
        control must be defined as 'standalone' in ngModelOptions.

```<code>  Example 1: <input [(ngModel)]="person.firstName" name="first">
  Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
</code>```

If i use the options like this (i tried with both ones):

```<code><ng-autocomplete
  name="ConName"
  [(ngModel)]="condos.conName"
  [data]="condominiums"
  [searchKeyword]="keyword"
  (selected)='selectEvent($event)'
  (inputChanged)='onChangeSearch($event)'
  (inputFocused)='onFocused($event)'
  (inputCleared)='onCleared()'
  [itemTemplate]="itemTemplate"
  [notFoundTemplate]="notFoundTemplate">
</ng-autocomplete>
</code>```

there's no error, but autocomplete doens't work anymore, it doesn't dropdown.

ANY IDEA??????

Thank you

答:
```<code> <ng-autocomplete
      [data]="locationList"
      [searchKeyword]="keyword"
      (selected)='selectEvent($event)'
      (inputChanged)='onChangeSearch($event)'
      (inputFocused)='onFocused($event)'
      [itemTemplate]="itemTemplate"
      [notFoundTemplate]="notFoundTemplate"
      [(ngModel)]= userLocation.name
      placeHolder="Search Location">
 </ng-autocomplete>
    <ng-template #itemTemplate let-item>
      <a [innerHTML]="item.name"></a>
    </ng-template>
    <ng-template #notFoundTemplate let-notFound>
      <div [innerHTML]="notFound"></div>
    </ng-template>
</code>```

[(ngModel)]= userLocation.name

-------------- In my .ts file----------------------------------

```<code>userLocation : any = {  id: 1, name : 'INDORE'}

LocationList = [{"id":1,"name":"INDORE"},{"id":2,"name":"UJJAIN"},{"id":3,"name":"AHMEDABAD"},{"id":4,"name":"UDAIPUR"}]`
</code>```

Its show auto fill value also with bind value using ngModel

Body:
i'm using angular 8, installed ng-autocomplete, it works like this:

HTML:

       Nombre del condominio:

            <ng-autocomplete

              [(ngModel)]="condos.conName"
              [data]="condominiums"
              [searchKeyword]="keyword"
              (selected)='selectEvent($event)'
              (inputChanged)='onChangeSearch($event)'
              (inputFocused)='onFocused($event)'
              (inputCleared)='onCleared()'
              [itemTemplate]="itemTemplate"
              [notFoundTemplate]="notFoundTemplate">
            </ng-autocomplete>

            <ng-template #itemTemplate let-item>

            </ng-template>

            <ng-template #notFoundTemplate let-notFound>

            </ng-template>

But send me an error in ng-autocomplete:

ERROR Error: If ngModel is used within a form tag, either the name
  attribute must be set or the form
        control must be defined as 'standalone' in ngModelOptions.

  Example 1: <input [(ngModel)]="person.firstName" name="first">
  Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

If i use the options like this (i tried with both ones):

<ng-autocomplete
  name="ConName"
  [(ngModel)]="condos.conName"
  [data]="condominiums"
  [searchKeyword]="keyword"
  (selected)='selectEvent($event)'
  (inputChanged)='onChangeSearch($event)'
  (inputFocused)='onFocused($event)'
  (inputCleared)='onCleared()'
  [itemTemplate]="itemTemplate"
  [notFoundTemplate]="notFoundTemplate">
</ng-autocomplete>

there's no error, but autocomplete doens't work anymore, it doesn't dropdown.

ANY IDEA??????

Thank you

Body:
 <ng-autocomplete
      [data]="locationList"
      [searchKeyword]="keyword"
      (selected)='selectEvent($event)'
      (inputChanged)='onChangeSearch($event)'
      (inputFocused)='onFocused($event)'
      [itemTemplate]="itemTemplate"
      [notFoundTemplate]="notFoundTemplate"
      [(ngModel)]= userLocation.name
      placeHolder="Search Location">
 </ng-autocomplete>
    <ng-template #itemTemplate let-item>
      <a [innerHTML]="item.name"></a>
    </ng-template>
    <ng-template #notFoundTemplate let-notFound>
      <div [innerHTML]="notFound"></div>
    </ng-template>

[(ngModel)]= userLocation.name

-------------- In my .ts file----------------------------------

userLocation : any = {  id: 1, name : 'INDORE'}

LocationList = [{"id":1,"name":"INDORE"},{"id":2,"name":"UJJAIN"},{"id":3,"name":"AHMEDABAD"},{"id":4,"name":"UDAIPUR"}]`

Its show auto fill value also with bind value using ngModel


问:
Uninitialize git repository
I have Initialized a git repository and have made some commit in that now for some reason I do not want to track any files in it and want to remove git from my local repo.
Is there some way I can Uninitialize it?</p>

答:
Go to "File Explorer Options" in the control panel, there go to "View" and check the option that allows you to see the hidden folders.

Then go to the folder where you want to un-initialize the git repository and you will find a folder called ".git" (it will be slightly faded since it's a hidden folder).

Deleting this folder will do the trick.

Title: Uninitialize git repository


问:
How do I make 2 lists correspond to each other?
I have 2 lists here:

```<code>list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
</code>```

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

```<code>if happy > sad:
    print ("you are happy")
</code>```

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

答:
An interesting way is to create a dict like this :

dico = {'happy':2, 'sad':5, 'grumpy':6, 'mad':9}
inv_dico = {v:k for k,v in dico.items()}

mood = inv_dico[max(dico['happy'], dico['sad'])]

print("you are : ", mood)
# you are : sad
```

note : you could use min instead of max to have the inverse effect

Body:
I have 2 lists here:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

if happy > sad:
    print ("you are happy")

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

Body:
An interesting way is to create a dict like this :

dico = {'happy':2, 'sad':5, 'grumpy':6, 'mad':9}
inv_dico = {v:k for k,v in dico.items()}

mood = inv_dico[max(dico['happy'], dico['sad'])]

print("you are : ", mood)
# you are : sad

note : you could use min instead of max to have the inverse effect


问:
Field ordonnanceService in ...OrdonnanceController required a bean of type 'OrdonnanceService' that could not be found
I am new to Spring Boot and I'm getting the following error when writing a file upload API:

```<code>    > 2020-05-31 12:07:30.713  INFO 22808 --- [           main]
    > o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with
    > port(s): 8080 (http) 2020-05-31 12:07:30.725  INFO 22808 --- [
    > main] o.apache.catalina.core.StandardService   : Starting service
    > [Tomcat] 2020-05-31 12:07:30.725  INFO 22808 --- [           main]
    > org.apache.catalina.core.StandardEngine  : Starting Servlet engine:
    > [Apache Tomcat/9.0.27] 2020-05-31 12:07:30.908  INFO 22808 --- [
    > main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring
    > embedded WebApplicationContext 2020-05-31 12:07:30.908  INFO 22808 ---
    > [           main] o.s.web.context.ContextLoader            : Root
    > WebApplicationContext: initialization completed in 3202 ms 2020-05-31
    > 12:07:30.978  WARN 22808 --- [           main]
    > ConfigServletWebServerApplicationContext : Exception encountered
    > during context initialization - cancelling refresh attempt:
    > org.springframework.beans.factory.UnsatisfiedDependencyException:
    > Error creating bean with name 'ordonnanceController': Unsatisfied
    > dependency expressed through field 'ordonnanceService'; nested
    > exception is
    > org.springframework.beans.factory.NoSuchBeanDefinitionException: No
    > qualifying bean of type 'pfa.ordodistance.services.OrdonnanceService'
    > available: expected at least 1 bean which qualifies as autowire
    > candidate. Dependency annotations:
    > {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    > 2020-05-31 12:07:30.982  INFO 22808 --- [           main]
    > o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
    > 2020-05-31 12:07:31.013  INFO 22808 --- [           main]
    > ConditionEvaluationReportLoggingListener :
    >
    > Error starting ApplicationContext. To display the conditions report
    > re-run your application with 'debug' enabled. 2020-05-31 12:07:31.153
    > ERROR 22808 --- [           main]
    > o.s.b.d.LoggingFailureAnalysisReporter   :
    >
    > *************************** APPLICATION FAILED TO START
    > ***************************
    >
    > Description:
    >
    > Field ordonnanceService in
    > pfa.ordodistance.controllers.OrdonnanceController required a bean of
    > type 'pfa.ordodistance.services.OrdonnanceService' that could not be
    > found.
    >
    > The injection point has the following annotations:
    >   - @org.springframework.beans.factory.annotation.Autowired(required=true)
    >
    >
    > Action:
    >
    > Consider defining a bean of type
    > 'pfa.ordodistance.services.OrdonnanceService' in your configuration.
</code>```

This is my class Service:

@Service
public class OrdonnanceService {

    @Autowired(required = true)
    private OrdonnanceRepository ordonnanceRepository;

    //Save new ordonnance
    public void save(Ordonnance ord) {
        ordonnanceRepository.save(ord);
    }
}
```

<p>Controller : </p>

<pre class="lang-java prettyprint-override"><code>@Controller
@ComponentScan("pfa.ordodistance.controllers")
public class OrdonnanceController {

    @Autowired(required = true)
    private OrdonnanceService ordonnanceService;

    @PostMapping("prescriptionPage")
    public String addNew(Ordonnance ord) {
        ordonnanceService.save(ord);
        return "redirect:/prescriptionPage";
    }
}
</code>```

Repository:

@Repository
public interface OrdonnanceRepository extends JpaRepository<Ordonnance, Integer> {
}
```

<p>Model :</p>

<pre class="lang-java prettyprint-override"><code>@Entity
public class Ordonnance {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    private Date dateO;

    @ManyToOne
    @JoinColumn(name="medecinid", insertable=false, updatable=false)
    private Medecin medecin;
    private Integer medecinid;

    @ManyToOne
    @JoinColumn(name="patientid", insertable=false, updatable=false)
    private Patient patient;
    private Integer patientid;

    public Ordonnance() {
    }

    public Ordonnance(int id, Date dateO, Medecin medecin, Integer medecinid, Patient patient, Integer patientid) {
        this.id = id;
        this.dateO = dateO;
        this.medecin = medecin;
        this.medecinid = medecinid;
        this.patient = patient;
        this.patientid = patientid;
    }
     //getters & setters
}
</code>```

答:
Most probably the OrdonnanceService cannot be registered as a spring bean and hence no OrdonnanceService can be auto-wired into OrdonnanceController and hence resulting this error.

One thing to check is to make sure  @ComponentScan covers all the required classes that should be registered as spring beans.

In your case , as you set the @ComponentScan as :

@ComponentScan("pfa.ordodistance.controllers")
```

<p>It will only scan and register spring beans coming for this and its sub-packages. So if <code>OrdonnanceService</code> is in the package of <code>pfa.ordodistance.service</code> , it will not be scanned.</p>

<p>One simply try is to change it to : </p>

<pre class="lang-java prettyprint-override"><code>@ComponentScan("pfa.ordodistance")
</code>```

On the other hands , if you follow the best practise as suggested in the docs which put the main application class (i.e class that annotated with @SpringBootApplication) to the root package above all packages  , you do not need to manually configure @ComponentScan as it will scan for every classes under this root package. See the example layout in the above link for I mean.

Body:
I am new to Spring Boot and I'm getting the following error when writing a file upload API:

    > 2020-05-31 12:07:30.713  INFO 22808 --- [           main]
    > o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with
    > port(s): 8080 (http) 2020-05-31 12:07:30.725  INFO 22808 --- [
    > main] o.apache.catalina.core.StandardService   : Starting service
    > [Tomcat] 2020-05-31 12:07:30.725  INFO 22808 --- [           main]
    > org.apache.catalina.core.StandardEngine  : Starting Servlet engine:
    > [Apache Tomcat/9.0.27] 2020-05-31 12:07:30.908  INFO 22808 --- [
    > main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring
    > embedded WebApplicationContext 2020-05-31 12:07:30.908  INFO 22808 ---
    > [           main] o.s.web.context.ContextLoader            : Root
    > WebApplicationContext: initialization completed in 3202 ms 2020-05-31
    > 12:07:30.978  WARN 22808 --- [           main]
    > ConfigServletWebServerApplicationContext : Exception encountered
    > during context initialization - cancelling refresh attempt:
    > org.springframework.beans.factory.UnsatisfiedDependencyException:
    > Error creating bean with name 'ordonnanceController': Unsatisfied
    > dependency expressed through field 'ordonnanceService'; nested
    > exception is
    > org.springframework.beans.factory.NoSuchBeanDefinitionException: No
    > qualifying bean of type 'pfa.ordodistance.services.OrdonnanceService'
    > available: expected at least 1 bean which qualifies as autowire
    > candidate. Dependency annotations:
    > {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    > 2020-05-31 12:07:30.982  INFO 22808 --- [           main]
    > o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
    > 2020-05-31 12:07:31.013  INFO 22808 --- [           main]
    > ConditionEvaluationReportLoggingListener :
    >
    > Error starting ApplicationContext. To display the conditions report
    > re-run your application with 'debug' enabled. 2020-05-31 12:07:31.153
    > ERROR 22808 --- [           main]
    > o.s.b.d.LoggingFailureAnalysisReporter   :
    >
    > *************************** APPLICATION FAILED TO START
    > ***************************
    >
    > Description:
    >
    > Field ordonnanceService in
    > pfa.ordodistance.controllers.OrdonnanceController required a bean of
    > type 'pfa.ordodistance.services.OrdonnanceService' that could not be
    > found.
    >
    > The injection point has the following annotations:
    >   - @org.springframework.beans.factory.annotation.Autowired(required=true)
    >
    >
    > Action:
    >
    > Consider defining a bean of type
    > 'pfa.ordodistance.services.OrdonnanceService' in your configuration.

This is my class Service:

@Service
public class OrdonnanceService {

    @Autowired(required = true)
    private OrdonnanceRepository ordonnanceRepository;

    //Save new ordonnance
    public void save(Ordonnance ord) {
        ordonnanceRepository.save(ord);
    }
}

Controller :

@Controller
@ComponentScan("pfa.ordodistance.controllers")
public class OrdonnanceController {

    @Autowired(required = true)
    private OrdonnanceService ordonnanceService;

    @PostMapping("prescriptionPage")
    public String addNew(Ordonnance ord) {
        ordonnanceService.save(ord);
        return "redirect:/prescriptionPage";
    }
}

Repository:

@Repository
public interface OrdonnanceRepository extends JpaRepository<Ordonnance, Integer> {
}

Model :

@Entity
public class Ordonnance {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    private Date dateO;

    @ManyToOne
    @JoinColumn(name="medecinid", insertable=false, updatable=false)
    private Medecin medecin;
    private Integer medecinid;

    @ManyToOne
    @JoinColumn(name="patientid", insertable=false, updatable=false)
    private Patient patient;
    private Integer patientid;

    public Ordonnance() {
    }

    public Ordonnance(int id, Date dateO, Medecin medecin, Integer medecinid, Patient patient, Integer patientid) {
        this.id = id;
        this.dateO = dateO;
        this.medecin = medecin;
        this.medecinid = medecinid;
        this.patient = patient;
        this.patientid = patientid;
    }
     //getters & setters
}

Body:
Most probably the OrdonnanceService cannot be registered as a spring bean and hence no OrdonnanceService can be auto-wired into OrdonnanceController and hence resulting this error.

One thing to check is to make sure  @ComponentScan covers all the required classes that should be registered as spring beans.

In your case , as you set the @ComponentScan as :

@ComponentScan("pfa.ordodistance.controllers")

It will only scan and register spring beans coming for this and its sub-packages. So if OrdonnanceService is in the package of pfa.ordodistance.service , it will not be scanned.

One simply try is to change it to :

@ComponentScan("pfa.ordodistance")

On the other hands , if you follow the best practise as suggested in the docs which put the main application class (i.e class that annotated with @SpringBootApplication) to the root package above all packages  , you do not need to manually configure @ComponentScan as it will scan for every classes under this root package. See the example layout in the above link for I mean.


问:
Trying to connect to SQL Server in Docker from external Python
I created the following Docker image following https://www.youtube.com/watch?v=BVNWRYPv78o:

```<code>docker pull microsoft/mssql-server-linux
docker run -d --name sql_server_name -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=YourPassword123' -p 1433:1433 microsoft/mssql-server-linux
</code>```

Now I want to try to access the server from a local Python script.
Following https://stackoverflow.com/a/58088919/6131111
I do:

```<code>brew install unixodbc
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
brew install msodbcsql17 mssql-tools
</code>```

My /usr/local/etc/odbcinst.ini file looks like this:

```<code>[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/usr/local/lib/libmsodbcsql.17.dylib
UsageCount=1
</code>```

To know my server I do:

```<code>$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' sql_server_name
172.17.0.2
</code>```

In the python script I create the connection string as:

```<code>connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=172.17.0.2;DATABASE=WideWorldImportersDW;UID=sa;PWD=YourPassword123'
</code>```

I have previously imported WideWorldImportersDW to my databases as can be seen here:

But I am getting:

```<code>pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
</code>```

答:
I solved it using my local IP address as server:</p>

```<code>connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=192.168.1.47,1433;DATABASE=WideWorldImportersDW;UID=sa;PWD=YourPassword123'
</code>```

Body:
I created the following Docker image following https://www.youtube.com/watch?v=BVNWRYPv78o:

docker pull microsoft/mssql-server-linux
docker run -d --name sql_server_name -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=YourPassword123' -p 1433:1433 microsoft/mssql-server-linux

Now I want to try to access the server from a local Python script.
Following https://stackoverflow.com/a/58088919/6131111
I do:

brew install unixodbc
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
brew install msodbcsql17 mssql-tools

My /usr/local/etc/odbcinst.ini file looks like this:

[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/usr/local/lib/libmsodbcsql.17.dylib
UsageCount=1

To know my server I do:

$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' sql_server_name
172.17.0.2

In the python script I create the connection string as:

connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=172.17.0.2;DATABASE=WideWorldImportersDW;UID=sa;PWD=YourPassword123'

I have previously imported WideWorldImportersDW to my databases as can be seen here:

But I am getting:

pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

Body:
I solved it using my local IP address as server:

connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=192.168.1.47,1433;DATABASE=WideWorldImportersDW;UID=sa;PWD=YourPassword123'


问:
My python code does not run the next line
Hi I'm trying to make some quiz programs but my code is stuck in input()

```<code>print("나라 퀴즈에 오신 여러분들을 환영합니다!\n이 퀴즈에서 여러분들은 국기를 보고 나라 이름을 맞추시면 됩니다!")
print("------------------------------------------------------------------------------------------------------------------------------")
print("\n1. 아메리카\n2. 아프리카\n3. 유럽\n4. 아시아\n5. 오세아니아\n6. 모든 나라\n")
continent=input("어느 대륙의 퀴즈를 맞출 건지 선택해주세요: ")

if(continent==1):
    quizamerica()
</code>```

my code does not run after line if(continent==1) and just stops the program after line continent=input("어느 대륙의 퀴즈를 맞출 건지 선택해주세요: ")

Help me please.

答: The input() function returns a string. Try if(continent == '1').

Body:
Hi I'm trying to make some quiz programs but my code is stuck in input()

print("나라 퀴즈에 오신 여러분들을 환영합니다!\n이 퀴즈에서 여러분들은 국기를 보고 나라 이름을 맞추시면 됩니다!")
print("------------------------------------------------------------------------------------------------------------------------------")
print("\n1. 아메리카\n2. 아프리카\n3. 유럽\n4. 아시아\n5. 오세아니아\n6. 모든 나라\n")
continent=input("어느 대륙의 퀴즈를 맞출 건지 선택해주세요: ")

if(continent==1):
    quizamerica()

my code does not run after line if(continent==1) and just stops the program after line continent=input("어느 대륙의 퀴즈를 맞출 건지 선택해주세요: ")

Help me please.


问:
Trying to load certain form if user is authenticated and preload all the information in the database with the user credentials
Trying to load certain form if a user is authenticated and preload all the information in the database but I get this error, most probably something is wrong in forms.py but the idea is that if the user is authenticated they should not go through the process of entering their name and email, they would just have to send the message. It currently works like a charm for non registered users but I never did something like this before for the registered users so I am stuck.

forms.py

```<code>from django import forms
from django.forms import ModelForm
from .models import Message

class NonAuthMessage(forms.ModelForm):

    class Meta:
        model = Message
        fields = "__all__"

class AuthMessage(forms.ModelForm):

    def __init__(self):
        self.name = user.request.username
        self.email = user.request.email

    class Meta:
        model = Message
        fields = ["message"]
</code>```

models.py

```<code>from django.db import models
from django.utils import timezone

class Message(models.Model):

    name = models.CharField(max_length=50)
    email = models.EmailField()
    message = models.TextField(max_length=3000)
    date_posted = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

    class Meta:
        ordering = ['-date_posted',]
</code>```

views.py

```<code>from django.shortcuts import render, redirect
from .models import Message
from .forms import NonAuthMessage, AuthMessage

def contact(request):

    formAuth = AuthMessage()
    formNonAuth = NonAuthMessage()
    mess = Message.objects.all()

    if request.user.is_authenticated:
        if request.method == "POST":
            form = AuthMessage(request.POST)
            if form.is_valid():
                form.save()
                return redirect('contact')
                messages.success(request, 'Message sent to Alex!')
    else:
        if request.method =="POST":
            form = NonAuthMessage(request.POST)
            if form.is_valid():
                form.save()
                return redirect('contact')
                messages.success(request, 'Message sent to Alex!')

    context = {'formAuth': formAuth, 'formNonAuth': formNonAuth, 'mess': mess}

    return render(request, 'contact/contact.html', context)
</code>```

contact.html

```<code>{% extends 'personal/base.html' %}
{% load crispy_forms_tags %}
{% block content %}

{% if user.is_authenticated %}
<form method="POST">
        {% csrf_token %}
            <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Contact Alex</legend>
                    {{formAuth | crispy}} <br>
                    <div class="form-group">
                        <button class="btn btn-outline-info" type="submit">Send</button>
                    </div>
            </fieldset>
</form>
{% else %}
<form method="POST">
        {% csrf_token %}
            <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Contact Alex</legend>
                    {{formNonAuth | crispy}} <br>
                    <div class="form-group">
                        <button class="btn btn-outline-info" type="submit">Send</button>
                    </div>
            </fieldset>
</form>
{% endif %}

           <!-- TESTING -->
           {% for message in mess %}
              <div class="col-md-4">
                <h3 >{{message.email}}</h3>
                    {{message.date_posted}}<hr>
                    <p>
                    {{message.message|truncatewords:"25"}}
                    </p>
              </div>
              {% endfor %}

{% endblock content %}
</code>```

And the error message that I get is:

NameError at /contact/;
name 'user' is not defined

Traceback:

views.py:

formAuth = AuthMessage()

forms.py:

```<code>self.name = user.request.username
</code>```

答:
Try to put needed user info directly in view instead of in form:</p>

```<code>if request.user.is_authenticated:
    if request.method == "POST":
        form = AuthMessage(request.POST)
        if form.is_valid():
            authmess = form.save(commit=False)
            authmess.name = request.user.first_name
            authmess.email = request.user.email
            authmess.save()
            messages.success(request, 'Message sent to Alex!')
            return redirect('contact')

</code>```

Body:
Trying to load certain form if a user is authenticated and preload all the information in the database but I get this error, most probably something is wrong in forms.py but the idea is that if the user is authenticated they should not go through the process of entering their name and email, they would just have to send the message. It currently works like a charm for non registered users but I never did something like this before for the registered users so I am stuck.

forms.py

from django import forms
from django.forms import ModelForm
from .models import Message

class NonAuthMessage(forms.ModelForm):

    class Meta:
        model = Message
        fields = "__all__"

class AuthMessage(forms.ModelForm):

    def __init__(self):
        self.name = user.request.username
        self.email = user.request.email

    class Meta:
        model = Message
        fields = ["message"]

models.py

from django.db import models
from django.utils import timezone

class Message(models.Model):

    name = models.CharField(max_length=50)
    email = models.EmailField()
    message = models.TextField(max_length=3000)
    date_posted = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

    class Meta:
        ordering = ['-date_posted',]

views.py

from django.shortcuts import render, redirect
from .models import Message
from .forms import NonAuthMessage, AuthMessage

def contact(request):

    formAuth = AuthMessage()
    formNonAuth = NonAuthMessage()
    mess = Message.objects.all()

    if request.user.is_authenticated:
        if request.method == "POST":
            form = AuthMessage(request.POST)
            if form.is_valid():
                form.save()
                return redirect('contact')
                messages.success(request, 'Message sent to Alex!')
    else:
        if request.method =="POST":
            form = NonAuthMessage(request.POST)
            if form.is_valid():
                form.save()
                return redirect('contact')
                messages.success(request, 'Message sent to Alex!')

    context = {'formAuth': formAuth, 'formNonAuth': formNonAuth, 'mess': mess}

    return render(request, 'contact/contact.html', context)

contact.html

{% extends 'personal/base.html' %}
{% load crispy_forms_tags %}
{% block content %}

{% if user.is_authenticated %}
<form method="POST">
        {% csrf_token %}
            <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Contact Alex</legend>
                    {{formAuth | crispy}}

                        <button class="btn btn-outline-info" type="submit">Send</button>

            </fieldset>
</form>
{% else %}
<form method="POST">
        {% csrf_token %}
            <fieldset class="form-group">
                    <legend class="border-bottom mb-4">Contact Alex</legend>
                    {{formNonAuth | crispy}}

                        <button class="btn btn-outline-info" type="submit">Send</button>

            </fieldset>
</form>
{% endif %}

           {% for message in mess %}

{{message.email}}

                    {{message.date_posted}}

                    {{message.message|truncatewords:"25"}}

              {% endfor %}

{% endblock content %}

And the error message that I get is:

NameError at /contact/;
name 'user' is not defined

Traceback:

views.py:

formAuth = AuthMessage()

forms.py:

self.name = user.request.username

Body:
Try to put needed user info directly in view instead of in form:

if request.user.is_authenticated:
    if request.method == "POST":
        form = AuthMessage(request.POST)
        if form.is_valid():
            authmess = form.save(commit=False)
            authmess.name = request.user.first_name
            authmess.email = request.user.email
            authmess.save()
            messages.success(request, 'Message sent to Alex!')
            return redirect('contact')


问:
T extends ChangeEvent<any> ? void : (e: string | ChangeEvent<any>)
I am using a custom formik component like this in my screens:

```<code> <Formik
                initialValues={initialValues}
                onSubmit={handleSubmitForm}
                validationSchema={validationSchema}>
                {({ handleChange, handleBlur, handleSubmit, values }) => (
                  <View style={styles.searchFieldContainer}>
                    <View style={styles.form}>
                      <FieldInput
                        handleChange={handleChange}
                        handleBlur={handleBlur}
                        value={values.phoneNumber}
                        fieldType="phoneNumber"
                        icon='phone'
                        placeholderText='49152901820'
                      />
                      <ErrorMessage
                        name="phoneNumber"
                        render={(msg) => (
                          <Text style={styles.errorText}>{msg}</Text>
                        )}
                      />
                    </View>
                    <View style={styles.buttonContainer}>
                      <Button
                        onPress={handleSubmit}>
                        Search
                      </Button>
                    </View>
                  </View>
                )}
              </Formik>
</code>```

I get a TypeScript error on handleChange and handleBlur that:

```<code>Type '{ (e: ChangeEvent<any>): void; <T = string | ChangeEvent<any>>(field: T): T extends ChangeEvent<any> ? void : (e: string | ChangeEvent<any>) => void; }' is not assignable to type '(e: string) => undefined'.
  Types of parameters 'e' and 'e' are incompatible.
    Type 'string' is not assignable to type 'ChangeEvent<any>'

FieldInput.tsx(9, 3): The expected type comes from property 'handleChange' which is declared here on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'
</code>```

The field inputs are supposed to be strings and I don't think I should change ChangeEvent's type to string. 'any' is also not a good option. How can I fix this?

答:
I believe error caused by this line

```<code>onChangeText={handleChange(fieldType)}
</code>```

because handleChange(fieldType) is a string, converting it to function like

```<code>onChangeText={(e: any) => handleChange(fieldType)}
</code>```

might fix the error

Body:
I am using a custom formik component like this in my screens:

 <Formik
                initialValues={initialValues}
                onSubmit={handleSubmitForm}
                validationSchema={validationSchema}>
                {({ handleChange, handleBlur, handleSubmit, values }) => (
                  <View style={styles.searchFieldContainer}>
                    <View style={styles.form}>
                      <FieldInput
                        handleChange={handleChange}
                        handleBlur={handleBlur}
                        value={values.phoneNumber}
                        fieldType="phoneNumber"
                        icon='phone'
                        placeholderText='49152901820'
                      />
                      <ErrorMessage
                        name="phoneNumber"
                        render={(msg) => (
                          <Text style={styles.errorText}>{msg}</Text>
                        )}
                      />
                    </View>
                    <View style={styles.buttonContainer}>
                      <Button
                        onPress={handleSubmit}>
                        Search
                      </Button>
                    </View>
                  </View>
                )}
              </Formik>

I get a TypeScript error on handleChange and handleBlur that:

Type '{ (e: ChangeEvent<any>): void; <T = string | ChangeEvent<any>>(field: T): T extends ChangeEvent<any> ? void : (e: string | ChangeEvent<any>) => void; }' is not assignable to type '(e: string) => undefined'.
  Types of parameters 'e' and 'e' are incompatible.
    Type 'string' is not assignable to type 'ChangeEvent<any>'

FieldInput.tsx(9, 3): The expected type comes from property 'handleChange' which is declared here on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'

The field inputs are supposed to be strings and I don't think I should change ChangeEvent's type to string. 'any' is also not a good option. How can I fix this?

Body:
I believe error caused by this line

onChangeText={handleChange(fieldType)}

because handleChange(fieldType) is a string, converting it to function like

onChangeText={(e: any) => handleChange(fieldType)}

might fix the error


问:
How to highlight SQL keywords using a regular expression?
I would like to highlight SQL keywords that occur within a string in a syntax highlighter. Here are the rules I would like to have:

Match the keywords SELECT and FROM (others will be added, but we'll start here). Must be all-caps

Must be contained in a string -- either starting with ' or "

The first word in that string (ignoring whitespace preceding it) should be one of the keywords.

This of course is not comprehensive (can ignore escapes within a string), but I'd like to start here.

Here are a few examples:

SELECT * FROM main -- will not match (not in a string)

"SELECT name FROM main" -- will match

"

      SELECT name FROM main" -- will match

"""Here is a SQL statement:

SELECT * FROM main""" -- no, string does not start with a keyword (SELECT...).

The only way I thought to do it in a single regex would be with a negative lookbehind...but then it would not be fixed width, as we don't know when the string starts. Something like:

(?<=["']\s*(SELECT)\s*)(SELECT|FROM)

But this of course won't work:

Would something like this be possible to do in a single regex?

答:
A suitable regular expression is likely to get pretty complex, especially as the rules evolve further. As others have noted, it may be worth considering using a parser instead. That said, here is one possible regex attempting to cover the rules mentioned so far:

(["'])\s*(SELECT)(?:\s+.*)?\s+(FROM)(?:\s+.*)?\1(?:[^\w]|$)

Online Demos

Debuggex Demo

Regex101 Demo

Explanation

As can be seen in the above visualisation, the regex looks for either a double or single quote at the start (saved in capturing group #1) and then matches this reference at the end via \1. The SELECT and FROM keywords are captured in capturing groups #2 and #3. (The (?:x|y) syntax ensures there aren't more groups for other choices as ?: at the start of a choice excludes it as a capturing group.) There are some further optional details such as limiting what is allowed between the SELECT and FROM and not counting the final quotation mark if it is immediately succeeded by a word character.

Results

SELECT * FROM tbl        -- no match - not in a string
"SELECT * FROM tbl"      -- matches - in a double-quoted string
'SELECT * FROM tbl;'     -- matches - in a single-quoted string
'SELECT * FROM it's      -- no match - letter after end quote
"SELECT * FROM tbl'      -- no match - quotation marks don't match
'SELECT * FROM tbl"      -- no match - quotation marks don't match
"select * from tbl"      -- no match - keywords not upper case
'Select * From tbl'      -- no match - still not all upper case
"SELECT col1 FROM"       -- matches - even though no table name
'  SELECT  col1  FROM '  -- matches - as above with more whitespace
'SELECT col1, col2 FROM' -- matches - with multiple columns
```

Possible Improvement?

It might also be necessary to exclude quotation marks from the "any character" parts. This can be done at the expense of increased complexity using the technique described here by replacing both instances of .* with (?:(?!\1).)*:

(["'])\s*(SELECT)(?:\s+(?:(?!\1).)*)?\s+(FROM)(?:\s+(?:(?!\1).)*)?\1(?:[^\w]|$)

See this Regex101 Demo.

Body:
A suitable regular expression is likely to get pretty complex, especially as the rules evolve further. As others have noted, it may be worth considering using a parser instead. That said, here is one possible regex attempting to cover the rules mentioned so far:

(["'])\s*(SELECT)(?:\s+.*)?\s+(FROM)(?:\s+.*)?\1(?:[^\w]|$)

Online Demos

Debuggex Demo

Regex101 Demo

Explanation

As can be seen in the above visualisation, the regex looks for either a double or single quote at the start (saved in capturing group #1) and then matches this reference at the end via \1. The SELECT and FROM keywords are captured in capturing groups #2 and #3. (The (?:x|y) syntax ensures there aren't more groups for other choices as ?: at the start of a choice excludes it as a capturing group.) There are some further optional details such as limiting what is allowed between the SELECT and FROM and not counting the final quotation mark if it is immediately succeeded by a word character.

Results

SELECT * FROM tbl        -- no match - not in a string
"SELECT * FROM tbl"      -- matches - in a double-quoted string
'SELECT * FROM tbl;'     -- matches - in a single-quoted string
'SELECT * FROM it's      -- no match - letter after end quote
"SELECT * FROM tbl'      -- no match - quotation marks don't match
'SELECT * FROM tbl"      -- no match - quotation marks don't match
"select * from tbl"      -- no match - keywords not upper case
'Select * From tbl'      -- no match - still not all upper case
"SELECT col1 FROM"       -- matches - even though no table name
'  SELECT  col1  FROM '  -- matches - as above with more whitespace
'SELECT col1, col2 FROM' -- matches - with multiple columns

Possible Improvement?

It might also be necessary to exclude quotation marks from the "any character" parts. This can be done at the expense of increased complexity using the technique described here by replacing both instances of .* with (?:(?!\1).)*:

(["'])\s*(SELECT)(?:\s+(?:(?!\1).)*)?\s+(FROM)(?:\s+(?:(?!\1).)*)?\1(?:[^\w]|$)

See this Regex101 Demo.


问:
Conditional update of vector
I want to update a vector depending on its value:

If f < 50, then x = f - 1

If f > 50, then  y = f + 1

If f == 50, then set the value to zero

```<code>f <- seq(0, 100, by = 5)
</code>```

I was trying to solve it with if, but the result wasn't good.

```<code>if (f<50)
{
  f = z
  x= z-1
  x
}
</code>```

```<code>if (f>50)
{
  f = c
  y= c+1
  y
}
</code>```

Title: Conditional update of vector

Body:
I want to update a vector depending on its value:

If f < 50, then x = f - 1

If f > 50, then  y = f + 1

If f == 50, then set the value to zero

f <- seq(0, 100, by = 5)

I was trying to solve it with if, but the result wasn't good.

if (f<50)
{
  f = z
  x= z-1
  x
}

if (f>50)
{
  f = c
  y= c+1
  y
}

Body:
You can try the code below

f-(f<50)-50*(f==50)+(f>50)

such that

> f-(f<50)+(f>50)
 [1]  -1   4   9  14  19  24  29  34  39  44  0  56  61  66  71  76  81  86  91
[20]  96 101


答:
You can zip the lists together and create a dict from them:

```<code>list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]

moods = dict(zip(list1, list2))
# This will create a dictionary like this
# {'happy': 2, 'sad': 5, 'grumpy': 6, 'mad': 9}

if moods["happy"] > moods["sad"]:
    print("You are happy")
else:
    print("You are sad")
</code>```

The output is:

```<code>You are sad
</code>```

Edit:

Another option would be directly choosing a mood if you don't care what the other values are (inspired by Laurent B. 's answer):

```<code>list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]

mood = list1[list2.index(max(list2))]
print("You are", mood)
</code>```

Output:

```<code>You are mad
</code>```

Title: How do I make 2 lists correspond to each other?

Body:
You can zip the lists together and create a dict from them:

list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]

moods = dict(zip(list1, list2))
# This will create a dictionary like this
# {'happy': 2, 'sad': 5, 'grumpy': 6, 'mad': 9}

if moods["happy"] > moods["sad"]:
    print("You are happy")
else:
    print("You are sad")

The output is:

You are sad

Edit:

Another option would be directly choosing a mood if you don't care what the other values are (inspired by Laurent B. 's answer):

list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]

mood = list1[list2.index(max(list2))]
print("You are", mood)

Output:

You are mad


问:
After installing a CDK of angular getting an error during compilation

ERROR in
  node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:29:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

29     get enabled(): boolean;
             ~~~~~~~ node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:30:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

30     set enabled(value: boolean);
             ~~~~~~~ node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:128:9 -
  error TS1086: An accessor cannot be declared in an ambient context.

128     get enabled(): boolean;
              ~~~~~~~ node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:129:9 -
  error TS1086: An accessor cannot be declared in an ambient context.

129     set enabled(value: boolean);
              ~~~~~~~ node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:134:9 -
  error TS1086: An accessor cannot be declared in an ambient context.

134     get autoCapture(): boolean;
              ~~~~~~~~~~~ node_modules/@angular/cdk/a11y/focus-trap/focus-trap.d.ts:135:9 -
  error TS1086: An accessor cannot be declared in an ambient context.

135     set autoCapture(value: boolean);
              ~~~~~~~~~~~ node_modules/@angular/cdk/a11y/key-manager/list-key-manager.d.ts:96:9
  - error TS1086: An accessor cannot be declared in an ambient context.

96     get activeItemIndex(): number | null;
             ~~~~~~~~~~~~~~~ node_modules/@angular/cdk/a11y/key-manager/list-key-manager.d.ts:98:9
  - error TS1086: An accessor cannot be declared in an ambient context.

98     get activeItem(): T | null;
             ~~~~~~~~~~ node_modules/@angular/cdk/a11y/live-announcer/live-announcer.d.ts:69:9
  - error TS1086: An accessor cannot be declared in an ambient context.

69     get politeness(): AriaLivePoliteness;
             ~~~~~~~~~~ node_modules/@angular/cdk/a11y/live-announcer/live-announcer.d.ts:70:9
  - error TS1086: An accessor cannot be declared in an ambient context.

70     set politeness(value: AriaLivePoliteness);
             ~~~~~~~~~~ node_modules/@angular/cdk/bidi/dir.d.ts:26:9 - error TS1086: An accessor cannot be declared in an ambient context.

26     get dir(): Direction;
             ~~~ node_modules/@angular/cdk/bidi/dir.d.ts:27:9 - error TS1086: An accessor cannot be declared in an ambient context.

27     set dir(value: Direction);
             ~~~ node_modules/@angular/cdk/bidi/dir.d.ts:29:9 - error TS1086: An accessor cannot be declared in an ambient context.

29     get value(): Direction;
             ~~~~~ node_modules/@angular/cdk/collections/selection-model.d.ts:24:9 -
  error TS1086: An accessor cannot be declared in an ambient context.

24     get selected(): T[];
             ~~~~~~~~ node_modules/@angular/cdk/observers/observe-content.d.ts:62:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

62     get disabled(): any;
             ~~~~~~~~ node_modules/@angular/cdk/observers/observe-content.d.ts:63:9 -
  39m91merror TS1086: An accessor cannot be declared in an ambient
  context.

63     set disabled(value: any);
             ~~~~~~~~ node_modules/@angular/cdk/observers/observe-content.d.ts:66:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

66     get debounce(): number;
             ~~~~~~~~ node_modules/@angular/cdk/observers/observe-content.d.ts:67:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

67     set debounce(value: number);
             ~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:60:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

60     get offsetX(): number;
             ~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:61:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

61     set offsetX(offsetX: number);
             ~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:63:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

63     get offsetY(): number;
             ~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:64:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

64     set offsetY(offsetY: number);
             ~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:86:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

86     get hasBackdrop(): any;
             ~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:87:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

87     set hasBackdrop(value: any);
             ~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:89:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

89     get lockPosition(): any;
             ~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:90:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

90     set lockPosition(value: any);
             ~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:92:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

92     get flexibleDimensions(): boolean;
             ~~~~~~~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:93:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

93     set flexibleDimensions(value: boolean);
             ~~~~~~~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:95:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

95     get growAfterOpen(): boolean;
             ~~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:96:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

96     set growAfterOpen(value: boolean);
             ~~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:98:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

98     get push(): boolean;
             ~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:99:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

99     set push(value: boolean);
             ~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:112:9 -
  error TS1086: An accessor cannot be declared in an ambient context.

112     get overlayRef(): OverlayRef;
              ~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-directives.d.ts:114:9 -
  error TS1086: An accessor cannot be declared in an ambient context.

114     get dir(): Direction;
              ~~~ node_modules/@angular/cdk/overlay/overlay-ref.d.ts:55:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

55     get overlayElement(): HTMLElement;
             ~~~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-ref.d.ts:57:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

57     get backdropElement(): HTMLElement | null;
             ~~~~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/overlay-ref.d.ts:63:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

63     get hostElement(): HTMLElement;
             ~~~~~~~~~~~ node_modules/@angular/cdk/overlay/position/connected-position-strategy.d.ts:36:9
  - error TS1086: An accessor cannot be declared in an ambient context.

36     get _isRtl(): boolean;
             ~~~~~~ node_modules/@angular/cdk/overlay/position/connected-position-strategy.d.ts:40:9
  - error TS1086: An accessor cannot be declared in an ambient context.

40     get onPositionChange():
  Observable;
             ~~~~~~~~~~~~~~~~ node_modules/@angular/cdk/overlay/position/connected-position-strategy.d.ts:43:9
  - error TS1086: An accessor cannot be declared in an ambient context.

43     get positions(): ConnectionPositionPair[];
             ~~~~~~~~~ node_modules/@angular/cdk/overlay/position/flexible-connected-position-strategy.d.ts:91:9
  - error TS1086: An accessor cannot be declared in an ambient context.

91     get positions(): ConnectionPositionPair[];
             ~~~~~~~~~ node_modules/@angular/cdk/portal/portal-directives.d.ts:49:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

49     get portal(): Portal | null;
             ~~~~~~ node_modules/@angular/cdk/portal/portal-directives.d.ts:50:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

50     set portal(portal: Portal | null);
             ~~~~~~ node_modules/@angular/cdk/portal/portal-directives.d.ts:54:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

54     get attachedRef(): CdkPortalOutletAttachedRef;
             ~~~~~~~~~~~ node_modules/@angular/cdk/portal/portal.d.ts:24:9 - error TS1086: An
  accessor cannot be declared in an ambient context.

24     get isAttached(): boolean;
             ~~~~~~~~~~ node_modules/@angular/cdk/portal/portal.d.ts:63:9 - error TS1086: An
  accessor cannot be declared in an ambient context.

63     get origin(): ElementRef;
             ~~~~~~ node_modules/@angular/cdk/scrolling/fixed-size-virtual-scroll.d.ts:75:9
  - error TS1086: An accessor cannot be declared in an ambient context.

75     get itemSize(): number;
             ~~~~~~~~ node_modules/@angular/cdk/scrolling/fixed-size-virtual-scroll.d.ts:76:9
  - error TS1086: An accessor cannot be declared in an ambient context.

76     set itemSize(value: number);
             ~~~~~~~~ node_modules/@angular/cdk/scrolling/fixed-size-virtual-scroll.d.ts:82:9
  - error TS1086: An accessor cannot be declared in an ambient context.

82     get minBufferPx(): number;
             ~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/fixed-size-virtual-scroll.d.ts:83:9
  - error TS1086: An accessor cannot be declared in an ambient context.

83     set minBufferPx(value: number);
             ~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/fixed-size-virtual-scroll.d.ts:88:9
  - error TS1086: An accessor cannot be declared in an ambient context.

88     get maxBufferPx(): number;
             ~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/fixed-size-virtual-scroll.d.ts:89:9
  - error TS1086: An accessor cannot be declared in an ambient context.

89     set maxBufferPx(value: number);
             ~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/virtual-for-of.d.ts:49:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

49     get cdkVirtualForOf(): DataSource | Observable |
  NgIterable | null | undefined;
             ~~~~~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/virtual-for-of.d.ts:50:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

50     set cdkVirtualForOf(value: DataSource | Observable |
  NgIterable | null | undefined);
             ~~~~~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/virtual-for-of.d.ts:56:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

56     get cdkVirtualForTrackBy(): TrackByFunction | undefined;
             ~~~~~~~~~~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/virtual-for-of.d.ts:57:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

57     set cdkVirtualForTrackBy(fn: TrackByFunction | undefined);
             ~~~~~~~~~~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/virtual-for-of.d.ts:60:9 - error
  TS1086: An accessor cannot be declared in an ambient context.

60     set cdkVirtualForTemplate(value:
  TemplateRef>);
             ~~~~~~~~~~~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/virtual-scroll-viewport.d.ts:27:9
  - error TS1086: An accessor cannot be declared in an ambient context.

27     get orientation(): 'horizontal' | 'vertical';
             ~~~~~~~~~~~ node_modules/@angular/cdk/scrolling/virtual-scroll-viewport.d.ts:28:9
  - error TS1086: An accessor cannot be declared in an ambient context.

28     set orientation(orientation: 'horizontal' | 'vertical');
             ~~~~~~~~~~~

I did npm install and npm update but it's not worked for me. Thanks in advance.

答:
The error is for version incompatibility, check the version details for angular,
angular/material & angular/cdk in package.json file or ng --version command on the project.

In my case the version angular version was 8.x and when i installed angular material & cdk dependencies the version was 9.x, i updated the material & cdk version to below versions and it worked fine

```<code>"@angular/cdk": "^8.2.3"
"@angular/material": "^8.2.3"
</code>```

You can view all the material versions in the material.angular.io website
enter image description here

Body:
The error is for version incompatibility, check the version details for angular,
angular/material & angular/cdk in package.json file or ng --version command on the project.

In my case the version angular version was 8.x and when i installed angular material & cdk dependencies the version was 9.x, i updated the material & cdk version to below versions and it worked fine

"@angular/cdk": "^8.2.3"
"@angular/material": "^8.2.3"

You can view all the material versions in the material.angular.io website
enter image description here


问:
Load family (and not typeface) name from font in file system
I'm loading fonts from the filesystem .

generally my code works very well, but as i load the fonts through a PrivateFontCollection the name of the loaded FontFamily is the name of the TypeFace in the font (what i can see under Typeface name in the Font previewer of windows) and not the FontFamily name...

As i have some fonts which have the same Typeface name but another font name i would like to be able to distinguish between them. Anyone has a idea how to get the real FontFamily name?

```<code>    public Dictionary<string, FontFamily> LoadFontsFromDirectory(string path)
    {
        Dictionary<string, FontFamily> foundFonts = new Dictionary<string, FontFamily>();

        if (!Directory.Exists(path)) throw new Exception("directory doesnt exist");

        foreach(FileInfo fi in new DirectoryInfo(path).GetFiles("*.ttf"))
        {
            PrivateFontCollection fileFonts = new PrivateFontCollection();
            fileFonts.AddFontFile(fi.FullName);
            if (!foundFonts.ContainsKey(fileFonts.Families[0].Name))
            {
                //add the font only if this fontfamily doesnt exist yet
                FontFamily family = new FontFamily(String.Format("file:///{0}#{1}", fi.FullName, fileFonts.Families[0].Name));
                foundFonts.Add(family.Name, family);
            }
        }

        return foundFonts;
    }
</code>```

答:
If you want to get the FontFamily as opposed to the value in fileFonts.Families[0].Name, you'll find it in family.FamilyNames by culture:

```<code>FontFamily family = new FontFamily(String.Format("file:///{0}#{1}", fi.FullName, fileFonts.Families[0].Name));
Console.WriteLine("\tFamilySource: {0}", family.Source);
foreach (var x in family.FamilyNames)
{
    Console.WriteLine("\tFamilyName: {0}", x);  // <------ HERE
}
foreach (var y in family.FamilyTypefaces)
{
    foreach (var z in y.AdjustedFaceNames)
    {
        Console.WriteLine("\tTypeface: {0}",z);
    }
}
</code>```

Sample output:

```<code>Arial
    FamilySource: file:///C:\Users\tim\Desktop\arial.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Regular]
    Typeface: [en-us, Bold]
    Typeface: [en-us, Bold Oblique]
    Typeface: [en-us, Oblique]
Arial
    FamilySource: file:///C:\Users\tim\Desktop\arialbd.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Bold]
    Typeface: [en-us, Bold Oblique]
Arial
    FamilySource: file:///C:\Users\tim\Desktop\arialbi.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Bold Italic]
Arial
    FamilySource: file:///C:\Users\tim\Desktop\ariali.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Italic]
    Typeface: [en-us, Bold Italic]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALN.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed]
    Typeface: [en-us, Condensed Bold]
    Typeface: [en-us, Condensed Bold Oblique]
    Typeface: [en-us, Condensed Oblique]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALNB.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed Bold]
    Typeface: [en-us, Condensed Bold Oblique]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALNBI.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed Bold Italic]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALNI.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed Italic]
    Typeface: [en-us, Condensed Bold Italic]
Arial Black
    FamilySource: file:///C:\Users\tim\Desktop\ariblk.ttf#Arial Black
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Black]
    Typeface: [en-us, Black Oblique]
</code>```

That said, your note that "i have some fonts which have the same Typeface name but another font name and i would like to be able to distinguish between them" suggests that FontFamily is not what you are actually looking for.

Body:
I'm loading fonts from the filesystem .

generally my code works very well, but as i load the fonts through a PrivateFontCollection the name of the loaded FontFamily is the name of the TypeFace in the font (what i can see under Typeface name in the Font previewer of windows) and not the FontFamily name...

As i have some fonts which have the same Typeface name but another font name i would like to be able to distinguish between them. Anyone has a idea how to get the real FontFamily name?

    public Dictionary<string, FontFamily> LoadFontsFromDirectory(string path)
    {
        Dictionary<string, FontFamily> foundFonts = new Dictionary<string, FontFamily>();

        if (!Directory.Exists(path)) throw new Exception("directory doesnt exist");

        foreach(FileInfo fi in new DirectoryInfo(path).GetFiles("*.ttf"))
        {
            PrivateFontCollection fileFonts = new PrivateFontCollection();
            fileFonts.AddFontFile(fi.FullName);
            if (!foundFonts.ContainsKey(fileFonts.Families[0].Name))
            {
                //add the font only if this fontfamily doesnt exist yet
                FontFamily family = new FontFamily(String.Format("file:///{0}#{1}", fi.FullName, fileFonts.Families[0].Name));
                foundFonts.Add(family.Name, family);
            }
        }

        return foundFonts;
    }

Body:
If you want to get the FontFamily as opposed to the value in fileFonts.Families[0].Name, you'll find it in family.FamilyNames by culture:

FontFamily family = new FontFamily(String.Format("file:///{0}#{1}", fi.FullName, fileFonts.Families[0].Name));
Console.WriteLine("\tFamilySource: {0}", family.Source);
foreach (var x in family.FamilyNames)
{
    Console.WriteLine("\tFamilyName: {0}", x);  // <------ HERE
}
foreach (var y in family.FamilyTypefaces)
{
    foreach (var z in y.AdjustedFaceNames)
    {
        Console.WriteLine("\tTypeface: {0}",z);
    }
}

Sample output:

Arial
    FamilySource: file:///C:\Users\tim\Desktop\arial.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Regular]
    Typeface: [en-us, Bold]
    Typeface: [en-us, Bold Oblique]
    Typeface: [en-us, Oblique]
Arial
    FamilySource: file:///C:\Users\tim\Desktop\arialbd.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Bold]
    Typeface: [en-us, Bold Oblique]
Arial
    FamilySource: file:///C:\Users\tim\Desktop\arialbi.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Bold Italic]
Arial
    FamilySource: file:///C:\Users\tim\Desktop\ariali.ttf#Arial
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Italic]
    Typeface: [en-us, Bold Italic]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALN.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed]
    Typeface: [en-us, Condensed Bold]
    Typeface: [en-us, Condensed Bold Oblique]
    Typeface: [en-us, Condensed Oblique]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALNB.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed Bold]
    Typeface: [en-us, Condensed Bold Oblique]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALNBI.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed Bold Italic]
Arial Narrow
    FamilySource: file:///C:\Users\tim\Desktop\ARIALNI.TTF#Arial Narrow
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Condensed Italic]
    Typeface: [en-us, Condensed Bold Italic]
Arial Black
    FamilySource: file:///C:\Users\tim\Desktop\ariblk.ttf#Arial Black
    FamilyName: [en-us, Arial]
    Typeface: [en-us, Black]
    Typeface: [en-us, Black Oblique]

That said, your note that "i have some fonts which have the same Typeface name but another font name and i would like to be able to distinguish between them" suggests that FontFamily is not what you are actually looking for.


问:
Fastest way to convert SqlDataReader to list of objects in C#
I try to get a lot of data from a SQL Server database using C#. I get something like 300K rows of data from the database (I believe it's not far from the worst case that can be.) that can contain hundreds of millions.

I don't think the problem it's about the size of the database because
of the command.ExecuteReader(); takes about nothing and less than a second.

I tried this code:

```<code>public List<ResultPulser> GetReportResult(SqlConnection opCon, SqlCommand command,
    int minReport,int maxReport,int machineNumber)
{
    List<ResultPulser> results = new List<ResultPulser>();

    using (DataContext dc = new DataContext(opCon))
    {
        try
        {
            command.CommandText = "select * from ResultPulser " +
                "where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber and " +
                "CAST(SUBSTRING([ReportNumber],8,LEN([ReportNumber])) as int) BETWEEN @minReport AND @maxReport";
            command.Parameters.Clear();
            command.Parameters.AddWithValue("@minReport", minReport);
            command.Parameters.AddWithValue("@maxReport", maxReport);
            command.Parameters.AddWithValue("@machineNumber", machineNumber);

            Stopwatch SW1 = Stopwatch.StartNew();
            SqlDataReader reader = command.ExecuteReader();
            SW1.Stop();

            DataTable table = new DataTable();
            Stopwatch SW2 = Stopwatch.StartNew();
            table.Load(reader);
            SW2.Stop();

            Stopwatch SW3 = Stopwatch.StartNew();
            ResultPulser[] report = new ResultPulser[table.Rows.Count];

            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow dr = table.Rows[i];
                report[i] = new ResultPulser(Convert.ToInt64(dr[0]), dr[1].ToString().Trim(),
                    dr[2].ToString().Trim(), Convert.ToDateTime(dr[3]), Convert.ToDouble(dr[4]),
                    Convert.ToDouble(dr[5]), Convert.ToDouble(dr[6]), Convert.ToDouble(dr[7]),
                    Convert.ToDouble(dr[8]), Convert.ToDouble(dr[9]), Convert.ToInt64(dr[10]),
                    Convert.ToInt64(dr[11]), Convert.ToInt64(dr[12]), Convert.ToBoolean(dr[13]),
                    Convert.ToInt32(dr[14]));
            }
            SW3.Stop();

            reader.Close();
            return report.ToList();
        }
        catch (Exception ex)
        {
            LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
            throw ex;
        }
    }
}
</code>```

But the next line table.Load(reader);  takes about 20 seconds to complete.

I also tried like this:

```<code>public List<ResultPulser> GetReportResult(SqlConnection opCon, SqlCommand command,
            int minReport,int maxReport,int machineNumber)
{
            List<ResultPulser> results = new List<ResultPulser>();

            using (DataContext dc = new DataContext(opCon))
            {
                try
                {
                    command.CommandText = "select * from ResultPulser " +
                        "where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber and " +
                        "CAST(SUBSTRING([ReportNumber],8,LEN([ReportNumber])) as int) BETWEEN @minReport AND @maxReport";
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("@minReport", minReport);
                    command.Parameters.AddWithValue("@maxReport", maxReport);
                    command.Parameters.AddWithValue("@machineNumber", machineNumber);

                    Stopwatch SW1 = Stopwatch.StartNew();
                    SqlDataReader reader = command.ExecuteReader();
                    SW1.Stop();

                    DataTable table = new DataTable();
                    Stopwatch SW2 = Stopwatch.StartNew();
                    while (reader.Read())
                    {
                        results.Add(new ResultPulser(reader.GetInt64(0), reader.GetString(1).Trim(), reader.GetString(2).Trim(),
                            reader.GetDateTime(3), reader.GetDouble(4), reader.GetDouble(5), reader.GetDouble(6),
                            reader.GetDouble(7), reader.GetDouble(8), reader.GetDouble(9), reader.GetInt64(10),
                            reader.GetInt64(11), reader.GetInt64(12), reader.GetBoolean(13), reader.GetInt32(14)));
                    }
                    SW2.Stop();

                    reader.Close();
                    return results;
                }
                catch (Exception ex)
                {
                    LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
                    throw ex;
                }
            }
 }
</code>```

In this case, this code part takes about 17-16 seconds...

```<code>  while (reader.Read())
  {
      results.Add(new ResultPulser(reader.GetInt64(0), reader.GetString(1).Trim(), reader.GetString(2).Trim(),
                            reader.GetDateTime(3), reader.GetDouble(4), reader.GetDouble(5), reader.GetDouble(6),
                            reader.GetDouble(7), reader.GetDouble(8), reader.GetDouble(9), reader.GetInt64(10),
                            reader.GetInt64(11), reader.GetInt64(12), reader.GetBoolean(13), reader.GetInt32(14)));
                    }
</code>```

How can I optimize my code to do it faster than that?

答:
This is your problem:

```<code>"where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber and " +
"CAST(SUBSTRING([ReportNumber],8,LEN([ReportNumber])) as int) BETWEEN @minReport AND @maxReport";
</code>```

By using these CAST(SUBSTRING(...)) expressions you're forcing full scan on this (presumably large) table.
You need to change it/optimize it so that it contains bare column names in WHERE.

What I assume from the predicates the ReportNumber column has values of the form
MMMMMMMMR+
where MMMMMMMM is the machine number and R+ is one or more digits of the report number.

I'm not sure what is the data type of the ReportNumber column. It can be a bigint or some kind of string. From the query it seems it's a string, but you might as well use implicit conversions.

Anyway there's great potential to optimize this and bring it to elapsed time measured in single milliseconds.

I can only give you a starting point as there's not enough info.

The first part is easy:

"where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber"
```

<p>becomes </p>

<pre class="lang-sql prettyprint-override"><code>"where ReportNumber LIKE @machineNumber"
</code>```

so this becomes a prefix search, and you change the C# part to pass the parameter as a prefix search for LIKE:

string machineNumberLikeString = machineNumber.ToString() + "%";
```

<p>then pass it to the query like so:</p>

<pre class="lang-cs prettyprint-override"><code>command.Parameters.AddWithValue("@machineNumber", machineNumberLikeString);
</code>```

Then on the SQL side you can create an index to support fast searching data for this query (but only if it's used quite often - which is a subjective and depending on your workload and requirements). Remember that indexes have their cost and the gain must outweigh it.

CREATE INDEX IX_ResultPulser_ReportNumber
    ON ResultPulser (ReportNumber);
```

It will work assuming the column ReportNumber is of some string data type, e.g. VARCHAR or NVARCHAR. If it's numeric, it may or may not work. A modified strategy is required. But I'm out of time and I don't have enough info on the data and the table.

EDIT: It may not help if you're extracting 300 thousand rows in one query. SQL Server would need 300k lookups to fetch remaining columns for your SELECT *. You may consider clustering this table on ReportNumber columns (CREATE CLUSTERED INDEX...).

And the last warning: do not use SELECT * (select star) in production code. Always explicitly specify which columns you require.

Hope that this will help you.

Body:
I try to get a lot of data from a SQL Server database using C#. I get something like 300K rows of data from the database (I believe it's not far from the worst case that can be.) that can contain hundreds of millions.

I don't think the problem it's about the size of the database because
of the command.ExecuteReader(); takes about nothing and less than a second.

I tried this code:

public List<ResultPulser> GetReportResult(SqlConnection opCon, SqlCommand command,
    int minReport,int maxReport,int machineNumber)
{
    List<ResultPulser> results = new List<ResultPulser>();

    using (DataContext dc = new DataContext(opCon))
    {
        try
        {
            command.CommandText = "select * from ResultPulser " +
                "where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber and " +
                "CAST(SUBSTRING([ReportNumber],8,LEN([ReportNumber])) as int) BETWEEN @minReport AND @maxReport";
            command.Parameters.Clear();
            command.Parameters.AddWithValue("@minReport", minReport);
            command.Parameters.AddWithValue("@maxReport", maxReport);
            command.Parameters.AddWithValue("@machineNumber", machineNumber);

            Stopwatch SW1 = Stopwatch.StartNew();
            SqlDataReader reader = command.ExecuteReader();
            SW1.Stop();

            DataTable table = new DataTable();
            Stopwatch SW2 = Stopwatch.StartNew();
            table.Load(reader);
            SW2.Stop();

            Stopwatch SW3 = Stopwatch.StartNew();
            ResultPulser[] report = new ResultPulser[table.Rows.Count];

            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow dr = table.Rows[i];
                report[i] = new ResultPulser(Convert.ToInt64(dr[0]), dr[1].ToString().Trim(),
                    dr[2].ToString().Trim(), Convert.ToDateTime(dr[3]), Convert.ToDouble(dr[4]),
                    Convert.ToDouble(dr[5]), Convert.ToDouble(dr[6]), Convert.ToDouble(dr[7]),
                    Convert.ToDouble(dr[8]), Convert.ToDouble(dr[9]), Convert.ToInt64(dr[10]),
                    Convert.ToInt64(dr[11]), Convert.ToInt64(dr[12]), Convert.ToBoolean(dr[13]),
                    Convert.ToInt32(dr[14]));
            }
            SW3.Stop();

            reader.Close();
            return report.ToList();
        }
        catch (Exception ex)
        {
            LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
            throw ex;
        }
    }
}

But the next line table.Load(reader);  takes about 20 seconds to complete.

I also tried like this:

public List<ResultPulser> GetReportResult(SqlConnection opCon, SqlCommand command,
            int minReport,int maxReport,int machineNumber)
{
            List<ResultPulser> results = new List<ResultPulser>();

            using (DataContext dc = new DataContext(opCon))
            {
                try
                {
                    command.CommandText = "select * from ResultPulser " +
                        "where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber and " +
                        "CAST(SUBSTRING([ReportNumber],8,LEN([ReportNumber])) as int) BETWEEN @minReport AND @maxReport";
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("@minReport", minReport);
                    command.Parameters.AddWithValue("@maxReport", maxReport);
                    command.Parameters.AddWithValue("@machineNumber", machineNumber);

                    Stopwatch SW1 = Stopwatch.StartNew();
                    SqlDataReader reader = command.ExecuteReader();
                    SW1.Stop();

                    DataTable table = new DataTable();
                    Stopwatch SW2 = Stopwatch.StartNew();
                    while (reader.Read())
                    {
                        results.Add(new ResultPulser(reader.GetInt64(0), reader.GetString(1).Trim(), reader.GetString(2).Trim(),
                            reader.GetDateTime(3), reader.GetDouble(4), reader.GetDouble(5), reader.GetDouble(6),
                            reader.GetDouble(7), reader.GetDouble(8), reader.GetDouble(9), reader.GetInt64(10),
                            reader.GetInt64(11), reader.GetInt64(12), reader.GetBoolean(13), reader.GetInt32(14)));
                    }
                    SW2.Stop();

                    reader.Close();
                    return results;
                }
                catch (Exception ex)
                {
                    LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
                    throw ex;
                }
            }
 }

In this case, this code part takes about 17-16 seconds...

  while (reader.Read())
  {
      results.Add(new ResultPulser(reader.GetInt64(0), reader.GetString(1).Trim(), reader.GetString(2).Trim(),
                            reader.GetDateTime(3), reader.GetDouble(4), reader.GetDouble(5), reader.GetDouble(6),
                            reader.GetDouble(7), reader.GetDouble(8), reader.GetDouble(9), reader.GetInt64(10),
                            reader.GetInt64(11), reader.GetInt64(12), reader.GetBoolean(13), reader.GetInt32(14)));
                    }

How can I optimize my code to do it faster than that?

Body:
This is your problem:

"where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber and " +
"CAST(SUBSTRING([ReportNumber],8,LEN([ReportNumber])) as int) BETWEEN @minReport AND @maxReport";

By using these CAST(SUBSTRING(...)) expressions you're forcing full scan on this (presumably large) table.
You need to change it/optimize it so that it contains bare column names in WHERE.

What I assume from the predicates the ReportNumber column has values of the form
MMMMMMMMR+
where MMMMMMMM is the machine number and R+ is one or more digits of the report number.

I'm not sure what is the data type of the ReportNumber column. It can be a bigint or some kind of string. From the query it seems it's a string, but you might as well use implicit conversions.

Anyway there's great potential to optimize this and bring it to elapsed time measured in single milliseconds.

I can only give you a starting point as there's not enough info.

The first part is easy:

"where CAST(SUBSTRING([ReportNumber], 0, 8) as int) = @machineNumber"

becomes

"where ReportNumber LIKE @machineNumber"

so this becomes a prefix search, and you change the C# part to pass the parameter as a prefix search for LIKE:

string machineNumberLikeString = machineNumber.ToString() + "%";

then pass it to the query like so:

command.Parameters.AddWithValue("@machineNumber", machineNumberLikeString);

Then on the SQL side you can create an index to support fast searching data for this query (but only if it's used quite often - which is a subjective and depending on your workload and requirements). Remember that indexes have their cost and the gain must outweigh it.

CREATE INDEX IX_ResultPulser_ReportNumber
    ON ResultPulser (ReportNumber);

It will work assuming the column ReportNumber is of some string data type, e.g. VARCHAR or NVARCHAR. If it's numeric, it may or may not work. A modified strategy is required. But I'm out of time and I don't have enough info on the data and the table.

EDIT: It may not help if you're extracting 300 thousand rows in one query. SQL Server would need 300k lookups to fetch remaining columns for your SELECT *. You may consider clustering this table on ReportNumber columns (CREATE CLUSTERED INDEX...).

And the last warning: do not use SELECT * (select star) in production code. Always explicitly specify which columns you require.

Hope that this will help you.


问:
What is the file named "setup.zst.sig" during installation?
I note that when cygwin's setup.exe installs packages now, it looks for a file named "setup.zst.sig" first. What's the content and format of this binary file? How to produce a valid "setup.zst.sig"?

This must have been a recent change. Previously it looked for "setup.exe.sig" first. I use the feature (to detect whether "setup.exe.sig" changed) to decide whether my cygwin installation needs to be updated. See also this for an application example.

EDIT: @matzeri:

答:
According to the documentation, the .sig files carry a SHA-512 hash of the respective file without that extension, signed with the private key available only to Cygwin the company.

https://www.cygwin.com/faq.html#faq.setup.install-security


问:
Close `showModalBottomSheet` after a timeout
I tried to close showModalBottomSheet widget through an event listener.

```<code>          showModalBottomSheet(
              useRootNavigator: true,
              context: context,
              builder: (newcontext) {
                return MyBottomDialog();
              });
</code>```

I tried to close this through an event listener:

```<code>class _MyBottomDialogState extends State<MyBottomDialog> {
...
...
  void initState() {
    _myEventStream.listen((state) {
      if (state == 'timeout') {
        Navigator.of(context, rootNavigator: true).pop();
      }
    });
    super.initState();
  }

</code>```

```<code>TypeError: Cannot read property 'findAncestorStateOfType' of null
.
.
.
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a
reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in
the widget's didChangeDependencies() method.
</code>```

How do I achieve this?

答:
May be I didn't capture properly what the error is saying.
Even after closing the dialog the stream subscription persists. So the handler is called even if the dialog is not open.

Adding _streamSubscription.cancel() in the widget's dispose method helps solve this problem.

Body:
I tried to close showModalBottomSheet widget through an event listener.

          showModalBottomSheet(
              useRootNavigator: true,
              context: context,
              builder: (newcontext) {
                return MyBottomDialog();
              });

I tried to close this through an event listener:

class _MyBottomDialogState extends State<MyBottomDialog> {
...
...
  void initState() {
    _myEventStream.listen((state) {
      if (state == 'timeout') {
        Navigator.of(context, rootNavigator: true).pop();
      }
    });
    super.initState();
  }

TypeError: Cannot read property 'findAncestorStateOfType' of null
.
.
.
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a
reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in
the widget's didChangeDependencies() method.

How do I achieve this?