text:
Q: Fastlane in Azure :Getting : security: SecKeychainItemImport: The specified keychain could not be found , reports finished successfully i trying to use Fastlane in the Azure DevOps pipeline only for build the iOS app, i try to import the certificate files i have but it keeps giving me the error that
removed all sensitive data to "xxxx"
Getting : security: SecKeychainItemImport: The specified keychain could not be found

Command executed
 default_platform(:ios)

platform :ios do

desc "Ios build "

lane :release do
    create_keychain(
    name: "iPhone Distribution: xxxx, INC",
    default_keychain: true,
    unlock: true,
    timeout: 3600,
    lock_when_sleeps: true,
    password:"xxx"
    )

    import_certificate(
    certificate_path: "xxxx.cer",
    keychain_name: "iPhone Distribution: xxxx, INC",
    keychain_password:"xxxx"
    )

    import_certificate(
    certificate_path: "xxxx.p12",
    certificate_password: "netics77perso",
    keychain_name: "iPhone Distribution: xxxx, INC",
    keychain_password:"xxxx"
)
end

output :
2020-09-08T21:05:36.7924880Z DEBUG [2020-09-08 21:05:36.79]: Checking if there are any plugins that should be loaded...
2020-09-08T21:05:36.9225840Z [33mSuccessfully loaded Appfile at path '/Users/runner/work/1/a/ios_artifacts/fastlane/Appfile'[0m
2020-09-08T21:05:36.9264960Z - [36mapp_identifier[0m: '[32mcom.xxxx.xxxx[0m'
2020-09-08T21:05:36.9274650Z - [36mapple_id[0m: '[32mxxxx@xxxx.com[0m'
2020-09-08T21:05:36.9282660Z -------
2020-09-08T21:05:37.0126610Z INFO [2020-09-08 21:05:37.01]: [32m------------------------------[0m
2020-09-08T21:05:37.0163310Z INFO [2020-09-08 21:05:37.01]: [32m--- Step: default_platform ---[0m
2020-09-08T21:05:37.0203110Z INFO [2020-09-08 21:05:37.01]: [32m------------------------------[0m
2020-09-08T21:05:37.0219820Z /Users/runner/hostedtoolcache/Ruby/2.7.1/x64/lib/ruby/gems/2.7.0/gems/fastlane-2.158.0/fastlane_core/lib/fastlane_core/ui/interface.rb:141: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
2020-09-08T21:05:37.0258670Z /Users/runner/hostedtoolcache/Ruby/2.7.1/x64/lib/ruby/gems/2.7.0/gems/fastlane-2.158.0/fastlane_core/lib/fastlane_core/ui/errors/fastlane_error.rb:9: warning: The called method `initialize' is defined here
2020-09-08T21:05:37.0271870Z INFO [2020-09-08 21:05:37.01]: [32mDriving the lane 'ios release' 🚀[0m
2020-09-08T21:05:37.0282040Z INFO [2020-09-08 21:05:37.01]: [32m-----------------------------[0m
2020-09-08T21:05:37.0311150Z INFO [2020-09-08 21:05:37.01]: [32m--- Step: create_keychain ---[0m
2020-09-08T21:05:37.0330570Z INFO [2020-09-08 21:05:37.01]: [32m-----------------------------[0m
2020-09-08T21:05:37.1553810Z INFO [2020-09-08 21:05:37.15]: [36m$ security list-keychains -d user[0m
2020-09-08T21:05:37.1710130Z INFO [2020-09-08 21:05:37.16]: â–¸ [35m"/Users/runner/Library/Keychains/iPhone Distribution: xxxx TECHNOLOGIES, INC-db"[0m
2020-09-08T21:05:37.1952790Z INFO [2020-09-08 21:05:37.19]: [32m--------------------------------[0m
2020-09-08T21:05:37.1965230Z INFO [2020-09-08 21:05:37.19]: [32m--- Step: import_certificate ---[0m
2020-09-08T21:05:37.1986400Z INFO [2020-09-08 21:05:37.19]: [32m--------------------------------[0m
2020-09-08T21:05:37.3147120Z ERROR [2020-09-08 21:05:37.31]: [31msecurity: SecKeychainItemImport: The specified keychain could not be found.[0m
2020-09-08T21:05:37.3157620Z INFO [2020-09-08 21:05:37.31]: [32m--------------------------------[0m
2020-09-08T21:05:37.3159000Z INFO [2020-09-08 21:05:37.31]: [32m--- Step: import_certificate ---[0m
2020-09-08T21:05:37.3161380Z INFO [2020-09-08 21:05:37.31]: [32m--------------------------------[0m
2020-09-08T21:05:37.3650880Z ERROR [2020-09-08 21:05:37.36]: [31msecurity: SecKeychainItemImport: The specified keychain could not be found.[0m
2020-09-08T21:05:37.3671550Z INFO [2020-09-08 21:05:37.36]: [32mSuccessfully generated documentation at path '/Users/runner/work/1/a/ios_artifacts/fastlane/README.md'[0m
2020-09-08T21:05:37.3725080Z
2020-09-08T21:05:37.3770750Z +------+--------------------+-------------+
2020-09-08T21:05:37.3780600Z |            [32mfastlane summary[0m             |
2020-09-08T21:05:37.3827850Z +------+--------------------+-------------+
2020-09-08T21:05:37.3828450Z | Step | Action             | Time (in s) |
2020-09-08T21:05:37.3834520Z +------+--------------------+-------------+
2020-09-08T21:05:37.3845600Z | 1    | default_platform   | 0           |
2020-09-08T21:05:37.3849370Z | 2    | create_keychain    | 0           |
2020-09-08T21:05:37.3862610Z | 3    | import_certificate | 0           |
2020-09-08T21:05:37.3899420Z | 4    | import_certificate | 0           |
2020-09-08T21:05:37.3900940Z +------+--------------------+-------------+
2020-09-08T21:05:37.3906010Z
2020-09-08T21:05:37.3907410Z INFO [2020-09-08 21:05:37.37]: [32mfastlane.tools finished successfully 🎉[0m
2020-09-08T21:05:37.4023220Z
2020-09-08T21:05:37.4095380Z ##[section]Finishing: create_keychain

Fastlane env Environment
2020-09-08T21:05:30.0950580Z ✅ fastlane environment ✅
2020-09-08T21:05:30.0951450Z
2020-09-08T21:05:30.0951640Z ### Stack
2020-09-08T21:05:30.0951760Z
2020-09-08T21:05:30.0952090Z | Key                         | Value                                              |
2020-09-08T21:05:30.0952960Z | --------------------------- | -------------------------------------------------- |
2020-09-08T21:05:30.0953470Z | OS                          | 10.14.6                                            |
2020-09-08T21:05:30.0953910Z | Ruby                        | 2.7.1                                              |
2020-09-08T21:05:30.0954380Z | Bundler?                    | false                                              |
2020-09-08T21:05:30.0954810Z | Git                         | git version 2.28.0                                 |
2020-09-08T21:05:30.0955290Z | Installation Source         | ~/hostedtoolcache/Ruby/2.7.1/x64/bin/fastlane      |
2020-09-08T21:05:30.0955730Z | Host                        | Mac OS X 10.14.6 (18G6020)                         |
2020-09-08T21:05:30.0956190Z | Ruby Lib Dir                | ~/hostedtoolcache/Ruby/2.7.1/x64/lib               |
2020-09-08T21:05:30.0956660Z | OpenSSL Version             | OpenSSL 1.1.1d  10 Sep 2019                        |
2020-09-08T21:05:30.0957090Z | Is contained                | false                                              |
2020-09-08T21:05:30.0957560Z | Is homebrew                 | false                                              |
2020-09-08T21:05:30.0957990Z | Is installed via Fabric.app | false                                              |
2020-09-08T21:05:30.0958460Z | Xcode Path                  | /Applications/Xcode_11.3.1.app/Contents/Developer/ |
2020-09-08T21:05:30.0958890Z | Xcode Version               | 11.3.1                                             |
2020-09-08T21:05:30.0959180Z
2020-09-08T21:05:30.0959290Z
2020-09-08T21:05:30.0959450Z ### System Locale
2020-09-08T21:05:30.0959580Z
2020-09-08T21:05:30.0959800Z | Variable | Value       |   |
2020-09-08T21:05:30.0960380Z | -------- | ----------- | - |
2020-09-08T21:05:30.0961020Z | LANG     | en_US.UTF-8 | ✅ |
2020-09-08T21:05:30.0961570Z | LC_ALL   | en_US.UTF-8 | ✅ |
2020-09-08T21:05:30.0961880Z | LANGUAGE |             |   |
2020-09-08T21:05:30.0962040Z
2020-09-08T21:05:30.0962150Z
2020-09-08T21:05:30.0962310Z ### fastlane files:
2020-09-08T21:05:30.0962510Z
2020-09-08T21:05:30.0962730Z `./fastlane/Fastfile`
2020-09-08T21:05:30.0962920Z
2020-09-08T21:05:30.0963100Z ```ruby
2020-09-08T21:05:30.0963290Z default_platform(:ios)
2020-09-08T21:05:30.0963440Z
2020-09-08T21:05:30.0963630Z platform :ios do
2020-09-08T21:05:30.0963770Z
2020-09-08T21:05:30.0963930Z   desc "Ios build "
2020-09-08T21:05:30.0964100Z
2020-09-08T21:05:30.0964270Z   lane :release do
2020-09-08T21:05:30.0964460Z create_keychain(
2020-09-08T21:05:30.0964780Z   name: "iPhone Distribution: xxxx, INC",
2020-09-08T21:05:30.0965080Z   default_keychain: true,
2020-09-08T21:05:30.0966120Z   unlock: true,
2020-09-08T21:05:30.0966690Z   timeout: 3600,
2020-09-08T21:05:30.0966960Z   lock_when_sleeps: true,
2020-09-08T21:05:30.0967190Z   password:"xxxx"
2020-09-08T21:05:30.0967370Z )
2020-09-08T21:05:30.0967510Z
2020-09-08T21:05:30.0967680Z import_certificate(
2020-09-08T21:05:30.0967920Z    certificate_path: "xxxx.cer",
2020-09-08T21:05:30.0968320Z    keychain_name: "iPhone Distribution: xxxx, INC",
2020-09-08T21:05:30.0968670Z         keychain_password:"xxxx"
2020-09-08T21:05:30.0969290Z )
2020-09-08T21:05:30.0969410Z
2020-09-08T21:05:30.0969570Z import_certificate(
2020-09-08T21:05:30.0969880Z   certificate_path: "xxxx.p12",
2020-09-08T21:05:30.0970190Z   certificate_password: "xxxx",
2020-09-08T21:05:30.0971200Z   keychain_name: 'iPhone Distribution: xxxx, INC',
2020-09-08T21:05:30.0971570Z   keychain_password:"xxxx"
2020-09-08T21:05:30.0971830Z )
2020-09-08T21:05:30.0971940Z
2020-09-08T21:05:30.0972080Z   end
2020-09-08T21:05:30.0972200Z
2020-09-08T21:05:30.0972380Z end
2020-09-08T21:05:30.0972490Z
2020-09-08T21:05:30.0972620Z ```
2020-09-08T21:05:30.0972800Z
2020-09-08T21:05:30.0973230Z
2020-09-08T21:05:30.0973530Z `./fastlane/Appfile`
2020-09-08T21:05:30.0973730Z
2020-09-08T21:05:30.0973870Z ```ruby
2020-09-08T21:05:30.0974130Z app_identifier("com.xxxx.xxxx")
2020-09-08T21:05:30.0974410Z apple_id("xxxx@xxxx.com")
2020-09-08T21:05:30.0974910Z
2020-09-08T21:05:30.0975120Z ```
2020-09-08T21:05:30.0975270Z
2020-09-08T21:05:30.0975390Z
2020-09-08T21:05:30.0975590Z ### fastlane gems
2020-09-08T21:05:30.0975730Z
2020-09-08T21:05:30.0976300Z | Gem      | Version | Update-Status |
2020-09-08T21:05:30.0976960Z | -------- | ------- | ------------- |
2020-09-08T21:05:30.0977650Z | fastlane | 2.158.0 | ✅ Up-To-Date  |
2020-09-08T21:05:30.0977920Z
2020-09-08T21:05:30.0978090Z
2020-09-08T21:05:30.0978290Z ### Loaded fastlane plugins:
2020-09-08T21:05:30.0978480Z
2020-09-08T21:05:30.0978680Z **No plugins Loaded**
2020-09-08T21:05:30.0978830Z
2020-09-08T21:05:30.0978930Z
2020-09-08T21:05:30.0979170Z Loaded gems
2020-09-08T21:05:30.0979360Z
2020-09-08T21:05:30.0979900Z | Gem                       | Version      |
2020-09-08T21:05:30.0980650Z | ------------------------- | ------------ |
2020-09-08T21:05:30.0980960Z | did_you_mean              | 1.4.0        |
2020-09-08T21:05:30.0981820Z | slack-notifier            | 2.3.2        |
2020-09-08T21:05:30.0982150Z | atomos                    | 0.1.3        |
2020-09-08T21:05:30.0982430Z | CFPropertyList            | 3.0.2        |
2020-09-08T21:05:30.0982770Z | claide                    | 1.0.3        |
2020-09-08T21:05:30.0983060Z | colored2                  | 3.1.2        |
2020-09-08T21:05:30.0983380Z | nanaimo                   | 0.3.0        |
2020-09-08T21:05:30.0983670Z | xcodeproj                 | 1.18.0       |
2020-09-08T21:05:30.0984320Z | rouge                     | 2.0.7        |
2020-09-08T21:05:30.0984630Z | xcpretty                  | 0.3.0        |
2020-09-08T21:05:30.0985610Z | terminal-notifier         | 2.0.0        |
2020-09-08T21:05:30.0986350Z | unicode-display_width     | 1.7.0        |
2020-09-08T21:05:30.0986950Z | terminal-table            | 1.8.0        |
2020-09-08T21:05:30.0987410Z | plist                     | 3.5.0        |
2020-09-08T21:05:30.0987770Z | public_suffix             | 4.0.6        |
2020-09-08T21:05:30.0988110Z | addressable               | 2.7.0        |
2020-09-08T21:05:30.0988740Z | multipart-post            | 2.0.0        |
2020-09-08T21:05:30.0989100Z | word_wrap                 | 1.0.0        |
2020-09-08T21:05:30.0990080Z | tty-screen                | 0.8.1        |
2020-09-08T21:05:30.0991060Z | tty-cursor                | 0.7.1        |
2020-09-08T21:05:30.0991870Z | tty-spinner               | 0.9.3        |
2020-09-08T21:05:30.0992330Z | babosa                    | 1.0.3        |
2020-09-08T21:05:30.0993330Z | colored                   | 1.2          |
2020-09-08T21:05:30.0993930Z | highline                  | 1.7.10       |
2020-09-08T21:05:30.0994960Z | commander-fastlane        | 4.4.6        |
2020-09-08T21:05:30.0995290Z | excon                     | 0.76.0       |
2020-09-08T21:05:30.0995580Z | faraday                   | 1.0.1        |
2020-09-08T21:05:30.0995900Z | unf_ext                   | 0.0.7.7      |
2020-09-08T21:05:30.0996190Z | unf                       | 0.1.4        |
2020-09-08T21:05:30.0996520Z | domain_name               | 0.5.20190701 |
2020-09-08T21:05:30.0997480Z | http-cookie               | 1.0.3        |
2020-09-08T21:05:30.0998160Z | faraday-cookie_jar        | 0.0.7        |
2020-09-08T21:05:30.0998470Z | faraday_middleware        | 1.0.0        |
2020-09-08T21:05:30.0998760Z | fastimage                 | 2.2.0        |
2020-09-08T21:05:30.0999090Z | gh_inspector              | 1.1.3        |
2020-09-08T21:05:30.0999380Z | json                      | 2.3.0        |
2020-09-08T21:05:30.0999710Z | mini_magick               | 4.10.1       |
2020-09-08T21:05:30.1000690Z | rubyzip                   | 2.3.0        |
2020-09-08T21:05:30.1001080Z | security                  | 0.1.3        |
2020-09-08T21:05:30.1001740Z | xcpretty-travis-formatter | 1.0.0        |
2020-09-08T21:05:30.1002050Z | dotenv                    | 2.7.6        |
2020-09-08T21:05:30.1002620Z | bundler                   | 2.1.4        |
2020-09-08T21:05:30.1002990Z | naturally                 | 2.2.0        |
2020-09-08T21:05:30.1003340Z | simctl                    | 1.6.8        |
2020-09-08T21:05:30.1003970Z | jwt                       | 2.2.2        |
2020-09-08T21:05:30.1004330Z | uber                      | 0.1.0        |
2020-09-08T21:05:30.1004770Z | declarative               | 0.0.20       |
2020-09-08T21:05:30.1006410Z | declarative-option        | 0.1.0        |
2020-09-08T21:05:30.1006810Z | representable             | 3.0.4        |
2020-09-08T21:05:30.1007660Z | retriable                 | 3.1.2        |
2020-09-08T21:05:30.1008320Z | mini_mime                 | 1.0.2        |
2020-09-08T21:05:30.1008630Z | multi_json                | 1.15.0       |
2020-09-08T21:05:30.1009480Z | signet                    | 0.14.0       |
2020-09-08T21:05:30.1009910Z | memoist                   | 0.16.2       |
2020-09-08T21:05:30.1010220Z | os                        | 1.1.1        |
2020-09-08T21:05:30.1011080Z | googleauth                | 0.13.1       |
2020-09-08T21:05:30.1011660Z | httpclient                | 2.8.3        |
2020-09-08T21:05:30.1012770Z | google-api-client         | 0.38.0       |
2020-09-08T21:05:30.1013390Z | google-cloud-env          | 1.3.3        |
2020-09-08T21:05:30.1015240Z | google-cloud-errors       | 1.0.1        |
2020-09-08T21:05:30.1016060Z | google-cloud-core         | 1.5.0        |
2020-09-08T21:05:30.1016440Z | rake                      | 13.0.1       |
2020-09-08T21:05:30.1017050Z | digest-crc                | 0.6.1        |
2020-09-08T21:05:30.1017950Z | google-cloud-storage      | 1.28.0       |
2020-09-08T21:05:30.1018340Z | emoji_regex               | 3.0.0        |
2020-09-08T21:05:30.1018640Z | jmespath                  | 1.4.0        |
2020-09-08T21:05:30.1019280Z | aws-partitions            | 1.365.0      |
2020-09-08T21:05:30.1019880Z | aws-eventstream           | 1.1.0        |
2020-09-08T21:05:30.1020750Z | aws-sigv4                 | 1.2.2        |
2020-09-08T21:05:30.1021550Z | aws-sdk-core              | 3.105.0      |
2020-09-08T21:05:30.1022190Z | aws-sdk-kms               | 1.37.0       |
2020-09-08T21:05:30.1022870Z | aws-sdk-s3                | 1.79.1       |
2020-09-08T21:05:30.1023180Z | uri                       | 0.10.0       |
2020-09-08T21:05:30.1023520Z | forwardable               | 1.3.1        |
2020-09-08T21:05:30.1023810Z | logger                    | 1.4.2        |
2020-09-08T21:05:30.1024130Z | cgi                       | 0.1.0        |
2020-09-08T21:05:30.1024420Z | timeout                   | 0.1.0        |
2020-09-08T21:05:30.1024850Z | stringio                  | 0.1.0        |
2020-09-08T21:05:30.1025660Z | ipaddr                    | 1.2.2        |
2020-09-08T21:05:30.1025950Z | openssl                   | 2.1.2        |
2020-09-08T21:05:30.1026280Z | ostruct                   | 0.2.0        |
2020-09-08T21:05:30.1026570Z | strscan                   | 1.0.3        |
2020-09-08T21:05:30.1027180Z | date                      | 3.0.0        |
2020-09-08T21:05:30.1027500Z | delegate                  | 0.1.0        |
2020-09-08T21:05:30.1027790Z | fileutils                 | 1.4.1        |
2020-09-08T21:05:30.1028120Z | zlib                      | 1.1.0        |
2020-09-08T21:05:30.1028400Z | singleton                 | 0.1.0        |
2020-09-08T21:05:30.1028730Z | rexml                     | 3.2.3        |
2020-09-08T21:05:30.1029020Z | open3                     | 0.1.0        |
2020-09-08T21:05:30.1029350Z | yaml                      | 0.1.0        |
2020-09-08T21:05:30.1029640Z | psych                     | 3.1.0        |
2020-09-08T21:05:30.1030200Z | mutex_m                   | 0.1.0        |
2020-09-08T21:05:30.1030580Z | webrick                   | 1.6.0        |
2020-09-08T21:05:30.1030810Z
2020-09-08T21:05:30.1030970Z
2020-09-08T21:05:30.1031080Z
2020-09-08T21:05:30.1031660Z *generated on:* **2020-09-08**
2020-09-08T21:05:30.1031950Z
2020-09-08T21:05:30.1032760Z [21:05:30]: [33mTake notice that this output may contain sensitive information, or simply information that you don't want to make public.[0m
2020-09-08T21:05:30.1033780Z [21:05:30]: [32mOpen https://github.com/fastlane/fastlane/issues/new to submit a new issue ✅[0m

UPDATE:
also added log_output:true to the import_certificate
and its show me :
security import xxxx.cer -k '/Users/runner/Library/Keychains/iPhone\ Distribution:\ xxxxx,\ INC-db' -P '' -T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild

but when i do :
ls -la /Users/runner/Library/Keychains/

i can see the file :
2020-09-09T07:42:02.4193010Z drwxr-xr-x   8 runner  staff    256 Sep  9 07:42 .
2020-09-09T07:42:02.4194280Z drwxr-xr-x@ 47 runner  staff   1504 Sep  4 12:26 ..
2020-09-09T07:42:02.4195140Z -r--r--r--   1 runner  staff      0 Jan  5  2018 .fl34AC2A0A
2020-09-09T07:42:02.4195990Z -r--r--r--   1 runner  staff      0 Sep  9 07:42 .fl5C99C5E2
2020-09-09T07:42:02.4197000Z drwx------   8 runner  staff    256 Sep  9 07:16 4203018E-580F-C1B5-9525-B745CECA79EB
2020-09-09T07:42:02.4197890Z -rw-r--r--   1 runner  staff  20460 Sep  9 07:42 iPhone Distribution: xxxxx, INC-db
2020-09-09T07:42:02.4198770Z -rw-r--r--@  1 runner  staff  74416 Sep  9 07:21 login.keychain-db
2020-09-09T07:42:02.4199520Z -rw-r--r--@  1 runner  staff  81040 Jul 22  2019 login_renamed_1.keychain-db


text:
Q: Azure Java SDK - set block blob to cool storage tier on upload Is there a way to set the storage tier to "cool" at the blob level when uploading a block blob to Azure Storage using the Java SDK? The closest thing I can find is setStandardBlobTier() on BlobProperties, which is a protected method, so it can't be accessed.

A: The class CloudBlockBlob now has two uploadStandardBlobTier() methods which can be used to set the blob tier on a block blob on a standard storage account. e.g.
cloudBlockBlob.uploadStandardBlobTier(StandardBlobTier.COOL);

A: I searched the Azure Storage java SDK source code and setStandardBlobTier() method is protected method. I tried to create subclass of the BlobProperties Class and overwrite the setStandardBlobTier() method, but BlobProperties Class was decorated with the final keyword.
I also searched Azure Storage c# SDK, only get method was found.
It seems you cannot set blob tier via sdk , however you can set tier via rest api.
You could refer to the sample code as below:
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class SetBlobTier {

    private static final String account = "***";
    private static final String key = "***";

    public static void main(String args[]) throws Exception {

        String urlString = "https://" + account + ".blob.core.windows.net/***/***?comp=tier";
        HttpURLConnection connection = (HttpURLConnection) (new URL(urlString)).openConnection();
        getFileRequest(connection, account, key);
        // connection.connect();
        connection.setDoInput(true);
        connection.setDoOutput(true);

        OutputStream out = connection.getOutputStream();
        out.flush();
        out.close();
        System.out.println("Response message : " + connection.getResponseMessage());
        System.out.println("Response code : " + connection.getResponseCode());

        BufferedReader br = null;
        if (connection.getResponseCode() != 200) {
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
        } else {
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        }
        System.out.println("Response body : " + br.readLine());
    }

    public static void getFileRequest(HttpURLConnection request, String account, String key)
            throws Exception {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
        fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";
        String stringToSign = "PUT\n" + "\n" // content encoding
                + "\n" // content language
                + "\n"// content length
                + "\n" // content md5
                + "\n" // content type
                + "\n" // date
                + "\n" // if modified since
                + "\n" // if match
                + "\n" // if none match
                + "\n" // if unmodified since
                + "\n" // range
                + "\n"
                + "x-ms-date:" + date + "\n"
                + "x-ms-version:2015-02-21"+"\n" // headers
                + "/" + account + request.getURL().getPath(); // resources
        System.out.println("stringToSign : " + stringToSign);
        String auth = getAuthenticationString(stringToSign);
        request.setRequestMethod("PUT");

        request.setRequestProperty("x-ms-date", date);
        request.setRequestProperty("x-ms-version", "2015-02-21");
        request.setRequestProperty("x-ms-access-tier", "Archive");
        request.setRequestProperty("Authorization", auth);

    }

    private static String getAuthenticationString(String stringToSign) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
        String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
        String auth = "SharedKey " + account + ":" + authKey;
        return auth;
    }
}

Hope it helps you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: prevent regular expression formatting in my javascript I'm sure someone else has asked this but my Google foo is failing me and I cannot find it.
When I divide more than once in an equation like this:
this.active[i].pos(last.pos()+(last.width()/2)+10+(this.active[i].width()/2));

"/2)+10+(this.active[i].width()/" will come up with regular expression formatting(all orange) in the editor which is driving me insane. :(
Is there a way I can change my settings to prevent this?  I do not use regular expression at all, so disabling it's formatting entirely in the editor would be acceptable.
Can anyone provide, or point me towards, an answer?
If you found it on Google, I would appreciate learning your search terms.
Thank you. :)

A: I've been searching the web for about 45 minutes trying to find a solution to this very question when I came across this question here on stack overflow. I almost started a bounty on it but decided I'd see if I could figure it out myself.
I came up with two possible solutions, both of which are much simpler than I though they would be.
Solution 1: Separate the formula into two sections that can be stored in variables and added together when needed. For example, I happened to be writing a formula for a surface area calculation, which formed a regular expression and returned the incorrect answer:

return [(this.base * this.height)/2] + [(this.perimeter * this.slant)/2];

I split the formula at the + and stored them in variables:
var a = (this.base * this.height)/2;
    var b = (this.perimeter * this.slant)/2;
    return  a + b

This solution worked just fine. But then I started thinking that there had to be a simpler solution I was over-looking which led me to:
Solution 2: Dividing by 2 is the same as multiplying by 0.5 (duh!) . In my case - and in almost any case - dividing by 2 and multiplying by 0.5 will get you the same answer. My code then looked like this:

return [(this.base * this.height) * 0.5] + [(this.perimeter * this.slant) * 0.5];

I tested both, and both work, though obviously solution 2 is more efficient (less code).
The only time I could imagine needing to use solution 1 is if you're dividing by a very long number or a prime number (dividing by 3 gives you a more accurate result than multiplying by 0.33).
Anyway, I know you posted this question months ago and probably either came up with a solution or moved on, but I figured I'd post this answer anyway as a reference for any future issues with the same idea.
(Also, this is in JavaScript but I can't imagine something this simple is any different in a similar language).


text:
Q: Selective package update Nuget We have just started publishing to an internal nuget feed using Proget. The projects are built in CI (Teamcity) but the assembly version numbers do not change just the informational version. I have recently come to understand that setting the informational version overrides using the assembly version to name the nuget package. We currently have a nupkg versioning scheme of major.minor.patch.buildNumber.
This should mean that a newer build should be represented as a potential update
There are two questions

*

*How do we do selective nuget updates in CI. For example we have third party packages like Moq and we want to keep those versions static whilst letting builds update the internally built packages to the latest available.

*In the same vein, how do we do it on a local machine?
Thanks for reading.

A: There is no way to do what you without deleting the same version from the packages directory, and additionally the NuGet cache (%LOCALAPPDATA%\NuGet\Cache). The root problem here is that you want a package to be both a different version and also not a different version at the same time.
What are the real reasons behind the conscious decision to keep the same version number even though the binaries are different? This is usually a symptom of a kink in the deployment process that could be improved with automation.


text:
Q: probability: arithmetic with random variables. I have a question of using arithmetic on random variables.
Please refer to the following question, to which I will present my solution using the arithmetic (which I thought it's correct but actually not).
$$P(X+Y+Z=1|X-Y=0) => P( [X+Y+Z=1]\text{ AND }[X-Y=0])/P(X-Y=0)  $$
for the top part :
$$[X-Y=0]  => X=Y$$
so
$$ P( [X+Y+Z=1]\text{ AND }[X-Y=0])=P(X+X+Z=1)=P(2X+Z=1)$$
But this is not correct. Why?

A: $P([X+Y+Z=1]\,and [X-Y=0]) = P(X=0\,and\,Y=0\,and\,Z=1)= (\frac{1}{2})^3$

A: What you can conclude it is the events $$\{X+Y+Z=1\} \cap \{X=Y\} = \{2X+Z=1\} \cap \{X=Y\}$$
$\cap$ means AND.
Note that the event $\{X+Y+Z=1\} \cap \{X=Y\} \neq \{2X+Z=1\}$ in general. For example, let be $w$ such that $X(w)=0$ and $Y(w)=Z(w)=1$. Such $w$ is a possibility in $\{2X+Z=1\}$ but it is not in $\{X+Y+Z=1\} \cap \{X=Y\}$. Then the events $\{X+Y+Z=1\} \cap \{X=Y\}$ and $\{2X+Z=1\}$  aren't equal, so
$$P(\{X+Y+Z=1\} \cap \{X=Y\}) \neq P(\{2X+Z=1\})$$


text:
Q: Mathematics - geometric progression question If $a$, $b$ and $c$ are in geometric progression, then what are $\log_ax$, $\log_bx$ and $\log_cx$ in?
What I did:
I substituted values for $x, a, b$ and $c$ and tried to solve it further.
What I got:
Using the value of x as 2 and a = 2 b = 4 c = 8:
I obtained that it is in harmonic progression.
$$\log_22, \log_42, \log_82$$
$$1, \frac{1}{2}, \frac{1}{3}$$
However, if I used x = 64, then I am not getting a harmonic progression. Instead, I got:
$$\log_264, \log_464, \log_864$$
$$6, 3, 2$$
I don't think that these numbers are in harmonic progression. What did I do wrong?
Btw. I know the answer is harmonic progression

A: Hint:
$$\log_y(x)=\frac{\log(x)}{\log(y)}$$
Now try examining
$$\frac{1}{\log_b(x)}-\frac{1}{\log_a(x)}$$ and $$\frac{1}{\log_c(x)}-\frac{1}{\log_b(x)}$$
Keep in mind that $\log(u)-\log(v)=\log(\frac{u}{v})$.


text:
Q: objective C: may not respond to (issue) I have two UINavigationController in the appdelegate.h
{
    UINavigationController *leftView;
    UINavigationController *rightView;
    UIWindow *window;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *leftView;
@property (nonatomic, retain) IBOutlet UINavigationController *rightView;

appdelegate.m
@synthesize leftView;
@synthesize rightView;

then in a different class
test.m
#import "appdelegate.h"

if I do:
[self leftView] pushViewController...; //(Everything is ok)

but if I change it to:
[self rightView] pushViewControll...; //it complains about ViewController may not respond to -rightView

A: I'm going to hazard a guess: Have you declared and synthesized a property for rightView, or at least provided your own manual getter?

A: You code seems right; what doesn't seem right is that you're including AppDelegate.  If the code was in AppDelegate.m, it would probably work without any complaints by the compiler.
Instead, you've defined @property lines for each, but that is in AppDelegate.h, not test.h - but you're using them in test.m.  That is probably the source of the problem.
Interestingly, does the code actually run?

A: It sounds like you declared a @property or method called leftView that returns the leftView ivar, but you forgot to do the same for rightView. The error is telling you that self doesn't respond to the selector rightView.


text:
Q: Advantage of using "--ctstate NEW" in addition to "--sync" for matching new TCP connections In iptables context, to match a new TCP connection, one can use:
-A INPUT -p tcp --syn -m conntrack --ctstate NEW -j ACCEPT

However, is --ctstate NEW necessary provided that the --syn flag is already there? In other words, aren't --syn packets always NEW by definition and, thus, the state checking is redundant or is there any benefit in doing it? Can --syn packets be not NEW?
I've read a lot of examples and, sometimes, the state checking is dropped but in other (most) texts it's still present. Also, I found these related questions but cannot figure out a precise answer to my specific question:
Advantage of using "--syn" for matching new TCP connections
https://serverfault.com/q/338553
Thanks a lot.

A: I've always found both --syn and --ctstate NEW to be redundant because I have -m state --state INVALID -j DROP as the first rule for all the relevant chains.
The thinking is maybe you want to be a purist and follow the TCP/IP stack to the letter which means only a new connection must be --syn, i.e. you cannot send a SYN packet within an already established connection because to terminate it you must use FIN.


text:
Q: printing out dictionnaires I have a rather specific question:
I want to print out characters at a specific place using the \033[ syntax. This is what the code below should do: (the dict cells has the same keys as coords but with either '*' or '-' as value.)
coords = {'x'+str(x)+'y'+str(y) : (x,y) for x,y, in itertools.product(range(60), range(20))}

for key, value in coords.items():

    char = cells[key]
    x,y = value
    HORIZ=str(x)
    VERT=str(y)
    char = str(char)
    print('\033['+VERT+';'+HORIZ+'f'+char)

However, I noticed that if I put this into a infinite while loop, it does not always prints the same characters at the same position. There are only slight changes, but it deletes some and puts them back in after some loops. I already tried it with lists, and there it seems to behave just fine, so I tend to think it has something todo with the dict, but I can not figure out what it could be. You can see the Problem in a console here: SharedConsole.I am happy for every tip on this matter.
On a related topic:
After the printing, some changes should be made at the values of the cells dict, but for reason unknown to me, the only the first two rules are executed and the rest is ignored. The rules should test how many neighbours (which is in population) are around the cell and apply the according rule. In my implemention of this I have some kind of weird tumor growth (which should not happen, as if there more than three around they should the cell should die) (see FreakingTumor):
if cells_copy [coord] == '-':
    if population == 3:
        cells [coord] = '*'
if cells_copy [coord] == '*':
    if population > 3:
        cells [coord] = '-'
    elif population <= 1:
        cells [coord] = '-'
    elif population == 2 or 3:
        cells [coord] = '*'

I checked the population variable several times, so I am quite sure that is not the matter.
I am sorry for the slow consoles.
Thanks in advance!
Kyril

A: Your syntax
    elif population == 2 or 3:

evaluates as
    elif (population == 2) or (3 != 0):

and 3 is never 0, so this clause is always True. What you meant to write was
    elif population == 2 or population == 3:

or maybe
    elif population in (2,3):

This logic could be reduce to
EMPTY = '-'
FULL = '*'
if cells_copy[coord] == EMPTY:
    if population == 3:
        cells[coord] = FULL
else:
    if population not in set([2,3]):
        cells[coord] = EMPTY

I also suggest coalescing your writes (writing a full line at a time):
# Make sure everything in `cells` is a string
ESC = chr(27)

for y in xrange(20):
    outp = (cells['x{}y{}'.format(x,y)] for x in xrange(60))
    print('{}[{};{}f{}'.format(ESC, y, x, ''.join(outp)), end='')

You would probably also benefit from making cells a list instead of a dict
WIDTH = 60
HEIGHT = 20
cells = [[EMPTY]*WIDTH for y in xrange(HEIGHT)]


text:
Q: How do I properly set up and cite a bibliographic entry from a bibtex file? I'm getting an undefined control sequence error when I typeset my Latex document that cites an article in a linked BibTex library. How to fix?
I have set my typesetter to pdfLaTeX > BibTex8, and path to the *.bib file where my citations are stored set to:
\bibliography{../../../Documents/BibtexLibrary/BibtexLibrary}
\bibliographystyle{plain}

The BibTex entry in *.bib file is:
@article{mcclusky2001,
  Author = {McClusky, Bjornstad, Hagar, King, Meade, Miller, Monastero, Souter},
  Date-Added = {2016-05-27 19:28:56 +0000},
  Date-Modified = {2016-05-27 19:36:26 +0000},
  Journal = {Geophysical Research Letters},
  Keywords = {Coso},
  Number = {17},
  Pages = {3369-3372},
  Title = {Present day kinematics of the Eastern California Shear Zone from a Geodetically Constrained Block Model},
  Volume = {28},
  Year = {2001}}

Citation in Latex input:
  "...the context of recently \citet{mcclusky2001} mapped surface..."

From LaTeX output:
  "...the context of recently mcclusky2001 mapped surface..."

A: As mentioned in comments, to use the macro \citet, you need to load the natbib package. For details on how to use that package and the macros it provides, you may refer to its manual/documentation at texdoc.net or from the command prompt/terminal type texdoc natbib in your computer.
Further, you have to use and to separate the author names instead of comma. So instead of
Author = {McClusky, Bjornstad, Hagar, King, Meade, Miller, Monastero, Souter},

you need
Author = {McClusky, Bjornstad and Hagar, King and Meade, Miller and Monastero, Souter},

More details on this can be found in taming the beast. It is always better to put the style well before i.e., the line \bibliographystyle{plainnat} be added before the \bibliography{BibtexLibrary}. Last, when you load the natbib package, better use the styles provided by it -- use plainnat instead of plain.
Here is your code snippet in the form of a MWE. Here the filecontents package and environment are used just for this demo and you don't need them in your actual example.
\documentclass{article}
\usepackage{natbib}
\usepackage{filecontents}
\begin{filecontents*}{BibtexLibrary.bib}
@article{mcclusky2001,
  Author = {McClusky, Bjornstad and Hagar, King and Meade, Miller and Monastero, Souter},
  Date-Added = {2016-05-27 19:28:56 +0000},
  Date-Modified = {2016-05-27 19:36:26 +0000},
  Journal = {Geophysical Research Letters},
  Keywords = {Coso},
  Number = {17},
  Pages = {3369-3372},
  Title = {Present day kinematics of the Eastern California Shear Zone from a Geodetically Constrained Block Model},
  Volume = {28},
  Year = {2001}}
\end{filecontents*}
\begin{document}
"...the context of recently \citet{mcclusky2001} mapped surface..."
\bibliographystyle{plainnat}
\bibliography{BibtexLibrary}

\end{document}

BTW, don't use bibtex8 for compiling, use bibtex. This will be enough. So the compilation sequence will be
pdflatex yourfile
bibtex yourfile
pdflatex yourfile
pdflatex yourfile

where yourfile is yourfile.tex, your actual .tex file name.

A: Your objectives aren't entirely clear. As you're using the plain bibliography style, which can only produce numeric-style citation call-outs, there seems to be little point in using \citet, which is a macro provided by the natbib package for the purpose of creating textual-style authoryear citation call-outs.
If, on the other hand, you do want to create authoyear-style citation call-outs and hence do want to use \citet (and possibly \citep as well), you should (a) load the natbib package with the option authoryear and (b) switch from the plain to the plainnat bibliography style.
Separately, you should fix two major issues in the bib entry. First, the author field is badly mangled. Second, you need to do something to ensure that the substring "Eastern California Shear Zone" in the title field won't get lowercased. Regarding the former issue: the author field currently reads
Author = {McClusky, Bjornstad, Hagar, King, Meade, Miller, Monastero, Souter},

To separate the authors, don't use commas; use the keyword and. Incidentally, you're missing the first names of all eight [!] authors. A quick Google search shows that the author field really should be rendered as
Author = {Simon C. McClusky and S. C. Bjornstad and Bradford H. Hager and
          R. W. King and Brendan J. Meade and M. M. Miller and
          F. C. Monastero and B. J. Souter},

Second, the title field currently reads
Title = {Present day kinematics of the Eastern California Shear Zone
        from a Geodetically Constrained Block Model},

A quick scan over the abstract of the publication reveals that "Eastern California Shear Zone" must be rendered in uppercase. (If nothing else, the word "California" should never be lowercased, right?) This won't happen by default, though, as both plain and plainnat practice "sentence style" for the contents of title fields: All letters of the entire field except for the very first one (here: "P") will be converted to lowercase. To override this setting, you need to encase the substring in question in a pair of curly braces. Thus, do write the field as follows:
Title = {Present day kinematics of the {Eastern California Shear Zone}
        from a Geodetically Constrained Block Model},

With this setting, the words "Geodetically", "Constrained", "Block", and "Model" will all be rendered in lowercase; presumably, this is just fine.


text:
Q: Solving a PDE with sympy or matlab i would like to know how to solve the following PDE with sympy or matlab
thanks in advance.

A: i just solved it with sympy
import sympy as sp

x1, x2 = sp.symbols('x1, x2')
f = sp.Function('f')
phi = f(x1, x2)
eq = phi.diff(x1) * sp.cos(x2) + phi.diff(x2)
print(sp.pdsolve(eq)) # f(x1, x2) == F(-x1 + sin(x2))


text:
Q: how to automate manage transactions in SQL Alchemy When use java Hibernate & Spring framework, there is a transaction manager which we can configure some transaction rules, then we don't need write "commit, flush, rollback" stuff each time.

A: For python SQL Alchemy, we can use decorators and context managers to manage transactions(official sample from doc):
from contextlib import contextmanager

@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

def run_my_program():
    with session_scope() as session:
        ThingOne().go(session)
        ThingTwo().go(session)

an transactions library is also a good choice to do that.


text:
Q: C# vs PowerShell I'm trying to re-write a C# script in PowerShell. I'm figuring it out piece by piece.
The PowerShell version is telling me 'Cannot find an overload for "Call" and the argument count: "2".'. So I know it's because PS is requiring that the 3rd parameter be present. But, why doesn't the C# require it? Because of the "params"?
What does the params even mean or do in this context?
How can I mimic that in PowerShell?
Yes, I left out a lot of code because I didn't feel it pertained to my issue of not understanding what's going on with this particular error.
C#
object dialog = r.Call(ofd, "CreateVistaDialog")

public class Reflector
{
    public object Call(object obj, string func, params object[] parameters)
    {
        return Call2(obj, func, parameters);
    }
}

PowerShell
$Dialog = $Reflector.Call($This.OFD, "CreateVistaDialog")

Class Reflector
{
    [Object]Call([Object]$Obj, [String]$Func, [Object[]]$Parameters)
    {
        return $This.Call2($Obj, $Func, $Parameters)
    }
}

A: In the C# Call parameters is an optional params type.
In your Powershell class, Call has three required parameters, $Parameters is not optional.
It looks like you could omit that parameter in your Powershell script since your not using it but I can't say whether Call2 uses it or not. You may just want to change the signatures of both methods in your Powershell script.


text:
Q: How do I programmatically select a qooxdoo table cell and then start editing? I would like to programmatically select a cell in a Qooxdoo table widget and then start the editor for that cell.
So far, I've been able to figure out the following: I can select and focus the cell as follows:
var pane = table.getPaneScroller(0);
var selectionModel = table.getSelectionModel();
selectionModel.resetSelection();
selectionModel.addSelectionInterval(row, row);
pane.setFocusedCell(col, row);

However, a subsequent call to table.startEditing() will not start the cell editor. It works if the cell had manually been selected by the user.
What does the user's selection of the cell do that my programmatic approximation fails to?
I've put together an example demonstrating the problem.

A: I've been so obsessed with the startEditing not working that I failed to see the obvious: I got the focusing part completely wrong. I had copied it from an old discussion thread. Obviously, it was much too old.
Now I'm doing this:
var selectionModel = table.getSelectionModel();
selectionModel.resetSelection();
selectionModel.addSelectionInterval(row, row);
table.setFocusedCell(col, row);
table.startEditing();

Selecting the row the cell is in is not even strictly necessary but a focused cell in an unselected row looks kinda weird.


text:
Q: Unchecking AutoLayout does not format subviews properly I have an iphone app that contains xib with "Use AutoLayOut" as checked.But building that app in iphone 5.0 simulator getting the app crasged due to "NSLayoutConstraint".
As autolayout not there in ios5 unchecked autolayout and the app runs on iphone5 simulator wiyh out crashing but the subviews present in that viewcontroller are not formatting properly.
Is there any way to do this .

A: if you create any xib in iso 6.0 or above means xcode(4.5.x) and above then you get Constraint in xib.
like :

if want to run it in lower version then please unchecked Use AutoLayout chkeckbox. in Xib
select FilesOwner->ShowFileInspector ->

if you unchecked it then it will run on ios5 and its lowerversion.


text:
Q: How to quickly select multiple tiles in Windows 8 apps? I would like to select multiple songs for the music app to play. The files are presented as tiles. Is there any sort of multi-select, other than brute force click'm all?

A: You can select multiple tiles by using the right mouse button:

*

*Right-click the first song

*hold Shift and right-click the last song.

This works not only in Music, but in many other applications, e.g. in SkyDrive. Also, you can replace right-click with Ctrl-left-click, so to select songs this way you would:

*

*Hold Ctrl and left-click the first song

*Hold Ctrl+Shift and left-click the last song.


text:
Q: How to pass dictionary using pytest fixture The following code gives the error "TypeError: 'function' object is not subscriptable.
import pytest

@pytest.fixture
def get_data():
  data = {'name': 'Bill', 'age': 20}
  return data

def test_get_data(get_data):
  test_data = get_data
  assert test_data['name'] == 'Bill'
  assert test_data['age'] == 20

test_get_data(get_data)


text:
Q: How to read cuda binary code Cuda generates 'cubin': cuda binary. This can be converted to assembly by running cuobjdump or nvdisasm (see also http://docs.nvidia.com/cuda/cuda-binary-utilities/index.html).
Now I have this wonderful assembly code and I have no proper way of reading it. Are there tools that

*

*place the assembly next to the source

*that explain the operations (like 'DMUL R4, R8, R2;' which is obviously a multiplication, but also something I don't know, like
'IMAD.HI.X')

*keep track of register count (I'm using cuda toolkit 5.5, I know that the tools spit out some counter as of version 6.5 or something)?

And is there something like a tutorial? It seems like almost nobody is reading cubins as googling results in hardly any results.

A: *

*nvdisasm --print-line-info, see http://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#nvdisasm-options

*See http://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#instruction-set-ref

*
*

*nvcc -v, see http://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#options-for-guiding-compiler-driver

*nvdisasm --print-life-ranges, see http://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#nvdisasm-options


text:
Q: Want to POST Text to Tumblr I am Able to Perform the GET Method for Tumblr Blog,
But Whenever I try to Perform the POST Method for Tumblr then At that time I get an Error as::
({"meta":{"status":401,"msg":"Not Authorized"},"response":[]});

I am using the Following code for Ajax Post::
$.ajax({
    type: 'POST',
    url: 'https://api.tumblr.com/v2/blog/firstblgpsa.tumblr.com/post',
    dataType: "jsonp",
    data: {
        api_key: "*key here*",
        type: 'text',
        title: 'First_Post',
        body:'This is My First Post to Tumblr.'
    },
    success:function(){
        alert("Blog Posted Successfully!!");
    }
})

A: On the client side (in the browser) you are allowed from default to use only GET requests. This is the same origin policy. There are some tricks to go around this but I would not recommend doing that.
It's not even possible with JSONP see more details in q: How to use type: "POST" in jsonp ajax call question
What you should do:
The correct way of doing things like this is to send the request to your domains server (backend) and do the request against tumblr from your backend server directly with php or ruby or w/e you got there.


text:
Q: Spring define a bean in session scope with java config I would like to use a bean in session scope, but I receive an error:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\testRestService\WEB-INF\classes\test\server\config\AppConfig.class];
nested exception is java.lang.annotation.AnnotationFormatError: Invalid default: public abstract org.springframework.beans.factory.annotation.Autowire org.springframework.config.java.annotation.Bean.autowire()

The Person Bean:
public class Person {
//This is a Pojo
//...
}

The AppConfig:
@Configuration
@EnableWebMvc
@ComponentScan("test.server")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean(scope = DefaultScopes.SESSION)
    @ScopedProxy
    public Person getPerson() {
        return new Person();
    }
}

The Person Sercive:
@Component
public class PersonService implements IPersonService {

    @Autowired
    protected Person person;

    @Override
    public void setPerson(Person person) {
        this.person = person;
    }

    @Override
    public Person getPerson() {
        return this.person;
    }
}

The PersonController:
@RestController()
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private IPersonService personService;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        binder.registerCustomEditor(Person.class, new GenericEditor<Person>(Person.class));
    }

    @RequestMapping(value = "/setPerson", method = RequestMethod.GET)
    public String setPerson(@RequestParam(value = "person") Person person) {
         this.personService.setPerson(person);
         return "Person: " + person + " saved.";
    }

    @RequestMapping(value = "/getPerson", method = RequestMethod.GET)
    public Person getPerson() {
         return this.personService.getPerson();
    }
}

I tried to use @Scope("session") on the Person bean, in this case I did not use the @ScopedProxy annotation in appconfig and used the @org.springframework.context.annotation.Bean("person") instead of org.springframework.config.java.annotation.Bean(scope = DefaultScopes.SESSION). In this case I didn't receive an error, but the Person bean wasn't in the session scope when I tested it.
Thanks for the help.

A: Session level beans are supported through JDK dynamic proxies. The following modifications are required in your code:

*

*remove the getPerson() method from the AppConfig class

*do not autowire your bean in PersonService, just instantiate it with it's default constructor

*annotate the PersonService with the following:

*

*@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)

A: Annotate the classes which bean has scope as follow:
@Scope(value = [scope], proxyMode = ScopedProxyMode.TARGET_CLASS)

Proxy Mode TARGET_CLASS: is used for creating AOP proxy of the bean.
  We must do it when injecting short lived bean scope (request,
  session…) to long lived bean scope (singleton, prototype) or injecting
  prototype to singleton scope.

@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class Address {
    private String address = "US";

    public Address() {
        System.out.println("Create new Address: " + this.address);
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

@Component
public class Customer {

    @Autowired
    private Address address;

    public String getCustomerAddress(){
        return address.getAddress();
    }

    public void setCustomerAddress(String address){
        this.address.setAddress(address);
    }

}


text:
Q: Showing an Null Reference Exception that values are garbage collected while loading the data My application is throwing an exception while loading the data and it's showing a message that "requested operation is cancelled due to object is garbage collected".
sometimes My application is working fine but unexpectedly in the middle it,s throwing this exception.
Can any one guide me to solve this issue.
Thanks

A: Please check this once https://forums.xamarin.com/discussion/18910/navigation-popasync-not-freeing-page
I don't think it will work or not but please check your xaml file once the issue in the design.If you are manually adding any controls like buttons,labels with bindings (any controls) from your ViewModel or any file it should throw this type exception I also faced this.In my case below line of code worked for me
await Task.Delay(your seconds);

before or after adding controls

A: There is a chance that you create some background task in your app and run and in this task, you get the null object.
In this case, you will need to:
put a debugger on System.NullReferenceException and find the exact issue location. please look below image.


text:
Q: mongodb aggregate function google cloud console I have a strange problem regarding how mongodb works for my MEAN.js application. It's not a problem straight for MEAN app, but goes directly just for MONGODB.
On my local computer(Win 8.1) and a VM(Ubuntu server 14.x) aggregate functions with mongoose works fine, but when I upload my project with the same version of Mongodb to a Google Cloud Virtual Instance (2 CPU's or 4 CPU's) everything works fine, untill the aggregate function will be triggered. I do not have an error from the server to show, that's why is weird...
(MongoDB v3.2.8 or 3.2.6, both works for local) I tried on 3 different Google Cloud VI, but ended with the same result...
My query is about counting records for each day if found. Here is my query:
    { "$match": { '$and':
           [ { firm: ObjectId('574e81be2153f45b0c3d6811') },
             { created:
                { '$gte': ISODate('Tue Jul 12 2016 15:56:04 GMT+0000 (UTC)'),
                  '$lte': ISODate('Thu Aug 11 2016 15:56:04 GMT+0000 (UTC)') } },
             { transactionStatus: 1 } ] }
        },
        { "$group": {
          "_id": {
            "$add": [
              { "$subtract": [
                { "$subtract": [ "$created", new Date(0) ] },
                { "$mod": [
                  { "$subtract": [ "$created", new Date(0) ] },
                  OneDay
                ] }
              ] },
              new Date(0)
            ]
          },
          "count": { "$sum": 1 }
        }
    }

I tried switching the MONGODB version to 2.6 or something similar, but still to a no end. I couldn't find anything similar here or anywhere else, that's why I am asking here.
Thanks a lot in advance.

A: I do not know why but if I change the query I am performing into the aggregation like this:
{ '$and':
  [ { created:
      { '$gte': ISODate('Tue Jul 12 2016 15:56:04 GMT+0000 (UTC)'),
        '$lte': ISODate('Thu Aug 11 2016 15:56:04 GMT+0000 (UTC)') } },
    { transactionStatus: 1 },
    { firm: ObjectId('574e81be2153f45b0c3d6811') }
  ]
}

From this:
{ '$and':
  [ { firm: ObjectId('574e81be2153f45b0c3d6811') },
    { created:
      { '$gte': ISODate('Tue Jul 12 2016 15:56:04 GMT+0000 (UTC)'),
        '$lte': ISODate('Thu Aug 11 2016 15:56:04 GMT+0000 (UTC)') } },
    { transactionStatus: 1 }
  ]
}

Works everything fine...can someone explain this to me? Anyways, this topic can be closed.


text:
Q: EXCEL DAX - Calculate the sum of a related table
I want to show in the Table 1 the sum of each SKU. The sum comes from the Table 2. I tried the following DAX code for table 1:
sumx(Filter(Table2[Sales],Related(Table1[Sales]),Table2[Sales])
I read the Summing up a related table's values in PowerPivot/DAX, but don't quite get it. My case is that I don't want to assign the primary key to Table 1 and assign the foreign key to Table 2.
Thanks a lot for any suggestion.

A: So you want to add a calculated column into Table1 which is the sum of sales from Table2?
As long as you have a relationship between the tables in Power Pivot (where Table2[Sku] points to Table1[Sku]) then it is easy. The calculated column would be:
=CALCULATE(SUM(Table2[Sales]))


text:
Q: Whenever I upload an icon on jlabel and run the jform. It doesn't display and gives an error in the output Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
This error occurs.
I use netbeans 12.6
[![stacktrace screenshot][1]][1]
Edit: I apologise for the lack of decorum in presenting the code and also sorry for the delay. The problem is basic in nature. My jform runs and displays 'Except' whenever I insert in images and gifs as icons for jlabel.
CODE:
public class Login extends javax.swing.JFrame {
/**
 * Creates new form Login
 */
public Login() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Login_ani.gif"))); // NOI18N

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(94, 94, 94)
            .addComponent(jLabel1)
            .addContainerGap(96, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(128, 128, 128)
            .addComponent(jLabel1)
            .addContainerGap(172, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Login().setVisible(true);
        }
    });
}

// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration

}
https://i.stack.imgur.com/t1bmT.png
https://i.stack.imgur.com/Iar3F.png


text:
Q: How to Read contents of Windows Event Log Using Delphi Is there a class or function which allows you to read the Windows event log.  This is the log you see when you open  eventvwr.msc.  And ideally select a specific log (in my case the Applications log under Windows Log), and place filters on date and source.

A: You can use the Win32_NTLogEvent WMI class to read the contents of the Windows Log.
Try this sample
{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;

procedure  GetLogEvents;
const
  wbemFlagForwardOnly = $00000020;
var
  FSWbemLocator : OLEVariant;
  FWMIService   : OLEVariant;
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
begin;
  FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
  FWbemObjectSet:= FWMIService.ExecQuery('SELECT Category,ComputerName,EventCode,Message,RecordNumber FROM Win32_NTLogEvent  Where Logfile="System"','WQL',wbemFlagForwardOnly);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
  while oEnum.Next(1, FWbemObject, iValue) = 0 do
  begin
    Writeln(Format('Category          %s',[String(FWbemObject.Category)]));
    Writeln(Format('Computer Name     %s',[String(FWbemObject.ComputerName)]));
    Writeln(Format('EventCode         %d',[Integer(FWbemObject.EventCode)]));
    Writeln(Format('Message           %s',[String(FWbemObject.Message)]));
    Writeln(Format('RecordNumber      %d',[Integer(FWbemObject.RecordNumber)]));
    FWbemObject:=Unassigned;
  end;
end;

begin
 try
    CoInitialize(nil);
    try
      GetLogEvents;
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

For more samples try this blog entry WMI Tasks using Delphi – Event Logs

A: Reading an event log is done with the ReadEventLog() function.  See MSDN for an example:
Querying for Event Information

A: JVCL includes a component named JvNTEventLog which can open and manipulate Windows Event Log.


text:
Q: How Do You Use curve_fit in Python? I am using curve_fit (from scipy.optimze) to solve the following:
my y axis is
si = np.log([426.0938, 259.2896, 166.8042, 80.9248])

my x axis is
b = np.array([50,300,600,1000])

I am doing log the y axis because my original equation is
si = exp(b * a)

I want to calculate a but I assume that it is the slope of the curve?
def fun(x,a):
 return np.dot(x,a)

popt, pcov = curve_fit(func,b,si)
print(popt)
[1.]

I really don't understand how to use the popt data obtained from curve_fit in my equation.

A: I don't understand what you are trying to do, but popt is basically the extimated value of a. In your case it is the value of the slope of a linear function which starts from 0 (without intercept value):
f(x) = a*x

because it will not fit correctly the data, it would be better to use linear function with an intercept value:
f(x) = a*x + b

defined as such:
def fun(x,a,b):
    return a * x + b

Basically, after running your example, you will obtain the best parameters (a the slope and b the intercept) for your linear function to fit your example data.
Below the full example with the results:
from scipy.optimize import curve_fit
import numpy as np

# e^(a * b)
e_exp_a_x_b = [426.0938, 259.2896, 166.8042, 80.9248]
# a * b
a_x_b = np.log(e_exp_a_x_b)
# b
b = np.array([50,300,600,1000])

def fun(x,a_slope,b_intercept):
    return a_slope * x + b_intercept

import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
x_data = b
y_data = a_x_b

popt, pcov = curve_fit(fun, b, a_x_b)
plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, fun(x_data, popt[0], popt[1]),
         label='Fitted function')
plt.legend(loc='best')
plt.show()

A: If you first visually inspect a scatterplot of the data you would pass to curve_fit(), you would see (as in the answer of @Nikaido) that the data appears to lie on a straight line. Here is a graphical Python fitter similar to that provided by @Nikaido:

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# the "dtype=float" ensures floating point numbers,
# otherwise this would be a numpy array of integers
b = numpy.array([50,300,600,1000], dtype=float)

# these are already floating point numbers
si = numpy.log([426.0938, 259.2896, 166.8042, 80.9248])

# alias data names to match previous example code
xData = b
yData = si

def func(x, slope, offset):
    return slope * x + offset

# same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)


text:
Q: Azure APIM versioning changing the path I am trying to create api and expose them via APIM. The path of the api that I expect is
baseUrl/v1/Product/Upload.
But when i try to use versioning of APIM, I could only come up with something like
baseUrl/Product/v1/Upload, where Product is API url suffix.
Is there a way in APIM to change the order in which version number is placed in the url path.

A: Every API Developer will have their own requirement of versioning. So Azure API Management provide several options instead of a single approach to versioning. And Path-based versioning is one of those options.
If you check this Path-based versioning section of Microsoft document then you will find -

When the path versioning scheme is used, the version identifier needs to be included in the URL path for any API requests.

The format of an API request URL when using path-based versioning is as follows.
https://{yourDomain}/{apiName}/{versionIdentifier}/{operationId}
It is recommended to follow this format but if you want to modify it you can use the API Management transformation policies. The rewrite-uri policy converts a request URL from its public form to the form expected by the web service.
Read this Rewrite URL and Policy Expressions in Azure API Management document for more information.


text:
Q: Assign myClass object to UIView object and using myClass selectors(variables) I try to assign myClass object to UIView class object and using myClass variables.
So,
I created myClass that contains units segment control
@interface myClass : UIView
@property (nonatomic,readonly) UISegmentedControl *units;

In my UIViewController I try to do something like this
myClass *newObject = [[myClass alloc]init];

UIView *newView;

newView = newObject;

[[newView units] addTarget:self action:@selector(changeUnit)
                      forControlEvents: UIControlEventValueChanged];

and I received "No visible @interface for UIView declares the selector 'units'"
Is it possible to do not use myClass *newView = [[myClass alloc]init]; object?

A: Well, thanks to Objective-C's flexibility it is possible to do what you're asking although it is a strange requirement.
This line of code: [[newView units] addTarget:...] shouldn't generate any complier errors (unless you've set the "Treat Warnings as Errors" flag to YES) but it will generate a warning. As long as the newView variable is in reality an instance of myClass everything will work as expected.
There are also some precautions you can take like using the respondsToSelector: and isKindOfClass: methods. Here is a way you can make your code more robust:
myClass *newObject = [[myClass alloc] init];

UIView *newView = nil; // always initialize method variables to nil

newView = newObject;

// make sure 'newView' can respond to the 'units' selector
if ( [newView respondsToSelector:@selector(units)] )
{
    // if it does, use 'performSelector' instead of calling the method
    // directly to avoid a compiler warning
    id unitsObject = [newView performSelector:@selector(units)];

    // make sure the object returned by 'performSelector' is actually
    // a UISegmentedControl
    if ( [unitsObject isKindOfClass:[UISegmentedControl class]] )
    {
        // if it is, cast it...
        UISegmentedControl *units = (UISegmentedControl*)unitsObject;

        // ... and add the Target-Action to it
        [units addTarget:self action:@selector(changeUnit)
                  forControlEvents: UIControlEventValueChanged];
    }
}

Just remember

*

*To correctly initialize the 'units' property inside 'myClass' or to correctly assign it before using it

*When you instantiate the 'newObject' variable you're calling 'init' instead of the default initalizer 'initWithRect:'. Make sure this is the intended behavior.

Hope this helps!

A: This is OOP basics. Your newView is a UIView, which doesn't have units.
Your subclass myClass has units.
Just use [[newObject units] addTarget...(etc)].


text:
Q: How to track how many times an iPhone app is opened? I am building an iphone app and would like to keep track of how many times it has been opened so that I can prompt the user to do certain actions after it has been opened X number of times. I have thought about storing a variable in Core Data which I update every time it is opened, but this seems like a waste since it is a singleton data, not multiple instances of an object. What is the best way to store data like this and access it without slowing down the app opening time?

A: You can store it user defaults. Here is the code:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self countOpen];
}

-(void) countOpen {
    int _coutn= 0;
    _count=  [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppCount"] intValue];

    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringFormat:@"%d",_count+1] forKey:@"AppCount"];
}


text:
Q: split a sentence so that adds each word in an array item I have a sentence, I want split the sentence so that adds each word in an array item.
I have done the following code but it still wrong.
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
    strWords[counter] = str[i];
    if(str[i] == ' '){
        counter++;
    }
}

A: I'm answering since you should learn from your mistakes: just use the += string operator and your code will work:
// strWords[counter] = str[i];   <- change this
strWords[counter] += str[i];     <- to this

to remove the spaces (if you don't want to append them) just change the order of the space check, something like:
for (short i = 0; i<str.length(); i++){
    if (str[i] == ' ')
        counter++;
    else
        strWords[counter] += str[i];
}

anyway I'm suggesting to use the duplicate link Split a string in C++? too

A: Very ugly way to do it, @Cyber has linked to the best answer. But here's your "corrected" version:
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;

for(short i=0;i<str.length();i++){
    if(str[i] == ' '){
        counter++;
        i++;
    }
    strWords[counter] += str[i];
}

A: As mentioned in the comments, there are a lot of more convenient ways to split a string (strtok, std functionality, etc.), but if we talk about your sample, you should not assign the 'str[i]' but append it, since it is a single character that you want to append to the current word like this:
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
    if(str[i] == ' ' && !strWords[counter].empty()){
        counter++;
    }
    else {
        strWords[counter] += str[i];
    }
}

But this will work only on the given input data, since you can access the array strWords outside bounds if  you have more than five words. Consider using a following code:
string str = "Welcome to the computer world.";
vector<string> strWords;
string currentWord;
for(short i=0;i<str.length();i++){
    if(str[i] == ' ' && !currentWord.empty()){
       strWords.push_back(currentWord);
       currentWord.clear();
    }
    else {
        currentWord += str[i];
    }
}

UPDATE
Since I assume you are new to C++, here is the demonstration of the space issue you have (if you only use the addition operator):
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    string str = "Welcome to the computer world.";
    string strWords[5];
    short counter = 0;
    for(short i=0;i<str.length();i++){
        strWords[counter] += str[i]; // Append fixed
        if(str[i] == ' '){
            counter++;
        }
    }
    for(short i=0;i<5;i++){
        cout << strWords[i] << "(" << strWords[i].size() << ")" << endl;
    }
    return 0;
}

Result:


text:
Q: Angular 8: Not getting selected dropdown values in component using Reactive Form I am dynamically populating drop downs and it's values. After selecting all the value when I click on the submit button I am not able to set it's value in form, I am getting blank values.
HTML:

                            Select {{ type.cat_name }}
                            <select class="form-control custom-select"
                                (change)="onChangeType($event.target.value)"
                                [value]="type.key_name" >
                                <option value="">-- Select --</option>
                                <ng-container *ngFor="let subType of dynamicCategoryData">
                                    <option *ngIf="subType.key == type.key_name" [value]="subType.value">{{subType.value}}</option>
                                </ng-container>
                            </select>

component.ts
  ngOnInit() {
    this.uploadArtWorkForm = this.formBuilder.group({
      thumb_img: ['', [Validators.required]],
      categoryArray: this.formBuilder.array([]),
    });

  }

addUploadArtWorkForm() {
    console.log("this.uploadArtWorkForm.value", this.uploadArtWorkForm.value)
}

OUTPUT:
{
    "categoryArray": [
        {
            "gems": null,
            "metal": null,
            "type": null
        }
    ]
}

Is it just because I am not using formControlName ? Can we do it without it?
Any help would be appreciated.

A:
Modify your app.component.html as below:

 0">

                    Select {{ types[k].cat_name }}
                    <select class="form-control custom-select" [class]="types[k].key_name" (change)="onChangeType($event.target.value)" formControlName="{{ types[k].key_name }}" *ngIf="types[k].cat_name == 'Type'">
              <option value="">-- Select --</option>
              <option *ngFor="let type of catTypeValue" [value]="type.cat_name">
                  {{type.cat_name}}
              </option>
          </select>
          <select class="form-control custom-select" [class]="types[k].key_name" (change)="onChangeType($event.target.value)" formControlName="{{ types[k].key_name }}" *ngIf="types[k].cat_name == 'Metal'">
              <option value="">-- Select --</option>
              <option *ngFor="let type of catMetalValue" [value]="type.category_id">
                  {{type.cat_name}}
              </option>
          </select>
          <select class="form-control custom-select" [class]="types[k].key_name" (change)="onChangeType($event.target.value)" formControlName="{{ types[k].key_name }}" *ngIf="types[k].cat_name == 'Gems'">
              <option value="">-- Select --</option>
              <option *ngFor="let type of catGemsValue" [value]="type.category_id">
                  {{type.cat_name}}
              </option>
          </select>

and app.component.ts as below:

//below value will be displayed in Select Type dropdown
  catTypeValue = [{"parent_id":2,"cat_name":"Anklets","category_id":3,"key_name":"anklets"}, {"parent_id":2, "cat_name":"Body", "category_id":4, "key_name":"body"}, {"parent_id":2, "cat_name":"Bracelets","category_id":5, "key_name":""}, {"parent_id":2, "cat_name":"Charms","category_id":6, "key_name":""}, {"parent_id":2,"cat_name":"Necklaces","category_id":7, "key_name":""}, {"parent_id":2,"cat_name":"Ornamental","category_id":8, "key_name":""}, {"parent_id":2, "cat_name":"Rings & Studs","category_id":9, "key_name":""}, {"parent_id":2, "cat_name":"Jewelry Metal","category_id":10,"key_name":""}, {"parent_id":2, "cat_name":"Yellow Gold","category_id":11, "key_name":""}, {"parent_id":2, "cat_name":"White Gold","category_id":12,"key_name":"whitegold"}, {"parent_id":2, "cat_name":"Silver","category_id":13,"key_name":"silver"}
    ]

  // below values will be displayed in Select Metal dd
  catMetalValue = [
    {"parent_id":14,"cat_name":"White Gold","category_id":24,"key_name":"whitegold"},
    {"parent_id":14,"cat_name":"Yellow Gold","category_id":24,"key_name":"whitegold"},
    ]

  // below values will be displayed in Select Gems dd
  catGemsValue = [
    {"parent_id":15,"cat_name":"Blue Gems","category_id":25,"key_name":"bluegems"}
    ]

  constructor(private formBuilder: FormBuilder) {
    this.uploadArtWorkForm = this.formBuilder.group({
    cat_id: new FormControl('', Validators.required),
    categoryArray: this.formBuilder.array([]),
  });
  onChangeType(value, id){
    console.log(value);
  }
  onChangeCategory(event, id) {
    if (id) {
      this.types = [
        {"parent_id":1, "cat_name":"Type", "category_id":2, "key_name":"type"}, {"parent_id":1, "cat_name":"Metal", "category_id":14, "key_name":"metal"}, {"parent_id":1, "cat_name":"Gems", "category_id":15, "key_name":"gems"}];
      if(this.uploadArtWorkForm.controls['categoryArray'].length > 0){
        this.uploadArtWorkForm.controls['categoryArray'].controls.length = 0
      }
      this.addInNewCategory(this.types);
    } else {
      this.types = null;
      this.subTypes = null;
    }
  }

  get category(): FormArray {
    return <FormArray>this.uploadArtWorkForm.controls['categoryArray'];
  }

  addInNewCategory(types) {['categoryArray'];
    types.forEach((element, i) => {
      this.category.push(this.formBuilder.group({[element["key_name"]]: new FormControl(element["key_name"])
      }));
    });
  }
}


text:
Q: SVG base64 encoded in CSS I created a logo that I'll be using on a site in AI and used an SVG Optimizer to output an optimized file. Initially I embedded the svg file into the HTML but seeing as it's a fixed logo across all pages I thought it would be best to remove it from the HTML and insert in my CSS as a background image. When I insert the base64 encoded link my link wraps line after line, maybe 15 lines, which just seems much too long.
Below is a clip of what I have. I obviously cut the remaining 14 or so lines. My questions is: Is there a way to shorten the actual link for this without using js? Similar to a relative path but for an encoded URI.
#logo { background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJb...); }

A: Sure you can add carriage returns and spaces and it will still work. Here's an example from the SVG test suite
    <image x="40" y="5" width="100" height="98" preserveAspectRatio="none" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAABCAMAAAAfBfuPAAAABGdBTUEAAK/INwWK6QAAABl0RVh0
     U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEsUExURfb/AK3/AAD/9/9sAIn/AN7/ABT/
     AAB//zD/AP9GAAD/s1H/AAD/H/8AxwD/bn8A/1wA/wD/XJv/AP8Ai//MAGP/ABMA/wD/LP8A6P8K
     AP8AF/8A9QD/xAAA/wD1/9MA/wD/gABY/wD/Cf8ATJEA//+6AACT/wCn/+v/AAD/TAD/kf8AYKMA
     //8kAAAk/wAV/y0A/3b/AP80AAD/O/cA//8A/wD///8An/8A2QD/Ev8AAMQA/+0A/7MA////AP8A
     CuAA//8AJ24A/0sA//8AOAA0/wAK/wBF//8WAAgA/x8A///2AL//AP8AdTwA/wn/AP/bAP+AAP+U
     AM//AP+nAP8AtADp/wD/o0D/AP/qAADb/wC5/wDL/wD/AAD/7QD/0gD/4CH/AABr//9ZAG2IeB4A
     AABvSURBVHjaYrCyl3J0Udb2FTYP5bWQkDY1sXGQt7bVUeF3EnD2M/AS85R109dzdVdMYldTj46J
     CpMzY4pLiJfhCtdS4BPUNBbnsVSK9WdL5IjgFjVkEWL0CWbVYLDzjgwQUQ0JCmRO5jTS9ZAECDAA
     3aQTV3E5iioAAAAASUVORK5CYII="/>


text:
Q: Resize checkbox in Checkbutton I've recently started learning about Tkinter in python.
What I want is to be able to resize all elements I use in my app.
I'm using mostly Labels and Buttons, but I also use one Checkbutton.
Changing the default font size does the trick for almost all elements, except for Checkbutton.
The text of Checkbutton scales, as does the area that Checkbutton occupies.
But the checkbox (the box beside the text) doesn't change.
If it could scale depending on the font size, that would be perfect, but manually setting the size is also accaptable.
I'm using pack() for placing the components, if it changes anything.
I didn't post any code as I see no point in it, if needed I can post it.

A: According to https://stackoverflow.com/a/46266090/12121416 (and my own research so far), there is no way to do this without creating your own checkbox.


text:
Q: How to get firestore instance with react-redux-firebase? authAction.js: Here firebase.set is not working neither firestore.set is working. If I'm including getFirestore then it says getFirestore is not a function. And if I'm doing in below way then it says permission denied.
firebase.set(users/${createdUser.user.uid}, { ...newUser })
How can I use set function of firestore here
export const registerUser = user =>
  async (dispatch, getState, getFirebase) => {
    const firebase = getFirebase();
    // const firestore = getFirestore();
    try {
      let createdUser = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
      console.log('createdUser', createdUser);
      await createdUser.user.updateProfile({
        displayName: user.displayName
      });
      let newUser = {
        displayName: user.displayName,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      }
      console.log('new user', newUser);
      await firebase.set(`users/${createdUser.user.uid}`, { ...newUser })
      dispatch(closeModal())
    }
    catch (err) {
      console.log(err.message)
    }
  }

firebase.js
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/database';
import 'firebase/auth';
import 'firebase/storage';

const firebaseConfig = {}

firebase.initializeApp(firebaseConfig);
firebase.firestore();

export default firebase;

configureStore.js
import { createStore, applyMiddleware } from "redux";
import { reactReduxFirebase, getFirebase } from 'react-redux-firebase';
import { reduxFirestore, getFirestore } from 'redux-firestore';
import { devToolsEnhancer, composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from "../reducers/rootReducer";
import thunk from "redux-thunk";
import firebase from '../config/firebase';

//react redux firebase config
export const rrfConfig = {
  userProfile: 'users',
  attachAuthIsReady: true,
  useFirestoreForProfile: true
}

/*
########section without applyMiddleware(thunk)##########
*/

// export const configureStore = () => {
//   const store = createStore(rootReducer, devToolsEnhancer());
//   return store;
// }

/*
########section with applyMiddleware(thunk)##########
*/
export const configureStore = () => {
  const middlewares = [thunk.withExtraArgument(getFirebase)];

  const composedEnhancer = composeWithDevTools(
    applyMiddleware(...middlewares),
    // reactReduxFirebase(firebase, rrfConfig),
    // reduxFirestore(firebase)
  );

  const store = createStore(rootReducer, composedEnhancer)

  return store
}

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import 'react-redux-toastr/lib/css/react-redux-toastr.min.css';
import App from './app/layout/App';
import ReduxToastr from 'react-redux-toastr';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { configureStore, rrfConfig } from './app/store/configureStore';
import ScrollToTop from './app/common/util/ScrollToTop';
import firebase from '../src/app/config/firebase';
import { ReactReduxFirebaseProvider } from 'react-redux-firebase';
import { createFirestoreInstance } from 'redux-firestore';

const store = configureStore();

ReactDOM.render(
  <Provider store={store}>
    <ReactReduxFirebaseProvider
      firebase={firebase}
      config={rrfConfig}
      dispatch={store.dispatch}
      createFirestoreInstance={createFirestoreInstance}
    >
      <BrowserRouter>
        <ScrollToTop>
          <ReduxToastr
            position='bottom-right'
            transitionIn='fadeIn'
            transitionOut='fadeOut'
          />
          <App />
        </ScrollToTop>
      </BrowserRouter>
    </ReactReduxFirebaseProvider>
  </Provider>,
  document.getElementById('root'));
serviceWorker.unregister();

A: One way to do it would be:
export const registerUser = user =>
  async (dispatch, getState, getFirebase) => {
    const firebase = getFirebase();
    const firestore = firebase.firestore();  // <===
    try {
      let createdUser = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
      console.log('createdUser', createdUser);
      /*await createdUser.user.updateProfile({
        displayName: user.displayName
      });*/
      let newUser = {
        displayName: user.displayName,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      }
      console.log('new user', newUser);
      await firestore.collection("users").doc(createdUser.user.uid).set({ ...newUser }); // <===
      dispatch(closeModal())
    }
    catch (err) {
      console.log(err.message)
    }
  }

But since you included userProfile: 'users' in your rrfConfig, updateProfile is already doing what you are trying to do I think. So this would be the same result, and you don't need the firestore instance:
export const registerUser = user =>
  async (dispatch, getState, getFirebase) => {
    const firebase = getFirebase();
    try {
      let createdUser = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
      console.log('createdUser', createdUser);
      // updateProfile adds these to the correct users document
      await firebase.updateProfile({
        displayName: user.displayName,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      });
      dispatch(closeModal())
    }
    catch (err) {
      console.log(err.message)
    }
  }


text:
Q: Serialization on self referenced entity I wonder if it's possible to have different properties shown on GET operation to an embedded entity.
Here is my class :
/**
 * @ORM\Table(name="folders")
 * @ORM\Entity(repositoryClass="App\Repository\FolderRepository")
 */
class Folder
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="Folder", inversedBy="childFolders", cascade={"persist"})
     * @ORM\JoinColumn(name="folder_parent", referencedColumnName="id")
     */
    private $parentFolder;

    /**
     * @ORM\OneToMany(targetEntity="Folder", mappedBy="parentFolder", cascade={"persist"})
     */
    private $childFolders;

    /**
     * @ORM\OneToMany(targetEntity="File", mappedBy="folder", cascade={"persist"})
     * @ORM\JoinColumn(name="id_folder", referencedColumnName="id")
     */
    private $files;
}

The result I want to get :
{
    "@context": "\/contexts\/Folder",
    "@id": "\/api\/folders\/561",
    "@type": "Folder",
    "id": 561,
    "name": "SOURCE(6)",
    "parentFolder": {
        "@id": "\/api\/folders\/52",
        "@type": "Folder",
        "id": 52,
        "name": "ashirama workspace",
        "parentFolder": null
     },
     "files": [
        {
            "name": "file(1).png"
        }
      ]
}

The actual result :
{
    "@context": "\/contexts\/Folder",
    "@id": "\/api\/folders\/561",
    "@type": "Folder",
    "id": 561,
    "name": "SOURCE(6)",
    "parentFolder": {
        "@id": "\/api\/folders\/52",
        "@type": "Folder",
        "id": 52,
        "name": "ashirama workspace",
        "parentFolder": null,
        "files": [
              {
                   "name": "file(1).png"
              }
         ]
      },
     "files": [
        {
            "name": "file(2).png"
        }
     ]
}

I would like to have files only on actual folder.
I think there is something I don't understand, but maybe there's a known recipe for that use case.
Thank you.


text:
Q: DIDISOFT PGP Lib Hangs during decryption of a particular string When I encrypt the following string, apparently the length of the string below is great than 1024 and once encrypted it can decrypt it, but once the string is reduced to less than 1024, it then decrypts the string without hanging
String s = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
                + "<FTSingleCreditResponse>\n"
                + "    <Amount>1000.00</Amount>\n"
                + "    <BeneficiaryAccountName>Akogun Olasoji</BeneficiaryAccountName>\n"
                + "    <BeneficiaryAccountNumber>000000020</BeneficiaryAccountNumber>\n"
                + "    <BeneficiaryBankVerificationNumber></BeneficiaryBankVerificationNumber>\n"
                + "    <BeneficiaryKYCLevel>1</BeneficiaryKYCLevel>\n"
                + "    <ChannelCode>12</ChannelCode>\n"
                + "    <DestinationInstitutionCode>999194</DestinationInstitutionCode>\n"
                + "    <NameEnquiryRef>999999200825144654200825144654</NameEnquiryRef>\n"
                + "    <Narration>Transaction from me you</Narration>\n"
                + "    <OriginatorAccountName>Ajao Niyi</OriginatorAccountName>\n"
                + "    <OriginatorAccountNumber>0105498919</OriginatorAccountNumber>\n"
                + "    <OriginatorBankVerificationNumber>10000000002</OriginatorBankVerificationNumber>\n"
                + "    <OriginatorKYCLevel>1</OriginatorKYCLevel>\n"
                + "    <PaymentReference>ref/2015/08/05/val 3</PaymentReference>\n"
                + "    <ResponseCode>00</ResponseCode>\n"
                + "    <SessionID>999999200827170808200827170807</SessionID>\n"
                + "    <TransactionLocation>6.4300747,3.4110715</TransactionLocation>\n"
                + "</FTSingleCreditResponse>";

PGPLib hands when decrypting the encrypted result of the string above.
Below are my encryption and decryption methods using pgpLib
Encrypt
public String encrypt(String text) {
        try {
            PGPLib pgp = new PGPLib();
            boolean armor = false;
            boolean withIntegrityCheck = true;

            ByteArrayOutputStream o = new ByteArrayOutputStream();
            logger.debug("step 1");
            InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
            logger.debug("step 2");
            if (publicKeyFile == null) {
                publicKeyFile = new File(publicKeyLocation);
            }
            logger.debug("step 3");
            InputStream publicKeyStream = new FileInputStream(publicKeyFile);
            logger.debug("step 4");
            pgp.encryptStream(is, publicKeyLocation, publicKeyStream, o, armor,
                    withIntegrityCheck);
            logger.debug("step 5");
            byte[] body = o.toByteArray();
            int numberRead = body.length;
            logger.debug(" -|- SSModuleClient :: pickMessage :: numberRead: " + numberRead);
            return byte2hex(body);
        } catch (IOException ex) {
            logger.debug(" -|- SSModule :: MessageProcessor :: encrypt () :: Error Occurred ..."
                    + ex.getMessage());
            logger.debug("SSModule", ex);
        } catch (PGPException ex) {
            logger.debug(" -|- SSModule :: MessageProcessor :: encrypt () :: Error Occurred ..."
                    + ex.getMessage());
            logger.debug("SSModule", ex);
        }

        return "";
    }

Decrypt
public String decrypt(String text) {

        String decryptedMessage = "";

        try {
            byte[] bytText = hex2byte(text);

            PGPLib pgp = new PGPLib();

            InputStream iStream = new ByteArrayInputStream(bytText);

            logger.debug("SSModule :: decrypt () :: iStream.available(): "
                    + iStream.available());

            if (privateKeyFile == null) {
                privateKeyFile = new File(privateKeyLocation);
            }
            InputStream privateKeyStream = new FileInputStream(privateKeyLocation);
            PipedInputStream pin = new PipedInputStream();
            OutputStream oStream = new PipedOutputStream(pin);

            logger.debug("text: " + text);

            logger.info("privateKeyPassPhrase: " + privateKeyPassPhrase);

            pgp.decryptStream(iStream, privateKeyStream, getPrivateKeyPassPhrase(),
                    oStream);
            do {
                logger.debug("pin.available(): " + pin.available());
            } while (pin.available() <= 0);
            byte[] body = new byte[pin.available()];
            pin.read(body);
            decryptedMessage = new String(body).toString();
        } catch (Exception ex) {
            logger.debug("SSModule :: MessageProcessor :: decrypt () :: Error Occurred ..."
                    + ex.getMessage());
            logger.debug("SSModule", ex);
        }

        return decryptedMessage;
    }

From the decryption method, it does not go beyond the pgp.decryptStream it just hangs and does not go further, other strings encrypt and decrypt well but this particular one does not


text:
Q: Swing JScrollPane fill one dimension and scroll another I have relatively big text which is represented by a single JLabel. The text is added to the JPanel component with GridBagLayout.
I would like the text to fill all available space within the panel on the x-axis and provide scrolling only on the y-axis. Also, scrolling and text alignment should change accordingly when the panel is scaled.
So, consider the following code sample :
JPanel panel = new JPanel(new GridBagLayout());
JLabel desc = new JLabel("largelarge text");
JScrollPane scrollPane = new JScrollPane(desc, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scrollPane, gbc constraints here);

Any suggestions?

A:
I would like the text to fill all available space within the panel on the x-axis and provide scrolling only on the y-axis

You would need to create a custom panel and implement the Scrollable interface.
You would implement the getScrollableTracksViewportWidth() method to return "true" and the getScrollableTracksViewportHeight() method to return "false". You would also need to implement the other methods of the interface to provide reasonable values.
Or, you can use the Scrollable Panel which implements all the Scrollable interface methods with default behaviour and provides methods to allow you to change the behaviour.


text:
Q: A phrasal verb that means to prepare/cook something casually There's a phrasal verb that I forgot again, I think it has similar meaning to "grab a bite"; if I got it right it means to prepare something casual, quick to eat, even kinda of like to snap up.
I remember vaguely there's an example sentence in Macmillan Dictionary that goes He came without calling so I XX an omelette for him, but I'm far from sure that this is the original sentence.
Can someone help?

A: Whip [something] up, or whip up [something].
https://dictionary.cambridge.org/amp/english/whip-sth-up

He whipped up an omelette.


text: Q: Does $a_1\sqrt{1}+a_2\sqrt{2}+...+a_n\sqrt{n}=0$ have no solutions over the rationals? I had recently met a question that asked to show that $a\sqrt{2}+b\sqrt{3}+c=0$ has no solutions over the rationals (except for $0$) for $a,b$ and $c$. To show this I moved $c$ to the other side then squared both sides. Then the equation re-arranges into $\sqrt{6}=\frac{c^2-2a^2-3b^2}{2ab}$, which is a contradiction as one side is irrational and the other side is rational. I was wondering if I could extend this to $n$ terms, i.e does $a_1\sqrt{1}+a_2\sqrt{2}+...+a_n\sqrt{n}=0$ have any rational solutions for any $a_1,a_2,...,a_n$ and how would I prove that if it did? This time I can't just square both sides because there are too many terms to isolate so I was wondering if anyone could help (dis)prove this statement that would be great.


text:
Q: Creating Id using javascript I want to create staffid from three different textboxes values by getting their first letter & adding auto increment number atlast.
eg "staffname", "gender", "designation" result staffid: sgd01 & I want to auto display in the staff id textbox while staffid textbox is disabled. Here is the code below:
<input name="staffname" id="staffname" size="30" type="text" value placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">

Script
function quick() {

    var gender = document.getElementById('gender').value;
    var staffname = document.getElementById('staffname');
    var desg = document.getElementById('desg').value;

    var gen = gender.charAt(0);
    var sn = staffname.charAt(0);
    var dg = desg.charAt(0);

    var val = gen + sn + dg;
    document.getElementById('staffid').value = val;
}

A: You have a missing .value for var staffname. It should be
var staffname = document.getElementById('staffname').value;

Also your function needs to be called on every keyup on each of the 3 input boxes so that updated values can be processed
Here is a working sample: http://jsbin.com/vobikejejo/1/
Hope this helps :)

A: You can try by updating your function as below:
<script>
 var num=01;
 function quick() {
  num+=1;
  var gender = document.getElementById('gender').value;
  var staffname = document.getElementById('staffname').value;
  var desg = document.getElementById('desg').value;
  var gen = gender.charAt(0);
  var sn = staffname.charAt(0);
  var dg = desg.charAt(0);

  var val = gen + sn + dg + num;
  document.getElementById('staffid').value = val;
}

By default there is no value, so it is not working. Try by setting the default value.
<input name="staffname" id="staffname" size="30" type="text" value="staffname" placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
<input name="gender" id="gender" size="30" type="text" value="gender" placeholder=" Staff Name" class="formTxtInput">
<input name="desg" id="desg" size="30" type="text" value="desg" placeholder=" Staff Name"class="formTxtInput">
<input name="staffid" id="staffid" size="30" disabled="disabled" type="text" value placeholder=" Staff Name" class="formTxtInput">

YOu can view demo here 1