问:
Tooltipster - how to have tooltips with the same content pop up if one of those tooltips is clicked
I'm setting up an anatomy comparison page where I have two illustrations side by side of two animals (e.g. mudpuppy and shark), with an svg overlayed on each so that clicking on a muscle triggers a tooltip with the muscle's name on it.

However, I want to be able to click on the "intermandibularis" muscle on a mudpuppy and have the "intermandibularis" tooltip of both the mudpuppy and shark pop-up as well.

How would I achieve this with Tooltipster? I was thinking of using the functionReady function but because I'm new to programming I'm not sure how to use it.

Here's a snippet of my code for now (please note there are more svg's in the actual file, I just took them out so the code is easier to read):

 $(document).ready(function() {
            $('.tooltip').tooltipster({
             theme: ['tooltipster-shadow', 'tooltipster-shadow-customized'],
             trigger: 'click'
             });

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Left column -->
 <div class='diagram' style="width:calc(50% - 49px); float:left; height: 85%; background-image: url(Images/mudpuppy_sideview.png); background-repeat: no-repeat; background-size:contain;" id="leftCol">
  <?xml version="1.0" encoding="utf-8"?>
  <!-- Generator: Adobe Illustrator 24.1.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
  <svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">
  <style type="text/css">
   .tooltip{opacity:0;fill:#FFFFFF;}
  </style>

  <path id="mud_intermandibularis" class="tooltip" title="Intermandibularis" d=" M185.78,232.53c-3.77-6.28-32.12,3.11-42.47,5.87c-10.36,2.76-39.02,8.98-41.44,14.5
   c-1.78,4.07,43.88,31.14,67.86,31.42c8.58,0.1,11.4-8.12,12.78-17.61C183.19,261.95,190.96,241.16,185.78,232.53z"/>
  </svg>
 </div>

<!-- Right column -->
 <div class="diagram" style="width:calc(50% - 49px); float:right; height: 85%; background-image: url(Images/shark_sideview.png); background-repeat: no-repeat; background-size:contain;">
  <?xml version="1.0" encoding="utf-8"?>
  <!-- Generator: Adobe Illustrator 24.1.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">
  <style type="text/css">
   .tooltip{opacity:0;fill:#FFFFFF;}
  </style>
  <path id="shark_intermandibularis" class="tooltip" title="Intermandibularis" d="M248.8,325.07c0,0-4.14,4.92-10.36,5.96c-6.22,1.04-18.39,0-18.39,0
   s8.55,13.47,22.01,15.28c13.47,1.81,49.73-2.59,50.24-6.47S251.39,325.33,248.8,325.07z"/>
  </svg>
 </div></code>```

Any help would be greatly appreciated! Thank you!

答:
Yes, use functionReady. Put an attribute on your element like data-muscle="intermandibularis"
and then

functionReady (instance, helper) {
  const muscle = $(instance.origin).data('muscle')
  $.tooltipster.instances()
    .forEach(inst => {
      if (inst !== instance && $(inst.origin).data('muscle') === muscle) {
        inst.open()
      }
    })
}
```

Body:
I'm setting up an anatomy comparison page where I have two illustrations side by side of two animals (e.g. mudpuppy and shark), with an svg overlayed on each so that clicking on a muscle triggers a tooltip with the muscle's name on it.

However, I want to be able to click on the "intermandibularis" muscle on a mudpuppy and have the "intermandibularis" tooltip of both the mudpuppy and shark pop-up as well.

How would I achieve this with Tooltipster? I was thinking of using the functionReady function but because I'm new to programming I'm not sure how to use it.

Here's a snippet of my code for now (please note there are more svg's in the actual file, I just took them out so the code is easier to read):

 $(document).ready(function() {
            $('.tooltip').tooltipster({
             theme: ['tooltipster-shadow', 'tooltipster-shadow-customized'],
             trigger: 'click'
             });

        });

  <?xml version="1.0" encoding="utf-8"?>

  <svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">

  <path id="mud_intermandibularis" class="tooltip" title="Intermandibularis" d=" M185.78,232.53c-3.77-6.28-32.12,3.11-42.47,5.87c-10.36,2.76-39.02,8.98-41.44,14.5
   c-1.78,4.07,43.88,31.14,67.86,31.42c8.58,0.1,11.4-8.12,12.78-17.61C183.19,261.95,190.96,241.16,185.78,232.53z"/>
  </svg>

  <?xml version="1.0" encoding="utf-8"?>

  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    viewBox="0 0 792 612" style="enable-background:new 0 0 792 612;" xml:space="preserve">

  <path id="shark_intermandibularis" class="tooltip" title="Intermandibularis" d="M248.8,325.07c0,0-4.14,4.92-10.36,5.96c-6.22,1.04-18.39,0-18.39,0
   s8.55,13.47,22.01,15.28c13.47,1.81,49.73-2.59,50.24-6.47S251.39,325.33,248.8,325.07z"/>
  </svg>

Any help would be greatly appreciated! Thank you!


来源: stackexchange

问:
Grails 3 Jasper path not found
I've been using jasper on grails 2.2.4 and everything works fine.  Now I'm trying to use it on grails 3.3.10 and seems that jasper cannot find its path as shown on the error.

I'm not sure if you need to specify the path for jasper since I did not specify any path on grails 2.2.4.

FYI: I'm using "compile 'org.grails.plugins:jasper:2.1.0'" and this is how I use it on show.gsp

```<code><g:jasperReport jasper="paymentreceipt" format="PDF"
   name="Payment_Voucher_${telmo.telnumber}">
   <input type="hidden" name="TELMO_ID" value="${telmo.id}" />
</g:jasperReport>
</code>```

I've added the "reports" folder to src/main/webapp and all my .jrxml and .jasper files are all in that folder also.

答: JasperReports work diferently in 3.3.10 than in previous versions, you should try adding the .jrxml into your view folder where you hold the .gsp you have the jasperReport tag in.</p>

ContentLicense: CC BY-SA 4.0

Title: Grails 3 Jasper path not found

Body:
I've been using jasper on grails 2.2.4 and everything works fine.  Now I'm trying to use it on grails 3.3.10 and seems that jasper cannot find its path as shown on the error.

I'm not sure if you need to specify the path for jasper since I did not specify any path on grails 2.2.4.

FYI: I'm using "compile 'org.grails.plugins:jasper:2.1.0'" and this is how I use it on show.gsp

<g:jasperReport jasper="paymentreceipt" format="PDF"
   name="Payment_Voucher_${telmo.telnumber}">
   <input type="hidden" name="TELMO_ID" value="${telmo.id}" />
</g:jasperReport>

I've added the "reports" folder to src/main/webapp and all my .jrxml and .jasper files are all in that folder also.


问:
Why does rails.bat work but rails does not?
When attempting to create a new Ruby on Rails app in Windows the command

```<code>rails new test_app
</code>```

returns an error

```<code>'rails' is not recognized as an internal or external command, operable program
or batch  file
</code>```

but the command

```<code>rails.bat new test_app
</code>```

works just fine. I have added the ..\ruby\bin directory to my PATH variable but it doesn't seem to change anything. A similar problem occurs for all other 'rails' commands as well as for 'rake' vs 'rake.bat'.

Running type rails.bat returns:

```<code>@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"ruby.exe" "C:/_LOCALdata/Ruby192/bin/rails" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"ruby.exe" "%~dpn0" %*
</code>```

答:
From your updated question I can assume that PATHEXT, the environment variable responsible for knowing files to be executed without extensions is missing .BAT from it.

To confirm, please do SET PATHEXT on a new command prompt and see the output, the result should be a semi-colon separated values that include .EXE, .BAT, .COM and perhaps .RB

If PATHEXT is empty or do not contain .BAT in it, that could explain why is not working.

Depending on your version of Windows, the installation of RubyInstaller might have caused that, in which case I recommend uninstall and verify the environment variables to see if it get restored.

Then try to install it again.

See this thread on RubyInstaller about this.

ContentLicense: CC BY-SA 3.0

Body:
When attempting to create a new Ruby on Rails app in Windows the command

rails new test_app

returns an error

'rails' is not recognized as an internal or external command, operable program
or batch  file

but the command

rails.bat new test_app

works just fine. I have added the ..\ruby\bin directory to my PATH variable but it doesn't seem to change anything. A similar problem occurs for all other 'rails' commands as well as for 'rake' vs 'rake.bat'.

Running type rails.bat returns:

@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"ruby.exe" "C:/_LOCALdata/Ruby192/bin/rails" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"ruby.exe" "%~dpn0" %*


问:
mongoDB project array element after filter
I have the following (simplified) aggregation:

```<code>Model.aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer',
        as: 'orders',
      },
    },
    {
      $project: {
        openOrders: {
          $filter: {
            input: '$orders',
            as: 'order',
            cond: { $eq: ['$$order.status', 'open'] },
          },
        },
      },
    },
  ])
</code>```

which returns the following:

```<code>{
  _id: ...,
  openOrders: [
    [Object], [Object]
  ],
}
</code>```

Those [Object]'s are simply the returned objects, persisted in the database, with all their fields.

I don't find a way to project/filter out those objects' fields and instead return only their _id's:

```<code>{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}
</code>```

EDIT: I'd rather prefer the following expected output:

```<code>{
  _id: ...,
  openOrders: [
    { _id: ... },
    { _id: ... }
  ],
}
</code>```

I tried adding a new $project stage at various points of the aggregation with no success. Can someone help me?

答:
As you need an array of _id's like this

```<code>openOrders: [ _id: ..., _id: .... ]
</code>```

but not an array of _id's in objects :

```<code>openOrders: [ {_id: ...}, {_id: ....} ]
</code>```

You need to use $reduce instead of $filter :

Try below query :

```<code> db.collection.aggregate([
    {
      $project: {
        openOrders: {
          $reduce: {
            input: "$orders", // Same like `$filter` use reduce to iterate on array
            initialValue: [], // consider an initial value
            in: { // If condition is met, push value to array else return holding array as is.
              $cond: [ { $eq: [ "$$this.status", "open" ] },
                { $concatArrays: [ "$$value", [ "$$this._id" ] ] },
                "$$value"
              ]
            }
          }
        }
      }
    }
  ])
</code>```

Test : mongoplayground

Note : In javaScript - if you're printing a JSON with objects, you need to print it with JSON.stringify(yourJSON) - which makes it a string, So that you don't see [Object], [Object] in console rather you would see actual objects.

Update :

If you need an array of objects with _id field just add another $project stage at the end, but I would highly suggest to use $reduce and get an array for your scenario :

```<code>{ $project: { "openOrders._id": 1 } } // which would just extract `_id` fields in each objects
</code>```

Test : mongoplayground

Body:
I have the following (simplified) aggregation:

Model.aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer',
        as: 'orders',
      },
    },
    {
      $project: {
        openOrders: {
          $filter: {
            input: '$orders',
            as: 'order',
            cond: { $eq: ['$$order.status', 'open'] },
          },
        },
      },
    },
  ])

which returns the following:

{
  _id: ...,
  openOrders: [
    [Object], [Object]
  ],
}

Those [Object]'s are simply the returned objects, persisted in the database, with all their fields.

I don't find a way to project/filter out those objects' fields and instead return only their _id's:

{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}

EDIT: I'd rather prefer the following expected output:

{
  _id: ...,
  openOrders: [
    { _id: ... },
    { _id: ... }
  ],
}

I tried adding a new $project stage at various points of the aggregation with no success. Can someone help me?

Body:
As you need an array of _id's like this

openOrders: [ _id: ..., _id: .... ]

but not an array of _id's in objects :

openOrders: [ {_id: ...}, {_id: ....} ]

You need to use $reduce instead of $filter :

Try below query :

 db.collection.aggregate([
    {
      $project: {
        openOrders: {
          $reduce: {
            input: "$orders", // Same like `$filter` use reduce to iterate on array
            initialValue: [], // consider an initial value
            in: { // If condition is met, push value to array else return holding array as is.
              $cond: [ { $eq: [ "$$this.status", "open" ] },
                { $concatArrays: [ "$$value", [ "$$this._id" ] ] },
                "$$value"
              ]
            }
          }
        }
      }
    }
  ])

Test : mongoplayground

Note : In javaScript - if you're printing a JSON with objects, you need to print it with JSON.stringify(yourJSON) - which makes it a string, So that you don't see [Object], [Object] in console rather you would see actual objects.

Update :

If you need an array of objects with _id field just add another $project stage at the end, but I would highly suggest to use $reduce and get an array for your scenario :

{ $project: { "openOrders._id": 1 } } // which would just extract `_id` fields in each objects

Test : mongoplayground


问:
RecyclerView cannot be found
I just started to try to use the RecyclerView. I added some lines into the build.grandle but I always get many error messages telling me:
' error: cannot find symbol'
' error: package androidx.recyclerview.widget does not exist'
and I do not understand why I am getting these error messages. Here you see the code of my grandle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.td.barapp"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        viewBinding {
            enabled = true
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.0.0'
    implementation 'com.android.support:cardview-v7:27.0.0'
}
</code>```

I'd appreciate every comment and would be quite thankful.

Update: I think I have a problem with AndroidX. I migrated to it by using Refactor-->Migrate to AndroidX in Android studio but I do not know how I should change my posted grandle.build file. At the moment in my grandle file I have some libararies like " implementation 'com.android.support:design:27.1.1' and I get the warning and error message: "This support library should not use a different version (27) than the compileSdkVersion (28) " But when I use " implementation 'com.android.support:appcompat-v7:28.0'" I also get an error message :"All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.1, 27.0.0. Examples include com.android.support:animated-vector-drawable..

Here you see a screenshot of the marked lines in the Build grandle file: How do I have to change these lines in order to use AndroidX? I'd be happy for your help because I am stuck on that problem.

答:
' error: cannot find symbol' ' error: package
  androidx.recyclerview.widget does not exist' and I do not understand
  why I am getting these error

It seems that you're using RecyclerView from androidx in your layout with androidx.recyclerview.widget.RecyclerView; but you need to add support library RecyclerView which is android.support.v7.widget.RecyclerView

this requires to include implementation 'com.android.support:recyclerview-v7:28.0.0' in your gradle module

Title: RecyclerView cannot be found

Body:
I just started to try to use the RecyclerView. I added some lines into the build.grandle but I always get many error messages telling me:
' error: cannot find symbol'
' error: package androidx.recyclerview.widget does not exist'
and I do not understand why I am getting these error messages. Here you see the code of my grandle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.td.barapp"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        viewBinding {
            enabled = true
        }

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.0.0'
    implementation 'com.android.support:cardview-v7:27.0.0'
}

I'd appreciate every comment and would be quite thankful.

Update: I think I have a problem with AndroidX. I migrated to it by using Refactor-->Migrate to AndroidX in Android studio but I do not know how I should change my posted grandle.build file. At the moment in my grandle file I have some libararies like " implementation 'com.android.support:design:27.1.1' and I get the warning and error message: "This support library should not use a different version (27) than the compileSdkVersion (28) " But when I use " implementation 'com.android.support:appcompat-v7:28.0'" I also get an error message :"All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.1, 27.0.0. Examples include com.android.support:animated-vector-drawable..

Here you see a screenshot of the marked lines in the Build grandle file: How do I have to change these lines in order to use AndroidX? I'd be happy for your help because I am stuck on that problem.


问:
Redirecting old permalink structure to the new one
I had a wordpress site installed in a sub folder with category/post-title permalink structure, which resulted in the following url structure

http://www.mysite.com/subfolder/category/post-title

However as I needed to move my site to the root folder and changed the permalink structure to year/month/post-title, which looks like below, users who visit my website through the links published on other websites see 404 error page as expected.

http://www.mysite.com/year/month/post-title

While doing the changes, moving wordpress to the root directory and changing permalink structure, I forgot to take into account that such problem could occur. Anyway, I made a mistake and now I'm trying to fix the problem.

I wonder is there a way to redirect the old urls to the new ones? Editing .htaccess or using a plugin or something else. The method doesn't matter at this stage. All I want is to solve the problem

Any help?
Thanks in advance.

答: Use WordPress › Redirection « WordPress Plugins, which will 301 redirect, import a csv of redirects and log 404s without having to deal with mod_rewrite and .htaccess.</p>


问:
HTML Table Row Height Problem (height="x" vs style="height:x")
Using Chrome on Windows 10, this code "works", in the sense that it creates an empty row that is 100px tall...

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>
  </head>
  <body>
    <table id="content" style="width:100%;border:1px solid black">
      <tr id="topRow" height="100" style="width:100%;"></tr>
    </table>
  </body>
</html>
</code>```

... but the following doesn't, in that it generates a very short row, certainly not 100 pixels tall ...

```<code><html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>
  </head>
  <body>
    <table id="content" style="width:100%;border:1px solid black">
      <tr id="topRow" style="width:100%;height=100px"></tr>
    </table>
  </body>
</html>
</code>```

I was trying to use the latter form since the former is deprecated (if not obsolete).

What am I doing wrong or, more likely, misunderstanding?

答:
I guess u can try changing table layout to fixed...
Cause maybe the row doesn't show 100px bcoz it's empty</p>

Body:
Using Chrome on Windows 10, this code "works", in the sense that it creates an empty row that is 100px tall...

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>

... but the following doesn't, in that it generates a very short row, certainly not 100 pixels tall ...

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Test</title>

I was trying to use the latter form since the former is deprecated (if not obsolete).

What am I doing wrong or, more likely, misunderstanding?


问:
Use map(v, reduce) to create Fibonacci sequence in R?
I was wondering if we could use purrr's map and reduce to create to Fibonacci function akin to this one in JavaScript:

```<code>function fib(n){
  return new Array(n).fill(1).reduce((arr, _ ,i) => {
    arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
    return arr
  },[]) ;
}
console.log(fib(10))
</code>```

I see answers here Fibonacci Sequence in R that use recursion but I was wondering if we could specifically use purrr's reduce and if so how?

答:
Here is a solution using reduce

```<code>fib <- function(n) reduce(rep(0,n-1), .f=function(x,y) c(x, x[length(x)-1] + x[length(x)]), .init=c(0,1))

fib(10)
# [1]  0  1  1  2  3  5  8 13 21 34 55
</code>```

The good point of this solution is that it is very easy to interpret. Basically you just use the most basic functionality of reduce and write Fibonacci number in a function as how it is defined, nothing fancy.

Body:
I was wondering if we could use purrr's map and reduce to create to Fibonacci function akin to this one in JavaScript:

function fib(n){
  return new Array(n).fill(1).reduce((arr, _ ,i) => {
    arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
    return arr
  },[]) ;
}
console.log(fib(10))

I see answers here Fibonacci Sequence in R that use recursion but I was wondering if we could specifically use purrr's reduce and if so how?

Body:
Here is a solution using reduce

fib <- function(n) reduce(rep(0,n-1), .f=function(x,y) c(x, x[length(x)-1] + x[length(x)]), .init=c(0,1))

fib(10)
# [1]  0  1  1  2  3  5  8 13 21 34 55

The good point of this solution is that it is very easy to interpret. Basically you just use the most basic functionality of reduce and write Fibonacci number in a function as how it is defined, nothing fancy.


问:
Python 3 matrix and image
I have a matrix rappresenation of an image where every pixel is a tuple of rgb:

Basically there are two squares:

(162, 201, 115)

(43, 39, 102)

over a black square (0, 0, 0)

The square 1 is over the square 2.

The scope of the exercise is to find all the squares in the correct order and the coordinates of up/left and down/right of the two squares.
The results should be:

(3 4) (4 6) of  (162, 201, 115)

(1 2) (3 5) of (43, 39, 102)

In order to get the square I found the way:

```<code>def funt(pic):
    color = []
    img = immagini.load(pic)
    for i in range(len(img)):
        for h in range(len(img[0])):
            if img[i][h] !=(0,0,0):
                    color.append([img[i][h]]) if [img[i][h]] not in color else color
    return color
</code>```

How can I get the coordinates? I cannot use numpy!

Thanks!

答:
Here's a possible implementation. I've created the following four functions:

get_pixels(img) returns a dictionary whose values are tuples with the RGB components of the colors in img (excluding (0, 0, 0)) and the values are lists of coordinates (row and column) of the pixels that have the corresponding color.

bounding_box(coords) returns the coordinates of diagonally opposed vertices of the bounding box of an image region defined through  a list of coordinates.

is_rectangle(coords) returns True if the passed list of coordinates makes up a rectangle.

create_image() returns the sample image.

def get_pixels(img):
    coords = {}
    for j in range(len(img[0])):
        for i in range(len(img)):
            rgb = img[i][j]
            if rgb != (0, 0, 0):
                pixels[rgb] = pixels.get(rgb, []) + [(i, j)]
    return pixels

def bounding_box(coords):
    upper = min([i for i,j in coords])
    lower = max([i for i,j in coords])
    left = min([j for i,j in coords])
    right = max([j for i,j in coords])
    return upper, lower, left, right

def is_rectangle(coords):
    upper, lower, left, right = bounding_box(coords)
    for i in range(upper, lower + 1):
        for j in range(left, right + 1):
            if (i, j) not in coords:
                return False
    return True
```
<h3>Demo</h3>
<pre class="lang-py prettyprint-override"><code>In [382]: img = create_image()

In [383]: pixels = get_pixels(img)

In [384]: for color, coords in pixels.items(): print(color, coords)
(43, 39, 102) [(2, 1), (3, 1), (4, 1), (5, 1), (2, 2), (3, 2), (4, 2), (5, 2), (2, 3), (3, 3)]
(162, 201, 115) [(4, 3), (5, 3), (6, 3), (4, 4), (5, 4), (6, 4)]

In [385]: colors = list(pixels.keys())

In [386]: if not is_rectangle(pixels[colors[0]]):
     ...:     colors = colors[::-1]

In [387]: colors
Out[387]: [(162, 201, 115), (43, 39, 102)]

In [388]: for n, color in enumerate(colors):
     ...:     upper, lower, left, right = bounding_box(pixels[color])
     ...:     print(f'{n}. ({left} {upper}) ({right} {lower}) of', color)
0. (3 4) (4 6) of (162, 201, 115)
1. (1 2) (3 5) of (43, 39, 102)
</code>```

Title: Python 3 matrix and image

Body:
I have a matrix rappresenation of an image where every pixel is a tuple of rgb:

Basically there are two squares:

(162, 201, 115)

(43, 39, 102)

over a black square (0, 0, 0)

The square 1 is over the square 2.

The scope of the exercise is to find all the squares in the correct order and the coordinates of up/left and down/right of the two squares.
The results should be:

(3 4) (4 6) of  (162, 201, 115)

(1 2) (3 5) of (43, 39, 102)

In order to get the square I found the way:

def funt(pic):
    color = []
    img = immagini.load(pic)
    for i in range(len(img)):
        for h in range(len(img[0])):
            if img[i][h] !=(0,0,0):
                    color.append([img[i][h]]) if [img[i][h]] not in color else color
    return color

How can I get the coordinates? I cannot use numpy!

Thanks!

Body:
Here's a possible implementation. I've created the following four functions:

get_pixels(img) returns a dictionary whose values are tuples with the RGB components of the colors in img (excluding (0, 0, 0)) and the values are lists of coordinates (row and column) of the pixels that have the corresponding color.

bounding_box(coords) returns the coordinates of diagonally opposed vertices of the bounding box of an image region defined through  a list of coordinates.

is_rectangle(coords) returns True if the passed list of coordinates makes up a rectangle.

create_image() returns the sample image.

def get_pixels(img):
    coords = {}
    for j in range(len(img[0])):
        for i in range(len(img)):
            rgb = img[i][j]
            if rgb != (0, 0, 0):
                pixels[rgb] = pixels.get(rgb, []) + [(i, j)]
    return pixels

def bounding_box(coords):
    upper = min([i for i,j in coords])
    lower = max([i for i,j in coords])
    left = min([j for i,j in coords])
    right = max([j for i,j in coords])
    return upper, lower, left, right

def is_rectangle(coords):
    upper, lower, left, right = bounding_box(coords)
    for i in range(upper, lower + 1):
        for j in range(left, right + 1):
            if (i, j) not in coords:
                return False
    return True

Demo

In [382]: img = create_image()

In [383]: pixels = get_pixels(img)

In [384]: for color, coords in pixels.items(): print(color, coords)
(43, 39, 102) [(2, 1), (3, 1), (4, 1), (5, 1), (2, 2), (3, 2), (4, 2), (5, 2), (2, 3), (3, 3)]
(162, 201, 115) [(4, 3), (5, 3), (6, 3), (4, 4), (5, 4), (6, 4)]

In [385]: colors = list(pixels.keys())

In [386]: if not is_rectangle(pixels[colors[0]]):
     ...:     colors = colors[::-1]

In [387]: colors
Out[387]: [(162, 201, 115), (43, 39, 102)]

In [388]: for n, color in enumerate(colors):
     ...:     upper, lower, left, right = bounding_box(pixels[color])
     ...:     print(f'{n}. ({left} {upper}) ({right} {lower}) of', color)
0. (3 4) (4 6) of (162, 201, 115)
1. (1 2) (3 5) of (43, 39, 102)


答:
replace

```<code>implementation 'androidx.recyclerview:recyclerview:1.0.0'
</code>```

And y delete 'com.android.support:appcompat-v7:..., because you've already import it with

```<code>  implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
</code>```

Title: RecyclerView cannot be found

Body:
replace

implementation 'androidx.recyclerview:recyclerview:1.0.0'

And y delete 'com.android.support:appcompat-v7:..., because you've already import it with

  implementation 'androidx.appcompat:appcompat:1.1.0-rc01'


问:
Unable to start Docker Container in Windows 10
I am using Windows 10 pro and successfully installed Docker Client 18.09.0 and fetched hello-world docker image.

But when I try to run the image in container using docker run, it is giving the below error

```<code>C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: CreateComputeSystem 7b206637bedeb11c5f4bb8a5c12f941da3980a5c0e6e18d823f3323b6640a9de: The virtual machine could not be started because a required feature is not installed.
(extra info: {"SystemType":"Container","Name":"7b206637bedeb11c5f4bb8a5c12f941da3980a5c0e6e18d823f3323b6640a9de","Owner":"docker","IgnoreFlushesDuringBoot":true,"LayerFolderPath":"C:\\ProgramData\\Docker\\windowsfilter\\7b206637bedeb11c5f4bb8a5c12f941da3980a5c0e6e18d823f3323b6640a9de","Layers":[{"ID":"ba045b84-94ef-5e96-a203-a8ef5cf53b41","Path":"C:\\ProgramData\\Docker\\windowsfilter\\2cbe39538cedc860f14e954ceed1044a5760df8830e8dc21bcbd4d21e88bf8f3"},{"ID":"959d85fc-a8bf-595a-84f9-a083080f2e27","Path":"C:\\ProgramData\\Docker\\windowsfilter\\3fc0987aeffab6be6b2bb0626867739cbad8dd80f42951e4e803b1e61b64543f"},{"ID":"40a5cfc0-ad6b-5b5e-85ff-dcd5826f380a","Path":"C:\\ProgramData\\Docker\\windowsfilter\\3e839c40c3c413a579f0f60a6ad8ec03daa496dcb61cfc621c35788beb6ae0d4"},{"ID":"be5e886a-ec0d-50e8-a735-c2c9a8b717de","Path":"C:\\ProgramData\\Docker\\windowsfilter\\12eddd7dc5f665f34ffebe1ff1600de14da8d7998950b9a3a180407b2781993a"}],"HostName":"7b206637bede","HvPartition":true,"EndpointList":["3C0F3EDA-3D0F-4C93-8908-C4DCB4FF6C8E"],"HvRuntime":{"ImagePath":"C:\\ProgramData\\Docker\\windowsfilter\\3e839c40c3c413a579f0f60a6ad8ec03daa496dcb61cfc621c35788beb6ae0d4\\UtilityVM"},"AllowUnqualifiedDNSQuery":true}).
</code>```

I am not sure what sure about the issue or what feature is not installed. When I searched the internet all the errors are about hyperv which is there in my environment. My docker info gives the below details by the way:

```<code>PS C:\Windows\system32> docker info
Containers: 14
 Running: 0
 Paused: 0
 Stopped: 14
Images: 2
Server Version: 18.09.0
Storage Driver: windowsfilter
 Windows:
Logging Driver: json-file
Plugins:
 Volume: local
 Network: ics l2bridge l2tunnel nat null overlay transparent
 Log: awslogs etwlogs fluentd gelf json-file local logentries splunk syslog
Swarm: inactive
Default Isolation: hyperv
Kernel Version: 10.0 17763 (17763.1.amd64fre.rs5_release.180914-1434)
Operating System: Windows 10 Pro Version 1809 (OS Build 17763.134)
OSType: windows
Architecture: x86_64
CPUs: 4
Total Memory: 23.54GiB
Name: DESKTOP-6MOD0L8
ID: 4QC3:QQKX:2BS2:P2JG:RUZA:3MK2:RAQ7:ZW7V:Q6YZ:5S56:Z3GQ:WXDC
Docker Root Dir: C:\ProgramData\Docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: -1
 Goroutines: 26
 System Time: 2018-12-10T12:14:05.5454663+05:30
 EventsListeners: 1
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false
Product License: Community Engine
</code>```

答:
This helped me with the same problem (I have virtualization enabled, but you can double-check on the Task Manager -> Performance tab):

Uninstall hyper-v (found in Windows Features)

Restart PC

Install hyper-v

Restart PC

Now you hopefully can build your container.

Source: https://github.com/docker/for-win/issues/2956#issuecomment-514572084

Body:
I am using Windows 10 pro and successfully installed Docker Client 18.09.0 and fetched hello-world docker image.

But when I try to run the image in container using docker run, it is giving the below error

C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: CreateComputeSystem 7b206637bedeb11c5f4bb8a5c12f941da3980a5c0e6e18d823f3323b6640a9de: The virtual machine could not be started because a required feature is not installed.
(extra info: {"SystemType":"Container","Name":"7b206637bedeb11c5f4bb8a5c12f941da3980a5c0e6e18d823f3323b6640a9de","Owner":"docker","IgnoreFlushesDuringBoot":true,"LayerFolderPath":"C:\\ProgramData\\Docker\\windowsfilter\\7b206637bedeb11c5f4bb8a5c12f941da3980a5c0e6e18d823f3323b6640a9de","Layers":[{"ID":"ba045b84-94ef-5e96-a203-a8ef5cf53b41","Path":"C:\\ProgramData\\Docker\\windowsfilter\\2cbe39538cedc860f14e954ceed1044a5760df8830e8dc21bcbd4d21e88bf8f3"},{"ID":"959d85fc-a8bf-595a-84f9-a083080f2e27","Path":"C:\\ProgramData\\Docker\\windowsfilter\\3fc0987aeffab6be6b2bb0626867739cbad8dd80f42951e4e803b1e61b64543f"},{"ID":"40a5cfc0-ad6b-5b5e-85ff-dcd5826f380a","Path":"C:\\ProgramData\\Docker\\windowsfilter\\3e839c40c3c413a579f0f60a6ad8ec03daa496dcb61cfc621c35788beb6ae0d4"},{"ID":"be5e886a-ec0d-50e8-a735-c2c9a8b717de","Path":"C:\\ProgramData\\Docker\\windowsfilter\\12eddd7dc5f665f34ffebe1ff1600de14da8d7998950b9a3a180407b2781993a"}],"HostName":"7b206637bede","HvPartition":true,"EndpointList":["3C0F3EDA-3D0F-4C93-8908-C4DCB4FF6C8E"],"HvRuntime":{"ImagePath":"C:\\ProgramData\\Docker\\windowsfilter\\3e839c40c3c413a579f0f60a6ad8ec03daa496dcb61cfc621c35788beb6ae0d4\\UtilityVM"},"AllowUnqualifiedDNSQuery":true}).

I am not sure what sure about the issue or what feature is not installed. When I searched the internet all the errors are about hyperv which is there in my environment. My docker info gives the below details by the way:

PS C:\Windows\system32> docker info
Containers: 14
 Running: 0
 Paused: 0
 Stopped: 14
Images: 2
Server Version: 18.09.0
Storage Driver: windowsfilter
 Windows:
Logging Driver: json-file
Plugins:
 Volume: local
 Network: ics l2bridge l2tunnel nat null overlay transparent
 Log: awslogs etwlogs fluentd gelf json-file local logentries splunk syslog
Swarm: inactive
Default Isolation: hyperv
Kernel Version: 10.0 17763 (17763.1.amd64fre.rs5_release.180914-1434)
Operating System: Windows 10 Pro Version 1809 (OS Build 17763.134)
OSType: windows
Architecture: x86_64
CPUs: 4
Total Memory: 23.54GiB
Name: DESKTOP-6MOD0L8
ID: 4QC3:QQKX:2BS2:P2JG:RUZA:3MK2:RAQ7:ZW7V:Q6YZ:5S56:Z3GQ:WXDC
Docker Root Dir: C:\ProgramData\Docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: -1
 Goroutines: 26
 System Time: 2018-12-10T12:14:05.5454663+05:30
 EventsListeners: 1
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false
Product License: Community Engine


问:
How to generate the JPA entity Metamodel?
In the spirit of type safety associated with the CriteriaQuery JPA 2.0 also has an API to support Metamodel representation of entities.

Is anyone aware of a fully functional implementation of this API (to generate the Metamodel as opposed to creating the metamodel classes manually)? It would be awesome if someone also knows the steps for setting this up in Eclipse (I assume it's as simple as setting up an annotation processor, but you never know).

EDIT:
Just stumbled across Hibernate JPA 2 Metamodel Generator . But the issue remains since I can't find any download links for the jar.

EDIT 2:
Awhile has passed since I asked this question, but I thought I'd come back and add a link to the Hibernate JPA Model Generator project on SourceForge

答:
Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath element of the compiler plugin.

```<code>    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>
</code>```

Body:
Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath element of the compiler plugin.

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>


问:
Session-Per-Request with SqlConnection / System.Transactions
I've just started using Dapper for a project, having mostly used ORMs like NHibernate and EF for the past few years.

Typically in our web applications we implement session per request, beginning a transaction at the start of the request and committing it at the end.

Should we do something similar when working directly with SqlConnection / System.Transactions?

How does StackOverflow do it?

Solution

Taking the advice of both @gbn and @Sam Safron I'm not using transactions. In my case I'm only doing read queries so it seems there is no real requirement to use transactions (contrary to what I've been told about implicit transactions).

I create a lightweight session interface so that I can use a connection per request. This is quite beneficial to me as with Dapper I often need to create a few different queries to build up an object and would rather share the same connection.

The work of scoping the connection per request and disposing it is done by my IoC container (StructureMap):

```<code>public interface ISession : IDisposable {
    IDbConnection Connection { get; }
}

public class DbSession : ISession {

    private static readonly object @lock = new object();
    private readonly ILogger logger;
    private readonly string connectionString;
    private IDbConnection cn;

    public DbSession(string connectionString, ILogger logger) {
        this.connectionString = connectionString;
        this.logger = logger;
    }

    public IDbConnection Connection { get { return GetConnection(); } }

    private IDbConnection GetConnection() {
        if (cn == null) {
            lock (@lock) {
                if (cn == null) {
                    logger.Debug("Creating Connection");
                    cn = new SqlConnection(connectionString);
                    cn.Open();
                    logger.Debug("Opened Connection");
                }
            }
        }

        return cn;
    }

    public void Dispose() {
        if (cn != null) {
            logger.Debug("Disposing connection (current state '{0}')", cn.State);
            cn.Dispose();
        }
    }
}
</code>```

答:
This is what we do:

We define a static called DB on an object called Current

```<code>public static DBContext DB
{
    var result = GetContextItem<T>(itemKey);

    if (result == null)
    {
        result = InstantiateDB();
        SetContextItem(itemKey, result);
    }

    return result;
}

public static T GetContextItem<T>(string itemKey, bool strict = true)
{

#if DEBUG // HttpContext is null for unit test calls, which are only done in DEBUG
    if (Context == null)
    {
        var result = CallContext.GetData(itemKey);
        return result != null ? (T)result : default(T);
    }
    else
    {
#endif
        var ctx = HttpContext.Current;
        if (ctx == null)
        {
            if (strict) throw new InvalidOperationException("GetContextItem without a context");
            return default(T);
        }
        else
        {
            var result = ctx.Items[itemKey];
            return result != null ? (T)result : default(T);
        }
#if DEBUG
    }
#endif
}

public static void SetContextItem(string itemKey, object item)
{
#if DEBUG // HttpContext is null for unit test calls, which are only done in DEBUG
    if (Context == null)
    {
        CallContext.SetData(itemKey, item);
    }
    else
    {
#endif
        HttpContext.Current.Items[itemKey] = item;

#if DEBUG
    }
#endif
}
</code>```

In our case InstantiateDB returns an L2S context, however in your case it could be an open SQLConnection or whatever.

On our application object we ensure that our connection is closed at the end of the request.

```<code>   protected void Application_EndRequest(object sender, EventArgs e)
   {
        Current.DisposeDB(); // closes connection, clears context
   }
</code>```

Then anywhere in your code where you need access to the db you simple call Current.DB and stuff automatically works. This is also unit test friendly due to all the #if DEBUG stuff.

We do not start any transactions per session, if we did and had updates at the beginning of our session, we would get serious locking issues, as the locks would not be released till the end.

Body:
I've just started using Dapper for a project, having mostly used ORMs like NHibernate and EF for the past few years.

Typically in our web applications we implement session per request, beginning a transaction at the start of the request and committing it at the end.

Should we do something similar when working directly with SqlConnection / System.Transactions?

How does StackOverflow do it?

Solution

Taking the advice of both @gbn and @Sam Safron I'm not using transactions. In my case I'm only doing read queries so it seems there is no real requirement to use transactions (contrary to what I've been told about implicit transactions).

I create a lightweight session interface so that I can use a connection per request. This is quite beneficial to me as with Dapper I often need to create a few different queries to build up an object and would rather share the same connection.

The work of scoping the connection per request and disposing it is done by my IoC container (StructureMap):

public interface ISession : IDisposable {
    IDbConnection Connection { get; }
}

public class DbSession : ISession {

    private static readonly object @lock = new object();
    private readonly ILogger logger;
    private readonly string connectionString;
    private IDbConnection cn;

    public DbSession(string connectionString, ILogger logger) {
        this.connectionString = connectionString;
        this.logger = logger;
    }

    public IDbConnection Connection { get { return GetConnection(); } }

    private IDbConnection GetConnection() {
        if (cn == null) {
            lock (@lock) {
                if (cn == null) {
                    logger.Debug("Creating Connection");
                    cn = new SqlConnection(connectionString);
                    cn.Open();
                    logger.Debug("Opened Connection");
                }
            }
        }

        return cn;
    }

    public void Dispose() {
        if (cn != null) {
            logger.Debug("Disposing connection (current state '{0}')", cn.State);
            cn.Dispose();
        }
    }
}

Body:
This is what we do:

We define a static called DB on an object called Current

public static DBContext DB
{
    var result = GetContextItem<T>(itemKey);

    if (result == null)
    {
        result = InstantiateDB();
        SetContextItem(itemKey, result);
    }

    return result;
}

public static T GetContextItem<T>(string itemKey, bool strict = true)
{

#if DEBUG // HttpContext is null for unit test calls, which are only done in DEBUG
    if (Context == null)
    {
        var result = CallContext.GetData(itemKey);
        return result != null ? (T)result : default(T);
    }
    else
    {
#endif
        var ctx = HttpContext.Current;
        if (ctx == null)
        {
            if (strict) throw new InvalidOperationException("GetContextItem without a context");
            return default(T);
        }
        else
        {
            var result = ctx.Items[itemKey];
            return result != null ? (T)result : default(T);
        }
#if DEBUG
    }
#endif
}

public static void SetContextItem(string itemKey, object item)
{
#if DEBUG // HttpContext is null for unit test calls, which are only done in DEBUG
    if (Context == null)
    {
        CallContext.SetData(itemKey, item);
    }
    else
    {
#endif
        HttpContext.Current.Items[itemKey] = item;

#if DEBUG
    }
#endif
}

In our case InstantiateDB returns an L2S context, however in your case it could be an open SQLConnection or whatever.

On our application object we ensure that our connection is closed at the end of the request.

   protected void Application_EndRequest(object sender, EventArgs e)
   {
        Current.DisposeDB(); // closes connection, clears context
   }

Then anywhere in your code where you need access to the db you simple call Current.DB and stuff automatically works. This is also unit test friendly due to all the #if DEBUG stuff.

We do not start any transactions per session, if we did and had updates at the beginning of our session, we would get serious locking issues, as the locks would not be released till the end.


问:
Laravel group by date and count
I'm trying to add extra information to a Laravel eloquent collection based on the counting number of start(date) field. so the scenario is I have an "appointments" table, I want to add extra attributes to the object in the collection that's returned by eloquent if any days have more than 10 appointments. I have tried many ways like group by and count but didn't work. anyway I have the code below that's I think I'm so close to it but I have been working on it but couldn't find how to make it achieve what I want. I think I'm stuck and I can't think any more. I have commented most of the lines.</p>

```<code>        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
                return Carbon::parse($val->start)->format('d');
            }); //here I'm returning appointments by group without the count

        $counter = [];

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {

                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = [Carbon::parse($appointment->start)->format('d') => $day]; //here I'm trying to make an array and count the days but not working
                }
                dd($counter);
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && count($counter) == 10) //here I want to compare the dates and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //here I want to add the extra information
                }
            }
        }
</code>```

答:
Do this          </p>

```<code>        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
            return Carbon::parse($val->start)->format('d');
        }); //returning appointments by group without the count

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {
                $counter = 0;
                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = count($appointments); //appointments counter
                }
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && $counter >= 10) //compare the date and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //add the extra information here
                }
            }
        }
</code>```

Title: Laravel group by date and count

Body:
I'm trying to add extra information to a Laravel eloquent collection based on the counting number of start(date) field. so the scenario is I have an "appointments" table, I want to add extra attributes to the object in the collection that's returned by eloquent if any days have more than 10 appointments. I have tried many ways like group by and count but didn't work. anyway I have the code below that's I think I'm so close to it but I have been working on it but couldn't find how to make it achieve what I want. I think I'm stuck and I can't think any more. I have commented most of the lines.

        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
                return Carbon::parse($val->start)->format('d');
            }); //here I'm returning appointments by group without the count

        $counter = [];

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {

                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = [Carbon::parse($appointment->start)->format('d') => $day]; //here I'm trying to make an array and count the days but not working
                }
                dd($counter);
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && count($counter) == 10) //here I want to compare the dates and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //here I want to add the extra information
                }
            }
        }

Body:
Do this

        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
            return Carbon::parse($val->start)->format('d');
        }); //returning appointments by group without the count

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {
                $counter = 0;
                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = count($appointments); //appointments counter
                }
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && $counter >= 10) //compare the date and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //add the extra information here
                }
            }
        }


问:
React Toastify with Bootstrap 4
Is there any way I can use react-toastify with Reactstrap's Toast component, or the Bootstrap 4 toast classes? Here's my current config:

import { toast } from 'react-toastify'

toast.configure({
  toastClassName: 'toast', // Bootstrap class
  bodyClassName: 'toast-body', // Another Bootstrap class
});
```

To be clear, I am using the following libraries:

React Toastify: https://github.com/fkhadra/react-toastify

Reactstrap: https://reactstrap.github.io

I would really like to be able to use this component as the Toast:

https://reactstrap.github.io/components/toasts

答:
You can build your react component as normal and insert it instead of a plain message. The docs for react-toastify show how to do just that.

Build your react toast component using bootstrap 4 classes/react
bootstrap

Place a <ToastContainer /> in your App

Use toast(*), where * is the component you built and imported into
App

More info on this here: https://fkhadra.github.io/react-toastify/render-what-you-want

Title: React Toastify with Bootstrap 4

Body:
Is there any way I can use react-toastify with Reactstrap's Toast component, or the Bootstrap 4 toast classes? Here's my current config:

import { toast } from 'react-toastify'

toast.configure({
  toastClassName: 'toast', // Bootstrap class
  bodyClassName: 'toast-body', // Another Bootstrap class
});

To be clear, I am using the following libraries:

React Toastify: https://github.com/fkhadra/react-toastify

Reactstrap: https://reactstrap.github.io

I would really like to be able to use this component as the Toast:

https://reactstrap.github.io/components/toasts


问:
exctract values by column from arrays of arrays, seperated in different arrays
I have an array of arrays as it is shown :

I want to collect all the values of the first column (118,117,115 etc) but seperated in different array for values that are in different arrays on my initial array of arrays. In more detail I want to have my value as:

```<code>array([118,117,115,...]),
array([461,460,459,...])
</code>```

Thank you in advance

Body:
I have an array of arrays as it is shown :

I want to collect all the values of the first column (118,117,115 etc) but seperated in different array for values that are in different arrays on my initial array of arrays. In more detail I want to have my value as:

array([118,117,115,...]),
array([461,460,459,...])

Thank you in advance

Body:
This code should work for you:

import numpy as np

arr = [
    np.array([[[1,2]],[[3,4]]]),
    np.array([[[5,6]],[[7,8]]]),
]

[x[:,:,0].flatten() for x in arr]

Out:

[array([1, 3]), array([5, 7])]


问:
Removing non-input parameters when using functools LRU cache?
I have a function that uses functools LRU cache, but I want to pass in some non-input parameters e.g. "a"

```<code>import functools
import random

def foo(d, a):
    @functools.lru_cache()
    def bar(d):
        random.seed(d)
        nonlocal a
        a = []
        s = 0
        for i in range(100):
            r = random.random()
            a.append(r)
            s += r
        if s < 50:
            return True
        else:
            return False
    return bar(d)
</code>```

But when I use these functions, "a" is not changed:

```<code>a = []
print(foo(random.randint(0, 100), a))
print(a)
</code>```

What's going on? Also is this the right way to use functools, nested?

Update

I used this in the end i.e. with global and without foo:

```<code>@functools.lru_cache()
def bar(d):
    global a
    random.seed(d)
    ...
</code>```

答:
It does not change a because you are redefining it in the function. You are basically doing this:

```<code>def foo(a):
    a = [1, 2, 3]
    return a

a = []
foo(a)
</code>```

So the outer a will remain as empty list after the function call. You may say but I'm using nonlocal keyword so I should be referencing to the original a. In fact, you are referencing to the parameter. So the effect is same as above code. If you run below code with and without nonlocal you can see what's going on:

```<code>def foo(a):
    def bar():
        # nonlocal a
        a = [1, 2, 3]
        print("bar", a)
    bar()
    print("foo", a)

a = []
foo(a)
print("global", a)
</code>```

Outputs:

```<code>bar [1, 2, 3]
foo []
global []
</code>```

And when you use nonlocal a:

```<code>bar [1, 2, 3]
foo [1, 2, 3]
global []
</code>```

What you can do in your function is delete nonlocal a statement since it does not have any effect on the outer a and replace a = [] with a.clear().

Body:
I have a function that uses functools LRU cache, but I want to pass in some non-input parameters e.g. "a"

import functools
import random

def foo(d, a):
    @functools.lru_cache()
    def bar(d):
        random.seed(d)
        nonlocal a
        a = []
        s = 0
        for i in range(100):
            r = random.random()
            a.append(r)
            s += r
        if s < 50:
            return True
        else:
            return False
    return bar(d)

But when I use these functions, "a" is not changed:

a = []
print(foo(random.randint(0, 100), a))
print(a)

What's going on? Also is this the right way to use functools, nested?

Update

I used this in the end i.e. with global and without foo:

@functools.lru_cache()
def bar(d):
    global a
    random.seed(d)
    ...

Body:
It does not change a because you are redefining it in the function. You are basically doing this:

def foo(a):
    a = [1, 2, 3]
    return a

a = []
foo(a)

So the outer a will remain as empty list after the function call. You may say but I'm using nonlocal keyword so I should be referencing to the original a. In fact, you are referencing to the parameter. So the effect is same as above code. If you run below code with and without nonlocal you can see what's going on:

def foo(a):
    def bar():
        # nonlocal a
        a = [1, 2, 3]
        print("bar", a)
    bar()
    print("foo", a)

a = []
foo(a)
print("global", a)

Outputs:

bar [1, 2, 3]
foo []
global []

And when you use nonlocal a:

bar [1, 2, 3]
foo [1, 2, 3]
global []

What you can do in your function is delete nonlocal a statement since it does not have any effect on the outer a and replace a = [] with a.clear().


问:
Load images separated from page loading
I am currently using lazy loading of images, in which all the images are loaded while page is loading and displayed after an image is loaded. In this method, page is shown loading at the tab section of browser till all the images are downloaded.

Now, I want to load the images separate from page loading. Like in google images, page is loaded within 1 second, and images are loaded one by one without showing the page loading in the tab of browser.

How can I achieve this?

So, the final question: How to first load the page fully, without downloading the images from server, and then download the image when the scroller is reached there. Till then, the image may be a grey box.

答:
Loading an image when it comes into view.

Loading attribute

We could use native lazy loading with the loading attribute.

Here's a demo.

```<code><div><img src="https://placeimg.com/410/410/any" loading="lazy" width="410" height="410"></div>
</code>```

Currently, the latest version of Chrome, Firefox and Edge support native lazy loading.

Be aware that the distance threshold does vary in browsers.

Chrome

The distance threshold after which the deferred content will start
  loading-in depends on factors including the current effective
  connection type, and whether Lite mode is enabled. The distance is
  chosen so that the deferred content almost always finishes loading by
  the time it becomes visible.

Firefox

Tells the user agent to hold off on loading the image until the
  browser estimates that it will be needed imminently. For instance, if
  the user is scrolling through the document, a value of lazy will cause
  the image to only be loaded shortly before it will appear in the
  window's visual viewport.

Intersection Observer

We could also use the IntersectionObserver API to determine when your images are in view. This offers better compatibility across browsers and offers greater control for when and how our images load.

CodePen

HTML

```<code><div>
    <img src="data:,"
        data-src="https://placeimg.com/410/410/any"
        class="lazy"
        alt=""
        width="410"
        height="410" />
</div>
</code>```

JS

```<code>document.addEventListener("DOMContentLoaded", lazyLoad);

function lazyLoad() {
  const images = [].slice.call(document.querySelectorAll("img.lazy"));
  var config = {
    // If the image gets within 500px in the Y axis, start the download.
    rootMargin: "500px 0px",
    // detect when visibility passes the 1% mark
    threshold: 0.01
  };

  if ("IntersectionObserver" in window) {
    const observer = new IntersectionObserver(showImage, config);

    images.forEach(function (image) {
      observer.observe(image);
    });
  }
}

function showImage(entries, observer) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting) {
      const image = entry.target;
      image.src = image.dataset.src;

      observer.unobserve(image);
    }
  });
}
</code>```

Existing libraries

There are also existing JavaScript libraries, such as lazySizes.

Title: Load images separated from page loading

Body:
Loading an image when it comes into view.

Loading attribute

We could use native lazy loading with the loading attribute.

Here's a demo.

<div><img src="https://placeimg.com/410/410/any" loading="lazy" width="410" height="410"></div>

Currently, the latest version of Chrome, Firefox and Edge support native lazy loading.

Be aware that the distance threshold does vary in browsers.

Chrome

The distance threshold after which the deferred content will start
  loading-in depends on factors including the current effective
  connection type, and whether Lite mode is enabled. The distance is
  chosen so that the deferred content almost always finishes loading by
  the time it becomes visible.

Firefox

Tells the user agent to hold off on loading the image until the
  browser estimates that it will be needed imminently. For instance, if
  the user is scrolling through the document, a value of lazy will cause
  the image to only be loaded shortly before it will appear in the
  window's visual viewport.

Intersection Observer

We could also use the IntersectionObserver API to determine when your images are in view. This offers better compatibility across browsers and offers greater control for when and how our images load.

CodePen

HTML

<div>
    <img src="data:,"
        data-src="https://placeimg.com/410/410/any"
        class="lazy"
        alt=""
        width="410"
        height="410" />
</div>

JS

document.addEventListener("DOMContentLoaded", lazyLoad);

function lazyLoad() {
  const images = [].slice.call(document.querySelectorAll("img.lazy"));
  var config = {
    // If the image gets within 500px in the Y axis, start the download.
    rootMargin: "500px 0px",
    // detect when visibility passes the 1% mark
    threshold: 0.01
  };

  if ("IntersectionObserver" in window) {
    const observer = new IntersectionObserver(showImage, config);

    images.forEach(function (image) {
      observer.observe(image);
    });
  }
}

function showImage(entries, observer) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting) {
      const image = entry.target;
      image.src = image.dataset.src;

      observer.unobserve(image);
    }
  });
}

Existing libraries

There are also existing JavaScript libraries, such as lazySizes.


问:
how to fix this condition will always return false in Angular
anybody know why I'm getting " This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap " when ever I tried to see if charTypeEnum is equal to ChartType.text

Chart-Design.ts

```<code>import { ChartType, ChartData, TextData } from 'src/app/mam-chart/models';

export class ChartDesignComponent implements OnInit {
  chartTypeEnum = ChartType;
}

  setupTypes() {
// I got error over here
    if (this.chartTypeEnum == ChartType.text)  {
      this.cardJsonV2 = JSON.stringify(this.chartData);
    }
}
</code>```

mam-model.ts

```<code>export enum ChartType {
    chart = 1,
    text,
    grid
}
</code>```

Chart-Design.html

```<code>            <mat-form-field appearance="fill">
                <mat-label>Text</mat-label>
                <input matInput [ngModel]="chartData?.textData?.text" />
            </mat-form-field >
</code>```

答:
Use Typecasting </p>

```<code> if (String(this.chartTypeEnum) === ChartType.text))  {
</code>```

Body:
anybody know why I'm getting " This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap " when ever I tried to see if charTypeEnum is equal to ChartType.text

Chart-Design.ts

import { ChartType, ChartData, TextData } from 'src/app/mam-chart/models';

export class ChartDesignComponent implements OnInit {
  chartTypeEnum = ChartType;
}

  setupTypes() {
// I got error over here
    if (this.chartTypeEnum == ChartType.text)  {
      this.cardJsonV2 = JSON.stringify(this.chartData);
    }
}

mam-model.ts

export enum ChartType {
    chart = 1,
    text,
    grid
}

Chart-Design.html

            <mat-form-field appearance="fill">
                <mat-label>Text</mat-label>
                <input matInput [ngModel]="chartData?.textData?.text" />
            </mat-form-field >

Body:
Use Typecasting

 if (String(this.chartTypeEnum) === ChartType.text))  {


问:
Possible to call stateful function in a class in Python?
Is it possible to directly set a certain value and get it in a class by any mean(inheritance, metaclass, class decorator) in Python? class B must not be polluted by set('a') in A.

import sys

class A:
    set('a')
    get()
    # -> 'a'

    print(sys.modules[__name__])
    # => <module '__main__'>

class B:
    get()
    # -> None
```

答:
These two independent classes don't reference each other, so as long as you don't pass the same object to both, then neither will 'pollute' the other. To set a value and get a value on an object, you could use something like this:

```<code>class A:
    def __init__(self):
        self.letter = None
    def set_value(self, letter):
        self.letter = letter
    def get_value(self):
        return self.letter if self.letter else '(none set)'

class B:
    def __init__(self):
        self.letter = None
    def set_value(self, letter):
        self.letter = letter
    def get_value(self):
        return self.letter if self.letter else '(none set)'

>>> a = A()
>>> aa = A()
>>> b = B()
>>> a.set_value('z')
>>> print(f'values in a, aa, and b are: {a.get_value()}, {aa.get_value()}, {b.get_value()}')
values in a, aa, and b are: z, (none set), (none set)
</code>```

So as you can see, setting the a object's letter doesn't set it in b (a different class), or in aa, which is a different instance of the same A class. Hope that helps!

Happy Coding!

Body:
These two independent classes don't reference each other, so as long as you don't pass the same object to both, then neither will 'pollute' the other. To set a value and get a value on an object, you could use something like this:

class A:
    def __init__(self):
        self.letter = None
    def set_value(self, letter):
        self.letter = letter
    def get_value(self):
        return self.letter if self.letter else '(none set)'

class B:
    def __init__(self):
        self.letter = None
    def set_value(self, letter):
        self.letter = letter
    def get_value(self):
        return self.letter if self.letter else '(none set)'

>>> a = A()
>>> aa = A()
>>> b = B()
>>> a.set_value('z')
>>> print(f'values in a, aa, and b are: {a.get_value()}, {aa.get_value()}, {b.get_value()}')
values in a, aa, and b are: z, (none set), (none set)

So as you can see, setting the a object's letter doesn't set it in b (a different class), or in aa, which is a different instance of the same A class. Hope that helps!

Happy Coding!


问:
How can i push an object to promises in vueJS?
I have the following function to load categories in vue JS

```<code>const self = this as any;
self.fetchFeaturedCategories();
</code>```

if i console log self.fetchFeaturedCategories(), it will return promises.

I would like to achieve something like this (This is in angular):

```<code>this.categories = categories.map(category => {
const parentCategory = {
  gender: category.gender,
  id: category.id,
  imageUrl: category.imageUrl,
  isFeatured: category.isFeatured,
  name: 'All ' + category.name,
  parent: category.parent,
  parentId: category.parentId,
  slug: category.slug,
  type: category.type,
};
  category.children = [parentCategory, ...category.children];
  return category;
});
</code>```

However, i would like to insert an object to each of the children's array. How can i achieve this?
Thanks!

答:
To manipulate Promise resolved values, you have to use .then, or await, to wait for the Promise to resolve and then act on the resolved value and return your new resolved value.</p>

```<code>  self.fetchFeaturedCategories() // assuming this is an array of Promises
   .then(categories => categories.map(category => {
      const parentCategory = {
        gender: category.gender,
        id: category.id,
        imageUrl: category.imageUrl,
        isFeatured: category.isFeatured,
        name: 'All ' + category.name,
        parent: category.parent,
        parentId: category.parentId,
        slug: category.slug,
        type: category.type,
      };
      const categoryMerged = {
         ...category, children: [parentCategory, ...category.children||[]]
      };
      return categoryMerged;
   }));
</code>```

Body:
I have the following function to load categories in vue JS

const self = this as any;
self.fetchFeaturedCategories();

if i console log self.fetchFeaturedCategories(), it will return promises.

I would like to achieve something like this (This is in angular):

this.categories = categories.map(category => {
const parentCategory = {
  gender: category.gender,
  id: category.id,
  imageUrl: category.imageUrl,
  isFeatured: category.isFeatured,
  name: 'All ' + category.name,
  parent: category.parent,
  parentId: category.parentId,
  slug: category.slug,
  type: category.type,
};
  category.children = [parentCategory, ...category.children];
  return category;
});

However, i would like to insert an object to each of the children's array. How can i achieve this?
Thanks!

Body:
To manipulate Promise resolved values, you have to use .then, or await, to wait for the Promise to resolve and then act on the resolved value and return your new resolved value.

  self.fetchFeaturedCategories() // assuming this is an array of Promises
   .then(categories => categories.map(category => {
      const parentCategory = {
        gender: category.gender,
        id: category.id,
        imageUrl: category.imageUrl,
        isFeatured: category.isFeatured,
        name: 'All ' + category.name,
        parent: category.parent,
        parentId: category.parentId,
        slug: category.slug,
        type: category.type,
      };
      const categoryMerged = {
         ...category, children: [parentCategory, ...category.children||[]]
      };
      return categoryMerged;
   }));


问:
Select only 1 child from each parent
One Author can have many Book. Table Book have Author_Id on it.

I Want a LINQ query that returns a IQueryable<Book> (So I can navigate with Book.Author.Name and stuff), but Only 1 Book per Author.

How do I do that with a LINQ?

答:
Pretty sure this is it:

```<code>var books = from a in authors
            from b in a.Books.Take(1)
            select b);
</code>```

Edit: Less hacky way to do this:

```<code>var books = authors.Select(author => author.Books.First())
                   .Select(book => book);
</code>```

Title: Select only 1 child from each parent

Body:
Pretty sure this is it:

var books = from a in authors
            from b in a.Books.Take(1)
            select b);

Edit: Less hacky way to do this:

var books = authors.Select(author => author.Books.First())
                   .Select(book => book);


问:
save a list of different Dataframes to json
I have different pandas dataframes, which I put in a list.
I want to save this list in json (or any other format) which can be read by R.

```<code>import pandas as pd

def create_df_predictions(extra_periods):
    """
    make a empty df for predictions
    params: extra_periods = how many prediction in the future the user wants
    """
    df = pd.DataFrame({ 'model': ['a'], 'name_id': ['a'] })
    for col in range(1, extra_periods+1):
        name_col = 'forecast' + str(col)
        df[name_col] = 0

    return df

df1 = create_df_predictions(9)
df2 = create_df_predictions(12)
list_df = [df1, df2]
</code>```

The question is how to save list_df in a readable format for R? Note that df1 and df2 are have a different amount of columns!

答:
To export the list of DataFrames to a single json file, you should convert the list into a DataFrame and then use the to_json() function as shown below:

```<code>df_to_export = pd.DataFrame(list_df)
json_output = df_to_export.to_json()
with open("output.txt", 'w') as outfile:
    outfile.write(json_output)
</code>```

This will export the full dataset to a single json string and export it to a file.

Body:
I have different pandas dataframes, which I put in a list.
I want to save this list in json (or any other format) which can be read by R.

import pandas as pd

def create_df_predictions(extra_periods):
    """
    make a empty df for predictions
    params: extra_periods = how many prediction in the future the user wants
    """
    df = pd.DataFrame({ 'model': ['a'], 'name_id': ['a'] })
    for col in range(1, extra_periods+1):
        name_col = 'forecast' + str(col)
        df[name_col] = 0

    return df

df1 = create_df_predictions(9)
df2 = create_df_predictions(12)
list_df = [df1, df2]

The question is how to save list_df in a readable format for R? Note that df1 and df2 are have a different amount of columns!

Body:
To export the list of DataFrames to a single json file, you should convert the list into a DataFrame and then use the to_json() function as shown below:

df_to_export = pd.DataFrame(list_df)
json_output = df_to_export.to_json()
with open("output.txt", 'w') as outfile:
    outfile.write(json_output)

This will export the full dataset to a single json string and export it to a file.


问:
focus() to input without scrolling
I have a search input text which I'd like to apply a focus() when loading the page, the problem is that the focus function automatically does a scroll to this field. Any solution to disable this scroll?

```<code><input id="search_terms" type="text" />
<script>
    document.getelementbyId('search-terms').focus();
</script>
</code>```

答:
I had a similar problem that was driving me crazy. Using jQuery, I've found a solution by discovering the coordinates of mouse and input and then scrolling to the difference between them. In your case it could be something like this: </p>

```<code>  document.addEventListener("mousemove", (e) => {
    mouseCoords = { x: e.clientX, y: e.clientY };
  });

  $('#search_terms').bind("focus", function (e) {
      var offset = e.offset();
      window.scrollTo(
        offset.left - mouseCoords.x,
        offset.top - mouseCoords.y
      );
  });
</code>```

Title: focus() to input without scrolling

Body:
I have a search input text which I'd like to apply a focus() when loading the page, the problem is that the focus function automatically does a scroll to this field. Any solution to disable this scroll?

<input id="search_terms" type="text" />

Body:
I had a similar problem that was driving me crazy. Using jQuery, I've found a solution by discovering the coordinates of mouse and input and then scrolling to the difference between them. In your case it could be something like this:

  document.addEventListener("mousemove", (e) => {
    mouseCoords = { x: e.clientX, y: e.clientY };
  });

  $('#search_terms').bind("focus", function (e) {
      var offset = e.offset();
      window.scrollTo(
        offset.left - mouseCoords.x,
        offset.top - mouseCoords.y
      );
  });


问:
How to write multi-threaded functions inside a big function?
I have a function like this that is working fine:

```<code>void BigFunction()
{
   void FunctionA(std::shared_ptr<ClassC> c);
}
</code>```

now I want to add another function inside BigFunction()

```<code>void FunctionB(std::shared_ptr<ClassC> c);
</code>```

which also take std::shared_ptr<ClassC> c as the input.
How do I do it correctly and safely so that both FunctionA() and FunctionB() can run in parallel, which means these two functions don't need to wait for each other and don't interfere with each other? Thanks.

Edit:
Here is the link of the code that I try but failed: https://onlinegdb.com/BJ5_BC0jI

答:
You can use std::thread or std::future/std::async. For these "task"'s it is better/easier to use std::assync/future since the thread management is done for you.

```<code>bool func1(int a) {...}
bool func2(int a) {...}

void some_func()
{
    std::future<bool> f1 = std::async(std::launch::async, func1, 1);
    std::future<bool> f2 = std::async(std::launch::async, func1, 2);

    bool res1 = f1.get(); // Only need this if you care about the result
    bool res2 = f2.get(); // Only need this if you care about the result
}
</code>```

If you don't care about the results you don't need that last two lines. But the .get() basically allows you to wait for your functions to finish. There are other options to do this... but its quite a general question...

Threads and lambda's:

```<code>bool func1(int a) {...}
bool func2(int a) {...}

void some_func()
{
    std::thread t1 = []{ return func1(1); };
    std::thread t2 = []{ return func2(2); };

    // You must do this, otherwise your threads will go out of scope and std::terminate is called!
    if (t1.joinable())
    {
        t1.join()
    }
    if (t2.joinable())
    {
        t2.join()
    }

    // Or instead of joining you can detach. But this is not recommend as you lose the ability to control your thread (left commented out as an example)
    // t1.detach();
    // t2.detach();
}
</code>```

Update

Link to your "fixed" code: https://onlinegdb.com/S1hcwRAsL

Here is the code snippet for your convinience (and I am not sure if I have to save the changes! in GDB online!):

```<code>int main()
{
  std::shared_ptr<classC> c = std::make_shared<classC>();

  classB* b;
  classA* a;
  std::thread first([&b, &c]{ b->functionB(c); });
  std::thread second([&a, &c]{ a->functionA(c); });

  // synchronize threads:
  first.join();
  second.join();

  std::cout << "A and B completed.\n";

  return 0;
}
</code>```

Body:
I have a function like this that is working fine:

void BigFunction()
{
   void FunctionA(std::shared_ptr<ClassC> c);
}

now I want to add another function inside BigFunction()

void FunctionB(std::shared_ptr<ClassC> c);

which also take std::shared_ptr<ClassC> c as the input.
How do I do it correctly and safely so that both FunctionA() and FunctionB() can run in parallel, which means these two functions don't need to wait for each other and don't interfere with each other? Thanks.

Edit:
Here is the link of the code that I try but failed: https://onlinegdb.com/BJ5_BC0jI

Body:
You can use std::thread or std::future/std::async. For these "task"'s it is better/easier to use std::assync/future since the thread management is done for you.

bool func1(int a) {...}
bool func2(int a) {...}

void some_func()
{
    std::future<bool> f1 = std::async(std::launch::async, func1, 1);
    std::future<bool> f2 = std::async(std::launch::async, func1, 2);

    bool res1 = f1.get(); // Only need this if you care about the result
    bool res2 = f2.get(); // Only need this if you care about the result
}

If you don't care about the results you don't need that last two lines. But the .get() basically allows you to wait for your functions to finish. There are other options to do this... but its quite a general question...

Threads and lambda's:

bool func1(int a) {...}
bool func2(int a) {...}

void some_func()
{
    std::thread t1 = []{ return func1(1); };
    std::thread t2 = []{ return func2(2); };

    // You must do this, otherwise your threads will go out of scope and std::terminate is called!
    if (t1.joinable())
    {
        t1.join()
    }
    if (t2.joinable())
    {
        t2.join()
    }

    // Or instead of joining you can detach. But this is not recommend as you lose the ability to control your thread (left commented out as an example)
    // t1.detach();
    // t2.detach();
}

Update

Link to your "fixed" code: https://onlinegdb.com/S1hcwRAsL

Here is the code snippet for your convinience (and I am not sure if I have to save the changes! in GDB online!):

int main()
{
  std::shared_ptr<classC> c = std::make_shared<classC>();

  classB* b;
  classA* a;
  std::thread first([&b, &c]{ b->functionB(c); });
  std::thread second([&a, &c]{ a->functionA(c); });

  // synchronize threads:
  first.join();
  second.join();

  std::cout << "A and B completed.\n";

  return 0;
}


问:
Concatenate a list until a certain character
I have this list:

```<code>Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
</code>```

I would want to concatenate the list as follow:

```<code>Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']
</code>```

Is this somehow possible?

Thank you,

答:
```<code>jokes = ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']
jokes2 = []
for i in range(len(jokes) // 2):
    jokes2.append(jokes[2 * i] + ' \n ' + jokes[2 * i + 1])
print(jokes2)
</code>```

Body:
I have this list:

Jokes =   ['First joke', 'Still first', '', 'Second Joke', 'Still second joke', 'Still 2nd joke']

I would want to concatenate the list as follow:

Jokes = ['First joke \n Still first', 'Second joke \n Still second joke \n Still 2nd joke']

Is this somehow possible?

Thank you,


问:
building unique list of select options from array in javascript?
I wrote this script,

```<code><script>

const http = new XMLHttpRequest()
url = "http://192.168.0.2/hotspots";
window.onload = function(){
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            result = eval(this.responseText)
            select = document.getElementById('access_points_select');
            for (var i = 0; i<=result.length; i++){
                var opt = document.createElement('option');
                opt.value = result[i];
                opt.innerHTML = result[i];
                select.appendChild(opt);
            }
        }
};

request.open('GET', url);
request.send();
}

</script>
</head>
<body>
<select name="access_points" id="access_points_select">
</select>
</code>```

but because resource also returns duplicates i want to avoid duplicate entries into the select dropdown, how can I achieve this without creating unique array without creating another array then result.

答:
If eval(this.responseText) returns an array you can use a Set to ensure there are no duplicates.

If you need to filter undefined you can do chain that on the end too:

```<code> result = [...new Set(this.responseText)].filter(Boolean)
</code>```

Body:
I wrote this script,

<select name="access_points" id="access_points_select">
</select>

but because resource also returns duplicates i want to avoid duplicate entries into the select dropdown, how can I achieve this without creating unique array without creating another array then result.

Body:
If eval(this.responseText) returns an array you can use a Set to ensure there are no duplicates.

If you need to filter undefined you can do chain that on the end too:

 result = [...new Set(this.responseText)].filter(Boolean)


问:
Find the two numbers that appear only once - divide and conquer
Given an array in which each element appears twice, I have to find which two numbers of the array appear only once. Maximum additional memory is O(1).

I have found this amazing solution: https://medium.com/@gurupad93/two-numbers-that-appear-once-b89e92a9334b

The problem is that my solution should be divide and conquer, and my understanding is that the solution I found is not.

I know how to solve this problem with divide and conquer when the element appearing once is just one. Here, I wouldn't know how to divide the array recursively to be honest.

Any suggestions?

Thank you so much!

答:
I assume that the numbers are positive integers. The list has an even number of elements. You compute the average and divide the list into two sublists, below and above average. Then either both have an odd number of elements or both an even. In the odd case you know that each sublist contains one singleton, and you solve the one-singleton problem for each of them. In the even case you know that one of the sublists has no singleton, i.e. is paired, while the other has two. You decide which one is paired and continue working on the other one, recursively solving the two-singleton problem.

If the integers are represented in standard binary you can XOR all of them to decide whether they are paired. Otherwise, if they are represented in BCD, floating point or whatever where the representative isn't unique, you can use the following test:
A list of integers is paired if and only if the product of all the elements is a square. Compute exp( 1/2 sum( log xi ) ) and if it's integral the list is paired, otherwise not.

But the solution in the link is admittedly much nicer than this.


问:
Is it possible to read php code from other sites?
Just a curious question. I was wondering is it possible to read a sites php/server side codes? Is there any software/method that can be used to do so? Sometimes for educational purposes, i really want to see how people form the backend infrastructure of their sites. </p>

答: it's not possible, except if you have the right access [permission] on their sites to do so, or you can hack the server :)</p>


答:
Try to replace chartTypeEnum = ChartType with chartTypeEnum: ChartType.

With chartTypeEnum = ChartType the type ChartType is (wrongfully?) assigned to the variable chartTypeEnum instead of defining the type.

Title: how to fix this condition will always return false in Angular


问:
AMP Email images automatically loading?
If you setup AMP email / Get approved.

Will your subscribers still need to "approve pictures from sender" or will images be automatically loaded?

Just trying to understand, if it's worth the hassle.

答:
For Gmail, the "Dynamic email" feature will only be enabled if the image setting is set to "Always allow external images". If the setting is set to "Always ask" (which would be the case in your question), then AMP emails will fall back to static HTML/plain text emails.

You can see a short blurb about this fact in the description of the image setting in Gmail. Also see the HIDING_IMAGES fallback reason at https://developers.google.com/gmail/ampemail/debugging-dynamic-email.

Title: AMP Email images automatically loading?


问:
Throwing new functions.https.HttpsError on Firebase Cloud Function rejects as Internal Error on Client
I have the following Cloud Function deployed to my Firebase Project:

```<code>exports.createCredentials = functions.https.onCall((data, context) => {
    if(!context.auth)
        throw new functions.https.HttpsError('failed-auth', 'You must be authenticated to call this function')

    const { email, password } = data;

    if(!(typeof email === 'string'))
        throw new functions.https.HttpsError('invalid-email', 'Email must be a string')
    if(!(typeof password === 'string'))
        throw new functions.https.HttpsError('invalid-password', 'Password must be a string')

    return admin.auth().createUser({
        email,
        password
    })
    .then(userRecord => {
        return { userRecord }
    })
    .catch((error) => {
        throw new functions.https.HttpsError(error.code, error.message)
    })
})
</code>```

The problem is that whenever I throw a new functions.https.HttpsError instead of the error being catched in the client as the docs state, I get an internal error code. In my function's log, it shows an unhandled error where I tried calling the HttpsError. Here's an example of the log:

```<code>Unhandled error Error: Unknown error status: auth/email-already-exists
    at new HttpsError (/user_code/node_modules/firebase-functions/lib/providers/https.js:80:19)
    at admin.auth.createUser.then.catch (/user_code/index.js:26:9)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
</code>```

I know that this type of function rejects an internal error if no HttpsError was thrown, but as far as I know that is not the case in my function. I am programming my front end in React so here's how I call this firebase function:

```<code>let options = {
    email: arquitect.email,
    password: arquitect.password
}

let createCredentials = firebase.functions().httpsCallable('createCredentials')
createCredentials(options)
    .then(result => {

    })
    .catch(error => console.log(error))
</code>```

Is there something I am missing?

答:
I had the same issue. Novice here, so my attempt may be wrong but I was calling the functions locally and I couldn't get to the HttpsError.

So whilst doing the following:

const functionsGlobal = require('firebase-functions')
const functions = functionsGlobal.region('europe-west2')
```

<p>I had to then get the <code>HttpsError</code> like this:</p>

<pre class="lang-js prettyprint-override"><code>throw new functionsGlobal.https.HttpsError('failed-precondition',
    'The function must be called while authenticated.', 'hello')
</code>```

Instead of:

throw new functions.https.HttpsError('failed-precondition',
    'The function must be called while authenticated.', 'hello')
```

It works now but I would love for someone to explain why.

Body:
I have the following Cloud Function deployed to my Firebase Project:

exports.createCredentials = functions.https.onCall((data, context) => {
    if(!context.auth)
        throw new functions.https.HttpsError('failed-auth', 'You must be authenticated to call this function')

    const { email, password } = data;

    if(!(typeof email === 'string'))
        throw new functions.https.HttpsError('invalid-email', 'Email must be a string')
    if(!(typeof password === 'string'))
        throw new functions.https.HttpsError('invalid-password', 'Password must be a string')

    return admin.auth().createUser({
        email,
        password
    })
    .then(userRecord => {
        return { userRecord }
    })
    .catch((error) => {
        throw new functions.https.HttpsError(error.code, error.message)
    })
})

The problem is that whenever I throw a new functions.https.HttpsError instead of the error being catched in the client as the docs state, I get an internal error code. In my function's log, it shows an unhandled error where I tried calling the HttpsError. Here's an example of the log:

Unhandled error Error: Unknown error status: auth/email-already-exists
    at new HttpsError (/user_code/node_modules/firebase-functions/lib/providers/https.js:80:19)
    at admin.auth.createUser.then.catch (/user_code/index.js:26:9)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

I know that this type of function rejects an internal error if no HttpsError was thrown, but as far as I know that is not the case in my function. I am programming my front end in React so here's how I call this firebase function:

let options = {
    email: arquitect.email,
    password: arquitect.password
}

let createCredentials = firebase.functions().httpsCallable('createCredentials')
createCredentials(options)
    .then(result => {

    })
    .catch(error => console.log(error))

Is there something I am missing?

Body:
I had the same issue. Novice here, so my attempt may be wrong but I was calling the functions locally and I couldn't get to the HttpsError.

So whilst doing the following:

const functionsGlobal = require('firebase-functions')
const functions = functionsGlobal.region('europe-west2')

I had to then get the HttpsError like this:

throw new functionsGlobal.https.HttpsError('failed-precondition',
    'The function must be called while authenticated.', 'hello')

Instead of:

throw new functions.https.HttpsError('failed-precondition',
    'The function must be called while authenticated.', 'hello')

It works now but I would love for someone to explain why.


问:
Label help for histograms
I have a set of histograms and would like to put labels on the +- 1 stdev and the mean.  I have the lines, but want the labels as well.  I would like the labels toward the bottom of the histograms with white background so the font is legible against the histogram colors.

```<code>library(dply)
library(ggplot2)

a = runif(1000,1,100)
b = runif(1000,1,100)
c = runif(1000,1,100)

amount = c(a,b,c)

cat = c(rep("a",1000), rep("b",1000), rep("c",1000))

hist.data = data.frame(amount,cat)
names(hist.data) = c("amount","cat")

hist.data$cat = factor(hist.data$cat, levels = c("a","b","c"))
pricedata = ddply(hist.data, c("cat"), summarize, avg = mean(amount), minus.stdev = mean(amount)-sd(amount),
  plus.stdev = mean(amount) + sd(amount))
pricedata = pricedata[order(pricedata$avg),]

ggplot(hist.data, aes(x=amount, fill = cat))+
  geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
  theme_test()+
  geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+

  geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  facet_grid(cat ~., scales = "free")+
  scale_y_continuous(expand = c(0,0),name = "Count")+
  scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))
</code>```

答:
And if you want to make the fewest changes to your existing code (although I agree the other answers are more elegant) you can add three lines to your existing

ggplot(hist.data, aes(x=amount, fill = cat))+
  geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
  theme_test()+
  geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+
  geom_label(aes(x = avg, y = 10, label = scales::dollar_format()(avg)), data = pricedata, fill = "white", size = 3) +
  geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+
  geom_label(aes(x = minus.stdev, y = 10, label = scales::dollar_format()(minus.stdev)), data = pricedata, fill = "white", size = 3) +
  geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+
  geom_label(aes(x = plus.stdev, y = 10, label = scales::dollar_format()(plus.stdev)), data = pricedata, fill = "white", size = 3) +
  facet_grid(cat ~., scales = "free")+
  scale_y_continuous(expand = c(0,0),name = "Count")+
  scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))

```

Title: Label help for histograms

Body:
I have a set of histograms and would like to put labels on the +- 1 stdev and the mean.  I have the lines, but want the labels as well.  I would like the labels toward the bottom of the histograms with white background so the font is legible against the histogram colors.

library(dply)
library(ggplot2)

a = runif(1000,1,100)
b = runif(1000,1,100)
c = runif(1000,1,100)

amount = c(a,b,c)

cat = c(rep("a",1000), rep("b",1000), rep("c",1000))

hist.data = data.frame(amount,cat)
names(hist.data) = c("amount","cat")

hist.data$cat = factor(hist.data$cat, levels = c("a","b","c"))
pricedata = ddply(hist.data, c("cat"), summarize, avg = mean(amount), minus.stdev = mean(amount)-sd(amount),
  plus.stdev = mean(amount) + sd(amount))
pricedata = pricedata[order(pricedata$avg),]

ggplot(hist.data, aes(x=amount, fill = cat))+
  geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
  theme_test()+
  geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+

  geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

  facet_grid(cat ~., scales = "free")+
  scale_y_continuous(expand = c(0,0),name = "Count")+
  scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))