问:
How to fix the git repo if I accidentally create the repo with a submodule (sub repo) in it?
If I do the following:

```<code>mkdir TryReactHooks
cd TryReactHooks
npx create-react-app my-app
git init
git remote add origin git@gitlab.com:username/tryreacthooks.git  # optional
git add .
git commit -am "Initial Commit"
git push -u origin master
</code>```

then for some reason, this repo doesn't seem to track any file in the my-app folder.  It is probably due to my-app is a repo by itself (because create-react-app did it).  If I do

```<code>mv my-app/.git my-app/.git-tmp
</code>```

so that my-app is no longer a git repo, I find that still the current repo won't track any changes made to my-app even if I do git add .  How can this be fixed?

答:
Does git status shows the my-app directory under "Untracked files:"? If yes, do git add my-app to start tracking the changes.

Inspect '.gitignore' file and see whether the relevant directory is being ignored.

If you don't need the "my-app" directory to be a separate repository, try deleting the '.git/' directory rather than moving it.

Let me know if any of this works.

Body:
If I do the following:

mkdir TryReactHooks
cd TryReactHooks
npx create-react-app my-app
git init
git remote add origin git@gitlab.com:username/tryreacthooks.git  # optional
git add .
git commit -am "Initial Commit"
git push -u origin master

then for some reason, this repo doesn't seem to track any file in the my-app folder.  It is probably due to my-app is a repo by itself (because create-react-app did it).  If I do

mv my-app/.git my-app/.git-tmp

so that my-app is no longer a git repo, I find that still the current repo won't track any changes made to my-app even if I do git add .  How can this be fixed?


来源: stackexchange

问:
Mutli indexing using pandas
df

```<code>ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE
</code>```

I tried using the below code

```<code>df.groupby(['CATEGORY', 'COLOR']).size().unstack(fill_value=0)
</code>```

which does not give me what I need. The output I am expecting is

```<code>CATEGORY      COLOR     ITEM

CAR           RED       48684
              BLACK     14582
BIKE          BLACK     54519
              BLUE      23661
JEEP          WHITE     45685
</code>```

答:
I believe you need DataFrame.set_index with DataFrame.sort_index:

```<code>df1 = df.set_index(['CATEGORY', 'COLOR']).sort_index()
print (df1)
                 ITEM
CATEGORY COLOR
BIKE     BLACK  54519
         BLUE   23661
CAR      BLACK  14582
         RED    48684
JEEP     WHITE  45685
</code>```

If order is omportant convert both columns to ordered categoricals:

```<code>cols = ['CATEGORY', 'COLOR']
for c in cols:
    df[c] = pd.Categorical(df[c], categories=df[c].drop_duplicates(), ordered=True)

df1 = df.set_index(cols).sort_index()
print (df1)
                 ITEM
CATEGORY COLOR
CAR      RED    48684
         BLACK  14582
BIKE     BLACK  54519
         BLUE   23661
JEEP     WHITE  45685
</code>```

ContentLicense: CC BY-SA 4.0

Title: Mutli indexing using pandas

Body:
df

ITEM      CATEGORY       COLOR

48684      CAR           RED
54519      BIKE          BLACK
14582      CAR           BLACK
45685      JEEP          WHITE
23661      BIKE          BLUE

I tried using the below code

df.groupby(['CATEGORY', 'COLOR']).size().unstack(fill_value=0)

which does not give me what I need. The output I am expecting is

CATEGORY      COLOR     ITEM

CAR           RED       48684
              BLACK     14582
BIKE          BLACK     54519
              BLUE      23661
JEEP          WHITE     45685

Body:
I believe you need DataFrame.set_index with DataFrame.sort_index:

df1 = df.set_index(['CATEGORY', 'COLOR']).sort_index()
print (df1)
                 ITEM
CATEGORY COLOR
BIKE     BLACK  54519
         BLUE   23661
CAR      BLACK  14582
         RED    48684
JEEP     WHITE  45685

If order is omportant convert both columns to ordered categoricals:

cols = ['CATEGORY', 'COLOR']
for c in cols:
    df[c] = pd.Categorical(df[c], categories=df[c].drop_duplicates(), ordered=True)

df1 = df.set_index(cols).sort_index()
print (df1)
                 ITEM
CATEGORY COLOR
CAR      RED    48684
         BLACK  14582
BIKE     BLACK  54519
         BLUE   23661
JEEP     WHITE  45685


问:
How to get Pipeline Folder Path in Azure Data Factory?
Is there a way/function to fetch complete folder path of a pipeline in Azure data factory?

If I have a data factory job like in str:

```<code>**datafactory-name/root-folder/etl-pipeline**
</code>```

I can use @pipeline().Pipeline function to fetch and store pipeline name in a variable which in this case would be etl-pipeline.

Is there a similar function to retrieve the name of folder in which the pipeline is? I would like to store root-folder also in a variable

Please help.

答: Don't think that there is any direct way to achieve this, however curious to know the use case why you would need to capture the name of the pipeline folder in a variable while executing it and why not parameterize the pipeline which would let you pass the name of the pipeline folder whenever you invoke the pipeline - this way you could still achieve what you are intending to do with pipeline parameter instead of a runtime initialized variable.</p>

Body:
Is there a way/function to fetch complete folder path of a pipeline in Azure data factory?

If I have a data factory job like in str:

**datafactory-name/root-folder/etl-pipeline**

I can use @pipeline().Pipeline function to fetch and store pipeline name in a variable which in this case would be etl-pipeline.

Is there a similar function to retrieve the name of folder in which the pipeline is? I would like to store root-folder also in a variable

Please help.


问:
How to download return from google collab?
I am using Google collab to analyze some data. I want to download the model file.
I have a code like that:

model.fit(x_train, y_train, epochs=1, batch_size=1,
```

I tried using the download(), but I doesn't work. Is there any way to download it?

答:
I assuming that you are using Keras, because model.save() method return None so if you put it as download() method parameter, it will make an error. Just save model first then download it after that:

```<code>model.save('model_name.h5')
download('model_name.h5')
</code>```

And make sure that you are at the correct directory that contain model_name.h5 file. You can check that with !ls command.

Body:
I am using Google collab to analyze some data. I want to download the model file.
I have a code like that:

model.fit(x_train, y_train, epochs=1, batch_size=1,

I tried using the download(), but I doesn't work. Is there any way to download it?

Body:
I assuming that you are using Keras, because model.save() method return None so if you put it as download() method parameter, it will make an error. Just save model first then download it after that:

model.save('model_name.h5')
download('model_name.h5')

And make sure that you are at the correct directory that contain model_name.h5 file. You can check that with !ls command.


问:
Why can't my compiler convert this?
Error:

```<code>Type mismatch: cannot convert from Set<ConstraintViolation<capture#1-of ?>> to Set<ConstraintViolation<Class<?>>>
</code>```

My code:

```<code>public class validateValue(Class<?> beanType, String propertyName, Object value, Class<?>... groups){
    TraversableResolver tr = new MyTraversableResolver();
    Validator validator = Validation.buildDefaultValidatorFactory().usingContext().traversableResolver(tr).getValidator();
    final Set<ConstraintViolation<Class<?>>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
}

private class MyTraversableResolver  implements TraversableResolver {

    public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
      return traversableObject == null || Hibernate.isInitialized(traversableObject);
      }
      public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
          return true;
      }
  }
</code>```

答:
I think the problem is your compiler doesn't know that the type of your beanType variable matches the set.  Try something like this (code may need to be tweaked a bit)

```<code>public <T> class validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups)
</code>```

Then changing:

```<code> final Set<ConstraintViolation<Class<?>>>
</code>```

to

```<code> final Set<ConstraintViolation<Class<T>>>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why can't my compiler convert this?

Body:
Error:

Type mismatch: cannot convert from Set<ConstraintViolation<capture#1-of ?>> to Set<ConstraintViolation<Class<?>>>

My code:

public class validateValue(Class<?> beanType, String propertyName, Object value, Class<?>... groups){
    TraversableResolver tr = new MyTraversableResolver();
    Validator validator = Validation.buildDefaultValidatorFactory().usingContext().traversableResolver(tr).getValidator();
    final Set<ConstraintViolation<Class<?>>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
}

private class MyTraversableResolver  implements TraversableResolver {

    public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
      return traversableObject == null || Hibernate.isInitialized(traversableObject);
      }
      public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
          return true;
      }
  }

Body:
I think the problem is your compiler doesn't know that the type of your beanType variable matches the set.  Try something like this (code may need to be tweaked a bit)

public <T> class validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups)

Then changing:

 final Set<ConstraintViolation<Class<?>>>

to

 final Set<ConstraintViolation<Class<T>>>


问:
How to make carousel image slide in php laravel from public folder
I'm trying to slide images using carousel from public folder of php laravel. The files are loading as the images that i have posted. But i wanted to slide one after the other. None of the methods are working. It's only showing images one by one all at once. Kindly please look into it and help me.

The codes for view page is.

```<code><div id="mycarousel" class="carousel slide" data-ride="carousel">

    <div class="carousel-inner" role="listbox">

         <ol class="carousel-indicators">
                    @foreach($images as $key => $image)
                       <li data-target="#home_main-slider" data-slide-to="{{$key}}" class="carousel-1">
                       </li>
                      @endforeach
                </ol>

                <!-- Wrapper for slides -->
                <div class="carousel-inner" role="listbox">
                    @foreach( $images as $image )

                     @if ($loop->first)
                      <div class="item image active">
                      @else
                      <div class="item image">
                      @endif

                            <img src="{{ asset('img/' . $image->getFilename()) }}">
                        </div>
                    @endforeach
                </div>
    </div>

    <a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">

        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>

        <span class="sr-only">Previous</span>

    </a>
    <a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">

        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>

        <span class="sr-only">Next</span>

    </a>
</code>```

the controller page code is..

```<code> public function testimonials() {
        $titleName = "Testimonials";
        $images = \File::allFiles(public_path('img'));

        return view('testimonials', compact('titleName'))->with('images', $images);
    }
</code>```

答:
Answer

You'll need to import BS3 JS and jQuery.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</code>```

Codepen Link

Here is a BS3 Carousel example that might help - includes all the necessary JS and CSS. codepen.io/darrenkhouston/pen/vYOKjzP

Body:
I'm trying to slide images using carousel from public folder of php laravel. The files are loading as the images that i have posted. But i wanted to slide one after the other. None of the methods are working. It's only showing images one by one all at once. Kindly please look into it and help me.

The codes for view page is.

                    @foreach($images as $key => $image)

                      @endforeach

                    @foreach( $images as $image )

                     @if ($loop->first)

                      @else

                      @endif

                            getFilename()) }}">

                    @endforeach

        Previous

        Next

the controller page code is..

 public function testimonials() {
        $titleName = "Testimonials";
        $images = \File::allFiles(public_path('img'));

        return view('testimonials', compact('titleName'))->with('images', $images);
    }

Body:
Answer

You'll need to import BS3 JS and jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

Codepen Link

Here is a BS3 Carousel example that might help - includes all the necessary JS and CSS. codepen.io/darrenkhouston/pen/vYOKjzP


答:
I will use Categorical first, since this will keep the original CATEGORY order

```<code>df.CATEGORY=pd.Categorical(df.CATEGORY,df.CATEGORY.unique())
s=df.sort_values(['CATEGORY','COLOR']).set_index(['CATEGORY','COLOR'])
                 ITEM
CATEGORY COLOR
CAR      BLACK  14582
         RED    48684
BIKE     BLACK  54519
         BLUE   23661
JEEP     WHITE  45685
</code>```

Title: Mutli indexing using pandas

Body:
I will use Categorical first, since this will keep the original CATEGORY order

df.CATEGORY=pd.Categorical(df.CATEGORY,df.CATEGORY.unique())
s=df.sort_values(['CATEGORY','COLOR']).set_index(['CATEGORY','COLOR'])
                 ITEM
CATEGORY COLOR
CAR      BLACK  14582
         RED    48684
BIKE     BLACK  54519
         BLUE   23661
JEEP     WHITE  45685


问:
EPERM: operation not permitted, chmod @react-native-community iOS
I am using React v16.8.6 and react-native v0.59.6. iOS.

While typing react-native --version or anything prefix with react-native, it is showing the following error.

```<code>internal/fs/utils.js:220
    throw err;
    ^

Error: EPERM: operation not permitted, chmod '/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/external/xsel'
    at Object.chmodSync (fs.js:1104:3)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/copyToClipBoard.js:50:15)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/middleware/copyToClipBoardMiddleware.js:8:47)
    at Module._compile (internal/modules/cjs/loader.js:956:30) {
  errno: -1,
  syscall: 'chmod',
  code: 'EPERM',
  path: '/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/external/xsel'
}
</code>```

I cleaned the project. Restarted it.

Deleted the npm package and reinstalled it.

Tried npm install -g react-native-cli.

I have react-native-community/cli version 1.12.0 in package.lock.json dependancies.

I don't have any clue about what to do. I cannot link any libraries and other stuff requiring react-native keywords.

Moreover,
If I run it with sudo like sudo react-native --version, it is giving like below mentioned.

```<code>warn Your project is using deprecated "rnpm" config that will stop working from next release. Please use a "react-native.config.js" file to configure the React Native CLI. Migration guide: https://github.com/react-native-community/cli/blob/master/docs/configuration.md
warn The following packages use deprecated "rnpm" config that will stop working from next release:
  - react-native-google-sign in: https://github.com/react-native-community/react-native-google-signin
  - react-native-video: https://github.com/react-native-community/react-native-video#readme
Please notify their maintainers about it. You can find more details at https://github.com/react-native-community/cli/blob/master/docs/configuration.md#migration-guide.
3.0.4
</code>```

Please suggest some guidance regarding the same.

Thanks.

答:
rm -rf node_modules && npm install this will solve your problem.

It's because of the compatibility issues of the dependent packages. Try to move/remove package-lock.json from the dir and do the installation again.

Body:
I am using React v16.8.6 and react-native v0.59.6. iOS.

While typing react-native --version or anything prefix with react-native, it is showing the following error.

internal/fs/utils.js:220
    throw err;
    ^

Error: EPERM: operation not permitted, chmod '/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/external/xsel'
    at Object.chmodSync (fs.js:1104:3)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/copyToClipBoard.js:50:15)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/middleware/copyToClipBoardMiddleware.js:8:47)
    at Module._compile (internal/modules/cjs/loader.js:956:30) {
  errno: -1,
  syscall: 'chmod',
  code: 'EPERM',
  path: '/usr/local/lib/node_modules/react-native/node_modules/@react-native-community/cli/build/commands/server/external/xsel'
}

I cleaned the project. Restarted it.

Deleted the npm package and reinstalled it.

Tried npm install -g react-native-cli.

I have react-native-community/cli version 1.12.0 in package.lock.json dependancies.

I don't have any clue about what to do. I cannot link any libraries and other stuff requiring react-native keywords.

Moreover,
If I run it with sudo like sudo react-native --version, it is giving like below mentioned.

warn Your project is using deprecated "rnpm" config that will stop working from next release. Please use a "react-native.config.js" file to configure the React Native CLI. Migration guide: https://github.com/react-native-community/cli/blob/master/docs/configuration.md
warn The following packages use deprecated "rnpm" config that will stop working from next release:
  - react-native-google-sign in: https://github.com/react-native-community/react-native-google-signin
  - react-native-video: https://github.com/react-native-community/react-native-video#readme
Please notify their maintainers about it. You can find more details at https://github.com/react-native-community/cli/blob/master/docs/configuration.md#migration-guide.
3.0.4

Please suggest some guidance regarding the same.

Thanks.


问:
create hyperlink that open in new tab/window using external javascript
How can I create a link that opens in a new window/tab to my HTML menu item (Try, Trying, TryTry) using external javascript? (and not edit anything from the HTML file)

Html file:

```<code><div id="highlights" class="container">
    <div id="menu">
        <ul>
            <li id="Try">Try!</li>
            <li id="Trying">Trying!</li>
            <li id="TryTry">TryTry!</li>
        </ul>
    </div>
</div>
</code>```

答:
document.getElementById("Try").innerHTML = `<li id="Try">Try!</li>`

document.getElementById("Trying").innerHTML = `<li id="Trying">Trying!</li>`

document.getElementById("TryTry").innerHTML = `<li id="TryTry">TryTry!</li>`
```

<pre class="lang-html prettyprint-override"><code><div id="highlights" class="container">
  <div id="menu">
    <ul>
      <li id="Try">Try!</li>
      <li id="Trying">Trying!</li>
      <li id="TryTry">TryTry!</li>
    </ul>
  </div>
</div>
</code>```

Once again. As StackOverflow doesn't allow snippets to open new pages here is a link to JSFiddle

Body:
How can I create a link that opens in a new window/tab to my HTML menu item (Try, Trying, TryTry) using external javascript? (and not edit anything from the HTML file)

Html file:

Try!

Trying!

TryTry!

Body:
document.getElementById("Try").innerHTML = `<li id="Try"><a href="link/to/try" target="_blank">Try!</a></li>`

document.getElementById("Trying").innerHTML = `<li id="Trying"><a href="link/to/trying" target="_blank">Trying!</a></li>`

document.getElementById("TryTry").innerHTML = `<li id="TryTry"><a href="link/to/trytry" target="_blank">TryTry!</a></li>`

<div id="highlights" class="container">
  <div id="menu">
    <ul>
      <li id="Try">Try!</li>
      <li id="Trying">Trying!</li>
      <li id="TryTry">TryTry!</li>
    </ul>
  </div>
</div>

Once again. As StackOverflow doesn't allow snippets to open new pages here is a link to JSFiddle


问:
this.shift = {x:this.x, y:this.y} works but not this.shift.x = this.x and this.shift.y = this.y?
```<code>this.x = (Math.random()*canvasWidth);
this.y = (Math.random()*canvasHeight);

(1) this.shift = {x: this.x, y: this.y};

(2) this.shift.x = this.x;
    this.shift.y = this.y;
</code>```

Hi guys, I am playing with canvas and on my way to create a particle system.

The first (1) one will work but not the second (2) one why?
I am getting an error saying "Cannot set property 'x' of undefined" when debug using Chrome dev tools.

Any idea?

答:
this.shift does not exist.

You need to create it first, by writing this.shift = { }.

Body:
this.x = (Math.random()*canvasWidth);
this.y = (Math.random()*canvasHeight);

(1) this.shift = {x: this.x, y: this.y};

(2) this.shift.x = this.x;
    this.shift.y = this.y;

Hi guys, I am playing with canvas and on my way to create a particle system.

The first (1) one will work but not the second (2) one why?
I am getting an error saying "Cannot set property 'x' of undefined" when debug using Chrome dev tools.

Any idea?


问:
deletion of one past end element in map and segmentation fault
When I tried to delete end() element from the map using erase I got no issues in compilation but on later printing the map.begin() key/mapped_value I got segmentation fault:

```<code> //RELEVANT HEADERS

 //main function starts

 map<int, string> m;
 m[0] = "hello";
 m[1] = "Mello";

 m.erase(m.end());

 cout<<(m.begin())->second;
</code>```

OUTPUT: Segmentation fault

My question is: on trying to delete the end() element nothing would've happened to the structure of map m as end refers to one past the real end element, so what really triggered that segmentation fault as the memory structure still holds same as before deletion.

答:
std::map::erase() can take one of three types of parameters:

iterator

iterator range

key value

You're passing an iterator but it is end(), which is one past the last element in the map. According to cppreference for std::map:erase():

The iterator pos must be valid and dereferenceable. Thus the end()
  iterator (which is valid, but is not dereferenceable) cannot be used
  as a value for pos.

So for std::map::erase() to work with an iterator the element pointed to must be a valid element within the map. Otherwise all bets are off and you can get undefined behaviour.

Body:
When I tried to delete end() element from the map using erase I got no issues in compilation but on later printing the map.begin() key/mapped_value I got segmentation fault:

 //RELEVANT HEADERS

 //main function starts

 map<int, string> m;
 m[0] = "hello";
 m[1] = "Mello";

 m.erase(m.end());

 cout<<(m.begin())->second;

OUTPUT: Segmentation fault

My question is: on trying to delete the end() element nothing would've happened to the structure of map m as end refers to one past the real end element, so what really triggered that segmentation fault as the memory structure still holds same as before deletion.


问:
Confuse in Binary Search when to use left < right ; left <= right ; and few more
I've difficulty in understanding when to use:

```<code>while (left < right ) {
}
</code>```

vs when to use:

```<code>while (left <= right ) {
}
</code>```

Also while setting left and right boundaries sometimes we use:

```<code>left = mid
</code>```

and sometime we use

```<code>left = mid + 1;
</code>```

similarly

```<code>right = mid; vs
right = mid - 1;
</code>```

Is there any fundamental I am missing in knowledge of Binary search ?

答:
The basic idea is to search and find the element:

```<code>public static int indexOf(int[] array, int target) {
   int lo = 0, hi = a.length - 1;
   while (lo <= hi) {
      // Key is in a[lo..hi] or may be it is not present.
      int mid = lo + (hi - lo) / 2;
      if      (target < a[mid]) hi = mid - 1;
      else if (target > a[mid]) lo = mid + 1;
      else return mid;
   }
   return -1;
}
</code>```

We can also use mid = (lo + hi) >>> 1 to compute the mid but using (lo+hi)/2 may cause overflow. Now the confusion part:

We use while (lo <= hi) if we are returning the match from inside
the loop. We use while (lo < hi) when we want to exit the loop
first and then use the result of lo or hi to return the match.

This is also a good intro for binary search use cases: https://leetcode.com/discuss/general-discussion/786126/Python-Powerful-Ultimate-Binary-Search-Template.-Solved-many-problems

Body:
I've difficulty in understanding when to use:

while (left < right ) {
}

vs when to use:

while (left <= right ) {
}

Also while setting left and right boundaries sometimes we use:

left = mid

and sometime we use

left = mid + 1;

similarly

right = mid; vs
right = mid - 1;

Is there any fundamental I am missing in knowledge of Binary search ?

Body:
The basic idea is to search and find the element:

public static int indexOf(int[] array, int target) {
   int lo = 0, hi = a.length - 1;
   while (lo <= hi) {
      // Key is in a[lo..hi] or may be it is not present.
      int mid = lo + (hi - lo) / 2;
      if      (target < a[mid]) hi = mid - 1;
      else if (target > a[mid]) lo = mid + 1;
      else return mid;
   }
   return -1;
}

We can also use mid = (lo + hi) >>> 1 to compute the mid but using (lo+hi)/2 may cause overflow. Now the confusion part:

We use while (lo <= hi) if we are returning the match from inside
the loop. We use while (lo < hi) when we want to exit the loop
first and then use the result of lo or hi to return the match.

This is also a good intro for binary search use cases: https://leetcode.com/discuss/general-discussion/786126/Python-Powerful-Ultimate-Binary-Search-Template.-Solved-many-problems


问:
How to center my asp.NET panels?
I've got panels containing tables to organize textboxes/labels, and I'd like to center them, but I can't figure out what attribute to use. I've tried to justify them in the design view, and horizontalalign:center in html, but to no avail. What's the best way to center panels containing tables?</p>

答:
Apply the following CSS rule for your panel (surrounding div would work):</p>

```<code>.centerPanel
{
  margin 0 auto;
}
</code>```

Title: How to center my asp.NET panels?

Body:
Apply the following CSS rule for your panel (surrounding div would work):

.centerPanel
{
  margin 0 auto;
}


问:
Set dynamic style for Checkbox in Ant Design
Is it possible to set tick container's style backgroundColor and borderColor in Checkbox dynamically from JSX?

I can do it with CSS/LESS, but I need to set specific color based on data from API.

Example:

.

答:
You just styled it, something like</p>

```<code>    <Checkbox
       style={{
           backgroundColor: data.backgroundColor,
           borderColor : data.borderColor
       }}
    />
</code>```

Body:
You just styled it, something like

    <Checkbox
       style={{
           backgroundColor: data.backgroundColor,
           borderColor : data.borderColor
       }}
    />


问:
CodeIgniter 4, helper function not working
I've tried to autoload the helper function. I've added the helper file in autoload.php and called the function in the view file, but it's not working.

app/Config/autoload.php

```<code>$psr4 = ['Config'      => APPPATH . 'Config',
         APP_NAMESPACE => APPPATH,
         'App'         => APPPATH,
         'Helpers'     => APPPATH . 'Helpers/MY_helper'];
</code>```

app/Helpers/My_helper.php

```<code><?php  if(!defined('BASEPATH')) exit('No direct script access allowed');

   function chicking_helper(){
       return 'welcome to helper function';
   }
</code>```

app/Views/welcome_message.php

```<code><h1>Welcome to CodeIgniter </h1>
<p class="version">version <?= CodeIgniter\CodeIgniter::CI_VERSION ?></p>

<?php
chicking_helper();
?>
</code>```

app/Controllers/BaseController

```<code>class BaseController extends Controller
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['url', 'file'];
</code>```

答:
I solved like this:
On your app/Config/autoload.php autoload array optional include the helper source. For attention every _helper is a suffix of each helper filemane.
So on app/Controllers/BaseController just add your prefix helper name: e.g: chicking_helper.php

class BaseController extends Controller
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['form', 'html', 'chicking',];
.....
}
```

Body:
I've tried to autoload the helper function. I've added the helper file in autoload.php and called the function in the view file, but it's not working.

app/Config/autoload.php

$psr4 = ['Config'      => APPPATH . 'Config',
         APP_NAMESPACE => APPPATH,
         'App'         => APPPATH,
         'Helpers'     => APPPATH . 'Helpers/MY_helper'];

app/Helpers/My_helper.php

<?php  if(!defined('BASEPATH')) exit('No direct script access allowed');

   function chicking_helper(){
       return 'welcome to helper function';
   }

app/Views/welcome_message.php

Welcome to CodeIgniter

version <?= CodeIgniter\CodeIgniter::CI_VERSION ?>

<?php
chicking_helper();
?>

app/Controllers/BaseController

class BaseController extends Controller
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['url', 'file'];


问:
Hide header in stack navigator React navigation
I'm trying to switch screens using both stack and tab navigator.

```<code>const MainNavigation = StackNavigator({
      otp: { screen: OTPlogin },
      otpverify: { screen: OTPverification},
      userVerified: {
        screen: TabNavigator({
          List: { screen: List },
          Settings: { screen: Settings }
        }),
      },
    });
</code>```

In this case stack navigator is used first and then tab navigator. I want to hide the headers from stack navigator. Which is not working properly when I use navigation options like::

```<code>navigationOptions: { header: { visible: false } }
</code>```

i'm trying this code on first two components which are using in stacknavigator.
if i use this line then getting some error like:

答:
You can hide header like this:</p>

```<code><Stack.Screen name="Login" component={Login} options={{headerShown: false}}  />
</code>```

Body:
I'm trying to switch screens using both stack and tab navigator.

const MainNavigation = StackNavigator({
      otp: { screen: OTPlogin },
      otpverify: { screen: OTPverification},
      userVerified: {
        screen: TabNavigator({
          List: { screen: List },
          Settings: { screen: Settings }
        }),
      },
    });

In this case stack navigator is used first and then tab navigator. I want to hide the headers from stack navigator. Which is not working properly when I use navigation options like::

navigationOptions: { header: { visible: false } }

i'm trying this code on first two components which are using in stacknavigator.
if i use this line then getting some error like:

Body:
You can hide header like this:

<Stack.Screen name="Login" component={Login} options={{headerShown: false}}  />


问:
Equivalent LINQ to SQL query
Can anyone help me with the equivalent LINQ query for the SQL below?
I am new to LINQ

```<code>Select * From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.ModifiedAt)from Students_History SH1
group by SH1.StudentId)
</code>```

This is what I have tried

```<code>var q =
    from h in Students_History
    where h.Active=1
    group h by h.StudentId into g
    select new
    {
        StudentID = g.Key,
        LatestModified = g.Max (x => x.ModifiedAt)
    }
</code>```

This linq query does not give me the right result and somehow the active=1  is ignored

I have about dozen fields in my Students_History table and I want all those fields not just studentId and ModifiedAt.

答:
Try this:</p>

```<code>var q =
    from hg in Students_History
    group hg by hg.StudentId into g
    join h in Students_History on g.Key equals h.StudentId
    where h.Active == 1 && h.ModifiedAt == g.Max(x => x.ModifiedAt)
    select new
    {
        StudentID = h.StudentId,
        LatestModified = h.ModifiedAt
    }
</code>```

Title: Equivalent LINQ to SQL query

Body:
Can anyone help me with the equivalent LINQ query for the SQL below?
I am new to LINQ

Select * From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.ModifiedAt)from Students_History SH1
group by SH1.StudentId)

This is what I have tried

var q =
    from h in Students_History
    where h.Active=1
    group h by h.StudentId into g
    select new
    {
        StudentID = g.Key,
        LatestModified = g.Max (x => x.ModifiedAt)
    }

This linq query does not give me the right result and somehow the active=1  is ignored

I have about dozen fields in my Students_History table and I want all those fields not just studentId and ModifiedAt.

Body:
Try this:

var q =
    from hg in Students_History
    group hg by hg.StudentId into g
    join h in Students_History on g.Key equals h.StudentId
    where h.Active == 1 && h.ModifiedAt == g.Max(x => x.ModifiedAt)
    select new
    {
        StudentID = h.StudentId,
        LatestModified = h.ModifiedAt
    }


问:
Significant drop in performance after migrating from UIWebView to WKWebView
The project I'm working on was using Xamarin Forms (3.4.0.x) Cross Platform, so obviously the iOS app had the UIWebView built in.

We decided to migrate to WKWebView, which required the Xamarin Forms 4.4 update so we proceeded to do that then added [assembly: ExportRenderer(typeof(WebView), typeof(Xamarin.Forms.Platform.iOS.WkWebViewRenderer))] to the AssemblyInfo.cs in our iOS app, like it says to do here. https://github.com/xamarin/Xamarin.Forms/pull/3346

Now I think that's all I need to do completely migrate to WK, but I have noticed that the app has slowed down significantly, taking ~5x as long to load a page, and on top of that, this loading icon stays on the screen even after the page is done loading

My questions are:
Did I migrate correctly, or are there any steps I'm missing/did wrong? Has anyone run into this loading icon problem before? Please ask me to clarify if I'm leaving information out, I'm new to Xamarin Forms so I'm not sure how to ask the best questions, and this is a big project I'm being introduced to. I have been told there is no custom iOS WebView Renderer though, so everything is done using the default WebView.

Thanks!

答:
There's an easier solution that just went public from the Xamarin team. All you need to do is update the Forms Nuget, Visual Studio, and Xamarin.iOS, and then:

... go to your iOS project, open the project properties and add this flag in the additional mtouch arguments field: --optimize=experimental-xforms-product-type.


问:
Axios get request getting cors issue
i'm trying to get some data from some endpoint.

I can't share the url of endpoint here but problem with cors.

when i'm using postman everything is ok.

But when make get request from my react app via axios i'm getting this error:

```<code>Refused to set unsafe header "origin"
Access to XMLHttpRequest at 'http://some.com/products.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

here is my request:

```<code>const baseUrl = "http://some.com/products.json"
const axiosConfig = {
  withCredentials: true,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  }
};

      axios
      .get(baseUrl, axiosConfig)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error)
      });
</code>```

i tried many things but i can't figure out with this.

答:
No 'Access-Control-Allow-Origin' header is present on the requested resource

As your error states, perhaps the problem will be solved if you specify the header like this.

```<code>headers: {
      'Access-Control-Allow-Origin': '*',
    }
</code>```

Similar issue was reported on github.

Getting 'Cross-Origin Request Blocked' on a GET request #853
  https://github.com/axios/axios/issues/853

Title: Axios get request getting cors issue

Body:
i'm trying to get some data from some endpoint.

I can't share the url of endpoint here but problem with cors.

when i'm using postman everything is ok.

But when make get request from my react app via axios i'm getting this error:

Refused to set unsafe header "origin"
Access to XMLHttpRequest at 'http://some.com/products.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

here is my request:

const baseUrl = "http://some.com/products.json"
const axiosConfig = {
  withCredentials: true,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  }
};

      axios
      .get(baseUrl, axiosConfig)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error)
      });

i tried many things but i can't figure out with this.

Body:
No 'Access-Control-Allow-Origin' header is present on the requested resource

As your error states, perhaps the problem will be solved if you specify the header like this.

headers: {
      'Access-Control-Allow-Origin': '*',
    }

Similar issue was reported on github.

Getting 'Cross-Origin Request Blocked' on a GET request #853
  https://github.com/axios/axios/issues/853


问:
PHP array key sum value if exist in loop with dynamic value
I create of Tree (Bill of Materials) from SQL and i'm make calculation of product. I have few if in if and if in if etc. I want to display sumamry of all individual part number with total quantitny which i'm calculating dynamicly. So, before loop and function if. i'm created three variables:

```<code>$TablicaMiH = array();
$TablicaBo = array();
$TablicaAss = array();
</code>```

when I meet the conditions, which depend on the if function, each of them performs operations of adding to the array. this is:

```<code>$TablicaMiH += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];
</code>```

or

```<code>$TablicaBo += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];
</code>```

or

```<code>$TablicaAssy += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];
</code>```

The commands execute correctly as needed, but they do not add the sum value from the $ multipler variable to me, they only do individual PartNumbers and take the last value from the $ multipler variable

here is the result of what was received from the script:

```<code>Tablica MiH:
Array ( [333/E8093] => 2 [332/F2592] => 3 [332/F3144] => 9 [332/F3147] => 21 [332/F2684] => 8 [333/D1641] => 12 [333/D1202] => 22 [332/F2588] => 1 [333/E7883] => 1 [333/E8131] => 1 )

Tablica BO:
Array ( [826/10381] => 12 [331/30854] => 7 [332/F3213] => 4 [123/06090] => 84 [1315/0307Z] => 1 [823/10874] => 1 [333/E7939] => 4 [813/10186] => 2 [332/H3476] => 3 [32/920300] => 11 [332/F3282] => 1 [32/926051] => 1 )

Tablica Ass:
Array ( [2th] => 1 [3TH] => 1 [4th] => 1 [5th] => 1 [6th] => 1 [7th] => 1 [8th] => 1 [9th] => 1 [10Th] => 1 [IN_1TH] => 1 )
</code>```

and result what i need to have:

```<code>$TablicaMiH
332/F2588||5
332/F2592||10
332/F2684||9
332/F3144||27
332/F3147||38
333/D1202||40
333/D1641||16
333/E7883||1
333/E8093||12
333/E8131||1

Tablica BO:
123/06090||85
1315/0307Z||1
32/920300||11
32/926051||1
331/30854||20
332/f3213||29
332/F3282||1
332/H3476||3
333/E7939||4
813/10186||3
823/10874||1
826/10381||13

Tablica Ass:
10Th||1
1TH||1
2TH||1
3TH||1
4th||1
5th||1
6th||1
7th||1
8th||1
9th||1
IN_1TH||1
</code>```

I Hope you understand me what i mean, and you can help me, thank you

Example to understand my problem:

```<code><?php

$exampleArraY = array(
            "PartNumber1" => 1,
            "PartNumber2" => 1,
            "PartNumber3" => 1,
            "PartNumber4" => 1,
            "PartNumber5" => 1,
            "PartNumber6" => 1,
            );

$value = "PartNumber1";
$value2 = "PartNumber2";
$value3 = "PartNumber3";
$value4 = "PartNumber4";
$value5 = "PartNumber5";
$value6 = "PartNumber6";
$value7 = "PartNumber7";

$multipler = 1;

if(in_array($value, $exampleArraY)){
    $exampleArraY[$value][1] += $multipler;
}else {
    $exampleArraY += [$value => $multipler];
}
if(in_array($value2, $exampleArraY)){
    $exampleArraY[$value2][1] += $multipler;
}else {
    $exampleArraY += [$value2 => $multipler];
}
if(in_array($value3, $exampleArraY)){
    $exampleArraY[$value3][1] += $multipler;
}else {
    $exampleArraY += [$value3 => $multipler];
}
if(in_array($value4, $exampleArraY)){
    $exampleArraY[$value4][1] += $multipler;
}else {
    $exampleArraY += [$value4 => $multipler];
}
if(in_array($value5, $exampleArraY)){
    $exampleArraY[$value5][1] += $multipler;
}else {
    $exampleArraY += [$value5 => $multipler];
}
if(in_array($value6, $exampleArraY)){
    $exampleArraY[$value6][1] += $multipler;
}else {
    $exampleArraY += [$value6 => $multipler];
}
if(in_array($value7, $exampleArraY)){
    $exampleArraY[$value7][1] += $multipler;
}else {
    $exampleArraY += [$value7 => $multipler];
}

print_r($exampleArraY);

?>
</code>```

Result:

```<code>Array ( [PartNumber1] => 1 [PartNumber2] => 1 [PartNumber3] => 1 [PartNumber4] => 1 [PartNumber5] => 1 [PartNumber6] => 1 )
</code>```

Desired Result:

```<code>Array ( [PartNumber1] => 2 [PartNumber2] => 2 [PartNumber3] => 2 [PartNumber4] => 2 [PartNumber5] => 2 [PartNumber6] => 2  [PartNumber7] => 1 )
</code>```

答:
The problem like i explained was in construction of arrays. Here is my solution to your problem:

```<code><?php
$exampleArraY = array(
            "PartNumber1" => 1,
            "PartNumber2" => 1,
            "PartNumber3" => 1,
            "PartNumber4" => 1,
            "PartNumber5" => 1,
            "PartNumber6" => 1,
            );

$values = array(
    "value" => "PartNumber1",
    "value2" => "PartNumber2",
    "value3" => "PartNumber3",
    "value4" => "PartNumber4",
    "value5" => "PartNumber5",
    "value6" => "PartNumber6",
    "value7" => "PartNumber7");

$multipler = 1;

foreach($values as $key => $item){
    if(isset($exampleArraY[$item])){
        echo $exampleArraY[$item] += $multipler;
    }else {
        $exampleArraY[$item] = $multipler;
    }

}
</code>```

Output:

```<code>array(7) {
  ["PartNumber1"]=>int(2)
  ["PartNumber2"]=>int(2)
  ["PartNumber3"]=>int(2)
  ["PartNumber4"]=>int(2)
  ["PartNumber5"]=>int(2)
  ["PartNumber6"]=>int(2)
  ["PartNumber7"]=>int(1)
}
</code>```

Body:
I create of Tree (Bill of Materials) from SQL and i'm make calculation of product. I have few if in if and if in if etc. I want to display sumamry of all individual part number with total quantitny which i'm calculating dynamicly. So, before loop and function if. i'm created three variables:

$TablicaMiH = array();
$TablicaBo = array();
$TablicaAss = array();

when I meet the conditions, which depend on the if function, each of them performs operations of adding to the array. this is:

$TablicaMiH += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];

or

$TablicaBo += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];

or

$TablicaAssy += [$SqlCheckAssyResultShowQ['PartNumber'] => $multipler];

The commands execute correctly as needed, but they do not add the sum value from the $ multipler variable to me, they only do individual PartNumbers and take the last value from the $ multipler variable

here is the result of what was received from the script:

Tablica MiH:
Array ( [333/E8093] => 2 [332/F2592] => 3 [332/F3144] => 9 [332/F3147] => 21 [332/F2684] => 8 [333/D1641] => 12 [333/D1202] => 22 [332/F2588] => 1 [333/E7883] => 1 [333/E8131] => 1 )

Tablica BO:
Array ( [826/10381] => 12 [331/30854] => 7 [332/F3213] => 4 [123/06090] => 84 [1315/0307Z] => 1 [823/10874] => 1 [333/E7939] => 4 [813/10186] => 2 [332/H3476] => 3 [32/920300] => 11 [332/F3282] => 1 [32/926051] => 1 )

Tablica Ass:
Array ( [2th] => 1 [3TH] => 1 [4th] => 1 [5th] => 1 [6th] => 1 [7th] => 1 [8th] => 1 [9th] => 1 [10Th] => 1 [IN_1TH] => 1 )

and result what i need to have:

$TablicaMiH
332/F2588||5
332/F2592||10
332/F2684||9
332/F3144||27
332/F3147||38
333/D1202||40
333/D1641||16
333/E7883||1
333/E8093||12
333/E8131||1

Tablica BO:
123/06090||85
1315/0307Z||1
32/920300||11
32/926051||1
331/30854||20
332/f3213||29
332/F3282||1
332/H3476||3
333/E7939||4
813/10186||3
823/10874||1
826/10381||13

Tablica Ass:
10Th||1
1TH||1
2TH||1
3TH||1
4th||1
5th||1
6th||1
7th||1
8th||1
9th||1
IN_1TH||1

I Hope you understand me what i mean, and you can help me, thank you

Example to understand my problem:

<?php

$exampleArraY = array(
            "PartNumber1" => 1,
            "PartNumber2" => 1,
            "PartNumber3" => 1,
            "PartNumber4" => 1,
            "PartNumber5" => 1,
            "PartNumber6" => 1,
            );

$value = "PartNumber1";
$value2 = "PartNumber2";
$value3 = "PartNumber3";
$value4 = "PartNumber4";
$value5 = "PartNumber5";
$value6 = "PartNumber6";
$value7 = "PartNumber7";

$multipler = 1;

if(in_array($value, $exampleArraY)){
    $exampleArraY[$value][1] += $multipler;
}else {
    $exampleArraY += [$value => $multipler];
}
if(in_array($value2, $exampleArraY)){
    $exampleArraY[$value2][1] += $multipler;
}else {
    $exampleArraY += [$value2 => $multipler];
}
if(in_array($value3, $exampleArraY)){
    $exampleArraY[$value3][1] += $multipler;
}else {
    $exampleArraY += [$value3 => $multipler];
}
if(in_array($value4, $exampleArraY)){
    $exampleArraY[$value4][1] += $multipler;
}else {
    $exampleArraY += [$value4 => $multipler];
}
if(in_array($value5, $exampleArraY)){
    $exampleArraY[$value5][1] += $multipler;
}else {
    $exampleArraY += [$value5 => $multipler];
}
if(in_array($value6, $exampleArraY)){
    $exampleArraY[$value6][1] += $multipler;
}else {
    $exampleArraY += [$value6 => $multipler];
}
if(in_array($value7, $exampleArraY)){
    $exampleArraY[$value7][1] += $multipler;
}else {
    $exampleArraY += [$value7 => $multipler];
}

print_r($exampleArraY);

?>

Result:

Array ( [PartNumber1] => 1 [PartNumber2] => 1 [PartNumber3] => 1 [PartNumber4] => 1 [PartNumber5] => 1 [PartNumber6] => 1 )

Desired Result:

Array ( [PartNumber1] => 2 [PartNumber2] => 2 [PartNumber3] => 2 [PartNumber4] => 2 [PartNumber5] => 2 [PartNumber6] => 2  [PartNumber7] => 1 )

Body:
The problem like i explained was in construction of arrays. Here is my solution to your problem:

<?php
$exampleArraY = array(
            "PartNumber1" => 1,
            "PartNumber2" => 1,
            "PartNumber3" => 1,
            "PartNumber4" => 1,
            "PartNumber5" => 1,
            "PartNumber6" => 1,
            );

$values = array(
    "value" => "PartNumber1",
    "value2" => "PartNumber2",
    "value3" => "PartNumber3",
    "value4" => "PartNumber4",
    "value5" => "PartNumber5",
    "value6" => "PartNumber6",
    "value7" => "PartNumber7");

$multipler = 1;

foreach($values as $key => $item){
    if(isset($exampleArraY[$item])){
        echo $exampleArraY[$item] += $multipler;
    }else {
        $exampleArraY[$item] = $multipler;
    }

}

Output:

array(7) {
  ["PartNumber1"]=>int(2)
  ["PartNumber2"]=>int(2)
  ["PartNumber3"]=>int(2)
  ["PartNumber4"]=>int(2)
  ["PartNumber5"]=>int(2)
  ["PartNumber6"]=>int(2)
  ["PartNumber7"]=>int(1)
}


问:
MFC: How do you print contents of a CRichEditView?
I have a simple task where I need to print the contents of a CRichEditView.  No scaling needed, No print range, just print contents.   Keeping it simple, I tried adding this to the message map:

```<code>ON_COMMAND(ID_FILE_PRINT, &CRichEditView::OnFilePrint)
</code>```

And implementing the virtual function:

```<code>BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  return DoPreparePrinting(pInfo);
}
</code>```

But when it printed (this is what was actually to be printed):

```<code>BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  return DoPreparePrinting(pInfo);
}
</code>```

I only got half of the 'r' on return "eturn DoPreparePrinting(pInfo);".  So it seems it must have to do with margins or something that the CRichEditView doesn't handle itself?

What am I missing?

TIA!!

EDIT:

I tried changing it to

```<code>BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  // note a MM_TWIPS is 1/1440 of an inch.

  // create 1/2" margin which most printers support
  CSize sizepaper = GetPaperSize();
  CRect rectmargins(720, 720, sizepaper.cx - 720, sizepaper.cy - 720);

  // Need to set the margins when printing from CRichEditView
  SetMargins(rectmargins);

  // per SetMargins API reference, call wrapchanged
  if (m_nWordWrap==WrapToTargetDevice) {
    WrapChanged();
  }

  return DoPreparePrinting(pInfo);
}
</code>```

But now it just spits out tons of blank pieces of paper.  I also tried it within the virtual function OnPrint(CDC* pDC, CPrintInfo* pInfo) prior to calling the base class.  Same result, so deleted OnPrint() (not using it).

EDIT:

So I took that sample above from the GetPaperSize() documentation.  But it was wrong.  It works using this (which the documentation for SetPaperSize() uses).

```<code>BOOL CMyRichView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
{
  // note a MM_TWIPS is 1/1440 of an inch.

  // Need to set the margins when printing from CRichEditView
  SetMargins(CRect(720, 720, 720, 720));

  // per SetMargins API reference, call wrapchanged
  if (m_nWordWrap==WrapToTargetDevice) {
    WrapChanged();
  }

  return __super::OnPrint(pDC, pInfo);
}
</code>```

答:
The answer is:</p>

```<code>ON_COMMAND(ID_FILE_PRINT, &CRichEditView::OnFilePrint)

BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  return DoPreparePrinting(pInfo);
}

BOOL CMyRichView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
{
  // note a MM_TWIPS is 1/1440 of an inch.

  // Need to set the margins when printing from CRichEditView
  SetMargins(CRect(720, 720, 720, 720));

  // per SetMargins API reference, call wrapchanged
  if (m_nWordWrap==WrapToTargetDevice) {
    WrapChanged();
  }

  return __super::OnPrint(pDC, pInfo);
}
</code>```

Body:
I have a simple task where I need to print the contents of a CRichEditView.  No scaling needed, No print range, just print contents.   Keeping it simple, I tried adding this to the message map:

ON_COMMAND(ID_FILE_PRINT, &CRichEditView::OnFilePrint)

And implementing the virtual function:

BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  return DoPreparePrinting(pInfo);
}

But when it printed (this is what was actually to be printed):

BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  return DoPreparePrinting(pInfo);
}

I only got half of the 'r' on return "eturn DoPreparePrinting(pInfo);".  So it seems it must have to do with margins or something that the CRichEditView doesn't handle itself?

What am I missing?

TIA!!

EDIT:

I tried changing it to

BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  // note a MM_TWIPS is 1/1440 of an inch.

  // create 1/2" margin which most printers support
  CSize sizepaper = GetPaperSize();
  CRect rectmargins(720, 720, sizepaper.cx - 720, sizepaper.cy - 720);

  // Need to set the margins when printing from CRichEditView
  SetMargins(rectmargins);

  // per SetMargins API reference, call wrapchanged
  if (m_nWordWrap==WrapToTargetDevice) {
    WrapChanged();
  }

  return DoPreparePrinting(pInfo);
}

But now it just spits out tons of blank pieces of paper.  I also tried it within the virtual function OnPrint(CDC* pDC, CPrintInfo* pInfo) prior to calling the base class.  Same result, so deleted OnPrint() (not using it).

EDIT:

So I took that sample above from the GetPaperSize() documentation.  But it was wrong.  It works using this (which the documentation for SetPaperSize() uses).

BOOL CMyRichView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
{
  // note a MM_TWIPS is 1/1440 of an inch.

  // Need to set the margins when printing from CRichEditView
  SetMargins(CRect(720, 720, 720, 720));

  // per SetMargins API reference, call wrapchanged
  if (m_nWordWrap==WrapToTargetDevice) {
    WrapChanged();
  }

  return __super::OnPrint(pDC, pInfo);
}

Body:
The answer is:

ON_COMMAND(ID_FILE_PRINT, &CRichEditView::OnFilePrint)

BOOL CMyRichView::OnPreparePrinting(CPrintInfo* pInfo)
{
  return DoPreparePrinting(pInfo);
}

BOOL CMyRichView::OnPrint(CDC* pDC, CPrintInfo* pInfo)
{
  // note a MM_TWIPS is 1/1440 of an inch.

  // Need to set the margins when printing from CRichEditView
  SetMargins(CRect(720, 720, 720, 720));

  // per SetMargins API reference, call wrapchanged
  if (m_nWordWrap==WrapToTargetDevice) {
    WrapChanged();
  }

  return __super::OnPrint(pDC, pInfo);
}


答:
```<code>ls -lt | grep ^d | sed -e '1,10d' |  awk '{sub(/.* /, ""); print }' | xargs rm -rf
</code>```

Explanation:

list all contents of current directory in chronological order (most recent files first)

filter out all the directories

ignore the 10 first lines / directories

use awk to extract the file names from the remaining 'ls -l' output

remove the files

Title: Linux - Save only recent 10 folders and delete the rest

Body:
I have a folder that contains versions of my application, each time I upload a new version a new sub-folder is created for it, the sub-folder name is the current timestamp, here is a printout of the main folder used (ls -l |grep ^d):

drwxrwxr-x 7 root root 4096 2011-03-31 16:18 20110331161649
drwxrwxr-x 7 root root 4096 2011-03-31 16:21 20110331161914
drwxrwxr-x 7 root root 4096 2011-03-31 16:53 20110331165035
drwxrwxr-x 7 root root 4096 2011-03-31 16:59 20110331165712
drwxrwxr-x 7 root root 4096 2011-04-03 20:18 20110403201607
drwxrwxr-x 7 root root 4096 2011-04-03 20:38 20110403203613
drwxrwxr-x 7 root root 4096 2011-04-04 14:39 20110405143725
drwxrwxr-x 7 root root 4096 2011-04-06 15:24 20110406151805
drwxrwxr-x 7 root root 4096 2011-04-06 15:36 20110406153157
drwxrwxr-x 7 root root 4096 2011-04-06 16:02 20110406155913
drwxrwxr-x 7 root root 4096 2011-04-10 21:10 20110410210928
drwxrwxr-x 7 root root 4096 2011-04-10 21:50 20110410214939
drwxrwxr-x 7 root root 4096 2011-04-10 22:15 20110410221414
drwxrwxr-x 7 root root 4096 2011-04-11 22:19 20110411221810
drwxrwxr-x 7 root root 4096 2011-05-01 21:30 20110501212953
drwxrwxr-x 7 root root 4096 2011-05-01 23:02 20110501230121
drwxrwxr-x 7 root root 4096 2011-05-03 21:57 20110503215252
drwxrwxr-x 7 root root 4096 2011-05-06 16:17 20110506161546
drwxrwxr-x 7 root root 4096 2011-05-11 10:00 20110511095709
drwxrwxr-x 7 root root 4096 2011-05-11 10:13 20110511100938
drwxrwxr-x 7 root root 4096 2011-05-12 14:34 20110512143143
drwxrwxr-x 7 root root 4096 2011-05-13 22:13 20110513220824
drwxrwxr-x 7 root root 4096 2011-05-14 22:26 20110514222548
drwxrwxr-x 7 root root 4096 2011-05-14 23:03 20110514230258

I'm looking for a command that will leave the last 10 versions (sub-folders) and deletes the rest.

Any thoughts?

Body:
ls -lt | grep ^d | sed -e '1,10d' |  awk '{sub(/.* /, ""); print }' | xargs rm -rf

Explanation:

list all contents of current directory in chronological order (most recent files first)

filter out all the directories

ignore the 10 first lines / directories

use awk to extract the file names from the remaining 'ls -l' output

remove the files


问:
Best approach in implementing both phone and email auth in firebase for a single use?
I am developing a flutter application I want my user to login using both email and phone.
My intention is to first register the user using phone no and allow the user to add an email address and password and the user should be able to login using them and also via phone no and the password used for email auth.
What is the best way to do this?</p>

答:
For both phone and Email based authentication using firebase is a good idea, as it supports both phone authentication and email authentication.

best way to use both is to create multiple auth pages
1) for accepting phone number and verifying it
2) for accepting email and setting up a password then verification by email.

then on the next screen set up a login method (use either email or phone number for authentication)


问:
Connect-AzAccount Powershell on-prem
I am new to Azure and I've successfully installed PowerShell on my macOS. Now I want to run get-azvm command and stop/delete a vm from on-prem (not cloud shell).

First thing I did from Terminal:
1. PWSH to launch PowerShell
2. Connect-AzAccount, browser opens to authenticate and I get an error:

Connect-AzAccount xx: Device authentication is required.
Trace ID: xx
Correlation ID: xx
+ CategoryInfo          : CloseError: (:) [Connect-AzAccount], AadAuthenticationFailedException

I continue with az login command. Result:
You have logged in. Now let us find all the subscriptions to which you have access...

{
}

I run: get-azvm and get another error:
get-azvm : No subscription found in the context.  Please ensure that the credentials you provided are authorized to access an Azure subscription, then run Connect-AzAccount to login.
At line:1 char:1

Please, what am I doing wrong? Do I need to register my on-prem machine somewhere?

Thanks for the help.

答:
As mentioned in above comment - you might have conditional access policies enabled on your Azure AD so you might want to check it out and confirm.
Secondly, if that's not the case - try running commands below before you access your azure resources

```<code>Add-AzAccount
Get-AzSubscription -SubscriptionId "your_azure_subscription_id" | Select-AzSubscription
$vm = Get-AzVM -ResourceGroupName "your_vm_resource_group_name" -Name "your_vm_name"
</code>```

Hope it helps?

Title: Connect-AzAccount Powershell on-prem

Body:
As mentioned in above comment - you might have conditional access policies enabled on your Azure AD so you might want to check it out and confirm.
Secondly, if that's not the case - try running commands below before you access your azure resources

Add-AzAccount
Get-AzSubscription -SubscriptionId "your_azure_subscription_id" | Select-AzSubscription
$vm = Get-AzVM -ResourceGroupName "your_vm_resource_group_name" -Name "your_vm_name"

Hope it helps?


问:
I have two classes that need to reference each other in the same cpp file, but the first one won't recognize objects of the second class type
The compiler gives me: "the variable has incomplete type rotation2d"</p>

```<code>class translation2d
{
    public:
       double x;
       double y;

        translation2d()
        {
            x=0;
            y=0;
        }
    translation2d rotateBy(rotation2d rotation) //issue here
    {
        translation2d copy=*this;
        copy=translation2d(x*rotation.cosM()-y*rotation.sinM(), x*rotation.sinM() + y*rotation.cosM());
        return copy;
    }
};
double kEpsilon = 0.000000009;

class translation2d;
class rotation2d
{

    public:
       double cosAngle;
       double sinAngle;

    public:
        rotation2d()
        {
            cosAngle=1;
            sinAngle=0;
        }

        rotation2d(translation2d& direction, bool norm)
        {
            cosAngle=direction.x;
            sinAngle=direction.y;
            if(norm)
                normalize();
        }

    double cosM()
    {
        return cosAngle;
    }
    double sinM()
    {
        return sinAngle;
    }
    double tanM()
    {
        if(abs(cosAngle)<kEpsilon)
        {
            if(sinAngle>=0.0)
                return std::numeric_limits<double>::infinity();
            else
                return -1*std::numeric_limits<double>::infinity();
        }
        return sinAngle/cosAngle;
    }
}
</code>```

答:
To resolve circular dependencies in C++, forward declarations are invented for.

Somehow OP tried it but in a wrong way.

So, if

class translation2d needs class rotation2d

and

class rotation2d needs class translation2d

the second one has to be forward declared before the first.

```<code>struct rotation2d; // forward declaration -> incomplete type

struct translation2d {
  void doSomethingWith(rotation2d rot);
};

struct rotation2d {
  void doSomethingWith(translation2d trans);
};
</code>```

Demo on Compiler Explorer

A forward declaration makes an incomplete type.
Incomplete types are restricted concerning what can be done with them.

Neither the size nor the contents of an incomplete type is known.
Hence, the compiler denies everything where this would be needed, e.g.

allocation of storage (i.e. makeing a variable or member variable of it)

access to contents (i.e. read/write member variables or call member functions).

It is allowed to use incomplete types for

pointers and references (with any qualification)

parameters of function declarations.

I must admit that I was not aware of the latter but found:

SO: Incomplete types as function parameters and return values

for my enlightment.

Please, note that parameters of function declarations may be incomplete but not parameters of function definitions. Hence, the second part of the fix is to make functions non- inline if incomplete types are needed in them.

```<code>struct rotation2d; // forward declaration -> incomplete type

struct translation2d {
  void doSomethingWith(rotation2d rot);
};

struct rotation2d {
  void doSomethingWith(translation2d trans)
  {
    trans; // will be processed somehow
  }
};

// now both types are complete

void translation2d::doSomethingWith(rotation2d rot)
{
  rot; // will be processed somehow
}
</code>```

Demo on Compiler Explorer

The fixed and completed sample code of OP:

```<code>#include <iostream>
#include <limits>
#include <cmath>

class rotation2d; // forward declaration

class translation2d
{
    public:
       double x;
       double y;

        translation2d()
        {
            x=0;
            y=0;
        }
        translation2d(double x, double y): x(x), y(y) { }

    translation2d rotateBy(rotation2d rotation); //issue here fixed
};
double kEpsilon = 0.000000009;

class rotation2d
{

    public:
       double cosAngle;
       double sinAngle;

    public:
        rotation2d()
        {
            cosAngle=1;
            sinAngle=0;
        }

        rotation2d(const translation2d& direction, bool norm)
        {
            cosAngle=direction.x;
            sinAngle=direction.y;
            if(norm)
                normalize();
        }

    double cosM()
    {
        return cosAngle;
    }
    double sinM()
    {
        return sinAngle;
    }
    double tanM()
    {
        if(abs(cosAngle)<kEpsilon)
        {
            if(sinAngle>=0.0)
                return std::numeric_limits<double>::infinity();
            else
                return -1*std::numeric_limits<double>::infinity();
        }
        return sinAngle/cosAngle;
    }

    void normalize()
    {
        const double len = std::sqrt(cosAngle * cosAngle + sinAngle * sinAngle);
        cosAngle /= len; sinAngle /= len;
    }
};

// both types complete now -> circular dependency resolved

translation2d translation2d::rotateBy(rotation2d rotation)
{
    translation2d copy=*this;
    copy=translation2d(x*rotation.cosM()-y*rotation.sinM(), x*rotation.sinM() + y*rotation.cosM());
    return copy;
}

int main()
{
    translation2d t(1.0, 2.0);
    rotation2d r(translation2d(0.0, 1.0), false);
    translation2d tR = t.rotateBy(r);
    std::cout << "tR: (" << tR.x << ", " << tR.y << ")\n";
}
</code>```

Output:

tR: (-2, 1)
```

Live Demo on coliru

Body:
The compiler gives me: "the variable has incomplete type rotation2d"

class translation2d
{
    public:
       double x;
       double y;

        translation2d()
        {
            x=0;
            y=0;
        }
    translation2d rotateBy(rotation2d rotation) //issue here
    {
        translation2d copy=*this;
        copy=translation2d(x*rotation.cosM()-y*rotation.sinM(), x*rotation.sinM() + y*rotation.cosM());
        return copy;
    }
};
double kEpsilon = 0.000000009;

class translation2d;
class rotation2d
{

    public:
       double cosAngle;
       double sinAngle;

    public:
        rotation2d()
        {
            cosAngle=1;
            sinAngle=0;
        }

        rotation2d(translation2d& direction, bool norm)
        {
            cosAngle=direction.x;
            sinAngle=direction.y;
            if(norm)
                normalize();
        }

    double cosM()
    {
        return cosAngle;
    }
    double sinM()
    {
        return sinAngle;
    }
    double tanM()
    {
        if(abs(cosAngle)<kEpsilon)
        {
            if(sinAngle>=0.0)
                return std::numeric_limits<double>::infinity();
            else
                return -1*std::numeric_limits<double>::infinity();
        }
        return sinAngle/cosAngle;
    }
}

Body:
To resolve circular dependencies in C++, forward declarations are invented for.

Somehow OP tried it but in a wrong way.

So, if

class translation2d needs class rotation2d

and

class rotation2d needs class translation2d

the second one has to be forward declared before the first.

struct rotation2d; // forward declaration -> incomplete type

struct translation2d {
  void doSomethingWith(rotation2d rot);
};

struct rotation2d {
  void doSomethingWith(translation2d trans);
};

Demo on Compiler Explorer

A forward declaration makes an incomplete type.
Incomplete types are restricted concerning what can be done with them.

Neither the size nor the contents of an incomplete type is known.
Hence, the compiler denies everything where this would be needed, e.g.

allocation of storage (i.e. makeing a variable or member variable of it)

access to contents (i.e. read/write member variables or call member functions).

It is allowed to use incomplete types for

pointers and references (with any qualification)

parameters of function declarations.

I must admit that I was not aware of the latter but found:

SO: Incomplete types as function parameters and return values

for my enlightment.

Please, note that parameters of function declarations may be incomplete but not parameters of function definitions. Hence, the second part of the fix is to make functions non- inline if incomplete types are needed in them.

struct rotation2d; // forward declaration -> incomplete type

struct translation2d {
  void doSomethingWith(rotation2d rot);
};

struct rotation2d {
  void doSomethingWith(translation2d trans)
  {
    trans; // will be processed somehow
  }
};

// now both types are complete

void translation2d::doSomethingWith(rotation2d rot)
{
  rot; // will be processed somehow
}

Demo on Compiler Explorer

The fixed and completed sample code of OP:

#include <iostream>
#include <limits>
#include <cmath>

class rotation2d; // forward declaration

class translation2d
{
    public:
       double x;
       double y;

        translation2d()
        {
            x=0;
            y=0;
        }
        translation2d(double x, double y): x(x), y(y) { }

    translation2d rotateBy(rotation2d rotation); //issue here fixed
};
double kEpsilon = 0.000000009;

class rotation2d
{

    public:
       double cosAngle;
       double sinAngle;

    public:
        rotation2d()
        {
            cosAngle=1;
            sinAngle=0;
        }

        rotation2d(const translation2d& direction, bool norm)
        {
            cosAngle=direction.x;
            sinAngle=direction.y;
            if(norm)
                normalize();
        }

    double cosM()
    {
        return cosAngle;
    }
    double sinM()
    {
        return sinAngle;
    }
    double tanM()
    {
        if(abs(cosAngle)<kEpsilon)
        {
            if(sinAngle>=0.0)
                return std::numeric_limits<double>::infinity();
            else
                return -1*std::numeric_limits<double>::infinity();
        }
        return sinAngle/cosAngle;
    }

    void normalize()
    {
        const double len = std::sqrt(cosAngle * cosAngle + sinAngle * sinAngle);
        cosAngle /= len; sinAngle /= len;
    }
};

// both types complete now -> circular dependency resolved

translation2d translation2d::rotateBy(rotation2d rotation)
{
    translation2d copy=*this;
    copy=translation2d(x*rotation.cosM()-y*rotation.sinM(), x*rotation.sinM() + y*rotation.cosM());
    return copy;
}

int main()
{
    translation2d t(1.0, 2.0);
    rotation2d r(translation2d(0.0, 1.0), false);
    translation2d tR = t.rotateBy(r);
    std::cout << "tR: (" << tR.x << ", " << tR.y << ")\n";
}

Output:

tR: (-2, 1)

Live Demo on coliru


问:
parsing an image in order to get the information out of it
Several days i mused about the three-folded job of

a. getting
b. parsing
c. storing a number of pages.

Two days ago i  thought that getting the pages would be the major-task. No this isnt the case - i guess that the parser-job would be a heroic task. Each of the pages  that are intended to be parsed is a png-image.

So the question is - after getting all them. How to parse them!? This seems to be the issue. Guess that there are some perl-modules out there - that can help in doing this...

Well - i think that this job only can be done with some OCR embedded! Question: is there a perl-module that can be use here to support this task:

BTW: see the result-pages.

BTW;: and as i thought i can find all 790 resultpages within a certain range between
Id= 0 and Id= 100000 i thought, that i can go the way with a loop:

http://www.foundationfinder.ch/ShowDetails.php?Id=11233&InterfaceLanguage=&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=927&InterfaceLanguage=1&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=949&InterfaceLanguage=1&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=20011&InterfaceLanguage=1&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=10579&InterfaceLanguage=1&Type=Html

i thought i can go the Perl-Way but i am not very very sure:
I was trying to use LWP::UserAgent on the same URLs [see below]
with different query arguments, and i am wondering if LWP::UserAgent provides a
way for us to loop through the query arguments? I am not sure that LWP::UserAgent has a method for us to do that. Well - i sometimes heard that it is easier to use Mechanize. But is it really easier!?

But - to be frank; The first task " GETTING all the pages is not very difficult - if we compare this task with the parsing... How can this be done!?

Any ideas - suggestions -

look forward to hear from you...

zero

答:
I would suggest using Image::OCR::Tesseract

I've had good experience with Tesseract in the past using C++.

See this for further info.


问:
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.

答:
This is due to the version incompatibility between angular/cdk, angular/material and angular/core. Most specifically, Angular Core version 8.x.x is not compatible with Angular CDK version 9.x.x.

Solution:

Delete node_modules folder

In package.json, change the version of cdk and material. Save.

npm install.

In my case, I was having:

```<code>"@angular/cdk": "~9.0.0",
"@angular/core": "~8.2.14",
"@angular/material": "~9.0.0"
</code>```

and I changed this to:

```<code>"@angular/cdk": "~8.2.3",
"@angular/core": "~8.2.14",
"@angular/material": "~8.2.3"
</code>```

and deleted node_modules and did npm install. Fixed.

Body:
This is due to the version incompatibility between angular/cdk, angular/material and angular/core. Most specifically, Angular Core version 8.x.x is not compatible with Angular CDK version 9.x.x.

Solution:

Delete node_modules folder

In package.json, change the version of cdk and material. Save.

npm install.

In my case, I was having:

"@angular/cdk": "~9.0.0",
"@angular/core": "~8.2.14",
"@angular/material": "~9.0.0"

and I changed this to:

"@angular/cdk": "~8.2.3",
"@angular/core": "~8.2.14",
"@angular/material": "~8.2.3"

and deleted node_modules and did npm install. Fixed.


问:
Input number then keeps reading int. values until the sum of those integer equals or become greater than the value that was input in the beginning
I had tried this logic , but it is not working, please help me to resolve the issue

```<code>import java.util.Scanner ;  // USing  Scanner class

class Check {

public static void main(String args[]){

 //Intializing & Declaring Variables
 int num ;
 int sum ;
 int x = 1;
 // Creating object of Scanner Class
 Scanner input  = new Scanner(System.in);

 while(x <= 100){

     System.out.println("Enter an Integer"); //Prompt
     num = input.nextInt(); // Taking input from User

     sum = num + num ;
     x = sum;

 } // while lop ends

} // mainMethod ends
</code>```

}// Class ends

答:
First, prompt the user for a target value (instead of hardcoding 100). Second, add num to sum (not num to num). Third, I would display the running total. Fourth, please prefer meaningful variable names. Something like,

```<code>Scanner input = new Scanner(System.in);
// Prompt the user for a "target value"
System.out.println("Enter target value");
int target = input.nextInt();
// Initialize a running sum
int sum = 0;
// While the sum is less than or equal to the target value
while (sum <= target) {
    // Prompt the user for a value
    System.out.println("Enter an Integer");
    // Add the value to the sum
    sum += input.nextInt();
    // Display the current sum
    System.out.println("The current sum is " + sum);
}
// Indicate loop has completed
System.out.println("Done.");
</code>```

Body:
I had tried this logic , but it is not working, please help me to resolve the issue

import java.util.Scanner ;  // USing  Scanner class

class Check {

public static void main(String args[]){

 //Intializing & Declaring Variables
 int num ;
 int sum ;
 int x = 1;
 // Creating object of Scanner Class
 Scanner input  = new Scanner(System.in);

 while(x <= 100){

     System.out.println("Enter an Integer"); //Prompt
     num = input.nextInt(); // Taking input from User

     sum = num + num ;
     x = sum;

 } // while lop ends

} // mainMethod ends

}// Class ends

Body:
First, prompt the user for a target value (instead of hardcoding 100). Second, add num to sum (not num to num). Third, I would display the running total. Fourth, please prefer meaningful variable names. Something like,

Scanner input = new Scanner(System.in);
// Prompt the user for a "target value"
System.out.println("Enter target value");
int target = input.nextInt();
// Initialize a running sum
int sum = 0;
// While the sum is less than or equal to the target value
while (sum <= target) {
    // Prompt the user for a value
    System.out.println("Enter an Integer");
    // Add the value to the sum
    sum += input.nextInt();
    // Display the current sum
    System.out.println("The current sum is " + sum);
}
// Indicate loop has completed
System.out.println("Done.");


问:
Incorrect column name after loading csv
After loading csv, the name of the first column changed from "communityname" to "Êcommunityname".

```<code>crime=read.csv('crimedata.csv',check.names=FALSE)
</code>```

Any one knows why and how to solve it?

答: Try to correct your Encoding. Try to use fileEncoding to correct it!

Title: Incorrect column name after loading csv

Body:
After loading csv, the name of the first column changed from "communityname" to "Êcommunityname".

crime=read.csv('crimedata.csv',check.names=FALSE)

Any one knows why and how to solve it?


问:
Roles and permissions in php
I am making a menu, but I want to limit it to only some users with a specific permission can see it.

the query:

SELECT idpermission,userid FROM user_permissions WHERE userid = "U001"

Result: User U001 has 3 permissions stored.

```<code>idpermission,userid
 IDP001,U001
 IDP002,U001
 IDP003,U001
</code>```

I have 3 tables (users,permissions and user_permissions), in user_permissions I store each permission of each user

```<code>Example:

Table

user | permission | user_permissions

result:

user: u001,carlos,carlos@...

permissions: IDP001 = book | IDP002 = create_book | IDP003 = edit_book | IDP004 = user | IDP005 = edit_user...

user_permissions:
IDP001,U001
IDP002,U001
IDP003,U001
IDP001,U002
IDP003,U002...
</code>```

when i call the query

```<code>while($sqlRow=$sqlPermissions->fetch(PDO::FETCH_ASSOC))
 {
   if ($sqlRow['idpermission'] == 'IDP001' || $sqlRow['idpermission'] == 'IDP002' || $sqlRow['idpermission'] == 'IDP003')
     {
        echo "user menu ";
     }
 }
</code>```

but the result that appears to me is 3:

user menu user menu user menu

You should only show me one, making only a comparison if you have such permission shows but shows nothing.

What I want to reach is that the user can have many permissions for different items on the menu, such as view, edit, create, delete, each one is a permission, and each item (user menu, books menu) is another permission.

答:
I'm not sure if your question was lacking information, or I may have missed a point.

Your example uses U001 as a user id. The while loop seems to be correct in showing three "user menu" echos as U001 has permission to view IDP001, IDP002, and IDP003.

If however, you try viewing U002, considering U002 does not have permission to view IDP002, and IDP003. You won't see three echos.

However, I'd approach this a little differently than you did.
Maybe this might make things simpler for you.

```<code>$userPermissions = array(
    'book'        => 1,
    'create_book' => 0,
    'edit_book'   => 0
);

$menuItems = array(
    'book' => 'View Booking',
    'create_book' => 'Create Booking',
    'edit_book' => 'Edit Booking'
);

foreach ($menuItems as $key => $value) {

    if ($userPermissions[$key]) {
        echo $value;
    }

}
</code>```

In the above scenario, you can store $userPermissions as serialized in your database. Then, once it's needed, get it from the Database and using the foreach loop create a menu by echoing the values of $menuItems if the user has permission to view it.

Your table (from my example) may look something like this:

```<code>id | user_id | permissions
</code>```

Title: Roles and permissions in php

Body:
I am making a menu, but I want to limit it to only some users with a specific permission can see it.

the query:

SELECT idpermission,userid FROM user_permissions WHERE userid = "U001"

Result: User U001 has 3 permissions stored.

idpermission,userid
 IDP001,U001
 IDP002,U001
 IDP003,U001

I have 3 tables (users,permissions and user_permissions), in user_permissions I store each permission of each user

Example:

Table

user | permission | user_permissions

result:

user: u001,carlos,carlos@...

permissions: IDP001 = book | IDP002 = create_book | IDP003 = edit_book | IDP004 = user | IDP005 = edit_user...

user_permissions:
IDP001,U001
IDP002,U001
IDP003,U001
IDP001,U002
IDP003,U002...

when i call the query

while($sqlRow=$sqlPermissions->fetch(PDO::FETCH_ASSOC))
 {
   if ($sqlRow['idpermission'] == 'IDP001' || $sqlRow['idpermission'] == 'IDP002' || $sqlRow['idpermission'] == 'IDP003')
     {
        echo "user menu ";
     }
 }

but the result that appears to me is 3:

user menu user menu user menu

You should only show me one, making only a comparison if you have such permission shows but shows nothing.

What I want to reach is that the user can have many permissions for different items on the menu, such as view, edit, create, delete, each one is a permission, and each item (user menu, books menu) is another permission.

Body:
I'm not sure if your question was lacking information, or I may have missed a point.

Your example uses U001 as a user id. The while loop seems to be correct in showing three "user menu" echos as U001 has permission to view IDP001, IDP002, and IDP003.

If however, you try viewing U002, considering U002 does not have permission to view IDP002, and IDP003. You won't see three echos.

However, I'd approach this a little differently than you did.
Maybe this might make things simpler for you.

$userPermissions = array(
    'book'        => 1,
    'create_book' => 0,
    'edit_book'   => 0
);

$menuItems = array(
    'book' => 'View Booking',
    'create_book' => 'Create Booking',
    'edit_book' => 'Edit Booking'
);

foreach ($menuItems as $key => $value) {

    if ($userPermissions[$key]) {
        echo $value;
    }

}

In the above scenario, you can store $userPermissions as serialized in your database. Then, once it's needed, get it from the Database and using the foreach loop create a menu by echoing the values of $menuItems if the user has permission to view it.

Your table (from my example) may look something like this:

id | user_id | permissions


问:
How to add a force to an object in Unity not relative to the objects rotation but relative to the game coordinates?
I am creating a 2d game and would like to have an object move up. I don't want it to move up relative to the object, but up relative to the game coordinates. I am currently using Rigidbody.AddForce(). Does anyone know of a way to do this?</p>

答: figured it out. Instead of doing Rigidbody.AddForce(transform.up);, use Rigidbody.AddForce(new Vector2(x, y));</p>