问:
Realm - reactive extension RxJava2
I am using Realm in conjunction with RxJava2. Must the instance of Realm be closed by programmer or is closed automatically?

I have a problems with this chain:

```<code> return Observable.merge(
      getEvents
        .toObservable()
      ,
      mChangeEventsNotification
        .flatMapMaybe(notification ->
          getEvents
          .firstElement()
        )
    )
</code>```

Realm throws java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.

Implementation of getEvents is same as getList().

I watched implementation RealmObservableFactory.

Can operator firstElement close Realm Instance for first Observable of merge operator?

Realm instance is shared between all Observers within one thread?

It looks as bug of Realm version 4.3.3. When I downgrade to version 4.1.0 everythink is ok. Maybe problem of ref count.

答:
To answer your question, I'll ask the source code for the Rx integration:

```<code>public Flowable<RealmResults<E>> asFlowable() {
    if (realm instanceof Realm) {
        return realm.configuration.getRxFactory().from((Realm) realm, this);
</code>```

Where RxObservableFactoryis by default RealmObservableFactory, which does:

```<code>@Override
public <E> Flowable<RealmResults<E>> from(final Realm realm, final RealmResults<E> results) {
    final RealmConfiguration realmConfig = realm.getConfiguration();
    return Flowable.create(new FlowableOnSubscribe<RealmResults<E>>() {
        @Override
        public void subscribe(final FlowableEmitter<RealmResults<E>> emitter) throws Exception {
            // Gets instance to make sure that the Realm is open for as long as the
            // Observable is subscribed to it.
            final Realm observableRealm = Realm.getInstance(realmConfig);
            resultsRefs.get().acquireReference(results);
            final RealmChangeListener<RealmResults<E>> listener = new RealmChangeListener<RealmResults<E>>() {
                @Override
                public void onChange(RealmResults<E> results) {
                    if (!emitter.isCancelled()) {
                        emitter.onNext(results);
                    }
                }
            };
            results.addChangeListener(listener);

            // Cleanup when stream is disposed
            emitter.setDisposable(Disposables.fromRunnable(new Runnable() {
                @Override
                public void run() {
                    results.removeChangeListener(listener);
                    observableRealm.close();
                    resultsRefs.get().releaseReference(results);
                }
            }));

            // Emit current value immediately
            emitter.onNext(results);

        }
    }, BACK_PRESSURE_STRATEGY);
}
</code>```

In which case what happens is that the Realm instance of the RealmResults you called asFlowable() on is used to obtain its RealmConfiguration, and the ref count is increased on the thread where the Flowable is created (which is the UI thread or a handler thread).

This means that even the following scenario would work:

```<code>public Flowable<List<MyObject>> getList() {
    try(Realm realm = Realm.getDefaultInstance()) {
        return realm.where(MyObject.class)
                    .findAllAsync()
                    .asFlowable()
                    .filter(RealmResults::isLoaded);
    } // auto-close
}
</code>```

And the Realm associated with this Flowable would stay open for as long as you don't unsubscribe from the Flowable as well.

To answer your question, yes, you do need to close the Realm instance you obtain the RealmResults from somewhere.

Title: Realm - reactive extension RxJava2

Body:
I am using Realm in conjunction with RxJava2. Must the instance of Realm be closed by programmer or is closed automatically?

I have a problems with this chain:

 return Observable.merge(
      getEvents
        .toObservable()
      ,
      mChangeEventsNotification
        .flatMapMaybe(notification ->
          getEvents
          .firstElement()
        )
    )

Realm throws java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.

Implementation of getEvents is same as getList().

I watched implementation RealmObservableFactory.

Can operator firstElement close Realm Instance for first Observable of merge operator?

Realm instance is shared between all Observers within one thread?

It looks as bug of Realm version 4.3.3. When I downgrade to version 4.1.0 everythink is ok. Maybe problem of ref count.

Body:
To answer your question, I'll ask the source code for the Rx integration:

public Flowable<RealmResults<E>> asFlowable() {
    if (realm instanceof Realm) {
        return realm.configuration.getRxFactory().from((Realm) realm, this);

Where RxObservableFactoryis by default RealmObservableFactory, which does:

@Override
public <E> Flowable<RealmResults<E>> from(final Realm realm, final RealmResults<E> results) {
    final RealmConfiguration realmConfig = realm.getConfiguration();
    return Flowable.create(new FlowableOnSubscribe<RealmResults<E>>() {
        @Override
        public void subscribe(final FlowableEmitter<RealmResults<E>> emitter) throws Exception {
            // Gets instance to make sure that the Realm is open for as long as the
            // Observable is subscribed to it.
            final Realm observableRealm = Realm.getInstance(realmConfig);
            resultsRefs.get().acquireReference(results);
            final RealmChangeListener<RealmResults<E>> listener = new RealmChangeListener<RealmResults<E>>() {
                @Override
                public void onChange(RealmResults<E> results) {
                    if (!emitter.isCancelled()) {
                        emitter.onNext(results);
                    }
                }
            };
            results.addChangeListener(listener);

            // Cleanup when stream is disposed
            emitter.setDisposable(Disposables.fromRunnable(new Runnable() {
                @Override
                public void run() {
                    results.removeChangeListener(listener);
                    observableRealm.close();
                    resultsRefs.get().releaseReference(results);
                }
            }));

            // Emit current value immediately
            emitter.onNext(results);

        }
    }, BACK_PRESSURE_STRATEGY);
}

In which case what happens is that the Realm instance of the RealmResults you called asFlowable() on is used to obtain its RealmConfiguration, and the ref count is increased on the thread where the Flowable is created (which is the UI thread or a handler thread).

This means that even the following scenario would work:

public Flowable<List<MyObject>> getList() {
    try(Realm realm = Realm.getDefaultInstance()) {
        return realm.where(MyObject.class)
                    .findAllAsync()
                    .asFlowable()
                    .filter(RealmResults::isLoaded);
    } // auto-close
}

And the Realm associated with this Flowable would stay open for as long as you don't unsubscribe from the Flowable as well.

To answer your question, yes, you do need to close the Realm instance you obtain the RealmResults from somewhere.


来源: stackexchange

问:
Is it possible to use GCC without Cygwin or MinGW?
GCC is a very well respected multi-language compiler (from what I've gathered). One thing I've not been able to definitively find out is: Is it possible to use GCC on windows without anything extra like Cygwin or MinGW?

I've learned that if you use GCC on Cygwin, there is a dependency on a DLL. If you use GCC with MinGW, you eliminate that dependency but you still must have MinGW to use GCC.

Is it possible to build GCC and utilize it by itself, completely native to Windows? Like Microsoft's Compiler?  After reading around, my guess is no. But I'd still like more info, if possible.

If not, why does GCC require environments like Cygwin or MinGW? I understand this now. It is because GCC requires a Unix/POSIX environment. Why it does, it still beyond me.

I did find this and it helps but doesn't really answer my question: Why does GCC-Windows depend on cygwin?

To refine my question, I guess what I'm trying  to understand why GCC can't stand on it's own -- Where I have just "GCC.exe".

答:
Linaro used to provide that long time ago, a GCC that runs naively on Windows without MinGW or Cygwin. I am currently using that GCC 4.9 on a Windows 10 PC to compile UEFI and it is working like charm.

https://releases.linaro.org/archive/14.09/components/toolchain/binaries/gcc-linaro-arm-none-eabi-4.9-2014.09_win32.zip

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How can I reference System.Data.Odbc for dotnet core in my project?
I have a project I'm deploying in Linux using dotnet core and I need to read a .mdb file. I want to use ODBC for it but even as I see that System.Data.Odbc has already been ported here and that the documentation for the library is out here I can't find the nuget for it.

How can I download this library? Do I have to download the corefx project and build it by myself from here? When is this library going to be released? Is there another way to read my mdb file?

答:
```<code>dotnet add package System.Data.Odbc --version 4.5.0-preview1-25915-02 --source https://dotnet.myget.org/F/dotnet-core/api/v3/index.json
</code>```


问:
View or Download image on click of image/filename
I followed a couple of tutorial about batch image upload using laravel but they all talk about displaying images as thumbnails which it is not what i want to achieve. I want to view stored image filenames and also a user be able to download the saved images.

Controller

```<code>class Controller_Name extends Controller {
//index
  public function index() {
    $variable = Model::all();
    return view('your.view', compact('variable'));
  }

//uploading images to DB
public function upload() {
    // getting all of the post data
    //$file = array('image' => Request::file('image'));
    $file = Input::file('images');

    //counting all selected images
    $file_count = count($file);
    $uploadcount = 0;

    // setting up rules
    foreach($file as $file) {
      $rules = array('form' => 'required');

      // doing the validation, passing post data, rules and the messages
      $validator = Validator::make(array ('form'=>$file), $rules);

      if ($validator->passes())
      {
        $destinationPath = 'path/to/upload/folder';
        $filename = $file->getClientOriginalName();
        $upload_success = $file->move($destinationPath, $filename);
        $uploadcount ++;

        $extension = $file->getClientOriginalExtension();
        $entry = new Model;
        $entry->format = $file->getClientMimeType();
        $entry->filename = $filename;
        $entry->save();
      }
    }

    if($uploadcount == $file_count)
    {
      Session::flash('message', 'Uploaded successfully');
    }
    else {
      return Redirect::to('your/view')->withInput()->withErrors($validator);
    }
  }
</code>```

I have a table that display image names stored in db and now i want a corresponding image to show or be downloaded when a user clicks on it or view button.

```<code><!-->displaying images filenames in tabular view<--><thead>
        <tr>
        <th >#</th>
        <th >Image Name</th>
        <th >File Format</th>
        <th>Action</th>
        </tr>
    </thead><tbody>

      @foreach( $variable_declared_in_download_function as $some_random_variable)                                                     <tr>
    <td class="text-left">{{ asset('img/') }}></td>                                    <td class="text-left">{{ $jan2017->format}}</td>
    <td>buttons here (delete/download)</td>
    </tr>                                                                   @endforeach
    </tbody>
    </table>
        @endsection
</code>```

Anyone out there who can help?
Thanks in advance

答:
Well this is close enough to what i wanted to achieve. I included a download button which picks the selected image and downloads it.
Here is the remodeled Controller

```<code>    Use DB;
class controller_name extends controller{
//index function goes here

//created a new function to download images for viewing
public function download(){
$download=DB::table('table_name')->get();
return view('path.to.view',compact('download'));
</code>```

And the route i used is this

```<code>Route::get('download', 'Controller_Name@download');
</code>```

In my index.blade.php

this is how i changed the structuring

```<code>   <td>
     <a href="path/to/where/your/app/stores/uploaded/images{{$download->filename}}"
download = "{{$download->filename}}">
<button type="button" class="btn btn-primary">View                                     </button>
</a>
</code>```

with that, i can now download and view the image saved in the DB.

Thanks to https://www.youtube.com/watch?v=AlnackyPJPY

Body:
I followed a couple of tutorial about batch image upload using laravel but they all talk about displaying images as thumbnails which it is not what i want to achieve. I want to view stored image filenames and also a user be able to download the saved images.

Controller

class Controller_Name extends Controller {
//index
  public function index() {
    $variable = Model::all();
    return view('your.view', compact('variable'));
  }

//uploading images to DB
public function upload() {
    // getting all of the post data
    //$file = array('image' => Request::file('image'));
    $file = Input::file('images');

    //counting all selected images
    $file_count = count($file);
    $uploadcount = 0;

    // setting up rules
    foreach($file as $file) {
      $rules = array('form' => 'required');

      // doing the validation, passing post data, rules and the messages
      $validator = Validator::make(array ('form'=>$file), $rules);

      if ($validator->passes())
      {
        $destinationPath = 'path/to/upload/folder';
        $filename = $file->getClientOriginalName();
        $upload_success = $file->move($destinationPath, $filename);
        $uploadcount ++;

        $extension = $file->getClientOriginalExtension();
        $entry = new Model;
        $entry->format = $file->getClientMimeType();
        $entry->filename = $filename;
        $entry->save();
      }
    }

    if($uploadcount == $file_count)
    {
      Session::flash('message', 'Uploaded successfully');
    }
    else {
      return Redirect::to('your/view')->withInput()->withErrors($validator);
    }
  }

I have a table that display image names stored in db and now i want a corresponding image to show or be downloaded when a user clicks on it or view button.

        #
        Image Name
        File Format
        Action

      @foreach( $variable_declared_in_download_function as $some_random_variable)

    {{ asset('img/') }}>	                                    {{ $jan2017->format}}
    buttons here (delete/download)

                                                                   @endforeach

        @endsection

Anyone out there who can help?
Thanks in advance

Body:
Well this is close enough to what i wanted to achieve. I included a download button which picks the selected image and downloads it.
Here is the remodeled Controller

    Use DB;
class controller_name extends controller{
//index function goes here

//created a new function to download images for viewing
public function download(){
$download=DB::table('table_name')->get();
return view('path.to.view',compact('download'));

And the route i used is this

Route::get('download', 'Controller_Name@download');

In my index.blade.php

this is how i changed the structuring

   <td>
     <a href="path/to/where/your/app/stores/uploaded/images{{$download->filename}}"
download = "{{$download->filename}}">
<button type="button" class="btn btn-primary">View                                     </button>
</a>

with that, i can now download and view the image saved in the DB.

Thanks to https://www.youtube.com/watch?v=AlnackyPJPY


问:
Chrome is allowing insecure pages via WebDriver
Using Chrome 62 with Chrome Driver 2.33 and WebDriver 3.6.0, Chrome allows pages to load with bad SSL certificates -- it says "Not Secure" in the URL bar when the page opens, but the page is loaded none-the-less. If I access the page manually, then I get the expected 'blocker page'.

However, I want Chrome to reject the page via WebDriver just like Chrome does to human users.

Unfortunately I cannot find anyone else reporting this same problem (just lots of people reporting the exact opposite problem -- i.e. they want to allow insecure connections via WebDriver, but Chrome keeps blocking them!).

Is there a flag I can set (or prevent from being set if WebDriver is passing one to Chrome internally)?

const {Builder, Capabilities} = require('selenium-webdriver');

const driver = new Builder()
  .withCapabilities(Capabilities.chrome())
  .build();

driver.get('https://localhost/'); // Uses self-signed certificate.
```

答:
By default, chromedriver accepts untrusted certificates.

To disable this feature, you'll have to exclude the switch ignore-certificate-errors:

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder()
  .withCapabilities({
    'browserName': 'chrome',
    'goog:chromeOptions': {
      'args': ['disable-infobars'],
      'excludeSwitches': ['ignore-certificate-errors'],
      'prefs': { }
    }
  }).build();

driver.get("https://self-signed.badssl.com/")
```


问:
In Ruby, is there a way to remove only 1 match in an Array easily?
In Ruby, the array subtraction or reject

```<code>>> [1,3,5,7,7] - [7]
=> [1, 3, 5]

>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]
</code>```

will remove all entries in the array.  Is there an easy to remove just 1 occurrence?

答:
While it doesn't directly answer your question, uniq might be what you want.

```<code>[1,3,5,7,7].uniq # => [1,3,5,7]
</code>```

Body:
In Ruby, the array subtraction or reject

>> [1,3,5,7,7] - [7]
=> [1, 3, 5]

>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]

will remove all entries in the array.  Is there an easy to remove just 1 occurrence?

Body:
While it doesn't directly answer your question, uniq might be what you want.

[1,3,5,7,7].uniq # => [1,3,5,7]


问:
Unpack ... with missing arguments
I'm writing a function that accepts a variable number of arguments. Moreover, I would like the user to be able to leave some of these arguments as missing.

Consider just the task of turning the ... into a list of arguments. Here is my first attempt:

```<code>f <- function(...) list(...)
</code>```

This fails:

```<code>f(1,,2)
## Error in f(1, , 2) : argument is missing, with no default
</code>```

I would like the result to be list(1, NULL, 2). (I am not worried about distinguishing f(1,,2) from f(1,NULL,2).)

Here is my second attempt:

```<code>g <- function(...)
{
    args <- match.call()
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    args[[1L]] <- quote(list)
    eval.parent(args)
}
</code>```

This works (sort of):

```<code>identical(g(1,,2), list(1, NULL, 2))
## [1] TRUE
</code>```

However, it fails when forwarding dots:

```<code>gg <- function(...) g(...)
identical(gg(1,,2), list(1,NULL,2))
## [1] FALSE
</code>```

Is there a way to achieve the same results as g, but in a way that allows forwarding dots and without using match.call()?

Edit: Issues with forwarding dots.

It's tempting to try the following:

```<code>h <- function(...)
{
    args <- substitute(list(...))
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    eval.parent(args)
}
</code>```

However, as @lionel points out, there will be issues if you try to forward ... from another function:

```<code>hh <- function(...) h(letters, ...)
local({ a <- "foo"; h(a) })
## Error in eval(expr, p) : object 'a' not found
</code>```

It seems like you either need the expand.dots functionality of match.call, or you need to use a quosure (from the rlang package).

答:
With the rlang package you have the option of ignoring empty arguments when capturing dots:

```<code>my_dots <- function(...) {
  rlang::dots_list(..., .ignore_empty = "all")
}

my_dots(1, , 2, )
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
</code>```

If you really need to translate empty arguments as NULL there is no other choice than quoting the dots and evaluating them after you've converted the missing arguments. Now if you do that with eval(substitute(alist(...)) you will get into trouble if you attempt to forward dots through several function calls. Base R provides no way of evaluating the quoted argument in their original environment.

Luckily it's easy to do by capturing the dots in quosures:

```<code>library("purrr")  # For convenient map_if()

my_dots <- function(...) {
  quos <- rlang::quos(..., .ignore_empty = "none")
  quos <- map_if(quos, rlang::quo_is_missing, function(x) NULL)
  map(quos, rlang::eval_tidy)
}

my_dots(1, , 2, )
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> NULL
#>
#> [[3]]
#> [1] 2
#>
#> [[4]]
#> NULL
</code>```

Title: Unpack ... with missing arguments

Body:
I'm writing a function that accepts a variable number of arguments. Moreover, I would like the user to be able to leave some of these arguments as missing.

Consider just the task of turning the ... into a list of arguments. Here is my first attempt:

f <- function(...) list(...)

This fails:

f(1,,2)
## Error in f(1, , 2) : argument is missing, with no default

I would like the result to be list(1, NULL, 2). (I am not worried about distinguishing f(1,,2) from f(1,NULL,2).)

Here is my second attempt:

g <- function(...)
{
    args <- match.call()
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    args[[1L]] <- quote(list)
    eval.parent(args)
}

This works (sort of):

identical(g(1,,2), list(1, NULL, 2))
## [1] TRUE

However, it fails when forwarding dots:

gg <- function(...) g(...)
identical(gg(1,,2), list(1,NULL,2))
## [1] FALSE

Is there a way to achieve the same results as g, but in a way that allows forwarding dots and without using match.call()?

Edit: Issues with forwarding dots.

It's tempting to try the following:

h <- function(...)
{
    args <- substitute(list(...))
    miss <- vapply(args, identical, NA, quote(expr=))
    args[miss] <- list(NULL)
    eval.parent(args)
}

However, as @lionel points out, there will be issues if you try to forward ... from another function:

hh <- function(...) h(letters, ...)
local({ a <- "foo"; h(a) })
## Error in eval(expr, p) : object 'a' not found

It seems like you either need the expand.dots functionality of match.call, or you need to use a quosure (from the rlang package).

Body:
With the rlang package you have the option of ignoring empty arguments when capturing dots:

my_dots <- function(...) {
  rlang::dots_list(..., .ignore_empty = "all")
}

my_dots(1, , 2, )
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2

If you really need to translate empty arguments as NULL there is no other choice than quoting the dots and evaluating them after you've converted the missing arguments. Now if you do that with eval(substitute(alist(...)) you will get into trouble if you attempt to forward dots through several function calls. Base R provides no way of evaluating the quoted argument in their original environment.

Luckily it's easy to do by capturing the dots in quosures:

library("purrr")  # For convenient map_if()

my_dots <- function(...) {
  quos <- rlang::quos(..., .ignore_empty = "none")
  quos <- map_if(quos, rlang::quo_is_missing, function(x) NULL)
  map(quos, rlang::eval_tidy)
}

my_dots(1, , 2, )
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> NULL
#>
#> [[3]]
#> [1] 2
#>
#> [[4]]
#> NULL


问:
Java Synchronized (int) is possible?
```<code>class Banco{

    int slots;
    int []av;

    public Banco(int n){
        slots = n;
        av=new int[slots];
        for(int i=0;i<slots;i++)
            av[i]=0;

    }

    public int query(int i){
            return this.av[i];

    }

    public int getSlots (){
        return this.slots;
    }

    public synchronized void credito(int i, int valor){
        av[i] += valor;
    }

    public synchronized void debito(int i, int valor){
        av[i] -= valor;
    }

    public void transferir(int valor){
        Random r = new Random();

        int a = r.nextInt(slots);
        int b = r.nextInt(slots);

        if(a<b){
            synchronized(this.query(a)){
                synchronized(this.query(b)){
                    this.credito(b,valor);
                    this.debito(b,valor);
                }
            }
        }
        else{
            a = r.nextInt(slots);
            b = r.nextInt(slots);
        }

    }
}
</code>```

This is my code, but on synchronized I get the following error I do not know why:

unexpected type
            synchronized(this.query(a))

required: reference

found:    int

error: unexpected type
                synchronized(this.query(b))

required: reference

found:    int

答: You can synchronize on an Integer but not on an int. I fail to see why you would want to synchronize on a value though. Usually you'll synchronize on an object created just for that purpose.</p>

Title: Java Synchronized (int) is possible?

Body:
class Banco{

    int slots;
    int []av;

    public Banco(int n){
        slots = n;
        av=new int[slots];
        for(int i=0;i<slots;i++)
            av[i]=0;

    }

    public int query(int i){
            return this.av[i];

    }

    public int getSlots (){
        return this.slots;
    }

    public synchronized void credito(int i, int valor){
        av[i] += valor;
    }

    public synchronized void debito(int i, int valor){
        av[i] -= valor;
    }

    public void transferir(int valor){
        Random r = new Random();

        int a = r.nextInt(slots);
        int b = r.nextInt(slots);

        if(a<b){
            synchronized(this.query(a)){
                synchronized(this.query(b)){
                    this.credito(b,valor);
                    this.debito(b,valor);
                }
            }
        }
        else{
            a = r.nextInt(slots);
            b = r.nextInt(slots);
        }

    }
}

This is my code, but on synchronized I get the following error I do not know why:

unexpected type
            synchronized(this.query(a))

required: reference

found:    int

error: unexpected type
                synchronized(this.query(b))

required: reference

found:    int


问:
docker compose: how to reference other service as localhost
I have two services - one is app and the other is db.
This is a sketch of a docker compose file:

```<code>version: "2"
services:
  company:
    container_name: company-app
    extends:
      file: ../base-config.yml
      service: company
    links:
      - company-db
    env_file: ./company.env
    extra_hosts:
     - "local.company.com:127.0.0.1"

  company-db:
    container_name: company-db
    hostname: localhost
    extends:
      file: ../base-config.yml
      service: company-db
    env_file: ../db.env
</code>```

Application service tries to connect to database on url jdbc:mysql://localhost/company_db

Which results in Communications link failure when running in docker container.

I've attached to running app container and check etc/hosts file and find next content:

```<code>root@d1a4391a83f4:/# cat etc/hosts
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
127.0.0.1   local.company.com
172.18.0.3  d1a4391a83f4
</code>```

As I understand the last entry added by docker compose is the ip by which i can reference db container, also I find out that it could be referenced by company-db domain.

Also as you see I've tried to add hostname option to company-db service, with no success.

My question is can I somehow by changing only compose configuration achieve ability to reference company-db service via same localhost url ?

答:
You can achieve this by mapping your localhost ports with containers.
For your company-db service write the following</p>

```<code>ports:
    - 3306:3306
</code>```

Body:
I have two services - one is app and the other is db.
This is a sketch of a docker compose file:

version: "2"
services:
  company:
    container_name: company-app
    extends:
      file: ../base-config.yml
      service: company
    links:
      - company-db
    env_file: ./company.env
    extra_hosts:
     - "local.company.com:127.0.0.1"

  company-db:
    container_name: company-db
    hostname: localhost
    extends:
      file: ../base-config.yml
      service: company-db
    env_file: ../db.env

Application service tries to connect to database on url jdbc:mysql://localhost/company_db

Which results in Communications link failure when running in docker container.

I've attached to running app container and check etc/hosts file and find next content:

root@d1a4391a83f4:/# cat etc/hosts
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
127.0.0.1   local.company.com
172.18.0.3  d1a4391a83f4

As I understand the last entry added by docker compose is the ip by which i can reference db container, also I find out that it could be referenced by company-db domain.

Also as you see I've tried to add hostname option to company-db service, with no success.

My question is can I somehow by changing only compose configuration achieve ability to reference company-db service via same localhost url ?

Body:
You can achieve this by mapping your localhost ports with containers.
For your company-db service write the following

ports:
    - 3306:3306


问:
CSS Flexbox 3 columns Grid (4X4 + 1 large)
I'm trying to figure out how to get this in Flexbox, but the only thing I can get is in the code snippet:

Do you have an idea to manage this CSS only (I can't really touch the structure of the HTML as it is a PHP foreach loop)?

Could using CSS grid help here?

.grid {
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
}

.photo {
  position: relative;
  flex: 0 0 calc(25% - 20px);
  margin: 10px;
  align-self: flex-start;
  overflow: hidden;
  background: black;
}

.photo:after {
  content: "";
  display: block;
  padding-top: 100%;
}

.large {
  flex: 0 0 calc(50% - 20px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="photo large"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
</div></code>```

答:
This solution uses css grid, just be mindful of its compatibility with Internet Explorer.

.grid {
  display: grid;
  grid-gap: 10px;
  width:100vw;
  height:100vh;
  grid-template: "item1 item2 large large" "item3 item4 large large"
}

.photo {
  background: black;
}
.large {
  grid-area:large;
}
.photo:nth-of-type(2){ grid-area:item1;}
.photo:nth-of-type(3){ grid-area:item2;}
.photo:nth-of-type(4){ grid-area:item3;}
.photo:nth-of-type(5){ grid-area:item4;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="photo large"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
</div></code>```

Body:
This solution uses css grid, just be mindful of its compatibility with Internet Explorer.

.grid {
  display: grid;
  grid-gap: 10px;
  width:100vw;
  height:100vh;
  grid-template: "item1 item2 large large" "item3 item4 large large"
}

.photo {
  background: black;
}
.large {
  grid-area:large;
}
.photo:nth-of-type(2){ grid-area:item1;}
.photo:nth-of-type(3){ grid-area:item2;}
.photo:nth-of-type(4){ grid-area:item3;}
.photo:nth-of-type(5){ grid-area:item4;}

<div class="grid">
  <div class="photo large"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
</div>


问:
table User has no column named USERNAME (code 1): , while compiling: INSERT INTO User(USERNAME,PASSWORD) VALUES (?,?)
Logcat

Error inserting USERNAME=raj PASSWORD=raj
      android.database.sqlite.SQLiteException: table User has no column named USERNAME (code 1): , while compiling: INSERT INTO
  User(USERNAME,PASSWORD) VALUES (?,?)

Code

```<code>package com.example.aaru.sqlapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    public static final String DBNAME = "mydatabase.db";
    public static final String TABLE = "User";
    public static final String UNAME = "USERNAME";
    public static final String PASS = "PASSWORD";
    public static final String ID = "UID";

    SQLiteDatabase db=this.getWritableDatabase();

    public DBHelper(Context context) {
        super(context, DBNAME, null, 1);
        //create database when we create DBHelper object
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //create table
        db.execSQL("create table "+TABLE+"(" + ID + " integer primary key autoincrement," + UNAME + " text," + PASS + " text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //Delete table if table is already exists
        db.execSQL("DROP TABLE IF EXISTS User");
        onCreate(sqLiteDatabase);
    }

    public long insert(String uname, String pass){
        ContentValues values = new ContentValues();
        values.put(UNAME, uname);
        values.put(PASS, pass);
        return db.insert(TABLE, null, values);
    }
}
</code>```

答:
You have multiple problems with your code.

First, your onCreate() nor onUpgrade() are not getting executed. The database file is already at version 1. You can uninstall your application to remove its old database file. When is SQLiteOpenHelper onCreate() / onUpgrade() run?

That would then trigger a NullPointerException since db is not initialized. onCreate() and onUpgrade() need to use the SQLiteDatabase passed in as parameter to the method, not a field that has not yet been initialized.

Body:
Logcat

Error inserting USERNAME=raj PASSWORD=raj
      android.database.sqlite.SQLiteException: table User has no column named USERNAME (code 1): , while compiling: INSERT INTO
  User(USERNAME,PASSWORD) VALUES (?,?)

Code

package com.example.aaru.sqlapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    public static final String DBNAME = "mydatabase.db";
    public static final String TABLE = "User";
    public static final String UNAME = "USERNAME";
    public static final String PASS = "PASSWORD";
    public static final String ID = "UID";

    SQLiteDatabase db=this.getWritableDatabase();

    public DBHelper(Context context) {
        super(context, DBNAME, null, 1);
        //create database when we create DBHelper object
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //create table
        db.execSQL("create table "+TABLE+"(" + ID + " integer primary key autoincrement," + UNAME + " text," + PASS + " text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //Delete table if table is already exists
        db.execSQL("DROP TABLE IF EXISTS User");
        onCreate(sqLiteDatabase);
    }

    public long insert(String uname, String pass){
        ContentValues values = new ContentValues();
        values.put(UNAME, uname);
        values.put(PASS, pass);
        return db.insert(TABLE, null, values);
    }
}


问:
Batch commands for rds
I have a project for my Radio Station where I copy the text within a .wsx file of what is on air and parse it to a Audio Processor in my private network for RDS Display using a wget command like

```<code>set /p TEXTO= 0<R:\40.wsx
wget -q "http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
</code>```

It works great but it won't filter if it's music or promotions.

My challenge is to be able to filter and only parse music names.

For the process I marked the Files that i don't want to show  up like commercial, or promotions to start with a "@-" without the quotes.

So the text will show like @-Promo1

My Code:

```<code>for /F "delims=" %%a in ('FINDSTR "\<@-.*"  C:\RDS\PRUEBAS\txt1.wsx') do set
"VAR=%%a"
  echo %VAR%
 if "%VAR%" == "true" (
    set /p VAR=0<C:\FILEPATH\LOS40.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%VAR%" -O NUL
) else (
    set /p TEXTO=0<C:\FILEPATH\ENVIVO.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
)
</code>```

I can't seem to find a correct way to filter it.

pls Heelpp..

答:
```<code>for /F "delims=" %%a in ('FINDSTR "\<@-.*"  C:\RDS\PRUEBAS\txt1.wsx') do set
</code>```

should be

```<code>for /F "delims=" %%a in ('FINDSTR /b "@-"  C:\RDS\PRUEBAS\txt1.wsx') do set
</code>```

to find those lines in the .wsx file that do /b begin with "@-"

If you want to find those lines that do not begin with "@-" then add /v to the /b.

The result will be a line from the file which does [not] begin with "@-" which will be placed in %%a.

If you simply assign %%a to a variable as you are doing, that variable will contain after the for the last value that was assigned to it.

If you want to execute your wget on each name, then use

```<code>for /F "delims=" %%a in ('FINDSTR /B "@-"  C:\RDS\PRUEBAS\txt1.wsx') do (
 echo %%a
)
</code>```

and between the parentheses you can execute commands using %%a as a filename.

Quite what you propose to do is obscure. I've no idea what the set/p from an unexplained file is meant to do, but be aware that any code between parentheses is subject to the delayedexpansion trap - please explain what processing you intend to apply to the filenames that do[not] match a leading @-.

You should read SO items on delayed expansion (it's documented with and without the space) to understand the problems with and solutions to processing values that are altered within a loop.

Title: Batch commands for rds

Body:
I have a project for my Radio Station where I copy the text within a .wsx file of what is on air and parse it to a Audio Processor in my private network for RDS Display using a wget command like

set /p TEXTO= 0<R:\40.wsx
wget -q "http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL

It works great but it won't filter if it's music or promotions.

My challenge is to be able to filter and only parse music names.

For the process I marked the Files that i don't want to show  up like commercial, or promotions to start with a "@-" without the quotes.

So the text will show like @-Promo1

My Code:

for /F "delims=" %%a in ('FINDSTR "\<@-.*"  C:\RDS\PRUEBAS\txt1.wsx') do set
"VAR=%%a"
  echo %VAR%
 if "%VAR%" == "true" (
    set /p VAR=0<C:\FILEPATH\LOS40.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%VAR%" -O NUL
) else (
    set /p TEXTO=0<C:\FILEPATH\ENVIVO.wsx & wget -q
"http://x.x.x.x:7380/parameter/fm/rds/rds_rt=%TEXTO%" -O NUL
)

I can't seem to find a correct way to filter it.

pls Heelpp..

Body:
for /F "delims=" %%a in ('FINDSTR "\<@-.*"  C:\RDS\PRUEBAS\txt1.wsx') do set

should be

for /F "delims=" %%a in ('FINDSTR /b "@-"  C:\RDS\PRUEBAS\txt1.wsx') do set

to find those lines in the .wsx file that do /b begin with "@-"

If you want to find those lines that do not begin with "@-" then add /v to the /b.

The result will be a line from the file which does [not] begin with "@-" which will be placed in %%a.

If you simply assign %%a to a variable as you are doing, that variable will contain after the for the last value that was assigned to it.

If you want to execute your wget on each name, then use

for /F "delims=" %%a in ('FINDSTR /B "@-"  C:\RDS\PRUEBAS\txt1.wsx') do (
 echo %%a
)

and between the parentheses you can execute commands using %%a as a filename.

Quite what you propose to do is obscure. I've no idea what the set/p from an unexplained file is meant to do, but be aware that any code between parentheses is subject to the delayedexpansion trap - please explain what processing you intend to apply to the filenames that do[not] match a leading @-.

You should read SO items on delayed expansion (it's documented with and without the space) to understand the problems with and solutions to processing values that are altered within a loop.


问:
Intraclass Correlation Coefficient in R, how to deal with NAs and not much overlap between raters and subjects
I have been trying to perform an icc (Intraclass Correlation Coefficient ) test for the agreement between raters in a k x m matrix. Where k are rows (subjects of study) and m are the raters. It is a 70 x 70 matrix, but it comes from randomised raters where each subject was assessed only ~6 times (range 2-13).

The subjects of study and raters do not have much overlap since groups are large.

That means that my matrix is full of NAs:

Subject___Rater1___Rater2___Rater3___Rater4___... Rater70

Subject1 ____ 3 _____ 1________NA_____NA ____ ...

Subject2_____NA ____5 _______NA______2 _____ ...

Subject3_____6 _____NA_______3 _______5_____ ...

...Subject70

I have tried the psych library finding 2 main problems:

First, not able to use na.rm (or similar) function. So, I don´t know how to deal with NAs

Second, I have not been able to define the type of test (ICC1, ICC2 or ICC3). Even if the manual and the help in R states the ICC types according to Shrout and Fleiss I cannot find an example or function for being sure of the type used.

This lines do not work:

Data_O<-na.omit(iccOTE)
  icc1<-icc(Data_O, na.rm=TRUE, type = c("agreement"),
      unit = c("single"), r0 = 0, conf.level = 0.95)

--------- So:
I switched to DescTools library. This helped when using the na.rm function. I tried the following code:

ICC(Data_O, type = c("ICC1k"), conf.level = 0.95, na.rm = TRUE)

I got the following error:
Error in stack.data.frame(data.frame(ratings)) :
  no vector columns were selected

I tried looking for the meaning of the error, but cannot find it. Also, I am a bit confused on how the library uses k. Where can I find information to understand if k is used in this example as (n-1) where k is calculated per case (row) [k=6] or generally according to the full matrix [k=70]? In the second case it would be totally inaccurate.

Thank you!!!

答:
There are 2 ways how to compute icc in  R. The first is the icc function from the irr package and the second is ICC from the psych package.

Concerning the definition of type of the test:

If you use ICC function, you don't need to specify anything. R will compute all forms and you will just select the right one. The output will be in this form:

```<code>Intraclass correlation coefficients
                         type  ICC   F df1 df2     p lower bound upper bound
Single_raters_absolute   ICC1 0.26 2.4   4  15 0.096       -0.10        0.83
Single_random_raters     ICC2 0.11 1.5   4  12 0.277       -0.22        0.77
Single_fixed_raters      ICC3 0.10 1.5   4  12 0.277       -0.19        0.75
Average_raters_absolute ICC1k 0.58 2.4   4  15 0.096       -0.58        0.95
Average_random_raters   ICC2k 0.34 1.5   4  12 0.277       -2.50        0.93
Average_fixed_raters    ICC3k 0.31 1.5   4  12 0.277       -1.84        0.92

 Number of subjects = 5     Number of Judges =  4
</code>```

If you use icc function, you'll get the correct type by correct setting of parameters model, type and unit. If you are not sure how to do it, I recommend you to read this article:

Koo, T. K., & Li, M. Y. (2016). A Guideline of Selecting and
Reporting Intraclass Correlation Coefficients for Reliability
Research. Journal of Chiropractic Medicine, 15(2), 155–163.
http://doi.org/10.1016/j.jcm.2016.02.012

Concerning NAs:

icc haven't worked me with high percentage of NAs too.

I managed to use ICC  with high percentage of missing values. However, ICC removes all incomplete cases by default. So in your case it will probably remove all data and gives you an error. You can set missing = F to include all cases.

However I'm not sure whether icc is good choice for data with many NAs. I have read that Krippendorff's alpha deals better with NAs. (See: Hallgren, K. A. (2012). Computing Inter-Rater Reliability for Observational Data: An Overview and Tutorial. Tutorials in Quantitative Methods for Psychology, 8(1), 23–34. http://doi.org/10.20982/tqmp.08.1.p023 or Hayes, A. F., & Krippendorff, K. (2017). Answering the Call for a Standard Reliability Measure for Coding Data, 2458(November). http://doi.org/10.1080/19312450709336664 or http://digital-activism.org/2013/05/picking-the-best-intercoder-reliability-statistic-for-your-digital-activism-content-analysis/)
You can find Krippendorff's alpha in irr package. The function is called kripp.alpha.

Body:
There are 2 ways how to compute icc in  R. The first is the icc function from the irr package and the second is ICC from the psych package.

Concerning the definition of type of the test:

If you use ICC function, you don't need to specify anything. R will compute all forms and you will just select the right one. The output will be in this form:

Intraclass correlation coefficients
                         type  ICC   F df1 df2     p lower bound upper bound
Single_raters_absolute   ICC1 0.26 2.4   4  15 0.096       -0.10        0.83
Single_random_raters     ICC2 0.11 1.5   4  12 0.277       -0.22        0.77
Single_fixed_raters      ICC3 0.10 1.5   4  12 0.277       -0.19        0.75
Average_raters_absolute ICC1k 0.58 2.4   4  15 0.096       -0.58        0.95
Average_random_raters   ICC2k 0.34 1.5   4  12 0.277       -2.50        0.93
Average_fixed_raters    ICC3k 0.31 1.5   4  12 0.277       -1.84        0.92

 Number of subjects = 5     Number of Judges =  4

If you use icc function, you'll get the correct type by correct setting of parameters model, type and unit. If you are not sure how to do it, I recommend you to read this article:

Koo, T. K., & Li, M. Y. (2016). A Guideline of Selecting and
Reporting Intraclass Correlation Coefficients for Reliability
Research. Journal of Chiropractic Medicine, 15(2), 155–163.
http://doi.org/10.1016/j.jcm.2016.02.012

Concerning NAs:

icc haven't worked me with high percentage of NAs too.

I managed to use ICC  with high percentage of missing values. However, ICC removes all incomplete cases by default. So in your case it will probably remove all data and gives you an error. You can set missing = F to include all cases.

However I'm not sure whether icc is good choice for data with many NAs. I have read that Krippendorff's alpha deals better with NAs. (See: Hallgren, K. A. (2012). Computing Inter-Rater Reliability for Observational Data: An Overview and Tutorial. Tutorials in Quantitative Methods for Psychology, 8(1), 23–34. http://doi.org/10.20982/tqmp.08.1.p023 or Hayes, A. F., & Krippendorff, K. (2017). Answering the Call for a Standard Reliability Measure for Coding Data, 2458(November). http://doi.org/10.1080/19312450709336664 or http://digital-activism.org/2013/05/picking-the-best-intercoder-reliability-statistic-for-your-digital-activism-content-analysis/)
You can find Krippendorff's alpha in irr package. The function is called kripp.alpha.


问:
selecting records from two csv files python
I have two csv files. train_all.csv :

```<code>    msno                                         is_churn
0   waLDQMmcOu2jLDaV1ddDkgCrB/jl6sD66Xzs0Vqax1Y=    1
1   QA7uiXy8vIbUSPOkCf9RwQ3FsT8jVq2OxDr8zqa7bRQ=    1
2   fGwBva6hikQmTJzrbz/2Ezjm5Cth5jZUNvXigKK2AFA=    1
3   mT5V8rEpa+8wuqi6x0DoVd3H5icMKkE9Prt49UlmK+4=    1
4   XaPhtGLk/5UvvOYHcONTwsnH97P4eGECeq+BARGItRw=    1
5   GBy8qSz16X5iYWD+3CMxv/Hm6OPSrXBYtmbnlRtknW0=    1
6   lYLh7TdkWpIoQs3i3o6mIjLH8/IEgMWP9r7OpsLX0Vo=    1
</code>```

It has 1963891 records, but only 1082190 unique records. Thats why i sorted unique msno-s with pandas.
The other csv is about 30GB, cointaining more than 900 million records with user logs.

```<code>msno    date    num_25  num_50  num_75  num_985 num_100 num_unq total_secs
rxIP2f2aN0rYNp+toI0Obt/N/FYQX8hcO1fTmmy2h34=    20150513    0   0   0   0   1   1   280.335
rxIP2f2aN0rYNp+toI0Obt/N/FYQX8hcO1fTmmy2h34=    20150709    9   1   0   0   7   11  1658.948
yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8=    20150105    3   3   0   0   68  36  17364.956
yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8=    20150306    1   0   1   1   97  27  24667.317
yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8=    20150501    3   0   0   0   38  38  9649.029
</code>```

I would like to iterate through the unique msno-s in train_all.csv and search for 5 user_log records in user_logs.csv for each msno. My code stops after about 20 minutes with only 104 records in the results.csv - desired output file with matched msno - user_logs.

```<code>import pandas as pd
import csv

reader = csv.reader(open('user_logs/user_logs.csv','r'))
writer = csv.writer(open('results.csv','w',newline=''))

data = pd.read_csv("train_all.csv")
unique_msnos = data["msno"].unique()

i = 0

for msno in range(len(unique_msnos)):
    counter = 0

    for row in reader:
        results_row = row

        if unique_msnos[msno] == row[0]:
            writer.writerow(results_row)
            counter+=1
            if counter == 5:
                i+=1
                break
            else:
                continue
        else:
            continue
</code>```

答:
Probable reason why it stops without finding everything:

the inner loop advances the position in the file every time it reads a row.

when you break out of the inner loop the the file counter/pointer/position(?) remains at the place it left off

during the next iteration of the outer loop, the inner loop starts at the last file position instead of at the beginning. So it cannot find any valid msno's in the previous lines/rows of the file. You can verify this by printing the file's position (file.tell()) just before the inner loop (remember ctrl-c to break out of it.)

You can fix this by sending the file back to the beginning after the inner loop has completed (whether by StopIteration or a break) so that the inner loop can search through the whole file looking for the msno. Be prepared for a much longer wait.

```<code>with open('user_logs/user_logs.csv','r') as infile:
    reader = csv.reader(infile)
    for msno in range(len(unique_msnos)):
        counter = 0
        #print(infile.tell())
        for row in reader:
            #inner_loop_stuff...
            #inner_loop_stuff...
            #inner_loop_stuff...
        infile.seek(0)
</code>```

unique_msnos has 1.1E6 records, reader has 9E8 records.  For each record in unique_msnos you will iterate 9e8 times - that would come to 1e15-ish  iterations.  You have to be careful with nested loops.

When checking for membership you should use a set.

```<code>unique_msnos = set(unique_msnos)
</code>```

You want to keep track of the number of records you find so maybe make unique_msnos a dictionary with the value holding the count.

```<code>unique_msnos = dict.fromkeys(unique_msnos, 0)
</code>```

Then iterate over reader check for membership and adding logic to see if there are already 5:

```<code>for row in reader:
    c = unique_msnos.get(row[0], None)
    if c in (5, None):
        continue
    writer.write(row)
    unique_msnos[row[0]] += 1
    ...
</code>```

This should alleviate it somewhat - 9e8 iterations.  There are probably other optimizations.

If the msno-s are guaranteed to all be the same length you may get an incremental improvement using slicing instead of using a csv.Reader.  I really don't know how fast csv readers are but slicing is pretty fast.

Something like

```<code># unique_msnos is a dictionary
with open(open('user_logs/user_logs.csv','r') as f:
    for line in f:
        c = unique_msnos.get(line[:44], None)
        ....
</code>```

It won't reduce the iteration count but if if you get (a_small_improvement * 9e8) improvement it might be noticeable.

Looks like you are making a DataFrame then throwing it away. It may be faster to just make unique_msnos directly from the file:

```<code>unique_msnos = {}
with open("train_all.csv") as f:
    for line in f:
        _, msno, churn = line.split()
        unique_msnos[msno] = 0
</code>```

You would need to try it to see if it is faster.

You may want to make yourself some smaller files to work with while you are trying to get it to work and making optimizations. Just do it once for each file then use the small files for debuging.  Using cprofile or timeit to try and figure out where the bottlenecks are

```<code>limit = 10000  # or whatever
with open(file_path, 'r') as infile, open(small_filepath, 'w') as outfile:
    for n, line in enumerate(infile):
        outfile.write(line)
        if n == limit:
            break
</code>```

Body:
I have two csv files. train_all.csv :

    msno                                         is_churn
0   waLDQMmcOu2jLDaV1ddDkgCrB/jl6sD66Xzs0Vqax1Y=    1
1   QA7uiXy8vIbUSPOkCf9RwQ3FsT8jVq2OxDr8zqa7bRQ=    1
2   fGwBva6hikQmTJzrbz/2Ezjm5Cth5jZUNvXigKK2AFA=    1
3   mT5V8rEpa+8wuqi6x0DoVd3H5icMKkE9Prt49UlmK+4=    1
4   XaPhtGLk/5UvvOYHcONTwsnH97P4eGECeq+BARGItRw=    1
5   GBy8qSz16X5iYWD+3CMxv/Hm6OPSrXBYtmbnlRtknW0=    1
6   lYLh7TdkWpIoQs3i3o6mIjLH8/IEgMWP9r7OpsLX0Vo=    1

It has 1963891 records, but only 1082190 unique records. Thats why i sorted unique msno-s with pandas.
The other csv is about 30GB, cointaining more than 900 million records with user logs.

msno    date    num_25  num_50  num_75  num_985 num_100 num_unq total_secs
rxIP2f2aN0rYNp+toI0Obt/N/FYQX8hcO1fTmmy2h34=    20150513    0   0   0   0   1   1   280.335
rxIP2f2aN0rYNp+toI0Obt/N/FYQX8hcO1fTmmy2h34=    20150709    9   1   0   0   7   11  1658.948
yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8=    20150105    3   3   0   0   68  36  17364.956
yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8=    20150306    1   0   1   1   97  27  24667.317
yxiEWwE9VR5utpUecLxVdQ5B7NysUPfrNtGINaM2zA8=    20150501    3   0   0   0   38  38  9649.029

I would like to iterate through the unique msno-s in train_all.csv and search for 5 user_log records in user_logs.csv for each msno. My code stops after about 20 minutes with only 104 records in the results.csv - desired output file with matched msno - user_logs.

import pandas as pd
import csv

reader = csv.reader(open('user_logs/user_logs.csv','r'))
writer = csv.writer(open('results.csv','w',newline=''))

data = pd.read_csv("train_all.csv")
unique_msnos = data["msno"].unique()

i = 0

for msno in range(len(unique_msnos)):
    counter = 0

    for row in reader:
        results_row = row

        if unique_msnos[msno] == row[0]:
            writer.writerow(results_row)
            counter+=1
            if counter == 5:
                i+=1
                break
            else:
                continue
        else:
            continue

Body:
Probable reason why it stops without finding everything:

the inner loop advances the position in the file every time it reads a row.

when you break out of the inner loop the the file counter/pointer/position(?) remains at the place it left off

during the next iteration of the outer loop, the inner loop starts at the last file position instead of at the beginning. So it cannot find any valid msno's in the previous lines/rows of the file. You can verify this by printing the file's position (file.tell()) just before the inner loop (remember ctrl-c to break out of it.)

You can fix this by sending the file back to the beginning after the inner loop has completed (whether by StopIteration or a break) so that the inner loop can search through the whole file looking for the msno. Be prepared for a much longer wait.

with open('user_logs/user_logs.csv','r') as infile:
    reader = csv.reader(infile)
    for msno in range(len(unique_msnos)):
        counter = 0
        #print(infile.tell())
        for row in reader:
            #inner_loop_stuff...
            #inner_loop_stuff...
            #inner_loop_stuff...
        infile.seek(0)

unique_msnos has 1.1E6 records, reader has 9E8 records.  For each record in unique_msnos you will iterate 9e8 times - that would come to 1e15-ish  iterations.  You have to be careful with nested loops.

When checking for membership you should use a set.

unique_msnos = set(unique_msnos)

You want to keep track of the number of records you find so maybe make unique_msnos a dictionary with the value holding the count.

unique_msnos = dict.fromkeys(unique_msnos, 0)

Then iterate over reader check for membership and adding logic to see if there are already 5:

for row in reader:
    c = unique_msnos.get(row[0], None)
    if c in (5, None):
        continue
    writer.write(row)
    unique_msnos[row[0]] += 1
    ...

This should alleviate it somewhat - 9e8 iterations.  There are probably other optimizations.

If the msno-s are guaranteed to all be the same length you may get an incremental improvement using slicing instead of using a csv.Reader.  I really don't know how fast csv readers are but slicing is pretty fast.

Something like

# unique_msnos is a dictionary
with open(open('user_logs/user_logs.csv','r') as f:
    for line in f:
        c = unique_msnos.get(line[:44], None)
        ....

It won't reduce the iteration count but if if you get (a_small_improvement * 9e8) improvement it might be noticeable.

Looks like you are making a DataFrame then throwing it away. It may be faster to just make unique_msnos directly from the file:

unique_msnos = {}
with open("train_all.csv") as f:
    for line in f:
        _, msno, churn = line.split()
        unique_msnos[msno] = 0

You would need to try it to see if it is faster.

You may want to make yourself some smaller files to work with while you are trying to get it to work and making optimizations. Just do it once for each file then use the small files for debuging.  Using cprofile or timeit to try and figure out where the bottlenecks are

limit = 10000  # or whatever
with open(file_path, 'r') as infile, open(small_filepath, 'w') as outfile:
    for n, line in enumerate(infile):
        outfile.write(line)
        if n == limit:
            break


问:
how to perform nightmare on every request?
how to perform nightmare on every request?

The method below runs only once, from the second on, the script does not run. It is in an infinite load. What can it be?

Thank you

```<code>app.get('/', (req, res) => {

    nightmare
        .goto('https://site.com.br')
        .wait(() => {
            return $('#url').text() !== ''
        })
        .evaluate(() => {

            return $('#url').text()
        })
        .end()
        .then((result) => {

            res.send(result)

        })
        .catch((error) => {
            console.error('Search failed:', error);
        });

})
</code>```

答:
It runs only once because you are calling .end on your first request which ends the instance and you won't be able to use the instance for future requests.

Remove that line and it should be absolutely fine.

```<code>app.get('/', (req, res) => {

    nightmare
        .goto('https://site.com.br')
        .wait(() => {
            return $('#url').text() !== ''
        })
        .evaluate(() => {

            return $('#url').text()
        })
        .end() // <-- remove this line
        .then((result) => {

            res.send(result)

        })
        .catch((error) => {
            console.error('Search failed:', error);
        });

})
</code>```

Body:
how to perform nightmare on every request?

The method below runs only once, from the second on, the script does not run. It is in an infinite load. What can it be?

Thank you

app.get('/', (req, res) => {

    nightmare
        .goto('https://site.com.br')
        .wait(() => {
            return $('#url').text() !== ''
        })
        .evaluate(() => {

            return $('#url').text()
        })
        .end()
        .then((result) => {

            res.send(result)

        })
        .catch((error) => {
            console.error('Search failed:', error);
        });

})

Body:
It runs only once because you are calling .end on your first request which ends the instance and you won't be able to use the instance for future requests.

Remove that line and it should be absolutely fine.

app.get('/', (req, res) => {

    nightmare
        .goto('https://site.com.br')
        .wait(() => {
            return $('#url').text() !== ''
        })
        .evaluate(() => {

            return $('#url').text()
        })
        .end() // <-- remove this line
        .then((result) => {

            res.send(result)

        })
        .catch((error) => {
            console.error('Search failed:', error);
        });

})


问:
Redshift loading CSV with commas in a text field
I've been trying to load a csv file with the following row in it:

91451960_NE,-1,171717198,50075943,"MARTIN LUTHER KING, JR WAY",1,NE

Note the comma in the name. I've tried all permutations of REMOVEQUOTES, DELIMITER ',', etc... and none of them work.

I have other rows with quotes in the middle of the name, so the ESCAPE option has to be there as well.

According to other posts,
DELIMITER ',' ESCAPE REMOVEQUOTES IGNOREHEADER 1;
should work but does not. Redshift gives a "Delimiter not found" error.

Is the ESCAPE causing issues and do I have to escape the comma?

答:
I have tried loading your data using CSV as data format parameter and this worked for me. Please keep in mind that CSV cannot be used with FIXEDWIDTH, REMOVEQUOTES, or ESCAPE.

```<code>create TEMP table awscptest (a varchar(40),b int,c bigint,d bigint,e varchar(40),f int,g varchar(10));

copy awscptest from 's3://sds-dev-db-replica/test.txt'
iam_role 'arn:aws:iam::<accounID>:<IAM_role>'
delimiter as ',' EMPTYASNULL CSV NULL AS '\0';
</code>```

References: http://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-format.html
http://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html
http://docs.aws.amazon.com/redshift/latest/dg/r_COPY_command_examples.html#load-from-csv

Body:
I have tried loading your data using CSV as data format parameter and this worked for me. Please keep in mind that CSV cannot be used with FIXEDWIDTH, REMOVEQUOTES, or ESCAPE.

create TEMP table awscptest (a varchar(40),b int,c bigint,d bigint,e varchar(40),f int,g varchar(10));

copy awscptest from 's3://sds-dev-db-replica/test.txt'
iam_role 'arn:aws:iam::<accounID>:<IAM_role>'
delimiter as ',' EMPTYASNULL CSV NULL AS '\0';

References: http://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-format.html
http://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html
http://docs.aws.amazon.com/redshift/latest/dg/r_COPY_command_examples.html#load-from-csv


问:
Moving common components to separate repo
How do i move my react components to separate repo. I tried moving the files to separate repo and doing a npm install with the git url and tried importing them but they dont work.</p>

答:
If your component have a github repo it's doesnt mean that you can use it as npm package.

NPM is a module package ecosystem for javascript and it has nothing in common with github.

It 's true that most npm package has a github repo but it's two differents things.

To achieve what you want you have to first publish your componenent in npm.
Enter this command in the root directories of your component.

```<code>npm init
</code>```

this will create a package.json with informations provided by you.
Then you give your credentials (you must create an account in npm)

```<code>npm login
</code>```

And you can publish

```<code>npm publish
</code>```

Only after these few steps you can start use npm install name-of-your-package

Body:
If your component have a github repo it's doesnt mean that you can use it as npm package.

NPM is a module package ecosystem for javascript and it has nothing in common with github.

It 's true that most npm package has a github repo but it's two differents things.

To achieve what you want you have to first publish your componenent in npm.
Enter this command in the root directories of your component.

npm init

this will create a package.json with informations provided by you.
Then you give your credentials (you must create an account in npm)

npm login

And you can publish

npm publish

Only after these few steps you can start use npm install name-of-your-package


问:
I am trying to import from selenium and selenium.webdriver.support.ui I have tried many ways to get geckodriver into my usr/bin/ but it is not working
I am using python 2.7 on a mac and writing in the Terminal. I have made sure that my geckodriver is readable, writable and executable:

```<code>-rwxrwxrwx@  1 Esi  staff  3600548 31 Oct 19:55 geckodriver
</code>```

The gecko driver is currently residing in my Dropbox folder. I have used:

```<code>cd Dropbox
sudo cp geckodriver /usr/bin/
</code>```

I have then entered my password and received:

```<code>cp: /usr/bin/geckodriver: Operation not permitted
</code>```

I have also tried

```<code>export PATH=$PATH:Dropbox/geckodriver
</code>```

答:
Your geckodriver is readable, writable and executable in the Dropbox folder. Your problem is about the System Integrity Protection.

Your user is not able to write in /usr/bin.

You could disable the SIP or set in the code the path to the geckodriver:

```<code>driver = webdriver.Firefox( executable_path=r'/whateverPathTo/geckodriver')
</code>```

Or you should set, in the $PATH environment variable, the absolute path to the geckodriver.

Body:
I am using python 2.7 on a mac and writing in the Terminal. I have made sure that my geckodriver is readable, writable and executable:

-rwxrwxrwx@  1 Esi  staff  3600548 31 Oct 19:55 geckodriver

The gecko driver is currently residing in my Dropbox folder. I have used:

cd Dropbox
sudo cp geckodriver /usr/bin/

I have then entered my password and received:

cp: /usr/bin/geckodriver: Operation not permitted

I have also tried

export PATH=$PATH:Dropbox/geckodriver

Body:
Your geckodriver is readable, writable and executable in the Dropbox folder. Your problem is about the System Integrity Protection.

Your user is not able to write in /usr/bin.

You could disable the SIP or set in the code the path to the geckodriver:

driver = webdriver.Firefox( executable_path=r'/whateverPathTo/geckodriver')

Or you should set, in the $PATH environment variable, the absolute path to the geckodriver.


问:
Batch loading in DynamoDB
Hi Currently I am loading each row row in Dynamodb which is veryslow.

I have a huge data which i want to load to DynamoDb by JAVA API.

But this takes huge time .For example to load 1 million data it took me 2 days to load to Dynamo.

Is Batch load possible in DynamoDb.I am not finding any information about bulkload or batch load.

Appreciate any help here.

答:
i know it's an old post, but we came up short exploring how to optimize this so embarked on a scientific discovery :)

http://tech.equinox.com/driving-miss-dynamodb/

long and short of it it Hive on EMR is an excellent option (i know, it's "old skool")..
using and tuning these parameters do the trick (see blog for details):

```<code>SET dynamodb.throughput.write.percent = x;
SET mapred.reduce.tasks = x;
SET hive.exec.reducers.bytes.per.reducer = x;
SET tez.grouping.split-count = x;
</code>```

Title: Batch loading in DynamoDB

Body:
i know it's an old post, but we came up short exploring how to optimize this so embarked on a scientific discovery :)

http://tech.equinox.com/driving-miss-dynamodb/

long and short of it it Hive on EMR is an excellent option (i know, it's "old skool")..
using and tuning these parameters do the trick (see blog for details):

SET dynamodb.throughput.write.percent = x;
SET mapred.reduce.tasks = x;
SET hive.exec.reducers.bytes.per.reducer = x;
SET tez.grouping.split-count = x;


问:
Converting Ohm model tree into a JSON structure
I have a tree of Ohm models. A Game has Players, a Player has Pieces. The full details are below. Basically, when I go to render the structure as json, I see an encoding error:

NoMethodError (undefined method `encode_json' for #Piece:0x00000102b8dbb8):

However, I can output the Player and their Pieces with no error.

```<code>Player = Player.create(:name => "Toby")
game.player << player

player.pieces << Piece.create(:name => "Rook")

# works fine
logger.debug(player.to_hash.to_json)

# FAILS with the above error
logger.debug(game.to_hash.to_json)
</code>```

My best guess is that there is something in the nesting of the collections that is causing the problem here.

Any ideas?

```<code>class Game < Ohm::Model
  collection :player, Player

  def to_hash
    super.merge(:players => players)
  end
end

class Player < Ohm::Model
  reference :game, Game
  collection :pieces, Piece

  attribute :name

  def to_hash
    super.merge(:name => name, :pieces => pieces)
  end
end

class Piece < Ohm::Model
  reference :player, Player

  def to_hash
    super.merge(:name => name)
  end
end
</code>```

答:
I found this works around the problem:</p>

```<code>class Player < Ohm::Model
  def to_hash
    super.merge(:name => name, :pieces => pieces.all)
  end
end
</code>```

Body:
I have a tree of Ohm models. A Game has Players, a Player has Pieces. The full details are below. Basically, when I go to render the structure as json, I see an encoding error:

NoMethodError (undefined method `encode_json' for #Piece:0x00000102b8dbb8):

However, I can output the Player and their Pieces with no error.

Player = Player.create(:name => "Toby")
game.player << player

player.pieces << Piece.create(:name => "Rook")

# works fine
logger.debug(player.to_hash.to_json)

# FAILS with the above error
logger.debug(game.to_hash.to_json)

My best guess is that there is something in the nesting of the collections that is causing the problem here.

Any ideas?

class Game < Ohm::Model
  collection :player, Player

  def to_hash
    super.merge(:players => players)
  end
end

class Player < Ohm::Model
  reference :game, Game
  collection :pieces, Piece

  attribute :name

  def to_hash
    super.merge(:name => name, :pieces => pieces)
  end
end

class Piece < Ohm::Model
  reference :player, Player

  def to_hash
    super.merge(:name => name)
  end
end

Body:
I found this works around the problem:

class Player < Ohm::Model
  def to_hash
    super.merge(:name => name, :pieces => pieces.all)
  end
end


问:
What is difference between these approaches in python?
First approach

```<code>n, m = [int(n), int(m)]
</code>```

Second approach

```<code>n, m = int(n), int(m)
</code>```

Both lines gives the same output. Then, is it necessary to close parameters under square bracket?

答: The first approach creates a list and the second one - a tuple. When this 2 variables are apart there is no difference</p>

Body:
First approach

n, m = [int(n), int(m)]

Second approach

n, m = int(n), int(m)

Both lines gives the same output. Then, is it necessary to close parameters under square bracket?


问:
Why does updating an object only work one, particular way?
I am trying to update an object using EF4. An object is passed from the strongly-typed page to the action method and

```<code>[HttpPost]
public ActionResult Index(Scenario scenario, Person person)
{
    // Some business logic.

    // Update Scenario with Person information.
    scenario.Person = person;

    // Update the corresponding object and persist the changes.
    // Note that the repository stems from the repository pattern. Contains the ObjectContext.
    Scenario updateScenario = repository.GetScenario(scenario.ScenarioID);
    updateScenario = scenario;

    repository.Save();
}
</code>```

However, the problem is that the changes do not persist when I do this. However, if I instead update every single property within the scenario individually and then persist the changes (via the Save method), everything is persisted.

I'm confused why this is happening. In my real application, there are MANY items and subobjects within a Scenario so it is not feasible to update every individual property. Can someone please help clear up what is happening and what I need to do to fix it?

答:
In the context of your action method, you have two different objects of type Scenario.  scenario points to one of the objects and updateScenario points to another one.  With the line of code:

```<code>updateScenario = scenario
</code>```

All you are doing is causing the updateScenario to point to the same object that scenario points to, you are not copying the values that make up the object from one to another.  Essentially, your database context is aware of only 1 of the 2 instances of Scenario.  The other instance of Scenario was created outside of the context and the context has not been made aware of it.

In your particular scenario you can accomplish what you want by not taking a Scenario on your parameter, and instead, pull the Scenario that you want to update from your database context and in your action method, invoke:

```<code>this.TryUpdateModel(updateScenario);
</code>```

This will cause the model binder to update the property/fields on the Scenario object that your database context is aware of, and therefore will persist the changes when you call Save().

HTH

Body:
I am trying to update an object using EF4. An object is passed from the strongly-typed page to the action method and

[HttpPost]
public ActionResult Index(Scenario scenario, Person person)
{
    // Some business logic.

    // Update Scenario with Person information.
    scenario.Person = person;

    // Update the corresponding object and persist the changes.
    // Note that the repository stems from the repository pattern. Contains the ObjectContext.
    Scenario updateScenario = repository.GetScenario(scenario.ScenarioID);
    updateScenario = scenario;

    repository.Save();
}

However, the problem is that the changes do not persist when I do this. However, if I instead update every single property within the scenario individually and then persist the changes (via the Save method), everything is persisted.

I'm confused why this is happening. In my real application, there are MANY items and subobjects within a Scenario so it is not feasible to update every individual property. Can someone please help clear up what is happening and what I need to do to fix it?

Body:
In the context of your action method, you have two different objects of type Scenario.  scenario points to one of the objects and updateScenario points to another one.  With the line of code:

updateScenario = scenario

All you are doing is causing the updateScenario to point to the same object that scenario points to, you are not copying the values that make up the object from one to another.  Essentially, your database context is aware of only 1 of the 2 instances of Scenario.  The other instance of Scenario was created outside of the context and the context has not been made aware of it.

In your particular scenario you can accomplish what you want by not taking a Scenario on your parameter, and instead, pull the Scenario that you want to update from your database context and in your action method, invoke:

this.TryUpdateModel(updateScenario);

This will cause the model binder to update the property/fields on the Scenario object that your database context is aware of, and therefore will persist the changes when you call Save().

HTH


问:
Ids param in Google Knowledge Graph API
I couldn't find a use-case or example of ids param in Google Knowledge Graph API. And every time I try putting any id in that field I get an error : "Request contains an invalid argument.". I have tried putting all possible arguments there like freebase id, wikiId but nothing seems to be working. Does anyone know how to use that argument and it what scenarios it will be useful.

答:
From its documentation:

To specify multiple IDs in the HTTP request, repeat the parameter in the URL as in ...?ids=A&ids=B

Where A or B is /m/0c3ss from an id like this one: kg:/m/0c3ss

Title: Ids param in Google Knowledge Graph API


问:
Unexpected C behavior in bisection method implementation
I'm trying to implement Bolzano's Bisection method in C, and while the algorithm appears to work, it terminates unexpectedly at around 4 steps
and the 4th step appears to increase the "err" and "divid" rather than have it continuously decrease. I'm trying to keep the code as simple as possible so no pointer/references/arrays/arguments in main etc please.</p>

```<code>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
//#define delta 0.00000000005
//#define epsilon 0.000000000005
//#define root1 1
//#define root2 -1
//#define maxit 7000

void bolzano(double a,double b, float root);
double function(double x);

int counter = 0;
//double err_global;//eps = 0.5e-6;
double maxit = 300;
double epsilon = 0.5E-6;
double delta = 0.5E-10;
int root1 = 1;
int root2 = -1;

int main(void){
    double a,b;
    printf("Eisagete tis times toy diastimatos [a,b]:  ");
    scanf("%lf%lf",&a,&b);
    printf("[a,b] = [%lf \\,%lf]\n",a, b);
    printf("                   ksi = %d\n", root1);
    printf("                            n   Xn   En   En+1/En");
    bolzano(a,b,root1);
    system("pause");
    printf("[a,b] = [%lf \\, %lf]\n",a, b);
    printf("                   ksi = %d", root2);
    bolzano(a,b,root2);
    system("pause");
    return 0;
}

double function(double x){
    return pow(x-1,3) * (x+1);
}

void bolzano(double a, double b, float root){
    double c,err,divit,err_global;
    while(b - a > epsilon && counter < maxit){
        //system("pause");
        c = (a + b)/2;
        err = fabs(c - root);
        if(counter == 0 ){
            err_global = err;
            printf("                           %d   %lf   %lf      \n", counter, c, err);
            counter++;
                if(function(a) * function(c) < 0){
                    b = c;
                    continue;
                }
                else{
                    a = c;
                    continue;
                }
        }
        divit = err/err_global;
        printf("                   ");
        printf("                           %d   %lf   %lf       %lf\n",counter, c ,err, divit);
        err_global = err;
        if(fabs(function(c)) < delta){
              break;
        }
        else if(function(a) * function(c) < 0){
            counter++;
            b = c;
            //continue;
        }
        else{
            counter++;
            a = c;
            //continue;
        }
    }
}
</code>```

答:
You are using the global

```<code>int counter = 0;
</code>```

to control the operations in function bolzano which is never reset.

Please add this line at the start of bolzano

```<code>counter = 0;
</code>```

Body:
I'm trying to implement Bolzano's Bisection method in C, and while the algorithm appears to work, it terminates unexpectedly at around 4 steps
and the 4th step appears to increase the "err" and "divid" rather than have it continuously decrease. I'm trying to keep the code as simple as possible so no pointer/references/arrays/arguments in main etc please.

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
//#define delta 0.00000000005
//#define epsilon 0.000000000005
//#define root1 1
//#define root2 -1
//#define maxit 7000

void bolzano(double a,double b, float root);
double function(double x);

int counter = 0;
//double err_global;//eps = 0.5e-6;
double maxit = 300;
double epsilon = 0.5E-6;
double delta = 0.5E-10;
int root1 = 1;
int root2 = -1;

int main(void){
    double a,b;
    printf("Eisagete tis times toy diastimatos [a,b]:  ");
    scanf("%lf%lf",&a,&b);
    printf("[a,b] = [%lf \\,%lf]\n",a, b);
    printf("                   ksi = %d\n", root1);
    printf("                            n   Xn   En   En+1/En");
    bolzano(a,b,root1);
    system("pause");
    printf("[a,b] = [%lf \\, %lf]\n",a, b);
    printf("                   ksi = %d", root2);
    bolzano(a,b,root2);
    system("pause");
    return 0;
}

double function(double x){
    return pow(x-1,3) * (x+1);
}

void bolzano(double a, double b, float root){
    double c,err,divit,err_global;
    while(b - a > epsilon && counter < maxit){
        //system("pause");
        c = (a + b)/2;
        err = fabs(c - root);
        if(counter == 0 ){
            err_global = err;
            printf("                           %d   %lf   %lf      \n", counter, c, err);
            counter++;
                if(function(a) * function(c) < 0){
                    b = c;
                    continue;
                }
                else{
                    a = c;
                    continue;
                }
        }
        divit = err/err_global;
        printf("                   ");
        printf("                           %d   %lf   %lf       %lf\n",counter, c ,err, divit);
        err_global = err;
        if(fabs(function(c)) < delta){
              break;
        }
        else if(function(a) * function(c) < 0){
            counter++;
            b = c;
            //continue;
        }
        else{
            counter++;
            a = c;
            //continue;
        }
    }
}

Body:
You are using the global

int counter = 0;

to control the operations in function bolzano which is never reset.

Please add this line at the start of bolzano

counter = 0;


问:
Doctrine expected Lexer::T_FROM, got '>'
(Symfony 3.2.7)

I've got this query created inside repository:

```<code>$qb = $this->createQueryBuilder('c');
$qb->select($qb->expr()->gte('c.createdDate', 'CURRENT_TIMESTAMP()').' AS HIDDEN x');
$qb->orderBy('x');
$qb->getQuery()->execute();
</code>```

It is generating this DQL:

```<code>SELECT c.createdDate >= CURRENT_TIMESTAMP() AS HIDDEN x
FROM App\CatalogBundle\Entity\Company c
ORDER BY x ASC
</code>```

And also... it is generating this error:

[Syntax Error] line 0, col 21: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got '>'

What could be wrong here?

SOLUTION

Thanks to @bishop answer, I managed to create a solution on my problem with creating a custom Doctrine DQL function. Configuration:

```<code>doctrine:
    orm:
        dql:
            datetime_functions:
                DATES_COMPARE: AppBundle\DQL\DatesCompareFunction
</code>```

And here is what mentioned class contains:

```<code>use Doctrine\ORM\Query;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;

class DatesCompareFunction extends FunctionNode
{
    /* @var Query\AST\Node  */
    public $param1;

    /* @var Query\AST\Node  */
    public $param2;

    /* @var Query\AST\Node  */
    public $param3;

    /** @inheritdoc */
    public function getSql(Query\SqlWalker $sqlWalker)
    {
        return sprintf(
            'CASE (%s %s %s) WHEN 1 THEN 1 ELSE 0 END',
            $this->param1->dispatch($sqlWalker),
            $this->param2,
            $this->param3->dispatch($sqlWalker)
        );
    }

    /** @inheritdoc */
    public function parse(Query\Parser $parser): void
    {
        $parser->match(Query\Lexer::T_IDENTIFIER);
        $parser->match(Query\Lexer::T_OPEN_PARENTHESIS);

        $this->param1 = $parser->StringPrimary();

        $parser->match(Query\Lexer::T_COMMA);

        $this->param2 = $parser->ComparisonOperator();

        $parser->match(Query\Lexer::T_COMMA);

        $this->param3 = $parser->StringPrimary();

        $parser->match(Query\Lexer::T_CLOSE_PARENTHESIS);
    }
}
</code>```

So all is working properly for the following DQL:

```<code>SELECT DATES_COMPARE(c.subscriptionEndDate, >, CURRENT_TIMESTAMP()) AS x
FROM App\CatalogBundle\Entity\Company c
ORDER BY x DESC
</code>```

答:
Your statement is valid SQL, but remember: SQL != DQL. Checking the docs for DQL, we see the SELECT has this BNF:

SelectExpression        ::= (IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression | NewObjectExpression) [["AS"] ["HIDDEN"] AliasResultVariable]

But the >= operator appears only in ConditionalExpression:

ConditionalExpression       ::= ConditionalTerm {"OR" ConditionalTerm}*
  ConditionalTerm             ::= ConditionalFactor {"AND" ConditionalFactor}*
  ConditionalFactor           ::= ["NOT"] ConditionalPrimary
  ConditionalPrimary          ::= SimpleConditionalExpression | "(" ConditionalExpression ")"
  SimpleConditionalExpression ::= ComparisonExpression | BetweenExpression | LikeExpression |
                                  InExpression | NullComparisonExpression | ExistsExpression |
                                  EmptyCollectionComparisonExpression | CollectionMemberExpression |
                                  InstanceOfExpression

ComparisonExpression     ::= ArithmeticExpression ComparisonOperator ( QuantifiedExpression | ArithmeticExpression )

ComparisonOperator       ::= "=" | "<" | "<=" | "<>" | ">" | ">=" | "!="

Since SelectExpression does not include ConditionalExpression, you're getting a lexing error.

To accomplish what you want, you'll need a custom function. See "Adding your own functions to the DQL language" for how to do this.

Body:
(Symfony 3.2.7)

I've got this query created inside repository:

$qb = $this->createQueryBuilder('c');
$qb->select($qb->expr()->gte('c.createdDate', 'CURRENT_TIMESTAMP()').' AS HIDDEN x');
$qb->orderBy('x');
$qb->getQuery()->execute();

It is generating this DQL:

SELECT c.createdDate >= CURRENT_TIMESTAMP() AS HIDDEN x
FROM App\CatalogBundle\Entity\Company c
ORDER BY x ASC

And also... it is generating this error:

[Syntax Error] line 0, col 21: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got '>'

What could be wrong here?

SOLUTION

Thanks to @bishop answer, I managed to create a solution on my problem with creating a custom Doctrine DQL function. Configuration:

doctrine:
    orm:
        dql:
            datetime_functions:
                DATES_COMPARE: AppBundle\DQL\DatesCompareFunction

And here is what mentioned class contains:

use Doctrine\ORM\Query;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;

class DatesCompareFunction extends FunctionNode
{
    /* @var Query\AST\Node  */
    public $param1;

    /* @var Query\AST\Node  */
    public $param2;

    /* @var Query\AST\Node  */
    public $param3;

    /** @inheritdoc */
    public function getSql(Query\SqlWalker $sqlWalker)
    {
        return sprintf(
            'CASE (%s %s %s) WHEN 1 THEN 1 ELSE 0 END',
            $this->param1->dispatch($sqlWalker),
            $this->param2,
            $this->param3->dispatch($sqlWalker)
        );
    }

    /** @inheritdoc */
    public function parse(Query\Parser $parser): void
    {
        $parser->match(Query\Lexer::T_IDENTIFIER);
        $parser->match(Query\Lexer::T_OPEN_PARENTHESIS);

        $this->param1 = $parser->StringPrimary();

        $parser->match(Query\Lexer::T_COMMA);

        $this->param2 = $parser->ComparisonOperator();

        $parser->match(Query\Lexer::T_COMMA);

        $this->param3 = $parser->StringPrimary();

        $parser->match(Query\Lexer::T_CLOSE_PARENTHESIS);
    }
}

So all is working properly for the following DQL:

SELECT DATES_COMPARE(c.subscriptionEndDate, >, CURRENT_TIMESTAMP()) AS x
FROM App\CatalogBundle\Entity\Company c
ORDER BY x DESC


问:
ASP.Net Core MVC Dependency Injection not working
I am trying to inject a interface into to my HomeController and I am getting this error:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate

My Startup class is as follows:

```<code>public Startup(IApplicationEnvironment appEnv)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ApplicationDbContext>(options => options
            .UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();
    services.AddSingleton(provider => Configuration);

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");

        try
        {
            using (var serviceScope = app.ApplicationServices
                .GetRequiredService<IServiceScopeFactory>()
                .CreateScope())
            {
                serviceScope.ServiceProvider
                        .GetService<ApplicationDbContext>()
                        .Database.Migrate();
            }
        }
        catch { }
    }

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.Run((async (context) =>
    {
        await context.Response.WriteAsync("Error");
    }));
}
</code>```

and my HomeController constructor is:

```<code>public HomeController(IConfiguration configuration, IEmailSender mailService)
{
    _mailService = mailService;
    _to = configuration["emailAddress.Support"];
}
</code>```

Please tell me where I am mistaken.

Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)

答: When moving a project from .Net Core 1.x to 2.0, change all IConfigurationRoot to IConfiguration

ContentLicense: CC BY-SA 4.0

Body:
I am trying to inject a interface into to my HomeController and I am getting this error:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate

My Startup class is as follows:

public Startup(IApplicationEnvironment appEnv)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<ApplicationDbContext>(options => options
            .UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();
    services.AddSingleton(provider => Configuration);

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");

        try
        {
            using (var serviceScope = app.ApplicationServices
                .GetRequiredService<IServiceScopeFactory>()
                .CreateScope())
            {
                serviceScope.ServiceProvider
                        .GetService<ApplicationDbContext>()
                        .Database.Migrate();
            }
        }
        catch { }
    }

    app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

    app.UseApplicationInsightsExceptionTelemetry();
    app.UseStaticFiles();
    app.UseIdentity();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.Run((async (context) =>
    {
        await context.Response.WriteAsync("Error");
    }));
}

and my HomeController constructor is:

public HomeController(IConfiguration configuration, IEmailSender mailService)
{
    _mailService = mailService;
    _to = configuration["emailAddress.Support"];
}

Please tell me where I am mistaken.

Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)


问:
ReplayKit stopRecording not entered the first time
I am trying to video capture an ARKIt app using ReplayKit. I have a record button, when pressed turned red and start recording, then pressed again to turn white and stop recording.

But the stopRecording method never worked on the first time.

if recorder.isAvailable {
            recorder.delegate = self

```<code>        if recorder.isRecording {
            print("Recorder is recording...")

            // Stop recording

            recorder.stopRecording { previewController, error in
                print("Stop recording...")
                self.recordImage.color = UIColor.white
                self.recordImage.colorBlendFactor = 1

                if let controller = previewController {
                    controller.previewControllerDelegate = self
                    self.present(controller, animated:true, completion:nil)
                }
            }
        }
        else {

            // Start recording

            recorder.startRecording { error in
                print("Starting to record…")

                if error == nil {
                    print("Start Recording…")
                    self.recordImage.color = UIColor.red
                    self.recordImage.colorBlendFactor = 1
                }
            }
        }
</code>```

When first pressed, I can see the recording started. Then when I pressed again, I can see that recorder.isRecording is entered, but the block in recorder.stopRecording does not work. I have to press again to start recording, then stop again before the recorder.stopRecording block is entered.

Any idea? Help is appreciated.

```<code>Press Record!
Starting to record…
Start Recording…
Press Record!
Recorder is recording...
</code>```

答:
I fixed this issue based on the replies at https://forums.developer.apple.com/thread/62624

This is definitely a bug in iOS; but removing the "Localization native development region" entry from the Info.plist seems to solve this issue.

Body:
I am trying to video capture an ARKIt app using ReplayKit. I have a record button, when pressed turned red and start recording, then pressed again to turn white and stop recording.

But the stopRecording method never worked on the first time.

if recorder.isAvailable {
            recorder.delegate = self

        if recorder.isRecording {
            print("Recorder is recording...")

            // Stop recording

            recorder.stopRecording { previewController, error in
                print("Stop recording...")
                self.recordImage.color = UIColor.white
                self.recordImage.colorBlendFactor = 1

                if let controller = previewController {
                    controller.previewControllerDelegate = self
                    self.present(controller, animated:true, completion:nil)
                }
            }
        }
        else {

            // Start recording

            recorder.startRecording { error in
                print("Starting to record…")

                if error == nil {
                    print("Start Recording…")
                    self.recordImage.color = UIColor.red
                    self.recordImage.colorBlendFactor = 1
                }
            }
        }

When first pressed, I can see the recording started. Then when I pressed again, I can see that recorder.isRecording is entered, but the block in recorder.stopRecording does not work. I have to press again to start recording, then stop again before the recorder.stopRecording block is entered.

Any idea? Help is appreciated.

Press Record!
Starting to record…
Start Recording…
Press Record!
Recorder is recording...


问:
Getting an error that function name is not defined
I've just started to mess around with "coding" recently and i tried to make this:

```<code>cake=4

def test():
    if cake<6:
        return "Less cake"

    elif cake>3:
        return "Enough cake"

    else:
        return "I dont want any cake"
</code>```

but, when i try to run it, and call "test" it says it's not defined. What can i do to fix it?

UPDATE: Thanks to everyone for helping!

答:
Create a file test.py and add the below codes in it and execute like:-

python test.py

```<code>cake=4

def test():
  if (cake < 6):
    return "Less cake"
  elif (cake>3):
    return "Enough cake"
  else:
    return "I dont want any cake"

print(test())
#or
order=test()
print(order)
</code>```

Body:
I've just started to mess around with "coding" recently and i tried to make this:

cake=4

def test():
    if cake<6:
        return "Less cake"

    elif cake>3:
        return "Enough cake"

    else:
        return "I dont want any cake"

but, when i try to run it, and call "test" it says it's not defined. What can i do to fix it?

UPDATE: Thanks to everyone for helping!

Body:
Create a file test.py and add the below codes in it and execute like:-

python test.py

cake=4

def test():
  if (cake < 6):
    return "Less cake"
  elif (cake>3):
    return "Enough cake"
  else:
    return "I dont want any cake"

print(test())
#or
order=test()
print(order)