问:
Cannot remove action noindex in wordpress
I've done some research and run up with this code

```<code>remove_action('wp_head','noindex',1);
</code>```

but apparently it's not removing the <meta name="robots" content="noindex,follow"/> in my WordPress header. I'm using WordPress 4.2.3

答:
I will show you how to remove meta name='robots' content='noindex nofollow' in WordPress using replace some code inside the admin panel.

Step 1 - public_html → wp-includes → general-template.php

Well, you log inside the public_html directory, now you find a folder, name wp-includes, double click to open this folder. At the same time, there are so many folders and files, take a breath and simply click to your keyboard Ctrl+f find file and type general-template.php.

Step 2 - Edit Two function

- First Code function Find:

```<code>function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='noindex,follow' />\n";
    return;
}

echo "<meta name='robots' content='noindex,nofollow' />\n";
</code>```

}

- First Code replace with bellow

```<code>function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='index,follow' />\n";
    return;
}
echo "<meta name='robots' content='index,follow' />\n";
</code>```

}

- Second Code function Find:

```<code>function wp_sensitive_page_meta() {
?>
<meta name='robots' content='noindex,noarchive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php
</code>```

}

- Second Code replaces with bellow:

```<code>function wp_sensitive_page_meta() {
?>
<meta name='robots' content='index,archive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php
</code>```

}

I hope that helps, For full Details Click this link:

Body:
I've done some research and run up with this code

remove_action('wp_head','noindex',1);

but apparently it's not removing the <meta name="robots" content="noindex,follow"/> in my WordPress header. I'm using WordPress 4.2.3

Body:
I will show you how to remove meta name='robots' content='noindex nofollow' in WordPress using replace some code inside the admin panel.

Step 1 - public_html → wp-includes → general-template.php

Well, you log inside the public_html directory, now you find a folder, name wp-includes, double click to open this folder. At the same time, there are so many folders and files, take a breath and simply click to your keyboard Ctrl+f find file and type general-template.php.

Step 2 - Edit Two function

- First Code function Find:

function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='noindex,follow' />\n";
    return;
}

echo "<meta name='robots' content='noindex,nofollow' />\n";

}

- First Code replace with bellow

function wp_no_robots() {
if ( get_option( 'blog_public' ) ) {
    echo "<meta name='robots' content='index,follow' />\n";
    return;
}
echo "<meta name='robots' content='index,follow' />\n";

}

- Second Code function Find:

function wp_sensitive_page_meta() {
?>
<meta name='robots' content='noindex,noarchive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php

}

- Second Code replaces with bellow:

function wp_sensitive_page_meta() {
?>
<meta name='robots' content='index,archive' />
<meta name='referrer' content='strict-origin-when-cross-origin' />
<?php

}

I hope that helps, For full Details Click this link:


来源: stackexchange

问:
Waiting for a blocking GC Alloc in Android studio logs
I have a pretty large double array of say 1,71,00,000 elements. I need to traverse through the array, slice the array in smaller arrays of 10k points each and the remaining points(if any) into the last slice.

I have a basic code:

```<code>public static boolean getSliceOfArray(double[] arr,int slice_len)
    {
        //arr: big array
        //slice_len: 10,000
        System.out.println(arr.length);
        int n_times=(arr.length/slice_len);
        int i=0;
        for(int n=0;n<n_times;n++)
        {
            Arrays.copyOfRange(arr,i,i+slice_len);
            i=i+slice_len;

        }
        System.out.println(n_times);

        if(i!=arr.length)
        {
            System.out.println( Arrays.copyOfRange(arr,i,arr.length).length);

        }

        return true;
    }
</code>```

It gives me following output:

```<code>I/System.out: 17100000
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 13.428ms
    Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 36.867ms
I/xample.styleap: Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 26.012ms
    Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 32.625ms
    Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 21.645ms
    Starting a blocking GC Alloc
I/System.out: 1710
</code>```

When I do the same with considerably smaller sized array the output is not like this. Why does it show "Waiting for a blocking GC Alloc" and these messages? Is it a serious issue? JVM issue or my logic error?

答: Using android:largeHeap="true"in my manifest.xml solved this issue.

ContentLicense: CC BY-SA 4.0

Body:
I have a pretty large double array of say 1,71,00,000 elements. I need to traverse through the array, slice the array in smaller arrays of 10k points each and the remaining points(if any) into the last slice.

I have a basic code:

public static boolean getSliceOfArray(double[] arr,int slice_len)
    {
        //arr: big array
        //slice_len: 10,000
        System.out.println(arr.length);
        int n_times=(arr.length/slice_len);
        int i=0;
        for(int n=0;n<n_times;n++)
        {
            Arrays.copyOfRange(arr,i,i+slice_len);
            i=i+slice_len;

        }
        System.out.println(n_times);

        if(i!=arr.length)
        {
            System.out.println( Arrays.copyOfRange(arr,i,arr.length).length);

        }

        return true;
    }

It gives me following output:

I/System.out: 17100000
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 13.428ms
    Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 36.867ms
I/xample.styleap: Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 26.012ms
    Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 32.625ms
    Starting a blocking GC Alloc
I/xample.styleap: Waiting for a blocking GC Alloc
I/xample.styleap: WaitForGcToComplete blocked Alloc on HeapTrim for 21.645ms
    Starting a blocking GC Alloc
I/System.out: 1710

When I do the same with considerably smaller sized array the output is not like this. Why does it show "Waiting for a blocking GC Alloc" and these messages? Is it a serious issue? JVM issue or my logic error?


问:
Customize .NET framework generated exception messages?
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

```<code>public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}
</code>```

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

```<code>KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}
</code>```

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...

答:
You seem to be doing this the right way to begin with. I would however change the way you check for exceptions:</p>

```<code>public string GetMetadata(string metaDataKey)
{
    try
    {
        string val = _Metadata[metaDataKey].TrimEnd();
        return val;
    }
    catch (KeyNotFoundException ex)
    {
        // or your own custom MetaDataNotFoundException or some such, ie:
        // throw new MetaDataNotFoundException(metaDatakey);
        throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...

Body:
You seem to be doing this the right way to begin with. I would however change the way you check for exceptions:

public string GetMetadata(string metaDataKey)
{
    try
    {
        string val = _Metadata[metaDataKey].TrimEnd();
        return val;
    }
    catch (KeyNotFoundException ex)
    {
        // or your own custom MetaDataNotFoundException or some such, ie:
        // throw new MetaDataNotFoundException(metaDatakey);
        throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
    }
}


问:
Aframe Texture Change
I am working on the following script. To change the image of the .glb model. It producing only a white color. No proper texture change is happening. Please help me.

    const nextButtonComponent = () => ({
  init: function() {
    const model = document.getElementById('model')
    const nextButton = document.getElementById('nextbutton')
    const loader = new THREE.TextureLoader();

    var material = new THREE.MeshStandardMaterial({
      side: THREE.DoubleSide,
      flatShading: true,
    });
    const mesh = model.getObject3D('mesh');

    nextButton.style.display = 'block';

    const nextAnimation = () => {
      loader.load( './assets/img/1.jpg' ,
            function(texture){
            material.map = texture;
            material.needsUpdate = true;

            if(mesh){
                mesh.traverse((node) => {
                  if (node.isMesh) {
                    node.material = material;
                    node.material.map = texture;
                    node.material.needsUpdate = true;
                  }
                });
              }
            });
    }
    nextButton.onclick = nextAnimation // Switch to the next animation when the button is pressed.
  }
})
export {nextButtonComponent}
```

答:
I have got another solution. That is working for me.

I am using THREE.ImageUtils.loadTexture(src)

```<code>export const textureSwapComponent = {
    init: function() {
      const nextButton = document.getElementById('nextbutton');
      nextButton.style.display = 'block';

      let src1 = document.getElementById('imageFile1').src;
      let src2 = document.getElementById('imageFile2').src;
      let src3 = document.getElementById('imageFile3').src;

     // this.ImageUtils = THREE.ImageUtils();

      this.text = document.getElementById('textDebug')
      const model = document.getElementById('model')
      this.mesh = model.getObject3D('mesh');

      this.material = new THREE.MeshStandardMaterial({
     // map : ImageUtils.loadTexture(src1),
      side: THREE.DoubleSide,
      flatShading: true,
      });

      model.addEventListener('model-loaded', (e) => {
        this.mesh = model.getObject3D('mesh');
        if(this.mesh){
        this.debugDisplay('Mesh Ok');
        nextAnimation();
        }else{
        this.debugDisplay('Mesh Not Ok');
        }
      })
      let idx = 0;

      const nextAnimation = () => {
        this.debugDisplay('On Click');
        var src = src1;
        if(idx >=3){
          idx = 0;
        }
        switch(idx){
          case 0:
          src = src1;
          break;
          case 1:
          src = src2;
          break;
          case 2:
          src = src3;
          break;
        }
        this.texture = THREE.ImageUtils.loadTexture(src);
        idx ++;
        if(this.mesh){
                this.debugDisplay('Mesh Ok');
                this.mesh.traverse((node) => {
                  if (node.isMesh) {
                    if(node.material !== this.material){
                    node.material = this.material;
                    }
                    node.material.map = this.texture;
                    node.material.needsUpdate = true;
                  }
                });
              }else{
                this.debugDisplay('Mesh Not Ok');
              }
      }
      nextButton.onclick = nextAnimation

  },
  debugDisplay : function(val){
    this.text.setAttribute('value', val);
  }

}
</code>```

Title: Aframe Texture Change

Body:
I have got another solution. That is working for me.

I am using THREE.ImageUtils.loadTexture(src)

export const textureSwapComponent = {
    init: function() {
      const nextButton = document.getElementById('nextbutton');
      nextButton.style.display = 'block';

      let src1 = document.getElementById('imageFile1').src;
      let src2 = document.getElementById('imageFile2').src;
      let src3 = document.getElementById('imageFile3').src;

     // this.ImageUtils = THREE.ImageUtils();

      this.text = document.getElementById('textDebug')
      const model = document.getElementById('model')
      this.mesh = model.getObject3D('mesh');

      this.material = new THREE.MeshStandardMaterial({
     // map : ImageUtils.loadTexture(src1),
      side: THREE.DoubleSide,
      flatShading: true,
      });

      model.addEventListener('model-loaded', (e) => {
        this.mesh = model.getObject3D('mesh');
        if(this.mesh){
        this.debugDisplay('Mesh Ok');
        nextAnimation();
        }else{
        this.debugDisplay('Mesh Not Ok');
        }
      })
      let idx = 0;

      const nextAnimation = () => {
        this.debugDisplay('On Click');
        var src = src1;
        if(idx >=3){
          idx = 0;
        }
        switch(idx){
          case 0:
          src = src1;
          break;
          case 1:
          src = src2;
          break;
          case 2:
          src = src3;
          break;
        }
        this.texture = THREE.ImageUtils.loadTexture(src);
        idx ++;
        if(this.mesh){
                this.debugDisplay('Mesh Ok');
                this.mesh.traverse((node) => {
                  if (node.isMesh) {
                    if(node.material !== this.material){
                    node.material = this.material;
                    }
                    node.material.map = this.texture;
                    node.material.needsUpdate = true;
                  }
                });
              }else{
                this.debugDisplay('Mesh Not Ok');
              }
      }
      nextButton.onclick = nextAnimation

  },
  debugDisplay : function(val){
    this.text.setAttribute('value', val);
  }

}


问:
How to register generic service with Autofac?
I have a generic service:

public class FileDataService<T> : IFileDataService<T>
{
    public async Task<List<T>> GetListResultAsync(IFileSearcher<T> searcher)
    {
        return await searcher.GetResultsAsync();
    }
}
```

<p>which I am trying to register:</p>

<pre class="lang-cs prettyprint-override"><code>builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
    .AsClosedTypesOf(typeof(IFileDataService<>));
builder.RegisterType<SampleService>().As<ISampleService>();
builder.AddMediatR(this.GetType().Assembly);

builder.Register(c => UmbracoContext.Current).AsSelf();
</code>```

to use it in dependency injection in MediatR handler;

public class QueryHandler : IRequestHandler<Query, Result>
{
    private readonly IFileDataService<ResultModel> _fileDataService;
    private readonly ISampleService _sampleService;
    private readonly UmbracoHelper _umbHelper;

    public QueryHandler(
        IFileDataService<ResultModel> fileDataService, ISampleService sampleService)
    {
        _fileDataService = fileDataService;
        _sampleService = sampleService;
        _umbHelper = new UmbracoHelper(UmbracoContext.Current);
    }
```

It's telling me that the handler has not been properly constructed:

Error constructing handler for request of type MediatR.IRequestHandler

How to properly register and use generic service in .NET 4.7.2 with Autofac & MediatR?

答:
I think your problem is caused by the fact that FileDataService<T> is not a closed type, so .AsClosedTypesOf(typeof(IFileDataService<>)); won't pick it up.

What you want to do is register FileDataService<T> as a generic component, using the Autofac RegisterGeneric method; this cannot be done via the Assembly Scanning mechanism.

builder.RegisterGeneric(typeof(FileDataService<T>)).As(typeof(IFileDataService<>));
```

Docs: https://autofaccn.readthedocs.io/en/latest/register/registration.html#open-generic-components

Body:
I have a generic service:

public class FileDataService<T> : IFileDataService<T>
{
    public async Task<List<T>> GetListResultAsync(IFileSearcher<T> searcher)
    {
        return await searcher.GetResultsAsync();
    }
}

which I am trying to register:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
    .AsClosedTypesOf(typeof(IFileDataService<>));
builder.RegisterType<SampleService>().As<ISampleService>();
builder.AddMediatR(this.GetType().Assembly);

builder.Register(c => UmbracoContext.Current).AsSelf();

to use it in dependency injection in MediatR handler;

public class QueryHandler : IRequestHandler<Query, Result>
{
    private readonly IFileDataService<ResultModel> _fileDataService;
    private readonly ISampleService _sampleService;
    private readonly UmbracoHelper _umbHelper;

    public QueryHandler(
        IFileDataService<ResultModel> fileDataService, ISampleService sampleService)
    {
        _fileDataService = fileDataService;
        _sampleService = sampleService;
        _umbHelper = new UmbracoHelper(UmbracoContext.Current);
    }

It's telling me that the handler has not been properly constructed:

Error constructing handler for request of type MediatR.IRequestHandler

How to properly register and use generic service in .NET 4.7.2 with Autofac & MediatR?

Body:
I think your problem is caused by the fact that FileDataService<T> is not a closed type, so .AsClosedTypesOf(typeof(IFileDataService<>)); won't pick it up.

What you want to do is register FileDataService<T> as a generic component, using the Autofac RegisterGeneric method; this cannot be done via the Assembly Scanning mechanism.

builder.RegisterGeneric(typeof(FileDataService<T>)).As(typeof(IFileDataService<>));

Docs: https://autofaccn.readthedocs.io/en/latest/register/registration.html#open-generic-components


问:
Python, how to calculate the difference between lists
I have list

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

and need to calculate the difference between two neighbor points in this list.

For example, (B-A), (C-B), (D-C) and get this output:

output = [(20, -2), (43, 7), (-70, 0)

Are there any fast ways how to do it?

答:
The question becomes trivial if you turn neighbors into pairs. This is the trick.

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

firsts = a[:-1]  # a without the last element.
seconds = a[1:]  # a without the first element.
pairs = zip(firsts, seconds)

for (first, second) in pairs:
  # Here first would be e.g. ('A', 10, 7),
  # and second would be e.g. ('B', 30, 5)
  # You can handle the rest yourself.
  print('first:', first, 'second:', second)  # To understand how it works.
  pass
```


问:
Timer function distorting a draggable line segment
I've a draggable line segment. Also I've got a timer.  This line segment is getting distorted when I operate a timer in this window.

```<code>protected:
   //  override / make our own of these function to track mouse movement and
         void mousePressEvent(QMouseEvent *event) ;
         void mouseReleaseEvent(QMouseEvent *event) ;
         void mouseMoveEvent(QMouseEvent *event) ;
</code>```

I've noticed this line segment is getting distorted (see figure) when I enable a timer (basically there is a digital clock to see running time in the left side of the widget).

I've following three functions for the timer:

```<code>public slots:

        void update();
        void startStopTimer();
        void resetTimer();
</code>```

```<code>
  //slot
    connect(ui->pushButton_stimStart, &QPushButton::clicked, this, &ProgramKeyGripV2::startStopTimer);
    connect(ui->pushButton_stimStop, &QPushButton::clicked, this, &ProgramKeyGripV2::resetTimer);

    QTimer *timer2 = new QTimer(this);
    connect(timer2, SIGNAL(timeout()), this, SLOT(update()));
    timer2->start(10);

void ProgramKeyGripV2::startStopTimer()
{
    if(watch->isRunning()) {
        //ui->startStopButton->setText("Restart");
        watch->pause();
    }
    else {
        //ui->startStopButton->setText("Pause");
        watch->start();
    }

}

void ProgramKeyGripV2::resetTimer()
{
    ui->hundredthsText->setText("00");
    ui->secondsText->setText("00");
    ui->minutesText->setText("00");
    watch->reset();
}

void ProgramKeyGripV2::update()
{
    QPalette p = ui->secondsText->palette();
    if(watch->isRunning())
    {
        qint64 time = watch->getTime();
        int h = time / 1000 / 60 / 60;
        int m = (time / 1000 / 60) - (h * 60);
        int s = (time / 1000) - (m * 60);
        int ms = time - ( s + ( m + ( h * 60)) * 60) * 1000;
        int ms_dis = ms / 10;
        if(ms_dis < 10) {
            ui->hundredthsText->setText(QStringLiteral("0%1").arg(ms_dis));
        }
        else {
            ui->hundredthsText->setText(QStringLiteral("%1").arg(ms_dis));
        }
        if(s < 10) {
            ui->secondsText->setText(QStringLiteral("0%1").arg(s));
           // p.setColor(QPalette::Base, Qt::white);
            //ui->secondsText->setPalette(p);
        }
        else {
            ui->secondsText->setText(QStringLiteral("%1").arg(s));

        }
        if(m < 10) {
            ui->minutesText->setText(QStringLiteral("0%1").arg(m));
        }
        else {
            ui->minutesText->setText(QStringLiteral("%1").arg(m));
        }

    }

}
</code>```

This problem is not there if I disable the timer. Can you spot an issue here?

答:
Could it be that your update method clashes with QWidget::update? (see https://doc.qt.io/qt-5/qwidget.html#update)

I'm not entire sure about what class your code is running it (what is the base class), but it seems like a plausable issue to me. Try renaming your update method to onTimeout or something like that instead.

Also, try using the &YourClass::yourSlot syntax instead of SLOT(yourSlot()), as the latter is going away.

Body:
I've a draggable line segment. Also I've got a timer.  This line segment is getting distorted when I operate a timer in this window.

protected:
   //  override / make our own of these function to track mouse movement and
         void mousePressEvent(QMouseEvent *event) ;
         void mouseReleaseEvent(QMouseEvent *event) ;
         void mouseMoveEvent(QMouseEvent *event) ;

I've noticed this line segment is getting distorted (see figure) when I enable a timer (basically there is a digital clock to see running time in the left side of the widget).

I've following three functions for the timer:

public slots:

        void update();
        void startStopTimer();
        void resetTimer();

  //slot
    connect(ui->pushButton_stimStart, &QPushButton::clicked, this, &ProgramKeyGripV2::startStopTimer);
    connect(ui->pushButton_stimStop, &QPushButton::clicked, this, &ProgramKeyGripV2::resetTimer);

    QTimer *timer2 = new QTimer(this);
    connect(timer2, SIGNAL(timeout()), this, SLOT(update()));
    timer2->start(10);

void ProgramKeyGripV2::startStopTimer()
{
    if(watch->isRunning()) {
        //ui->startStopButton->setText("Restart");
        watch->pause();
    }
    else {
        //ui->startStopButton->setText("Pause");
        watch->start();
    }

}

void ProgramKeyGripV2::resetTimer()
{
    ui->hundredthsText->setText("00");
    ui->secondsText->setText("00");
    ui->minutesText->setText("00");
    watch->reset();
}

void ProgramKeyGripV2::update()
{
    QPalette p = ui->secondsText->palette();
    if(watch->isRunning())
    {
        qint64 time = watch->getTime();
        int h = time / 1000 / 60 / 60;
        int m = (time / 1000 / 60) - (h * 60);
        int s = (time / 1000) - (m * 60);
        int ms = time - ( s + ( m + ( h * 60)) * 60) * 1000;
        int ms_dis = ms / 10;
        if(ms_dis < 10) {
            ui->hundredthsText->setText(QStringLiteral("0%1").arg(ms_dis));
        }
        else {
            ui->hundredthsText->setText(QStringLiteral("%1").arg(ms_dis));
        }
        if(s < 10) {
            ui->secondsText->setText(QStringLiteral("0%1").arg(s));
           // p.setColor(QPalette::Base, Qt::white);
            //ui->secondsText->setPalette(p);
        }
        else {
            ui->secondsText->setText(QStringLiteral("%1").arg(s));

        }
        if(m < 10) {
            ui->minutesText->setText(QStringLiteral("0%1").arg(m));
        }
        else {
            ui->minutesText->setText(QStringLiteral("%1").arg(m));
        }

    }

}

This problem is not there if I disable the timer. Can you spot an issue here?


问:
How can I align my text/border to the center of my page with the
 element?

div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div1 style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div1>
</body></code>```

I'm trying to align both my border and text to the center of my page, but somethings not working. If I haven't explained it well enough please ask for more details :). Here is the code:

HTML

```<code><body>
  <div1 style="font-size: 30px; text-align: center;">
    <b>Text here</b>
  </div1>
</body>
</code>```

CSS

```<code>div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }
</code>```

答:
<div1> isn't a valid HTML element. Always use
 and if you want to differentiate between your divs you can add an id="div1" or  class="div1" attribute. If your component should be re-usable (multiple times on the page), then use class. Otherwise use id (which should be unique).

I created a div.div1 selector, which selects all elements that are a
 element with the .div1 class attribute (class="div1").

And it looks like your code works as expected.

div.div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
     font-size: 30px;
     text-align: center;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="div1">
    <b>Text here</b>
  </div>
</body></code>```

Title: How can I align my text/border to the center of my page with the <div> element?

Body:
div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }

  <div1 style="font-size: 30px; text-align: center;">
    Text here
  </div1>

I'm trying to align both my border and text to the center of my page, but somethings not working. If I haven't explained it well enough please ask for more details :). Here is the code:

HTML

  <div1 style="font-size: 30px; text-align: center;">
    Text here
  </div1>

CSS

div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
 }

Body:
<div1> isn't a valid HTML element. Always use <div> and if you want to differentiate between your divs you can add an id="div1" or  class="div1" attribute. If your component should be re-usable (multiple times on the page), then use class. Otherwise use id (which should be unique).

I created a div.div1 selector, which selects all elements that are a <div> element with the .div1 class attribute (class="div1").

And it looks like your code works as expected.

div.div1 {
     background-color: aqua;
     font-family: Candara;
     padding: 10px;
     border-radius: 10px;
     margin: 10px;
     width: auto;
     font-size: 30px;
     text-align: center;
 }

<body>
  <div class="div1">
    <b>Text here</b>
  </div>
</body>


问:
SQL like & matches query on string in Swift
I want to write a function that can perform comparison with two strings.

Something like this:

```<code>func stringComparison(_ str1:String, comparisonOperator:StringComparisonOperator, _ str2:String)
{
   ...
}
</code>```

I want to support the following types in the StringComparisonOperator

```<code>enum StringComparisonOperator {
    case equals
    case contains
    case beginsWith
    case endsWith
    case like
    case matches
}
</code>```

Swift provides ==(for equals), .contains(for contains), .hasPrefix(for beginsWith) and .hasSuffix(for endsWith).

But, I don't have any idea about like and matches options. Can someone help me in this?

答:
You can create an infix operator for like and matches

```<code>infix operator =~
func =~ (string: String, regex: String) -> Bool {
    return string.range(of: regex, options: .regularExpression) != nil
}
</code>```

and use like: "abcd" =~ "ab*cd"

Body:
I want to write a function that can perform comparison with two strings.

Something like this:

func stringComparison(_ str1:String, comparisonOperator:StringComparisonOperator, _ str2:String)
{
   ...
}

I want to support the following types in the StringComparisonOperator

enum StringComparisonOperator {
    case equals
    case contains
    case beginsWith
    case endsWith
    case like
    case matches
}

Swift provides ==(for equals), .contains(for contains), .hasPrefix(for beginsWith) and .hasSuffix(for endsWith).

But, I don't have any idea about like and matches options. Can someone help me in this?

Body:
You can create an infix operator for like and matches

infix operator =~
func =~ (string: String, regex: String) -> Bool {
    return string.range(of: regex, options: .regularExpression) != nil
}

and use like: "abcd" =~ "ab*cd"


问:
Unable to mount EFS on EC2 instance; 'connection timed out' error
I am unable to mount EFS to an EC2 instance. It fails with a 'connection timed out' error.

Steps used:

Connected to Amazon EC2 instance using SSH

created EFS

Using DNS name in EFS trying to mount EFS on to the instance(using default security group)

sudo mount fs-0a9a08a3.efs.us-west-2.amazonaws.com:/ /usr/local/mousetrap/remote

How can I resolve this?

答:
ending up in time out can have several reasons.
Please check following:

security group and port is allowed on ec2 AND on network interface! Check for port 2049 (nmap -Pn -p 2049)

if there is ICMP allowed, you can also try to ping the ip address

in order to use DNS hostnames, it must be allowed in the VPC. But for troubleshooting, try the IP

if the network stuff is not working, check whether all your components are in place.

e.g. all your components are in the same subnet


问:
How to maintain history data whose schema changes quarterly using Hadoop
I have json input file which stores survey data(feedback from the customers).

The columns in json file can vary

for e.g. in first quarter there can
be 70 columns and in next quarter it can have 100 columns and so on.

I want to store all this quarterly data in same table on hdfs.

Is there a way to maintain history either by drop and re-creating the table with changing schema?

How will it behave if the column length goes down let's say in 3rd quarter we get only 30 columns.

答:
First point is that in HDFS you don't store tables just files. You create tables in hive impala etc. on top of files.

Some of the formats support schema merging at read, for example parquet
In general you will be able to recreate your table with a super-set of columns. In Impala you have similar capabilities for schema evolution.


问:
What is the best method to use ObservableLists for both GUI and background Tasks?
SSCCE:

```<code>package sample;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        ListView<Integer> root = new ListView<Integer>();
        ObservableList<Integer> data = Model.getInstance().getData();
        root.setItems(data);

        // A Thread that simulates changes to GUI Observant List.
        Thread populate = new Thread(()->{
            for(int i=0;i<20000;i+=1){
                int finalInstance = i;
                // Changes are done on FXThread
                Platform.runLater(()->{
                    data.add(finalInstance);
                });
                try{
                    Thread.sleep(5);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });populate.start();
        // Populates at 200 elements/s

        // Server Thread that Sends current status of ObservableList<Integer> data
        Thread server = new Thread(()->{
            try{
                // Server Socket
                ServerSocket ss = new ServerSocket(5555);System.out.println("SERVER ONLINE:");
                while(true){
                    Socket s = ss.accept();
                    // Client Handler Thread to Handle Clients
                    Thread clientHandler = new Thread(()->{
                        try{
                            System.out.println("SERVER CLIENT:"+s);
                            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
                            List<Integer> dataCopy = new ArrayList<Integer>();

                            // Get Current Status of data List that is being used in FXThread adn store in dataCopy
                            Semaphore waitForReadToComplete = new Semaphore(0);
                            Platform.runLater(()->{
                                System.out.println("EXPECTED LENGTH: "+data.size());
                                for(Integer a:data){
                                    dataCopy.add(a);
                                    try{
                                        Thread.sleep(5); // Simulate delay while copying large elements
                                    }catch (InterruptedException e){e.printStackTrace();}
                                }
                                waitForReadToComplete.release(); // Marks Read Operation Complete
                            });
                            waitForReadToComplete.acquire();// Resumes Client Thread
                            oos.writeObject(dataCopy);oos.flush();
                            s.close();
                        }catch (InterruptedException | IOException e){
                            e.printStackTrace();
                        }
                    });clientHandler.start();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        });server.start();

        // Client Thread that requests for current status of ObservableList<Integer> data.
        Thread client = new Thread(()->{
            try{
                Thread.sleep(1000);
                Socket s = new Socket(InetAddress.getLocalHost(),5555);
                ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                List<Integer> dataCopy;
                dataCopy = (ArrayList<Integer>)ois.readObject();
                s.close();
                System.out.println("ACTUAL LENGTH RECIEVED BY CLIENT "+dataCopy.size());
            }catch (IOException | ClassNotFoundException | InterruptedException e){
                e.printStackTrace();
            }
        });client.start();

        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

// Singleton Class with Eager Initialization
class Model{
    static Model onlyInstance = new Model();
    ObservableList<Integer> data = FXCollections.<Integer>observableArrayList();
    public static Model getInstance(){
        return onlyInstance;
    }

    public ObservableList<Integer> getData(){
        return data;
    }
}
</code>```

In this example, I intend to send over the status of the data List to a client when it connects to my Server Thread.

The problem is that every time I want to read the data List, I need to do it using a Platform.runLater() call, whose scheduling is not in my control.

I use a Semaphore to block the Server's Client Handler thread in order to make sure that the complete List is copied and then sent to the client.

As visible, This method makes my client wait for a longer period of time since copying the data List is done inside Platform.runLater().

I was wondering if there was a better way to share my data List between the FXThread and Background Threads.

EDIT:

Better wording, courtesy of @James_D

I have a model with some (possibly large amount of) data. The model is being updated by a background thread. The server has access to the model and sends the data on demand to network-connected clients. And then there's a UI, which is server-side. And I want the UI to display the current state of the model on the server-side and perform add/remove operations on the data from the UI user.

答:
One thing that you could change is the order that your submitting your tasks. Instead of starting the client thread, then calling run later and waiting for the response. Just call Platform.runLater, populate the copy and then start the client thread. Now there is no reason for a semaphore.

```<code>    // Immediately following the accept.
    Platform.runLater(()->{
        System.out.println("EXPECTED LENGTH: "+data.size());
        List<Integer> dataCopy = new ArrayList<>(data);
        Thread clientHandler = new Thread(()->{
            try(ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()) ) {
                System.out.println("SERVER CLIENT:"+s);
                oos.writeObject(dataCopy);
                oos.flush();
            }catch (InterruptedException | IOException e){
                e.printStackTrace();
            }
         });
         clientHandler.start();
     });
</code>```

Creating a new thread each time should be replaced with an executor service of some sort. Depending on the task, consider using javafx.concurrent Task. Your server loop could be a task for example.

It's possible to expose an view of the data backing your observable list.

```<code>List<String> cowal = new CopyOnWriteArrayList<>();
ObservableList<String> data = FXCollections.observableList(cowal);
List<String> dataCopy = Collections.unmodifiableList(cowal);
</code>```

I made it a copy on write array list so you can iterate over the view without getting a CCME. I called it a dataCopy to be consistent with the previous naming, but it is a view of the data.

Also, as a matter of taste, instead of });server.start(); create a new line to call server.start();

Body:
SSCCE:

package sample;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        ListView<Integer> root = new ListView<Integer>();
        ObservableList<Integer> data = Model.getInstance().getData();
        root.setItems(data);

        // A Thread that simulates changes to GUI Observant List.
        Thread populate = new Thread(()->{
            for(int i=0;i<20000;i+=1){
                int finalInstance = i;
                // Changes are done on FXThread
                Platform.runLater(()->{
                    data.add(finalInstance);
                });
                try{
                    Thread.sleep(5);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });populate.start();
        // Populates at 200 elements/s

        // Server Thread that Sends current status of ObservableList<Integer> data
        Thread server = new Thread(()->{
            try{
                // Server Socket
                ServerSocket ss = new ServerSocket(5555);System.out.println("SERVER ONLINE:");
                while(true){
                    Socket s = ss.accept();
                    // Client Handler Thread to Handle Clients
                    Thread clientHandler = new Thread(()->{
                        try{
                            System.out.println("SERVER CLIENT:"+s);
                            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
                            List<Integer> dataCopy = new ArrayList<Integer>();

                            // Get Current Status of data List that is being used in FXThread adn store in dataCopy
                            Semaphore waitForReadToComplete = new Semaphore(0);
                            Platform.runLater(()->{
                                System.out.println("EXPECTED LENGTH: "+data.size());
                                for(Integer a:data){
                                    dataCopy.add(a);
                                    try{
                                        Thread.sleep(5); // Simulate delay while copying large elements
                                    }catch (InterruptedException e){e.printStackTrace();}
                                }
                                waitForReadToComplete.release(); // Marks Read Operation Complete
                            });
                            waitForReadToComplete.acquire();// Resumes Client Thread
                            oos.writeObject(dataCopy);oos.flush();
                            s.close();
                        }catch (InterruptedException | IOException e){
                            e.printStackTrace();
                        }
                    });clientHandler.start();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        });server.start();

        // Client Thread that requests for current status of ObservableList<Integer> data.
        Thread client = new Thread(()->{
            try{
                Thread.sleep(1000);
                Socket s = new Socket(InetAddress.getLocalHost(),5555);
                ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                List<Integer> dataCopy;
                dataCopy = (ArrayList<Integer>)ois.readObject();
                s.close();
                System.out.println("ACTUAL LENGTH RECIEVED BY CLIENT "+dataCopy.size());
            }catch (IOException | ClassNotFoundException | InterruptedException e){
                e.printStackTrace();
            }
        });client.start();

        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

// Singleton Class with Eager Initialization
class Model{
    static Model onlyInstance = new Model();
    ObservableList<Integer> data = FXCollections.<Integer>observableArrayList();
    public static Model getInstance(){
        return onlyInstance;
    }

    public ObservableList<Integer> getData(){
        return data;
    }
}

In this example, I intend to send over the status of the data List to a client when it connects to my Server Thread.

The problem is that every time I want to read the data List, I need to do it using a Platform.runLater() call, whose scheduling is not in my control.

I use a Semaphore to block the Server's Client Handler thread in order to make sure that the complete List is copied and then sent to the client.

As visible, This method makes my client wait for a longer period of time since copying the data List is done inside Platform.runLater().

I was wondering if there was a better way to share my data List between the FXThread and Background Threads.

EDIT:

Better wording, courtesy of @James_D

I have a model with some (possibly large amount of) data. The model is being updated by a background thread. The server has access to the model and sends the data on demand to network-connected clients. And then there's a UI, which is server-side. And I want the UI to display the current state of the model on the server-side and perform add/remove operations on the data from the UI user.

Body:
One thing that you could change is the order that your submitting your tasks. Instead of starting the client thread, then calling run later and waiting for the response. Just call Platform.runLater, populate the copy and then start the client thread. Now there is no reason for a semaphore.

    // Immediately following the accept.
    Platform.runLater(()->{
        System.out.println("EXPECTED LENGTH: "+data.size());
        List<Integer> dataCopy = new ArrayList<>(data);
        Thread clientHandler = new Thread(()->{
            try(ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()) ) {
                System.out.println("SERVER CLIENT:"+s);
                oos.writeObject(dataCopy);
                oos.flush();
            }catch (InterruptedException | IOException e){
                e.printStackTrace();
            }
         });
         clientHandler.start();
     });

Creating a new thread each time should be replaced with an executor service of some sort. Depending on the task, consider using javafx.concurrent Task. Your server loop could be a task for example.

It's possible to expose an view of the data backing your observable list.

List<String> cowal = new CopyOnWriteArrayList<>();
ObservableList<String> data = FXCollections.observableList(cowal);
List<String> dataCopy = Collections.unmodifiableList(cowal);

I made it a copy on write array list so you can iterate over the view without getting a CCME. I called it a dataCopy to be consistent with the previous naming, but it is a view of the data.

Also, as a matter of taste, instead of });server.start(); create a new line to call server.start();


问:
How can a Word document be created in C#?
I have a project where I would like to generate a report export in MS Word format.  The report will include images/graphs, tables, and text.  What is the best way to do this?  Third party tools?  What are your experiences?</p>

答:
I currently do this exact thing.

If the document isn't very big, doesn't contain images and such, then I store it as an RTF with #MergeFields# in it and simply replace them with content, sending the result down to the user as an RTF.

For larger documents, including images and dynamically inserted images, I save the initial  Word document as a Single Webpage *.mht file containing the #MergeFields# again.  I then do the same as above.  Using this, I can easily render a DataTable with some basic Html table tags and replace one of the #MergeFields# with a whole table.

Images can be stored on your server and the url embedded into the document too.

Interestingly, the new Office 2007 file formats are actually zip files - if you rename the extension to .zip you can open them up and see their contents.  This means you should be able to switch content such as images in and out using a simple C# zip library.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Nico

OwnerDisplayName: littlecharva


问:
Embedding word 2010 editor in a wpf application
How do I use the word editor in a WPF application? Is it possible using windows forms hosting in WPF only? Is there another way to accomplish that?

I found AvalonEdit but it does not have features that I need. So using this way, my problem may not be solved.

Also there is some stuffs out there to host a windows forms control in WPF, but it could not be my answer.

I want to understand that is there a way to use word editor in a native way in a wpf app?
Will all APIs be available in that solution?

Thanks in advance.

答:
Well, Word proper isn't technically designed to be hosted by another app, whether it's WPF, WINFORMS or anything else.

You CAN use api tricks (like SetParent) to move the Main Word window into a WPF hosted window. I've done it before, but it's pretty tricky business and it's very easy to miss things that cause GPFs (both in Word and your app).

Is there any reason why it needs to be "Word in your app"? Why not write a little word addin and then launch Word from your app when necessary. then the Addin can communicate with your app, or your DB or whatever as necessary from within Word.

Users may find that to be a more usable approach in any case.


问:
Update Postgresql to newer version breaks legacy code
As Postgresql versions less than 9.5 are becoming unsupported I need to update this package in my Centos environment.

Current version: postgres -V (PostgreSQL) 9.2.24

Also in my ecosystem, there is another rpm that uses postgresql. For this rpm there are build, restart scripts and also various scripts that monitor dependency services, check status etc.

These scripts all reference postgresql using kwywork postgresql

https://www.postgresql.org/download/linux/redhat/ provided the exact steps how to do update/install. However for 9.6 version for example one need to use postgresql-9.6 keywords to refer to postgresql

This means one will need to go through all references of postgresql in scripts and code and analyze if it needs to be changed. Updating to another version afterwards would of course mean repeating this process.

Is there any 'out of the box' approach that allows us to leave the scripts untouched for this update?

I'm also copy/pasting the install postgresql 9.6 steps here.

```<code>yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

yum install postgresql96-devel postgresql96-server

/usr/pgsql-9.6/bin/postgresql96-setup initdb

systemctl enable postgresql-9.6

systemctl start postgresql-9.6
</code>```

This is to check all is good

```<code>service postgresql-9.6 status
</code>```

答:
I don't know any "out of the box approach".

You should alyways read detailed release notes to check if there is some incompatibility when upgrading.

Body:
As Postgresql versions less than 9.5 are becoming unsupported I need to update this package in my Centos environment.

Current version: postgres -V (PostgreSQL) 9.2.24

Also in my ecosystem, there is another rpm that uses postgresql. For this rpm there are build, restart scripts and also various scripts that monitor dependency services, check status etc.

These scripts all reference postgresql using kwywork postgresql

https://www.postgresql.org/download/linux/redhat/ provided the exact steps how to do update/install. However for 9.6 version for example one need to use postgresql-9.6 keywords to refer to postgresql

This means one will need to go through all references of postgresql in scripts and code and analyze if it needs to be changed. Updating to another version afterwards would of course mean repeating this process.

Is there any 'out of the box' approach that allows us to leave the scripts untouched for this update?

I'm also copy/pasting the install postgresql 9.6 steps here.

yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

yum install postgresql96-devel postgresql96-server

/usr/pgsql-9.6/bin/postgresql96-setup initdb

systemctl enable postgresql-9.6

systemctl start postgresql-9.6

This is to check all is good

service postgresql-9.6 status


答: The formula is: k = (n - 1) / 2, where n is kernel size. Here's a visualization:

Title: padding='same' conversion to PyTorch padding=#

Body:
I'm trying to convert the following Keras model code to pytorch, but am having problems dealing with padding='same'.

    model = Sequential()
    model.add(Conv2D(64, (3, 3), input_shape=img_size))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(Dropout(0.3))
    model.add(Conv2D(64, (3, 3), padding='same'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'))

Which produces the following summary:

Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 30, 30, 64)        1792
_________________________________________________________________
batch_normalization_1 (Batch (None, 30, 30, 64)        120
_________________________________________________________________
activation_1 (Activation)    (None, 30, 30, 64)        0
_________________________________________________________________
dropout_1 (Dropout)          (None, 30, 30, 64)        0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 30, 30, 64)        36928
_________________________________________________________________
batch_normalization_2 (Batch (None, 30, 30, 64)        120
_________________________________________________________________
activation_2 (Activation)    (None, 30, 30, 64)        0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 15, 15, 64)        0
=================================================================
Total params: 38,960
Trainable params: 38,840
Non-trainable params: 120

Right now, I would write:

self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3,
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Dropout(0.3),
            nn.Conv2d(64, 64, kernel_size=3, padding = ?
                      bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2, padding = ?),
        )

Where padding should have numerical value. I was wondering if there is an easier way to calculate this since we're using padding='same'.

Also, the next line of the Keras model looks like:

model.add(Conv2D(128, (3, 3), padding='same'))

So I really need to brush up on how to calculate padding, especially after stride too. From a rough eye only, is the padding 2?


问:
How to get rid of the use of "end" in loops(python) for only the last element?
By using end="-" I got this loop. I want to remove that '-' for the last element.

```<code>  m=4
  n=1
  for i in range(1,4):
      for x in range(5,n,-1):
          print(" ",end="")
      n+=2
      for y in range(3,3-i,-1):
          print(y,end="-")
      for z in range(m,4):
          print(z,end="-")
      m-=1
      print()
</code>```

Output:

```<code>           3-
       3-2-3-
    3-2-1-2-3-
</code>```

答:
Welcome to SO!

Nice work progress! Here, in my solution I am trying to is to divide the responsibilities into smaller tasks.

To generate the number to print

To print these in design format

```<code>m=4
n=1
max_line_length = 20

def special_print(items):
    # convert each number to string
    str_items = [str(each) for each in items]
    # prepare output string
    output_string = '-'.join(str_items)
    prefix = ' ' * (max_line_length - len(output_string))
    print(prefix + output_string)
    # try
    # print(output_string.center(max_line_length))

for i in range(1,4):
    items = []
    n+=2
    for y in range(3,3-i,-1):
        items.append(y)
    for z in range(m,4):
        items.append(z)
    m-=1
    # print(items)
    special_print(items)
</code>```

Output

```<code>                   3
               3-2-3
           3-2-1-2-3
</code>```

Note:  This solution can be further simplified by Python Pros but I tried to keep simple enough for you to understand.

You can explore python string objects features like center, join and list-comprehension, len function to improve your Python skills.

Body:
By using end="-" I got this loop. I want to remove that '-' for the last element.

  m=4
  n=1
  for i in range(1,4):
      for x in range(5,n,-1):
          print(" ",end="")
      n+=2
      for y in range(3,3-i,-1):
          print(y,end="-")
      for z in range(m,4):
          print(z,end="-")
      m-=1
      print()

Output:

           3-
       3-2-3-
    3-2-1-2-3-

Body:
Welcome to SO!

Nice work progress! Here, in my solution I am trying to is to divide the responsibilities into smaller tasks.

To generate the number to print

To print these in design format

m=4
n=1
max_line_length = 20

def special_print(items):
    # convert each number to string
    str_items = [str(each) for each in items]
    # prepare output string
    output_string = '-'.join(str_items)
    prefix = ' ' * (max_line_length - len(output_string))
    print(prefix + output_string)
    # try
    # print(output_string.center(max_line_length))

for i in range(1,4):
    items = []
    n+=2
    for y in range(3,3-i,-1):
        items.append(y)
    for z in range(m,4):
        items.append(z)
    m-=1
    # print(items)
    special_print(items)

Output

                   3
               3-2-3
           3-2-1-2-3

Note:  This solution can be further simplified by Python Pros but I tried to keep simple enough for you to understand.

You can explore python string objects features like center, join and list-comprehension, len function to improve your Python skills.


问:
Using AJAX with an asp:Calendar
Total newb to .NET programming (and AJAX) but I've been working on this program a while. Many things I state in this question might not make sense, so please correct me where my understanding is off.

Right now I've got an ASP:Calendar which has this property: OnSelectionChanged = "SelectionChanged". So the SelectionChanged method is called on the server when the user clicks on the calendar. But this requires a postback, which is crazy slow -- in terms of my program, there's no need for the server to be involved at this point; the client can handle everything.

So I'd like to handle it with javascript. Have some kind of way for clicking the asp:Calendar to trigger a piece of javascript code. Do I do this with a some kind of ajax extender? Or is there another way?

答: I've used the jQuery datepicker before which doesn't do a postback when a date is chosen. </p>

Title: Using AJAX with an asp:Calendar


问:
Compilation problem on armhf with cmake on qt "Syntax error: wird unexpected (expecting ")""
recently i've been interested in qt for my work, I started a project on it and i needed to cross compile it.
On my computer, everything seems to work just fine like you can see below but on my colleague's computer I've got some errors. I've been searching for some answers but didn't find anything ...

```<code>~/work/qt/malo_zelie/armhf_build >cmake ..
-- Configuring done
-- Generating done
-- Build files have been written to: malo_zelie/armhf_build
    ~/work/qt/malo_zelie/armhf_build >make
Scanning dependencies of target malo_zelie_automoc
[ 16%] Automatic moc, uic and rcc for target malo_zelie
Generating moc source malo_zelie_automoc.dir/moc_mainwindow_BMDIVWC5MAP5U5.cpp
Generating moc compilation malo_zelie_automoc.cpp
Generating ui header ui_mainwindow.h
[ 16%] Built target malo_zelie_automoc
[ 33%] Generating ../malo_zelie_fr_FR.ts
Scanning directory '/home/mael/work/qt/malo_zelie'...
Updating '../malo_zelie_fr_FR.ts'...
    Found 1 source text(s) (0 new and 1 already existing)
Scanning dependencies of target malo_zelie
[ 50%] Building CXX object CMakeFiles/malo_zelie.dir/src/main.cpp.o
[ 66%] Building CXX object CMakeFiles/malo_zelie.dir/src/mainwindow.cpp.o
[ 83%] Building CXX object CMakeFiles/malo_zelie.dir/malo_zelie_automoc.cpp.o
[100%] Linking CXX executable malo_zelie
[100%] Built target malo_zelie
</code>```

but on my friend's computer here is what I got :

```<code>    :~/workspace/malo_zelie_qt/armhf_build$ cmake ..
    -- Configuring done
    -- Generating done
    -- Build files have been written to: malo_zelie_qt/armhf_build
    colin@debian:~/workspace/malo_zelie_qt/armhf_build$ make
    [ 16%] Automatic moc, uic and rcc for target malo_zelie
    Generating moc source malo_zelie_automoc.dir/moc_mainwindow_BMDIVWC5MAP5U5.cpp
    /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: Syntax error: word unexpected (expecting ")")
    AUTOGEN: error: process for /home/colin/workspace/malo_zelie_qt/armhf_build/malo_zelie_automoc.dir/moc_mainwindow_BMDIVWC5MAP5U5.cpp failed:
    /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: Syntax error: word unexpected (expecting ")")
    Generating moc compilation malo_zelie_automoc.cpp
    Generating ui header ui_mainwindow.h
    /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: Syntax error: word unexpected (expecting ")")
    AUTOUIC: error: process for ui_mainwindow.h needed by
     "/home/colin/workspace/malo_zelie_qt/src/mainwindow.cpp"
    failed:
    /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: Syntax error: word unexpected (expecting ")")
    moc failed...
    CMakeFiles/malo_zelie_automoc.dir/build.make:57 : la recette pour la cible « CMakeFiles/malo_zelie_automoc » a échouée
    make[2]: [CMakeFiles/malo_zelie_automoc]
Erreur 1 CMakeFiles/Makefile2:104 : la recette pour la cible « CMakeFiles/malo_zelie_automoc.dir/all » a échouée make[1]: [CMakeFiles/malo_zelie_automoc.dir/all]
Erreur 2 Makefile:83 : la recette pour la cible « all » a échouée make: [all] Erreur 2
</code>```

here is the CmakeList.txt :

```<code>cmake_minimum_required(VERSION 3.5)

project(malo_zelie LANGUAGES CXX)

set( CMAKE_PREFIX_PATH "~/Qt/5.15.0" )

option( USE_CLANG "Use Clang compiler." OFF )
option( USE_LIBCPP "Use LLVM's libc++ instead of GNU's libstdc++ (requires clang)" OFF )
option( USE_ARMHF "use armhf compiler and linker." OFF)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# QtCreator supports the following variables for Android, which are identical to qmake Android variables.
# Check http://doc.qt.io/qt-5/deployment-android.html for more information.
# They need to be set before the find_package(Qt5 ...) call.

#if(ANDROID)
#    set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
#    if (ANDROID_ABI STREQUAL "armeabi-v7a")
#        set(ANDROID_EXTRA_LIBS
#            ${CMAKE_CURRENT_SOURCE_DIR}/path/to/libcrypto.so
#            ${CMAKE_CURRENT_SOURCE_DIR}/path/to/libssl.so)
#    endif()
#endif()

if( USE_ARMHF )
        set( CMAKE_FIND_ROOT_PATH "/usr/lib/arm-linux-gnueabihf/")
        set( COMXENTEO "ComXenteo2-armhf")
        set( CMAKE_LINKER "arm-linux-gnueabihf-ld")
        set( CMAKE_CXX_COMPILER "arm-linux-gnueabihf-g++" )
        set( CMAKE_C_COMPILER "arm-linux-gnueabihf-gcc" )
        set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FMAGS} -Wno-attributes")
        set( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g3" )
        set( Qt5Core_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5Core" )
        set( Qt5Gui_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5Gui" )
        set( Qt5LinguistTools_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5LinguistTools" )
        set( Qt5Widgets_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5Widgets" )
        set( Qt5_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5" )
else()
        set( CMAKE_FIND_ROOT_PATH "/usr/lib/x86_64-linux-gnu/")
        set( Qt5Core_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5Core" )
        set( Qt5Gui_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5Gui" )
        set( Qt5LinguistTools_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5LinguistTools" )
        set( Qt5Widgets_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5Widgets" )
        set( Qt5_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5" )
        set(COMXENTEO "ComXenteo2-x64")
        if( USE_CLANG )
                set( CMAKE_CXX_COMPILER "clang++" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Weverything" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-padded" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-weak-vtables" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++98-compat -Wno-c++98-compat-pedantic" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-exit-time-destructors" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-global-constructors" )
                if( USE_LIBCPP )
                        set( ${CMAKE_CXX_FLAGS} "${CMAKE_CXX_FLAGS} -stdlib=libc++" )
                endif
      endif()
endif()

find_package( Qt5 COMPONENTS Widgets LinguistTools REQUIRED)

set(TS_FILES malo_zelie_fr_FR.ts)

file( GLOB malo_zelie_src "src/*.cpp" "src/*.h" "src/*.ui" )

if(ANDROID)
  add_library(malo_zelie SHARED
                ${malo_zelie_src}
    ${TS_FILES}
  )
else()
  add_executable(malo_zelie
                ${malo_zelie_src}
    ${TS_FILES}
  )
endif()

set( EXT_LIBS
        #       ${sga_LIBRARIES}
        ${COMXENTEO}
)

set( EXT_INCLUDES
        #       ${sga_INCLUDE_DIRS}
)

set( EXT_COMP
        # ${sga_CFLAGS_OTHER}
)

target_link_libraries( malo_zelie PRIVATE Qt5::Widgets ${EXT_LIBS} )
target_include_directories( malo_zelie PUBLIC src ${EXT_INCLUDES} )
target_compile_options( malo_zelie PUBLIC ${EXT_COMP} )

qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})()
</code>```

does someone has any idea ? Sorry for the clumsy post, it's my first one.

答: Okey that was it, thanx to Frant, on my computer there was qemu installed so I could run arm binary, but on my colleague's computer, qemu wasn't installed and moc uic and rcc called are arm binary, I should change this in the future but for now I just installed qemu on his computer and everythings works just fine, thx.</p>

Body:
recently i've been interested in qt for my work, I started a project on it and i needed to cross compile it.
On my computer, everything seems to work just fine like you can see below but on my colleague's computer I've got some errors. I've been searching for some answers but didn't find anything ...

~/work/qt/malo_zelie/armhf_build >cmake ..
-- Configuring done
-- Generating done
-- Build files have been written to: malo_zelie/armhf_build
    ~/work/qt/malo_zelie/armhf_build >make
Scanning dependencies of target malo_zelie_automoc
[ 16%] Automatic moc, uic and rcc for target malo_zelie
Generating moc source malo_zelie_automoc.dir/moc_mainwindow_BMDIVWC5MAP5U5.cpp
Generating moc compilation malo_zelie_automoc.cpp
Generating ui header ui_mainwindow.h
[ 16%] Built target malo_zelie_automoc
[ 33%] Generating ../malo_zelie_fr_FR.ts
Scanning directory '/home/mael/work/qt/malo_zelie'...
Updating '../malo_zelie_fr_FR.ts'...
    Found 1 source text(s) (0 new and 1 already existing)
Scanning dependencies of target malo_zelie
[ 50%] Building CXX object CMakeFiles/malo_zelie.dir/src/main.cpp.o
[ 66%] Building CXX object CMakeFiles/malo_zelie.dir/src/mainwindow.cpp.o
[ 83%] Building CXX object CMakeFiles/malo_zelie.dir/malo_zelie_automoc.cpp.o
[100%] Linking CXX executable malo_zelie
[100%] Built target malo_zelie

but on my friend's computer here is what I got :

    :~/workspace/malo_zelie_qt/armhf_build$ cmake ..
    -- Configuring done
    -- Generating done
    -- Build files have been written to: malo_zelie_qt/armhf_build
    colin@debian:~/workspace/malo_zelie_qt/armhf_build$ make
    [ 16%] Automatic moc, uic and rcc for target malo_zelie
    Generating moc source malo_zelie_automoc.dir/moc_mainwindow_BMDIVWC5MAP5U5.cpp
    /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: Syntax error: word unexpected (expecting ")")
    AUTOGEN: error: process for /home/colin/workspace/malo_zelie_qt/armhf_build/malo_zelie_automoc.dir/moc_mainwindow_BMDIVWC5MAP5U5.cpp failed:
    /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/moc: Syntax error: word unexpected (expecting ")")
    Generating moc compilation malo_zelie_automoc.cpp
    Generating ui header ui_mainwindow.h
    /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: Syntax error: word unexpected (expecting ")")
    AUTOUIC: error: process for ui_mainwindow.h needed by
     "/home/colin/workspace/malo_zelie_qt/src/mainwindow.cpp"
    failed:
    /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: 1: /usr/lib/arm-linux-gnueabihf/qt5/bin/uic: Syntax error: word unexpected (expecting ")")
    moc failed...
    CMakeFiles/malo_zelie_automoc.dir/build.make:57 : la recette pour la cible « CMakeFiles/malo_zelie_automoc » a échouée
    make[2]: [CMakeFiles/malo_zelie_automoc]
Erreur 1 CMakeFiles/Makefile2:104 : la recette pour la cible « CMakeFiles/malo_zelie_automoc.dir/all » a échouée make[1]: [CMakeFiles/malo_zelie_automoc.dir/all]
Erreur 2 Makefile:83 : la recette pour la cible « all » a échouée make: [all] Erreur 2

here is the CmakeList.txt :

cmake_minimum_required(VERSION 3.5)

project(malo_zelie LANGUAGES CXX)

set( CMAKE_PREFIX_PATH "~/Qt/5.15.0" )

option( USE_CLANG "Use Clang compiler." OFF )
option( USE_LIBCPP "Use LLVM's libc++ instead of GNU's libstdc++ (requires clang)" OFF )
option( USE_ARMHF "use armhf compiler and linker." OFF)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# QtCreator supports the following variables for Android, which are identical to qmake Android variables.
# Check http://doc.qt.io/qt-5/deployment-android.html for more information.
# They need to be set before the find_package(Qt5 ...) call.

#if(ANDROID)
#    set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
#    if (ANDROID_ABI STREQUAL "armeabi-v7a")
#        set(ANDROID_EXTRA_LIBS
#            ${CMAKE_CURRENT_SOURCE_DIR}/path/to/libcrypto.so
#            ${CMAKE_CURRENT_SOURCE_DIR}/path/to/libssl.so)
#    endif()
#endif()

if( USE_ARMHF )
        set( CMAKE_FIND_ROOT_PATH "/usr/lib/arm-linux-gnueabihf/")
        set( COMXENTEO "ComXenteo2-armhf")
        set( CMAKE_LINKER "arm-linux-gnueabihf-ld")
        set( CMAKE_CXX_COMPILER "arm-linux-gnueabihf-g++" )
        set( CMAKE_C_COMPILER "arm-linux-gnueabihf-gcc" )
        set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FMAGS} -Wno-attributes")
        set( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g3" )
        set( Qt5Core_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5Core" )
        set( Qt5Gui_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5Gui" )
        set( Qt5LinguistTools_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5LinguistTools" )
        set( Qt5Widgets_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5Widgets" )
        set( Qt5_DIR "/usr/lib/arm-linux-gnueabihf/cmake/Qt5" )
else()
        set( CMAKE_FIND_ROOT_PATH "/usr/lib/x86_64-linux-gnu/")
        set( Qt5Core_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5Core" )
        set( Qt5Gui_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5Gui" )
        set( Qt5LinguistTools_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5LinguistTools" )
        set( Qt5Widgets_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5Widgets" )
        set( Qt5_DIR "/usr/lib/x86_64-linux-gnu/cmake/Qt5" )
        set(COMXENTEO "ComXenteo2-x64")
        if( USE_CLANG )
                set( CMAKE_CXX_COMPILER "clang++" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Weverything" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-padded" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-weak-vtables" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++98-compat -Wno-c++98-compat-pedantic" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-exit-time-destructors" )
                set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-global-constructors" )
                if( USE_LIBCPP )
                        set( ${CMAKE_CXX_FLAGS} "${CMAKE_CXX_FLAGS} -stdlib=libc++" )
                endif
      endif()
endif()

find_package( Qt5 COMPONENTS Widgets LinguistTools REQUIRED)

set(TS_FILES malo_zelie_fr_FR.ts)

file( GLOB malo_zelie_src "src/*.cpp" "src/*.h" "src/*.ui" )

if(ANDROID)
  add_library(malo_zelie SHARED
                ${malo_zelie_src}
    ${TS_FILES}
  )
else()
  add_executable(malo_zelie
                ${malo_zelie_src}
    ${TS_FILES}
  )
endif()

set( EXT_LIBS
        #       ${sga_LIBRARIES}
        ${COMXENTEO}
)

set( EXT_INCLUDES
        #       ${sga_INCLUDE_DIRS}
)

set( EXT_COMP
        # ${sga_CFLAGS_OTHER}
)

target_link_libraries( malo_zelie PRIVATE Qt5::Widgets ${EXT_LIBS} )
target_include_directories( malo_zelie PUBLIC src ${EXT_INCLUDES} )
target_compile_options( malo_zelie PUBLIC ${EXT_COMP} )

qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})()

does someone has any idea ? Sorry for the clumsy post, it's my first one.


问:
File not found dependency error while running react native ios app
So I wanted to install a dependency using npm which is react-native-router-flux, but since it wasn't working due to the compatibility versions with react & react-native, it was breaking my project app. So I removed it from the package.json file.

Tried removing it by doing:

npm uninstall --save react-native-router-flux

Even tried to remove it manually from the package.json file, but for some reason, now it looks like my whole project is broken due to that.
Now whenever I do npm start

This is what is being displayed in my terminal:

```<code>error: bundling: Error: ENOENT: no such file or directory, open '/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native-router-flux/node_modules/react-native/Libraries/Components/ActivityIndicator/ActivityIndicator.js'
    at Error (native)
    at Object.fs.openSync (fs.js:634:18)
    at Object.fs.readFileSync (fs.js:502:33)
    at Module._readSourceCode (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:200:29)
    at Module._getCacheProps (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:420:29)
    at Module._readFromTransformCache (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:376:29)
    at Module.readCached (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:363:25)
    at Promise.resolve.then (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/DependencyGraph/ResolutionRequest.js:167:29)
    at process._tickCallback (internal/process/next_tick.js:103:7)
Bundling `index.ios.js`  94.0% (2941/3033)
</code>```

I tried to rm -rf /node_modules 100 times and npm install another 100 times and this keeps failing and failing, I can't understand where is trying to access that file! if it was removed!!!

This is my package.json now:

```<code>{
  "name": "myapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "moment": "^2.18.1",
    "native-base": "^2.1.3",
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.0",
    "react-native-flags": "^1.0.0"
  },
  "devDependencies": {
    "babel-jest": "19.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "19.0.2",
    "react-test-renderer": "16.0.0-alpha.6"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

Is also throwing WARNINGS for versions and other things too:

```<code>npm WARN native-base-shoutem-theme@0.1.3 requires a peer of react@>=15.1.0 but none was installed.
npm WARN @shoutem/animation@0.8.10 requires a peer of react@^15.0.0 but none was installed.
npm WARN react-static-container@1.0.1 requires a peer of react@^0.13.0 || ^0.14.0 || ^15.0.0 but none was installed.
</code>```

This is being thrown for native-base dependency:

```<code> UNMET PEER DEPENDENCY react@^0.13.0 || ^0.14.0 || ^15.0.0
</code>```

Can anyone help me? this is driving me crazy, been 'fighting' with this for hours now and I can't continue with my app.

Thanks in advance.

EDIT:

After changing some versions for react, react-native and native-base. Still having warnings and looks like the packager is trying to access a react-native file within react-native-route-flux.

1) This is my current package.json

```<code>{
  "name": "myapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "moment": "^2.18.1",
    "native-base": "^2.1.3",
    "react": "16.0.0-alpha.3",
    "react-native": "^0.43.0",
    "react-native-flags": "^1.0.0"
  },
  "devDependencies": {
    "babel-jest": "19.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "19.0.2",
    "react-test-renderer": "16.0.0-alpha.6"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

2) These are the warnings:

```<code>npm WARN react-native@0.43.4 requires a peer of react@16.0.0-alpha.6 but none was installed.
npm WARN native-base-shoutem-theme@0.1.3 requires a peer of react@>=15.1.0 but none was installed.
npm WARN @shoutem/animation@0.8.10 requires a peer of react@^15.0.0 but none was installed.
npm WARN react-static-container@1.0.1 requires a peer of react@^0.13.0 || ^0.14.0 || ^15.0.0 but none was installed.
npm WARN react-test-renderer@16.0.0-alpha.6 requires a peer of react@^16.0.0-alpha.6 but none was installed.
</code>```

Also throws some UNMET PEER DEPENDENCY on native-base:

```<code>├─┬ native-base@2.1.3
│ ├─┬ @shoutem/animation@0.8.10
│ │ ├── hoist-non-react-statics@1.2.0
│ │ └── lodash@4.17.4
│ ├── blueimp-md5@2.7.0
│ ├── clamp@1.0.1
│ ├─┬ color@0.11.4
│ │ ├── clone@1.0.2
│ │ ├─┬ color-convert@1.9.0
│ │ │ └── color-name@1.1.2
│ │ └── color-string@0.3.0
│ ├─┬ fs-extra@2.1.2
│ │ └── jsonfile@2.4.0
│ ├── lodash@4.11.2
│ ├── native-base-shoutem-theme@0.1.3
│ ├── print-message@2.1.0
│ ├── UNMET PEER DEPENDENCY react@^15.0.0
│ ├── react-native-drawer@2.3.0
│ ├── react-native-easy-grid@0.1.7
│ ├── react-native-keyboard-aware-scroll-view@0.2.7
│ ├─┬ react-native-scrollable-tab-view@0.7.4
│ │ ├── UNMET PEER DEPENDENCY react@^0.13.0 || ^0.14.0 || ^15.0.0
│ │ └── react-static-container@1.0.1
│ ├── react-native-vector-icons@4.0.1
│ ├─┬ react-tween-state@0.1.5
│ │ └─┬ raf@3.3.2
│ │   └── performance-now@2.1.0
│ └── tween-functions@1.2.0
├─┬ UNMET PEER DEPENDENCY react@16.0.0-alpha.3
</code>```

And in console when run, throws the red screen error in the simulator from XCode saying:

No Dimension set for key window

Looks it's a known issue according to his github. But damn, I don't want react-native-router-flux anymore, I don't even have it in my package.json nor installed and is still causing trouble, this dependency is a virus.

答:
```<code>npm install react-native-reanimated
react-native-gesture-handler
react-native-screens
react-native-safe-area-context
@react-native-community/masked-view
</code>```

Body:
So I wanted to install a dependency using npm which is react-native-router-flux, but since it wasn't working due to the compatibility versions with react & react-native, it was breaking my project app. So I removed it from the package.json file.

Tried removing it by doing:

npm uninstall --save react-native-router-flux

Even tried to remove it manually from the package.json file, but for some reason, now it looks like my whole project is broken due to that.
Now whenever I do npm start

This is what is being displayed in my terminal:

error: bundling: Error: ENOENT: no such file or directory, open '/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native-router-flux/node_modules/react-native/Libraries/Components/ActivityIndicator/ActivityIndicator.js'
    at Error (native)
    at Object.fs.openSync (fs.js:634:18)
    at Object.fs.readFileSync (fs.js:502:33)
    at Module._readSourceCode (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:200:29)
    at Module._getCacheProps (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:420:29)
    at Module._readFromTransformCache (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:376:29)
    at Module.readCached (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/Module.js:363:25)
    at Promise.resolve.then (/Users/marian-mac/Documents/dev/example/myapp/node_modules/react-native/packager/src/node-haste/DependencyGraph/ResolutionRequest.js:167:29)
    at process._tickCallback (internal/process/next_tick.js:103:7)
Bundling `index.ios.js`  94.0% (2941/3033)

I tried to rm -rf /node_modules 100 times and npm install another 100 times and this keeps failing and failing, I can't understand where is trying to access that file! if it was removed!!!

This is my package.json now:

{
  "name": "myapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "moment": "^2.18.1",
    "native-base": "^2.1.3",
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.0",
    "react-native-flags": "^1.0.0"
  },
  "devDependencies": {
    "babel-jest": "19.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "19.0.2",
    "react-test-renderer": "16.0.0-alpha.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

Is also throwing WARNINGS for versions and other things too:

npm WARN native-base-shoutem-theme@0.1.3 requires a peer of react@>=15.1.0 but none was installed.
npm WARN @shoutem/animation@0.8.10 requires a peer of react@^15.0.0 but none was installed.
npm WARN react-static-container@1.0.1 requires a peer of react@^0.13.0 || ^0.14.0 || ^15.0.0 but none was installed.

This is being thrown for native-base dependency:

 UNMET PEER DEPENDENCY react@^0.13.0 || ^0.14.0 || ^15.0.0

Can anyone help me? this is driving me crazy, been 'fighting' with this for hours now and I can't continue with my app.

Thanks in advance.

EDIT:

After changing some versions for react, react-native and native-base. Still having warnings and looks like the packager is trying to access a react-native file within react-native-route-flux.

1) This is my current package.json

{
  "name": "myapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "moment": "^2.18.1",
    "native-base": "^2.1.3",
    "react": "16.0.0-alpha.3",
    "react-native": "^0.43.0",
    "react-native-flags": "^1.0.0"
  },
  "devDependencies": {
    "babel-jest": "19.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "19.0.2",
    "react-test-renderer": "16.0.0-alpha.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

2) These are the warnings:

npm WARN react-native@0.43.4 requires a peer of react@16.0.0-alpha.6 but none was installed.
npm WARN native-base-shoutem-theme@0.1.3 requires a peer of react@>=15.1.0 but none was installed.
npm WARN @shoutem/animation@0.8.10 requires a peer of react@^15.0.0 but none was installed.
npm WARN react-static-container@1.0.1 requires a peer of react@^0.13.0 || ^0.14.0 || ^15.0.0 but none was installed.
npm WARN react-test-renderer@16.0.0-alpha.6 requires a peer of react@^16.0.0-alpha.6 but none was installed.

Also throws some UNMET PEER DEPENDENCY on native-base:

├─┬ native-base@2.1.3
│ ├─┬ @shoutem/animation@0.8.10
│ │ ├── hoist-non-react-statics@1.2.0
│ │ └── lodash@4.17.4
│ ├── blueimp-md5@2.7.0
│ ├── clamp@1.0.1
│ ├─┬ color@0.11.4
│ │ ├── clone@1.0.2
│ │ ├─┬ color-convert@1.9.0
│ │ │ └── color-name@1.1.2
│ │ └── color-string@0.3.0
│ ├─┬ fs-extra@2.1.2
│ │ └── jsonfile@2.4.0
│ ├── lodash@4.11.2
│ ├── native-base-shoutem-theme@0.1.3
│ ├── print-message@2.1.0
│ ├── UNMET PEER DEPENDENCY react@^15.0.0
│ ├── react-native-drawer@2.3.0
│ ├── react-native-easy-grid@0.1.7
│ ├── react-native-keyboard-aware-scroll-view@0.2.7
│ ├─┬ react-native-scrollable-tab-view@0.7.4
│ │ ├── UNMET PEER DEPENDENCY react@^0.13.0 || ^0.14.0 || ^15.0.0
│ │ └── react-static-container@1.0.1
│ ├── react-native-vector-icons@4.0.1
│ ├─┬ react-tween-state@0.1.5
│ │ └─┬ raf@3.3.2
│ │   └── performance-now@2.1.0
│ └── tween-functions@1.2.0
├─┬ UNMET PEER DEPENDENCY react@16.0.0-alpha.3

And in console when run, throws the red screen error in the simulator from XCode saying:

No Dimension set for key window

Looks it's a known issue according to his github. But damn, I don't want react-native-router-flux anymore, I don't even have it in my package.json nor installed and is still causing trouble, this dependency is a virus.


问:
Using functions in postgres query skips the index. Any solution to use functions with index applied
For eg:

If lower function is removed, the query performance is better than using lower. Using lower skips the index. Is

```<code>SELECT X.article_number, X.online_description
FROM articles X
WHERE LOWER(X.online_description) % usp_get_search_terms ('coke');
</code>```

答:
An index can only be used to speed up a WHERE condition if the condition is of the following form:

```<code><indexed expression> <operator> <constant>
</code>```

Here <operator> must be an operator in the operator class of the index, and <constant> need not really be a constant, but fixed for the duration of the index scan.

I assume that % is the similarity operator from the pg_trgm extension. Then you need either a GIN index with the gin_trgm_ops operator class or a GiST index with the gist_trgm_ops operator class.

Since trigram operations are case insensitive anyway, you should remover the lower() from the query. Otherwise, you'd have to create the index on lower(online_description), which would be a waste of CPU.

Body:
For eg:

If lower function is removed, the query performance is better than using lower. Using lower skips the index. Is

SELECT X.article_number, X.online_description
FROM articles X
WHERE LOWER(X.online_description) % usp_get_search_terms ('coke');

Body:
An index can only be used to speed up a WHERE condition if the condition is of the following form:

<indexed expression> <operator> <constant>

Here <operator> must be an operator in the operator class of the index, and <constant> need not really be a constant, but fixed for the duration of the index scan.

I assume that % is the similarity operator from the pg_trgm extension. Then you need either a GIN index with the gin_trgm_ops operator class or a GiST index with the gist_trgm_ops operator class.

Since trigram operations are case insensitive anyway, you should remover the lower() from the query. Otherwise, you'd have to create the index on lower(online_description), which would be a waste of CPU.


问:
NSWindow problem
Please help me. I set frame to the window like this:

```<code>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
[window makeKeyWindow];
[window setFrame:NSMakeRect(0, 0, 1024, 768) display:YES];
[window setBackgroundColor:[NSColor clearColor]];
[window center];
}
</code>```

But real window size: width = 1024, height = 620. I think because my screen size (1280x720).

So, when [window setContentView:myView], myView is disable a part.

I can't solve this problem. Please help me solve this.

Thanks.

答: Size your content view to fit the space available using -[NSWindow contentRectForFrameRect:]. You should also consider sizing your window's frame to fit the available space, as well, such as by using -[NSScreen visibleFrame]. Both the Dock and the menu bar eat some space, so you should not expect to have the full screen size available to your application.

Title: NSWindow problem

Body:
Please help me. I set frame to the window like this:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
[window makeKeyWindow];
[window setFrame:NSMakeRect(0, 0, 1024, 768) display:YES];
[window setBackgroundColor:[NSColor clearColor]];
[window center];
}

But real window size: width = 1024, height = 620. I think because my screen size (1280x720).

So, when [window setContentView:myView], myView is disable a part.

I can't solve this problem. Please help me solve this.

Thanks.