text:
Q: Circleci - always getting "There are no local code signing identities found." I'm trying to setup a CI pipeline to build an application for iOS; specifically my goal, apart from building the app, is to also setup the automatic signing and push it to Testflight in the end. When I try to run the fastlane command to build the app locally it works as expected, however, every time I try to build it on circleci with fastlane I always get a "There are no local code signing identities found" error and then the certificates and provisioning profiles are installed from the repository, but in the end my build fails with an error: "error: There are no accounts registered with Xcode. Add your developer account to Xcode...".
I'm not sure exactly what's the issue with this and I've changed my fastfile many times to include or exclude various options that I've found while debugging this, but I'm still getting the same errors.
Here is how the pipeline looks on circleci:
/Users/distiller/project/********
[⠋]  [⠙]  [⠹]  [⠸]  [⠼]  [⠴]  [⠦]  [⠧]  [⠇]  [⠏]  [⠋]  [⠙]  [⠹]  [⠸]  [⠼]  [⠴]  [⠦]  [⠧]  [⠇]  [✔]
[09:00:06]: Sending anonymous analytics information
[09:00:06]: Learn more at https://docs.fastlane.tools/#metrics
[09:00:06]: No personal or sensitive data is sent.
[09:00:06]: You can disable this by adding `opt_out_usage` at the top of your Fastfile
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:00:06]: ----------------------------------------
[09:00:06]: --- Step: Verifying fastlane version ---
[09:00:06]: ----------------------------------------
[09:00:06]: Your fastlane version 2.190.0 matches the minimum requirement of 2.171.0  ✅
[09:00:06]: Driving the lane 'ios beta'
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:00:06]: --------------------------------------
[09:00:06]: --- Step: Switch to ios build lane ---
[09:00:06]: --------------------------------------
[09:00:06]: Cruising over to lane 'ios build'
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:00:06]: -----------------------------
[09:00:06]: --- Step: setup_circle_ci ---
[09:00:06]: -----------------------------
[09:00:06]: Creating temporary keychain: "fastlane_tmp_keychain".
[09:00:06]: $ security list-keychains -d user
[09:00:06]: ▸ "/Users/distiller/Library/Keychains/fastlane_tmp_keychain-db"
[09:00:06]: Found keychain '/Users/distiller/Library/Keychains/fastlane_tmp_keychain-db' in list-keychains, adding to search list skipped
[09:00:06]: Enabling match readonly mode.
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:00:06]: -------------------
[09:00:06]: --- Step: is_ci ---
[09:00:06]: -------------------
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:00:06]: -------------------
[09:00:06]: --- Step: match ---
[09:00:06]: -------------------
[09:00:06]: Successfully loaded '/Users/distiller/project/********/fastlane/Matchfile'

+----------------+-----------------------------------------------------------------+
|                   Detected Values from './fastlane/Matchfile'                    |
+----------------+-----------------------------------------------------------------+
| git_url        | git@***********************.git |
| storage_mode   | git                                                             |
| type           | adhoc                                                           |
| app_identifier | com.********.app                                            |
| username       | ****@************.****                                   |
+----------------+-----------------------------------------------------------------+

+--------------------------------+-----------------------------------------------------------------+
|                                    Summary for match 2.190.0                                     |
+--------------------------------+-----------------------------------------------------------------+
| type                           | adhoc                                                           |
| readonly                       | true                                                            |
| generate_apple_certs           | true                                                            |
| skip_provisioning_profiles     | false                                                           |
| app_identifier                 | ["com.********.app"]                                        |
| username                       | ****@************.***                                     |
| team_id                        | ***********|
| storage_mode                   | git                                                             |
| git_url                        | git@***********************.git |
| git_branch                     | master                                                          |
| shallow_clone                  | false                                                           |
| clone_branch_directly          | false                                                           |
| keychain_name                  | fastlane_tmp_keychain                                           |
| force                          | false                                                           |
| force_for_new_devices          | false                                                           |
| skip_confirmation              | false                                                           |
| skip_docs                      | false                                                           |

| platform                       | ios                                                             |
| derive_catalyst_app_identifier | false                                                           |
| fail_on_name_taken             | false                                                           |
| skip_certificate_matching      | false                                                           |
| skip_set_partition_list        | false                                                           |
| verbose                        | false                                                           |
+--------------------------------+-----------------------------------------------------------------+

[09:00:06]: Cloning remote git repo...
[09:00:06]: If cloning the repo takes too long, you can use the `clone_branch_directly` option in match.
[09:00:11]: Checking out branch master...
[09:00:11]:   Successfully decrypted certificates repo
[09:00:11]: Installing certificate...
[09:00:12]: There are no local code signing identities found.
You can run `security find-identity -v -p codesigning fastlane_tmp_keychain` to get this output.
This Stack Overflow thread has more information: https://stackoverflow.com/q/35390072/774.
(Check in Keychain Access for an expired WWDR certificate: https://stackoverflow.com/a/35409835/774 has more info.)
[09:00:12]: Setting key partition list... (this can take a minute if there are a lot of keys installed)
[09:00:12]: security: SecItemCopyMatching: The specified item could not be found in the keychain.
[09:00:12]: Setting key partition list... (this can take a minute if there are a lot of keys installed)

+-------------------+-----------------------------------------+
|                    Installed Certificate                    |
+-------------------+-----------------------------------------+
| User ID           | **********                              |
| Common Name       | *********************                   |
| Organisation Unit | **********                              |
| Organisation      | *****                                   |
| Country           | **                                      |
| Start Datetime    | 2021-07-13 10:57:41 UTC                 |
| End Datetime      | 2022-07-13 10:57:40 UTC                 |
+-------------------+-----------------------------------------+

[09:00:12]: Installing provisioning profile...

+---------------------+----------------------------------------------+------------------------------------------------------------------------------------------------------------------+
|                                                                            Installed Provisioning Profile                                                                             |
+---------------------+----------------------------------------------+------------------------------------------------------------------------------------------------------------------+
| Parameter           | Environment Variable                         | Value                                                                                |
+---------------------+----------------------------------------------+------------------------------------------------------------------------------------------------------------------+
| App Identifier      |                                              | com.********.app                                                                                |
| Type                |                                              | adhoc                                                                                |
| Platform            |                                              | ios                                                                                |
| Profile UUID        | sigh_com.********.app_adhoc              | g611aca9-****-*****-****-*****                                                                             |
| Profile Name        | sigh_com.********.app_adhoc_profile-name | match AdHoc com.********.app                                                                                |
| Profile Path        | sigh_com.********.app_adhoc_profile-path | /Users/distiller/Library/MobileDevice/Provisioning Profiles/g611aca9-****-*****-****-*****.mobileprovision |
| Development Team ID | sigh_com.********.app_adhoc_team-id      | ****************                                                                                |
+---------------------+----------------------------------------------+------------------------------------------------------------------------------------------------------------------+

[09:00:12]: All required keys, certificates and provisioning profiles are installed
[09:00:12]: Setting Provisioning Profile type to 'ad-hoc'
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:00:12]: ----------------------------------------------------------
[09:00:12]: --- Step: ns prepare ios --clean --release --env.stage ---
[09:00:12]: ----------------------------------------------------------
[09:00:12]: $ ns prepare ios --clean --release --env.stage
[09:01:48]: ▸
[09:01:48]: ▸ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[09:01:48]: ▸ *                                                                             *
[09:01:48]: ▸ *  Using material components 5.x the N tabs component                         *
[09:01:48]: ▸ *  will not be fonctional anymore.                                            *
[09:01:48]: ▸ *  If you need it migrate to using @nativescript-community/ui-material-tabs   *
[09:01:48]: ▸ *  or go back the 4.x                                                         *
[09:01:48]: ▸ *                                                                             *
[09:01:48]: ▸ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[09:01:48]: ▸ Copying template files...
[09:01:53]: ▸ Platform ios successfully added. v8.0.0
[09:01:53]: ▸ Preparing project...
...................................................................
[09:14:59]: ▸ Project successfully prepared (ios)
[09:14:59]: ▸ Configure firebase
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:15:00]: ------------------------------------------
[09:15:00]: --- Step: update_code_signing_settings ---
[09:15:00]: ------------------------------------------

+-----------------------+---------------------------------------+
|               Summary for code signing settings               |
+-----------------------+---------------------------------------+
| use_automatic_signing | true                                  |
| team_id               | **********                            |
| path                  | ./platforms/ios/********.xcodeproj |
+-----------------------+---------------------------------------+

[09:15:00]: Updating the Automatic Codesigning flag to enabled for the given project '/Users/distiller/project/********/platforms/ios/********.xcodeproj/project.pbxproj'
[09:15:00]: Set Team id to: ********* for target: ******** for build configuration: Debug
[09:15:00]: Set Team id to: ********* for target: ******** for build configuration: Release
[09:15:00]: Successfully updated project settings to use Code Sign Style = 'Automatic'
[09:15:00]: Modified Targets:
[09:15:00]:      * ********
[09:15:00]: Modified Build Configurations:
[09:15:00]:      * Debug
[09:15:00]:      * Release
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
[09:15:00]: -----------------------
[09:15:00]: --- Step: build_app ---
[09:15:00]: -----------------------
[09:15:00]: Resolving Swift Package Manager dependencies...
[09:15:00]: $ xcodebuild -resolvePackageDependencies -workspace ./platforms/ios/********.xcworkspace -scheme ********
[09:15:06]: ▸ resolved source packages:
[09:15:06]: $ xcodebuild -showBuildSettings -workspace ./platforms/ios/********.xcworkspace -scheme ********
[09:15:09]: Command timed out after 3 seconds on try 1 of 4, trying again with a 6 second timeout...
[09:15:12]: Detected provisioning profile mapping: {:"com.********.app"=>"match AdHoc com.********.app"}

+----------------------------------------------------------+--------------------------------------------------------------+
|                                                 Summary for gym 2.190.0                                                 |
+----------------------------------------------------------+--------------------------------------------------------------+
| xcargs                                                   | -allowProvisioningUpdates                                    |
| scheme                                                   | ********                                                  |
| workspace                                                | ./platforms/ios/********.xcworkspace                      |
| export_method                                            | ad-hoc                                                       |
| export_options.provisioningProfiles.com.********.app | match AdHoc com.********.app                             |
| clean                                                    | false                                                        |
| output_directory                                         | ~/project/output/gym                                         |
| output_name                                              | ********                                                  |
| silent                                                   | false                                                        |
| skip_package_ipa                                         | false                                                        |
| skip_package_pkg                                         | false                                                        |
| build_path                                               | /Users/distiller/Library/Developer/Xcode/Archives/2021-08-03 |
| result_bundle                                            | false                                                        |
| buildlog_path                                            | ~/project/output/buildlogs/gym                               |
| destination                                              | generic/platform=iOS                                         |
| skip_profile_detection                                   | false                                                        |
| skip_package_dependencies_resolution                     | false                                                        |
| disable_package_automatic_updates                        | false                                                        |
| use_system_scm                                           | false                                                        |
| xcode_path                                               | /Applications/Xcode-11.GM.Seed.2.app                         |
+----------------------------------------------------------+--------------------------------------------------------------+

[09:15:12]: $ set -o pipefail && xcodebuild -workspace ./platforms/ios/********.xcworkspace -scheme ******** -destination 'generic/platform=iOS' -archivePath /Users/distiller/Library/Developer/Xcode/Archives/2021-08-03/********\ 2021-08-03\ 09.15.12.xcarchive -allowProvisioningUpdates archive | tee /Users/distiller/project/output/buildlogs/gym/********-********.log | xcpretty
[09:15:18]: ▸ ❌  error: There are no accounts registered with Xcode. Add your developer account to Xcode (in target '********' from project '********')
[09:15:18]: ▸ ❌  error: No profiles for 'com.********.app' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.********.app'. (in target '********' from project '********')
[09:15:18]: ▸ ** ARCHIVE FAILED **

❌  error: There are no accounts registered with Xcode. Add your developer account to Xcode (in target '********' from project '********')

❌  error: No profiles for 'com.********.app' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.********.app'. (in target '********' from project '********')

** ARCHIVE FAILED **
[09:15:18]: Exit status: 65
[09:15:18]:
[09:15:18]: Maybe the error shown is caused by using the wrong version of Xcode
[09:15:18]: Found multiple versions of Xcode in '/Applications/'
[09:15:18]: Make sure you selected the right version for your project
[09:15:18]: This build process was executed using '/Applications/Xcode-11.GM.Seed.2.app'
[09:15:18]: If you want to update your Xcode path, either
[09:15:18]:
[09:15:18]: - Specify the Xcode version in your Fastfile
[09:15:18]: ▸ xcversion(version: "8.1") # Selects Xcode 8.1.0
[09:15:18]:
[09:15:18]: - Specify an absolute path to your Xcode installation in your Fastfile
[09:15:18]: ▸ xcode_select "/Applications/Xcode8.app"
[09:15:18]:
[09:15:18]: - Manually update the path using
[09:15:18]: ▸ sudo xcode-select -s /Applications/Xcode.app
[09:15:18]:

+---------------+--------------------------------------+
|                  Build environment                   |
+---------------+--------------------------------------+
| xcode_path    | /Applications/Xcode-11.GM.Seed.2.app |
| gym_version   | 2.190.0                              |
| export_method | ad-hoc                               |
| sdk           | iPhoneOS13.0.sdk                     |
+---------------+--------------------------------------+

[09:15:18]: ▸ note: Using new build system
[09:15:18]: ▸ note: Planning build
[09:15:18]: ▸ note: Constructing build description
[09:15:18]: ▸ error: There are no accounts registered with Xcode. Add your developer account to Xcode (in target '********' from project '********')
[09:15:18]: ▸ error: No profiles for 'com.********.app' were found: Xcode couldn't find any iOS App Development provisioning profiles matching 'com.********.app'. (in target '********' from project '********')
[09:15:18]:
[09:15:18]: ⬆  Check out the few lines of raw `xcodebuild` output above for potential hints on how to solve this error
[09:15:18]:   For the complete and more detailed error log, check the full log at:
[09:15:18]:   /Users/distiller/project/output/buildlogs/gym/********-********.log
[09:15:18]:
[09:15:18]: Looks like fastlane ran into a build/archive error with your project
[09:15:18]: It's hard to tell what's causing the error, so we wrote some guides on how
[09:15:18]: to troubleshoot build and signing issues: https://docs.fastlane.tools/codesigning/getting-started/
[09:15:18]: Before submitting an issue on GitHub, please follow the guide above and make
[09:15:18]: sure your project is set up correctly.
[09:15:18]: fastlane uses `xcodebuild` commands to generate your binary, you can see the
[09:15:18]: the full commands printed out in yellow in the above log.
[09:15:18]: Make sure to inspect the output above, as usually you'll find more error information there
[09:15:18]:
+------------------------------------+--------------------------------------------------------------+
|                                           Lane Context                                            |
+------------------------------------+--------------------------------------------------------------+
| PLATFORM_NAME                      | ios                                                          |
| LANE_NAME                          | ios beta                                                     |
| KEYCHAIN_PATH                      | ~/Library/Keychains/fastlane_tmp_keychain                    |
| ORIGINAL_DEFAULT_KEYCHAIN          | "/Users/distiller/Library/Keychains/login.keychain-db"       |
| SIGH_PROFILE_TYPE                  | ad-hoc                                                       |
| MATCH_PROVISIONING_PROFILE_MAPPING | {"com.********.app"=>"match AdHoc com.********.app"} |
+------------------------------------+--------------------------------------------------------------+
[09:15:18]: Error building the application - see the log above

+------+----------------------------------------------+-------------+
|                         fastlane summary                          |
+------+----------------------------------------------+-------------+
| Step | Action                                       | Time (in s) |
+------+----------------------------------------------+-------------+
| 1    | Verifying fastlane version                   | 0           |
| 2    | Switch to ios build lane                     | 0           |
| 3    | setup_circle_ci                              | 0           |
| 4    | is_ci                                        | 0           |
| 5    | match                                        | 5           |
| 6    | ns prepare ios --clean --release --env.stage | 887         |
| 7    | update_code_signing_settings                 | 0           |
|    | build_app                                    | 18          |
+------+----------------------------------------------+-------------+

[09:15:18]: fastlane finished with errors

[!] Error building the application - see the log above
failed or skipped
cat: /Users/distiller/Library/Logs/gym/********-********.log: No such file or directory
log not found

Some things that I've tried on the fastfile is to:

*

*create a temporary keychain and unlock it by using create_keychain(...) and unlock_keychain()

*include keychain_name and keychain_password on  match(...)

*use setup_circle_ci which is an option for circleci to create a temporary keychain for you.
Lastly, this is what my fastfile looks like:
fastlane_version '2.171.0'

platform :ios do

  before_all do
    setup_circle_ci
  end

 desc 'Fetch certificates and provisioning profiles'
 lane :certificates do
    match(type: 'development')
    match(type: "appstore")

 end

 desc 'Build the iOS application.'
 lane :build do
    # setup_circle_ci

    # sh("security", "list-keychains", "-d", "user")

    # create_keychain(
    #   name: "login.keychain",
    #   password: "test",
    #   default_keychain: true,
    #   unlock: true,
    #   timeout: 3600,
    #   lock_when_sleeps: false,
    #   add_to_search_list: true
    # )

    # unlock_keychain(
    #   path: "/Users/distiller/Library/Keychains/login.keychain",
    #   add_to_search_list: :replace,
    #   password: "test",
    # )

    # sh("security", "find-identity", "-v", "-p", "codesigning", "login.keychain")

    match(
      type: "appstore",
      readonly: is_ci,
      keychain_name: "fastlane_tmp_keychain",
      keychain_password: "",
      verbose: true
    )

    # sh("security", "find-identity", "-v", "-p", "codesigning", "login.keychain")

    sh("ns", "prepare", "ios", "--clean", "--release",  "--env.stage")

    update_code_signing_settings(
      use_automatic_signing: true,
      team_id: "*****",
      path: "./platforms/ios/*******.xcodeproj"
    )

  #   update_project_provisioning(
  #     xcodeproj: "./platforms/ios/*******.xcodeproj",
  #     profile: ENV["sigh_com.*******.app_adhoc_profile-path"]
  #     # build_configuration: "Release"
  #  )

    build_app(
      xcargs: "-allowProvisioningUpdates",
      scheme: "*******",
      workspace: './platforms/ios/*******.xcworkspace',
      export_method: "app-store"
      # export_options: {
      #   provisioningProfiles: {
      #     "com.*******.app" => "match Appstore com.********.app"
      #   }
      # }
    )

 end

 desc 'Ship to Testflight.'
 lane :beta do
    build

    changelog_from_git_commits

    upload_to_testflight(
      beta_app_feedback_email: "****@*******.****",
      beta_app_description: "Test deployment",
      demo_account_required: false,
      distribute_external: false,
      groups: [],
      notify_external_testers: false,
      skip_submission: true
    )

 end

end

If anyone can help me with this you'll be saving me! Thanks!


text:
Q: java.lang.NoSuchMethodError: org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub.addAnonymousOperations Hi im having while im trying to create a web application and i want to call the WSO2 identity server API RemoteUserStoreManagerService
The error is this
java.lang.NoSuchMethodError: org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub.addAnonymousOperations()V
    org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub.populateAxisService(RemoteUserStoreManagerServiceStub.java:42)
    org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub.<init>(RemoteUserStoreManagerServiceStub.java:636)
    org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub.<init>(RemoteUserStoreManagerServiceStub.java:625)
    org.wso2.sample.LoginServlet.authenticate(LoginServlet.java:83)
    org.wso2.sample.LoginServlet.doPost(LoginServlet.java:56)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.wso2.sample.AuthenticationFilter.doFilter(AuthenticationFilter.java:56)

I dont know the error but i imported the org.wso2.carbon.um.ws.api.stub in /WEB-INF/lib
is this the version of the .jar file or not?
Can someone help me..
Here is my code
private boolean authenticate(String userName, Object credential) throws Exception {
    if (!(credential instanceof String)) {
        throw new Exception("Unsupported type of password");
    }
    try {
        if(stub == null) {
            stub = new RemoteUserStoreManagerServiceStub(null, serverUrl
                    + "RemoteUserStoreManagerService");
            HttpTransportProperties.Authenticator basicAuth = new HttpTransportProperties.Authenticator();
            basicAuth.setUsername(basicAuthUserID);
            basicAuth.setPassword(basicAuthPassword);
            basicAuth.setPreemptiveAuthentication(true);

            final Options clientOptions = stub._getServiceClient().getOptions();
            clientOptions.setProperty(HTTPConstants.AUTHENTICATE, basicAuth);
            stub._getServiceClient().setOptions(clientOptions);

        }
        return stub.authenticate(userName, (String) credential);
    } catch (Exception e) {
        handleException(e.getMessage(), e);
    }
    return false;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the best way to frame external webpages under a banner? Google Images is the best example. Once you follow an image, a frame remains at the top of the page, always reminding you to return to Google. Does this technique have a special name and what is the most efficient way to do this?
I have this so far:
<!DOCTYPE html>

    <title>Framed content</title>

How can I adapt the above so that #bar can read 100px high rather than 10% high? How does that affect the code? This is the crux of my question.
Many thanks. Patrick

A: I think it's still just called 'framing' even if it's more advanced than the old frameset style popular in the late '90s and early 2000s.  Other examples you could study include Facebook and Stumbleupon.

A: I've seen it called a "topbar"...
Personally, though, I find them really annoying unless they're serving a very useful purpose. I don't need to be reminded to go back to your website. You might as well just open the link in a new window at that point.

A: You could do what google does, and remove your doctype tag. your markup will pretty much work right away with this one modification, and you'll be able to set the bar's height to 100px, and the iFrame's height to 100% -- producing the desired results.

A: After a bit of investigation, I came across this, which doesn't use iframes at all. I know some people won't touch framesets with a bargepole, but I'd be interested to know what people think could be potential problems, other than the obvious "frames not supported".

<frameset rows="100,*" frameborder="no" framespacing="0">
  <frame name="h" src="top_source" scrolling="no" noresize >
  <frame name="t" src="main_source" scrolling="auto" noresize >
</frameset>

This makes use of the wildcard " * ", which div height attributes don't have.


text:
Q: Is it possible to profile line-by-line in .NET? I have a bit of an interesting question here about performance and was wondering if there was any way to do what I want to do:
I'm dealing with a large code-base (10,000+ lines), I want to run the code and get a visual analysis of what lines takes up the most time in the code. Like for example, is there anything that can highlight the lines of code that take up the longest amounts of time in .NET and/or give you a time spent on each line? In my mind, I'm visualizing something simple, like a green, yellow, and red highlight for each line of code and perhaps an amount of time that tells you how long each line took to run.
One way to get times would be through the Stopwatch, but its such a pain to have to have to add Stopwatches over and over again. How could I go about profiling my codebase like this? Does Visual Studio or .NET have anything out of the box for this?
Edit: Thanks to Patrick, I found out about ANTS, which does exactly what I wanted above (also shows HOT! lines in red in another window - lines that take up the most time...FYI: this isn't a profiler advertisement; I just required a line-by-line profiler for my needs and this does the trick so take it or leave it):

A: It's called a profiler, and there are many of them.
Some Visual Studio versions come with built-in analysis tools. Another tool I commonly use is ANTS Performance Profiler.
They sample which method is active (sampling), or even collect info on a per line / statement basis (instrumentation), depending on the settings used. You can use that to check what lines are most commonly used, or what lines consume most time each.
As a sample, take a look at the images in my question regarding statistics acquired from profiling.


text:
Q: 3gp file format opens in safari but not in a UIWebView why? I am trying to play a video in my iPhone application using the UIWebView component, the video is of format 3gp. If I try to open the url link to the video in the built in "Safari" application on my iPhone the video plays successfully without any problem, but when I try to open the link in the UIWebView i get an error message: "The opperation could not be completed".
Why is that happening?
My code:
NSURLRequest *pageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:_urlString]]; [_webView loadRequest:pageRequest];

A: 3GP is a container format. You should find what are the video and audio formats in it. Most probably your audio is with AMR encoding, which can't be played by UIWebView.


text:
Q: How to convert from RedirectMatch to RewriteRule and remove the query string I want to convert from rewritematch to RewriteRule and remove the query string. Example:
RedirectMatch 301  ^/(.*)/old-path/$   /$1/new-path/

A: You can use:
RewriteEngine On

RewriteRule ^(.+?)/old-path/?$ /$1/new-path/? [L,NC,R=301]


text:
Q: how do you paste unique values without showing the rows that were skipped? I'm trying to extract the unique purchase orders from a row and paste that list into another sheet. The problem is that when I paste, it doesn't list the purchase orders sequentially (a1,a2,a3,a4); It pastes them from the location that they were copied (a3,a112,a194, etc)
here's the macro:
Sub unique_values()
'
' unique_values Macro
'
'
    Columns("A:A").Select
    Selection.Copy
    Sheets("Sheet1").Select
    Sheets.Add After:=ActiveSheet
    Columns("A:A").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    Range("A1:A394").AdvancedFilter Action:=xlFilterInPlace, Unique:=True
End Sub

A: Just updated you code a little. You were almost there. Just delete the empty cells after you copy.
    Columns("A:A").Select
    Selection.Copy
    Sheets("Sheet1").Select
    Sheets.Add After:=ActiveSheet
    Columns("A:A").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    Range("A1:A394").RemoveDuplicates Columns:=Array(1)
    On Error Resume Next
With Range("A:A")
    If WorksheetFunction.CountA(.Cells) > 0 Then .SpecialCells(xlCellTypeBlanks).Delete Shift:=xlShiftUp
End With


text:
Q: Qual a necessidade de se utilizar o sufixo "f" em uma constante numérica em C? É necessário adicionar f a um valor float dentro dos parâmetros de um if?
Exemplo:
if (a == 2.5f && a > 2.0f) {}

A: Nada tem a ver com if, é uma questão de escolher o literal que quer usar.
Se quer que o número seja um float então deve usar o f sempre. Se não usar e tiver ponto decimal ele será por padrão um double. Este tipo possui 64 bits e o float tem 32 bits. Então com o sufixo f ou F ele ocupará menos espaço na memória, e claro, terá menos precisão.
Se o número for inteiro, ou seja, não tenha um ponto no literal, aí ele não será double, e muito menos float, a não ser que use um f.
Em ambos não haverá exatidão, como já mostrado em pergunta anterior sua. Se for isso que deseja, não pode usar qualquer um deles. Precisa criar um mecanismo próprio, usar outra forma ou uma biblioteca que trate isso corretamente.


text:
Q: ideas for creating a report Colleagues, I really need your advice on how to create a report with the following format in Cognos Analitics:

I only have the value "amount of money" and the dimensions "date" and "Person", and I need to display in the report the value for a specific date, and the change from the previous date.
for example, 01.02.2018 Person1 had 50 of the money, and 01.03.2018 Person1 had 61, so field № 3 is equal to 11 (61-50).
As you can see, there is no "change" column after the first field, because there is nothing to compare it with.
Do you have any ideas on how to generate such a report?
P.S. user selects the start date and end date of the report independently in the invitation

A: Maybe try creating multiple metrics

*

*Call the first Day 1 Amount

*Call the second Day 2 Amount

*Call the third Day 3 Amount

You could even define each metric relative to the other
Day 1 is based on the date selected
Day 2 is for the prior day
Day 3 is 2 days before... etc
Build the crosstab slightly different.  Instead of placing the metric in the middle
place them side by side
Then you can run calculations, %difference, growth etc on the fly


text:
Q: Close: off-topic, missing returns I have this question:
When i use:
async function createElement(req,res){
   const time1 = new Date().getTime();
   console.log("turn on time 1 ",time1)
   await new Promise((resolve) => setTimeout(resolve,1000));
   await new Promise((resolve) => setTimeout(resolve,1000));
   const time2 = new Date().getTime();
   console.log("turn on time 2 ",time2)
   console.log('result : ', time2 - time1);
}

the result is:
turn on time 1 1531957505408
turn on time 2 1531957507413
result : 2005

and is fine, but when i try use promise.all with await
async function createElement(req,res){
let fn1 = () => {
    new Promise((resolve) => {

        setTimeout(() => {
            console.log("message from fn1")
            resolve()
       },1000)
    });
}
let fn2 = () => {
    new Promise((resolve) => {
        setTimeout(() => {
             console.log("message from fn2")
             resolve()
        },1000)

    });
}
const time1 = new Date().getTime();
console.log("turn on time 1 ",time1)
let responses = await Promise.all([fn1(),fn2()])
console.log("waiting for responses")
const time2 = new Date().getTime();
console.log("turn on time 2 ",time2)
console.log('result : ', time2 - time1);
}

the result is:
turn on time 1 1531957505408
turn on time 2  1531957505408
result 0
message from fn1
message from fn2

so... in the case that i need the result to fn1 or/and fn2 for other operation, how i can to wait the response to promise.all

A: return the promises from your functions

A: You are not returning promise from fn1 and fn2.

async function createElement(req,res){
let fn1 = () => {
   return new Promise((resolve) => {

        setTimeout(() => {
            console.log("message from fn1")
            resolve()
       },1000)
    });
}
let fn2 = () => {
   return new Promise((resolve) => {
        setTimeout(() => {
             console.log("message from fn2")
             resolve()
        },1000)

    });
}
const time1 = new Date().getTime();
console.log("turn on time 1 ",time1)
let responses = await Promise.all([fn1(),fn2()])
console.log("waiting for responses")
const time2 = new Date().getTime();
console.log("turn on time 2 ",time2)
console.log('result : ', time2 - time1);
}

createElement();


text:
Q: Replacing img src in textarea using jquery from a pop-up window I'm trying to replace the textarea and input box image source in the parent window using jquery from a pop-up window. The text in the input box changes without any trouble, however the text in the textarea box remains unchanged.
Here's the code for the parent window:
<textarea cols="100" rows="20" class="editor">

</textarea>

<input type="text" value="image.jpg" maxlength="255" MultiLine="false" Class="inputBox" style="width:875px;" />

Click Here To Add An Image/s

Here's the code for the pop-up window:

<input id="select" class="selectImage" type="button" data-imagepath="image2.jpg" value="Select">

Any ideas why this isn't working?

A: You can't get image source in a textarea.Textarea respond to code as text not element.
You can use div and make it contenteditable.

Or get the value of editor and paste it in a div, select your image from a div
var editor = $(".editor").val();
$(".output").html(editor);

jQuery live function is deprecated use "0n"

A: Try replacing the textarea value with the updated HTML string as shown below:

A: In your popup window, just replace this JS code:

A: @Vikram Deshmukh is along the right lines. @Olalekan is also correct, the content of a textarea is text, it can't manipulated like HTML.
I posted the same question here to get the answer:
https://forum.jquery.com/topic/replacing-img-src-in-textarea-using-jquery-from-a-pop-up-window-25-9-2014
Here's the solution which works:

Thanks for all your help.


text:
Q: How to get maximum value among N counters in constant time? We have N integer counters, initially showing 0. Operations:
int getMax() - returns the highest value shown by counters.
void increment(int i) - increments value of counter i.
void zero() - set zero value for all the counters. Alternative name was flood(), maybe this name will be helpful to you.
Present implementation of these operations and underlying data structure, knowing that we want these operations to be as fast as possible.

It was my interview question. There is a small chance that I stated something a little wrong, because of my lack of memory, but I tried my best. Maybe it is similar to some well-known problem? (I hope.)
As far as I remember, all of the operations could be done in O(1)... And one of the operations was "lazy" (maybe increment)... i.e. in a moment of call it was doing nothing, but later when the user asked for value with getMax() - it worked.

A: This can be done with simply an array of size N, where each element consists of 2 numbers - the current value, and a version (say a timestamp, for example). And you also need a global last reset (zero'd) version and a global max value.
To increment:

*

*If that element's version is less than the global, simply set it's value to 1. Otherwise increment it.

*If it's greater than the global max, set the global max to its value.

*Set its version appropriately (to the current time).

To get the maximum:

*

*Simply return the global max.

To reset:

*

*Simply set the global last reset version (to the current time) and also set the global max value to 0.

All operations: O(1).


text:
Q: Getting DatePicker to place the selected date in the closest input field I have a datepicker that works when I click on the input field; however, I also wanted for it to work when I click on a font-awesome icon that is joined to the input field.
HTML:

    <input name="DelDate" type="datetime" id="datepicker" class="form-control" style="width:80%!important;" />

JQUERY:
    $('.dp, #datepicker').datepicker({
        firstDay: 1,
        autoclose: true,
        todayHighlight: true,
        dateFormat: 'mm/dd/yy',
        constrainInput: true
    });

From this code, if I click on the inside of the input field, and then select a specific date, that date will then be dropped into the input field.  Great!
But, if I click on the calendar icon, right next to the input field, the datepicker calendar pops-up, and does not drop the selected date into the input filed.
How do I bind the fa-calendar click to the input field so both methods yield a date getting dropped into the input field?

A: You can assign click to your icon then focus on date picker.

$(document).ready(function() {
  $('.dp, #datepicker').datepicker({
    firstDay: 1,
    autoclose: true,
    todayHighlight: true,
    dateFormat: 'mm/dd/yy',
    constrainInput: true
  });

  $('.dp').click(function() {
    $("#datepicker").focus();
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <input name="DelDate" type="datetime" id="datepicker" class="form-control" style="width:80%!important;" />


text:
Q: Set php $value inside function foreach I have this code:
<?php
// EXAMPLE PICTURE
$url='https://admin2.e-hjemmeside.dk/upload/images/89.jpg';

//var_dump(getColorPallet($url));

echoColors(getColorPallet($url));

function echoColors($pallet){ // OUTPUT COLORSBAR
    foreach ($pallet as $key=>$val)
        echo '

';
}

function getColorPallet($imageURL, $palletSize=[3,3]){ // GET PALLET FROM IMAGE PLAY WITH INPUT PALLET SIZE
    // SIMPLE CHECK INPUT VALUES
    if(!$imageURL) return false;

    // IN THIS EXEMPLE WE CREATE PALLET FROM JPG IMAGE
    $img = imagecreatefromjpeg($imageURL);

    // SCALE DOWN IMAGE
    $imgSizes=getimagesize($imageURL);

    $resizedImg=imagecreatetruecolor($palletSize[0],$palletSize[1]);

    imagecopyresized($resizedImg, $img , 0, 0 , 0, 0, $palletSize[0], $palletSize[1], $imgSizes[0], $imgSizes[1]);

    imagedestroy($img);

    //CHECK IMAGE
    /*header("Content-type: image/png");
    imagepng($resizedImg);
    die();*/

    //GET COLORS IN ARRAY
    $colors=[];

    for($i=0;$i<$palletSize[1];$i++)
        for($j=0;$j<$palletSize[0];$j++)
            $colors[]=dechex(imagecolorat($resizedImg,$j,$i));

    imagedestroy($resizedImg);

    //REMOVE DUPLICATES
    $colors= array_unique($colors);

    return $colors;

}
?>

from this question Detect main colors in an image with PHP
I want to set a value inside the function, like
$colorsinimage = "".$colorsinimage."#".$val."";
to store all the colors in the image as a string. This string can be used outside the function to store into database, echo the string, sort the colors ...
How do I do that?
Thanks in advance :-)
EDIT
Thanks for your comments :-) The link to question .../16959576/.. was very helpful to understand it all. After that I find $GLOBALS og it seems to work in a way. If I ad $GLOBALS['imagecolors'] = ""; first in the code, and $GLOBALS['imagecolors'] = "".$GLOBALS['imagecolors']."#".$val.""; in the first function, I end up to echo $imagecolors; at the end, where the result is the latest color #291a17. Instead of the latest color, I want to set $GLOBALS['imagecolors'] to a string with all the colors, an array of all the different values of $val.
New code with the $GLOBALS:
<?php
$GLOBALS['imagecolors'] = "";
// EXAMPLE PICTURE
$url='https://admin2.e-hjemmeside.dk/upload/images/89.jpg';

//var_dump(getColorPallet($url));

echoColors(getColorPallet($url));

function echoColors($pallet){ // OUTPUT COLORSBAR
    foreach ($pallet as $key=>$val)
        echo '

';
        $GLOBALS['imagecolors'] = "".$GLOBALS['imagecolors']."#".$val."";
}

function getColorPallet($imageURL, $palletSize=[3,3]){ // GET PALLET FROM IMAGE PLAY WITH INPUT PALLET SIZE

    // SIMPLE CHECK INPUT VALUES
    if(!$imageURL) return false;

    // IN THIS EXEMPLE WE CREATE PALLET FROM JPG IMAGE
    $img = imagecreatefromjpeg($imageURL);

    // SCALE DOWN IMAGE
    $imgSizes=getimagesize($imageURL);

    $resizedImg=imagecreatetruecolor($palletSize[0],$palletSize[1]);

    imagecopyresized($resizedImg, $img , 0, 0 , 0, 0, $palletSize[0], $palletSize[1], $imgSizes[0], $imgSizes[1]);

    imagedestroy($img);

    //CHECK IMAGE
    /*header("Content-type: image/png");
    imagepng($resizedImg);
    die();*/

    //GET COLORS IN ARRAY
    $colors=[];

    for($i=0;$i<$palletSize[1];$i++)
        for($j=0;$j<$palletSize[0];$j++)
            $colors[]=dechex(imagecolorat($resizedImg,$j,$i));

    imagedestroy($resizedImg);

    //REMOVE DUPLICATES
    $colors= array_unique($colors);

    return $colors;
}

echo $imagecolors;
?>

Thanks Alex - it is working perfect :-)
Right code
<?php
// EXAMPLE PICTURE
$url='https://admin2.e-hjemmeside.dk/upload/images/89.jpg';

//var_dump(getColorPallet($url));

echoColors(getColorPallet($url));

function echoColors($pallet){
    global $imagecolors;
    $imagecolors = '';
    foreach ($pallet as $key=>$val) {
        echo '

';
        $imagecolors .= "#".$val;
    }
}

function getColorPallet($imageURL, $palletSize=[3,3]){ // GET PALLET FROM IMAGE PLAY WITH INPUT PALLET SIZE

    // SIMPLE CHECK INPUT VALUES
    if(!$imageURL) return false;

    // IN THIS EXEMPLE WE CREATE PALLET FROM JPG IMAGE
    $img = imagecreatefromjpeg($imageURL);

    // SCALE DOWN IMAGE
    $imgSizes=getimagesize($imageURL);

    $resizedImg=imagecreatetruecolor($palletSize[0],$palletSize[1]);

    imagecopyresized($resizedImg, $img , 0, 0 , 0, 0, $palletSize[0], $palletSize[1], $imgSizes[0], $imgSizes[1]);

    imagedestroy($img);

    //CHECK IMAGE
    /*header("Content-type: image/png");
    imagepng($resizedImg);
    die();*/

    //GET COLORS IN ARRAY
    $colors=[];

    for($i=0;$i<$palletSize[1];$i++)
        for($j=0;$j<$palletSize[0];$j++)
            $colors[]=dechex(imagecolorat($resizedImg,$j,$i));

    imagedestroy($resizedImg);

    //REMOVE DUPLICATES
    $colors= array_unique($colors);

    return $colors;
}

echo $imagecolors;
?>

A: Main problem in your code is kind typo.
You have no curly braces after foreach, so you get only the last value from array to your var I guess.
Just fixing this you should get some better result:
function echoColors($pallet){ // OUTPUT COLORSBAR
    foreach ($pallet as $key=>$val) {
        echo '

';
        $GLOBALS['imagecolors'] = "".$GLOBALS['imagecolors']."#".$val."";
    }
}

But here how is better deal with global variables and some other code optimization:
function echoColors($pallet){
    global $imagecolors;
    $imagecolors = '';
    foreach ($pallet as $key=>$val) {
        echo '

';
        $imagecolors .= "#".$val;
    }
}


text:
Q: Constructor, Class, union, struct I have some doubts I would like to clear regarding class, struct and union. I know class and struct are considered object. I would like to check whether union is consider object too. Whereby, I can have a constructor inside?
union ABC
{
  ABC() {};
  int x;
}A, B, C

Since I have object name. I could do this?
Union ABC obj1(); //Call constructor?
A.x;  //Variable accessing the member

???
Secondly,
what if i typedef union. What does A B C mean?
Can I do this
union ABC obj1();
A.x;

typedef union ABC
{
  ABC() {};
  int x;
}A, B, C

A: *

*The difference between a struct and a class is that by default
members in struct are public, but private in class; otherwise, they
are functional equivalent. A union can have member functions (including constructors   and destructors), but not virtual functions. A union shall not have base classes. A union shall not be used as a base class.

*Union ABC obj1(); //Call constructor?
No, This does not call a constructor
union ABC obj1() means you
declare a function with name obj1 and returns an object of union ABC

*You have syntax errors in both cases, you have to do the following:
union ABC
{
   ABC() {};
   int x;
 }A, B, C;   //You cannot miss this ;

*You can do:
typedef union ABC ABCUnion;   then

 ABCUnion A, B,C;

It is the same as
union ABC A, B,C;


text:
Q: Number above ULONG_MAX during unsigned arithmetic So I'm working on creating a precise Decimal structure that stores it's characteristic and mantissa within a long and an unsigned long respectfully. Because I'm doing this I've had to come up with my own subtraction and addition functions.
While testing my functions I ran across the troublesome problem of "negative zero". Essentially, I cannot represent -0.1 through -0.9 because there is no way for me to put a negative sign on my zero without just using a flag value of some kind. This is background information and I'll post the code so you can see how I'm doing the arithmetic. The STRANGE behavior though is that I'm getting a number above ULONG_MAX. Specifically this is the output of my log:
diff->right: 18446744073699551616
b->right10000000
MANTISSA_LIMIT: 100000000
ULONG_MAX: 18446744073709551615
Subtracting 10.10000000 from 10.00000000
Test: tests/bin/decimal.out(subtractDecimalsWithCarry+0x79) [0x40109f]  Decimal: 0.10000000

And the code:
helpers/decimal.h:
#ifndef __DECIMAL_H__
#include <limits.h>
#define MANTISSA_LIMIT 100000000
#define __DECIMAL_H__
typedef struct{          /* Calling them more convenient terms: */
    long left;           /* characteristic */
    unsigned long right; /* mantissa */
}Decimal;

void createDecimal(long left, unsigned long right, Decimal * dec);

/* Perform arithmetic operations on Decimal structures */
void add_decimals(Decimal* a, Decimal* b, Decimal* sum);
void subtract_decimals(Decimal* a, Decimal* b, Decimal* diff);
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
void createDecimalFromString(Decimal * dec, const char * str);
#endif

And then decimal.c's relavant code:
/* Subtract two decimals, a - b */
void subtract_decimals(Decimal* a, Decimal* b, Decimal* diff){
    diff->left = a->left - b->left;
    diff->right = a->right - b->right;
    fprintf(stderr, "diff->right: %lu\n", diff->right);
    fprintf(stderr, "b->right%lu\n", b->right);
    fprintf(stderr, "MANTISSA_LIMIT: %d\n", MANTISSA_LIMIT);
    fprintf(stderr, "ULONG_MAX: %lu\n", ULONG_MAX);
    if(diff->right > MANTISSA_LIMIT) {
    if(diff->right != 18446744073699551616UL)
        diff->left -= 1;
    else
        diff->left *= -1; /* This is where I might put a flag for -0*/
    diff->right = ULONG_MAX - diff->right + (18446744073699551616UL == diff->right ? 1 : 0);     /* +1 because of the wrap around, we have to 'count' 0. */
    }
}

void createDecimalFromString(Decimal * dec, const char * str){
    long left;
    unsigned long right;
    char * dotLocation;
    char rawLeft[9];
    char rawRight[9];
    int i;
    int dotPos;
    long leadingZeros;
    int numDetected;

    if(str == NULL)
         return;

    bzero(rawLeft,9);
    bzero(rawRight,9);

    dotLocation = strstr(str, ".");
    leadingZeros = numDetected = 0;
        if(dotLocation == NULL){
           left = atol(str);
           right = 0;
        }else{
        /* ghetto strncpy */
        for(i=0; i != 9 && str[i] != *dotLocation; ++i)
            rawLeft[i] = str[i];
        rawLeft[i] = '\0';
        dotPos = i+1;
        left = atol(rawLeft);
        for(i=0; i != 9 && str[dotPos] != '\0'; ++i,++dotPos){
            if(str[dotPos] == '0' && numDetected == 0)
               leadingZeros++;
            else
               numDetected = 1;

            rawRight[i] = str[dotPos];
        }
        rawRight[i] = '\0';
        right = strtoul(rawRight,NULL,10);
        if(leadingZeros > 0)
            /* subtract the leading zeros, then also the powers of ten taken by the number  itself*/
            right = (right*(powlu(10,7-leadingZeros-(i-2))));
        else
            right = right*(powlu(10,(i > 1 ? 8-(i-1) : 7 )));
    }

    dec->left = left;
    dec->right = right;

}

And finally the calling code:
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <unistd.h>

#include "helpers/decimal.h"

void traceAndPrintDecimal(Decimal testDec){
    int nptrs;
void *buffer[100];
    char **strings;
    nptrs = backtrace(buffer, 100);
    strings = backtrace_symbols(buffer, nptrs);
    printf("Test: %s  Decimal: %ld.%08lu\n", strings[1], testDec.left, testDec.right);

    free(strings);
}

void subtractDecimalsWithCarry(){
    Decimal oper1;
    Decimal oper2;
    Decimal result;
    createDecimalFromString(&oper1, "10.0");
    createDecimalFromString(&oper2, "10.1");
    subtract_decimals(&oper1, &oper2, &result);
    printf("Subtracting %ld.%08lu from %ld.%08lu\n",oper2.left,oper2.right,oper1.left,oper1.right);
    traceAndPrintDecimal(result);
}

int main(){

subtractDecimalsWithCarry();
return 0;
}

And the piece of my makefile for compiling:
decimal.o: src/helpers/decimal.c
    cc -I./headers -std=gnu99 -pedantic -Wall -Wextra -Werror -g -c src/helpers/decimal.c -o obj/decimal.o

test-decimal: tests/decimal-test.c decimal.o
    cc -I./headers -std=gnu99 -pedantic -Wall -Wextra -Werror -g tests/decimal-test.c obj/decimal.o -o tests/bin/decimal.out -lm -rdynamic

It's strange that diff->right is larger than ULONG_MAX, does anyone know why this might be?  If you need anymore information let me know and I'll do my best to update the question.

A: Mistaken "Number above ULONG_MAX".
At first glance diff->right with the value "18446744073699551616" appeared to be larger than ULONG_MAX ("18446744073709551615").  But is 9999999 less.  (@UncleO)

OP's asserts in comment "any idea why the ones place goes a little cockeyed? The number should only be off by 1000000 because of the way the mantissa works. But it's off by 10000001 instead".  Suggest this is incorrect.
// from createDecimalFromString(&oper1, "10.0");
oper1.right = 0
// from createDecimalFromString(&oper2, "10.1");
oper1.right = 10000000
// from subtract_decimals(&oper1, &oper2, &result)
diff->right = oper1.right - oper2.right --> 18446744073699551616

unsigned subtraction is well defined in C.  In this case the difference oper1.right - oper2.right will mathematically result in oper1.right - oper1.right + (ULONG_MAX + 1).
" ... a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type."  C11 6.2.5 8


text:
Q: Use Bootstrap 3 dropdown menu as context menu for multilevel asp grid I'm using bootstrap 3 and Asp.net gridview. I have created a context menu for  my gridview using this solution example in fiddle
<table id="myTable" class="table table-hover">

My question is that I have a nested grid or a multi level grid. i want to have a different context menu for each level. is this possible with this solution.

A: Yes, it's possible to have different context menus for different tables on your page, it's just a matter of how you handle it.
Here are two options, one simple and one a bit more sophisticated.
1: Multiple selectors
Simply change the jQuery selector on which you call contextMenu.
Here is an example which shows a different context menu for the first table and the second nested table: http://jsfiddle.net/Sly_cardinal/46sHX/1/
// Only add this context menu to cells that are
// a direct descendent of #myTable
$("#myTable > tbody > tr > td").contextMenu({
    menuSelector: "#contextMenu",
    menuSelected: function (invokedOn, selectedMenu) {
        var msg = "You selected the menu item '" + selectedMenu.text() +
            "' on the value '" + invokedOn.text() + "'";
        alert(msg);
    }
});

// Only add this context menu to cells that are in a table
// that is nested inside #myTable
$("#myTable td > table td").contextMenu({
    menuSelector: "#contextMenu2",
    menuSelected: function (invokedOn, selectedMenu) {
        var msg = "You selected the menu item '" + selectedMenu.text() +
            "' on the value '" + invokedOn.text() + "'";
        alert(msg);
    }
});

2: Dynamic menuSelector
The more sophisticated option requires a change to your context menu plugin to allow the menuSelector property to be a function that receives the clicked element and returns the selector of the context menu that should be shown.
Here's the altered contextMenu plugin:
(function ($, window) {

    $.fn.contextMenu = function (settings) {

        return this.each(function () {
            var selector;

            // Open context menu
            $(this).on("contextmenu", function (e) {
                selector = $(getMenuSelector(e, settings.menuSelector))

                //open menu
                $(selector)
                    .data("invokedOn", $(e.target))
                    .show()
                    .css({
                        position: "absolute",
                        left: getLeftLocation(e, selector),
                        top: getTopLocation(e, selector)
                    });

                //add click listener on menu
                ContextMenuClickHandler();

                return false;
            });

            // click handler for context menu
            function ContextMenuClickHandler() {
                $(selector)
                    .off('click')
                    .on( 'click', function (e) {
                        $(this).hide();

                        var $invokedOn = $(this).data("invokedOn");
                        var $selectedMenu = $(e.target);

                        settings.menuSelected.call($(this), $invokedOn, $selectedMenu);
                });

            }

            //make sure menu closes on any click
            $(document).click(function () {
                $(selector).hide();
            });
        });

        function getMenuSelector(e, menuSelector){
            var selector = menuSelector;
            if ($.isFunction(menuSelector)){
                selector = menuSelector.call(null, e);
            }
            return selector;
        }

        function getLeftLocation(e, selector) {
            var mouseWidth = e.pageX;
            var pageWidth = $(window).width();
            var menuWidth = $(selector).width();

            // opening menu would pass the side of the page
            if (mouseWidth + menuWidth > pageWidth &&
                menuWidth < mouseWidth) {
                return mouseWidth - menuWidth;
            }
            return mouseWidth;
        }

        function getTopLocation(e, selector) {
            var mouseHeight = e.pageY;
            var pageHeight = $(window).height();
            var menuHeight = $(selector).height();

            // opening menu would pass the bottom of the page
            if (mouseHeight + menuHeight > pageHeight &&
                menuHeight < mouseHeight) {
                return mouseHeight - menuHeight;
            }
            return mouseHeight;
        }

    };
})(jQuery, window);

$("#myTable td").contextMenu({
    menuSelector: function(e){
        // Do something with the clicked element to work out what to show
        var selector = "#contextMenu";
        if ($(e.target).closest('table').is('table table')){
            selector = '#contextMenu2';
        }
        return selector;
    },
    menuSelected: function (invokedOn, selectedMenu) {
        var msg = "You selected the menu item '" + selectedMenu.text() +
            "' on the value '" + invokedOn.text() + "'";
        alert(msg);
    }
});

And here's a fiddle showing it working: http://jsfiddle.net/Sly_cardinal/d8EfA/
I'd recommend going through the original and the altered version to see how it works.


text:
Q: Structure CodeIgniter Application EDIT:
What is the best way to structure complex applications with CodeIgniter?  To make this question more specific, maybe to just focus on structuring controllers: If you have a Users controller, than should all functions be in this one file?  In other words, you might have controller actions that tie to specific views, but a bunch of helper functions as well.
ORIGINAL QUESTION:   Given a complex application, with Users, Transactions, Products, does it make sense to have a Controller for each of them?  And since each of these corresponds to a database table, to have a corresponding model for each of them?  I think it does, but an application I am currently working on consists of one 3000 line controller and one 3000 line model.  Just want to verify the standard practice regarding CI and the application structure.

A: I'd like to share my application structure here.
I start with model. I write 1 model for one table in the mysql database. I already have MY_Model class that I put in system/application/libraries/ folder. This class have get_detail, get_list, get_total, get_all, insert, update, and delete method. I store the table name in a var, so basically I just need this code in model to make it worked:
class Some_table_model extends MY_Model {
  function Some_table_model()
  {
    $this->tablename = 'some_table';
    $this->primary_key = 'id';
  }

}

Update: after some more project, I have added new var to hold the column name used for primary key in the table. This way, I will have more flexibility by not hard coded the column name for primary key in MY_Model.
For the controller, I create it according to it's usage by user. Example for a product, I will have this controller:
function Product extends Controller {
  function index()
  {
    //display product list, paginated
  }
  function admin()
  {
    //protected by session
    //display product list for admin, paginated
    //handle POST request to delete a product or products
  }
  function form()
  {
    //protected by session
    //handle add/edit product for admin
  }
}

View is related to controller. For above controller, I will have at least 3 view file:
product_list.php
product_admin.php
product_form.php

View can be placed in subdir, for example, I can arrange it like this:
system/application/views/front/product.php
system/application/views/admin/product_list.php
system/application/views/admin/product_form.php

If product have category, I will need another table and model for it, but for controller, I can put the page inside Product controllers, by adding category into the function name:
function category_admin()
{
  //get parameter
  //...
  //process data
  //...
  //redirect or load view
  //...
}

function category_form()
{
  //get parameter
  //...
  //process data
  //...
  //redirect or load view
  //...
}

That's what I do and it's work for me. Hope this help you find a better way to refactor your CodeIgniter's code.

A: should separate controller. but controller also change the url if you do not use router to alter it.
for Model, i usually map 1 controller to 1 model, if DB cost more than 4 lines.

A: First of all, model definately needs seperating to something like:
user_model:
 add_user();
 delete_user();
 ...

products:
 add_product();
 delete_product();
 ...

transaction:
 ...
 ...

you should get the idea.
Controller could do with some seperation as well. My controllers in this scenario would be.
products:
 add_product();
 show_product();
 get_product();
 ...

users:
 add_user();
 delete_user();
 ...

and so on.
The reason for repeating same functions in controllers and models is that you can easily change model to access different database/data source and nothing beyond that needs changing.
Besides, there's absolutely no need to load product model when you're adding user for example.

A: If you're really concerned about project organization, you should check out Matchbox.
From the Matchbox Docs:

Matchbox is a set of extended libraries that lets you organize your application in small components (modules). These modules have several advantages, the main one being portability. Modules are stored in their own folders and so they can be reused in other applications or shared between users by copying just that one folder.

This allows you to really organize your content by placing related models and controllers in the same folder.


text:
Q: How to remove the lines that have empty fields? I have a CSV file with multiple columns, comma ", " separated and numbers of lines.
some lines have empty one or two fields "Columns". How I can identify in a separate file and/or remove those line with one or more empty columns with Awk command.
example
aaaa,bbbb,cccc,dddd,
,bbbb,cccc,dddd,
aaaa,,cccc,dddd,
aaaa,,,dddd,
,,,dddd,

The ", ," means empty columns.
I tried this command but it did not work!
awk -F, '$1,4~/^$/' filename

The expected output should be only :
aaaa, bbbb, cccc, dddd,

A: Can you just drop any line with two commas that are adjacent or separated only by whitespace, or that are first on the line? Something like:
 [dynamic<1>butlet]tmp $ cat data2
aaaa,bbbb,cccc,dddd,
,bbbb,cccc,dddd,
aaaa,,cccc,dddd,
aaaa,,,dddd,
,,,dddd,

 $ egrep -v ',[ ^I]*,|^[ ^I]*,' data2
aaaa,bbbb,cccc,dddd,

A: awk -F, '{for(i=1;i<=NF;i++)if($i==""){next}}1' inputfile


text:
Q: Why this time complexity is not a valid answer? We are working on a solver for a problem having next open question:
Is possible to implement a solver for the problem in time $O(2^{(1-\epsilon) \cdot \frac{n}{2}})$, for some $\epsilon>0$
And we implemented a solver in time $O(2^{(1-\frac{4}{n}) \cdot \frac{n}{2}})$
When checking this result with the question's author, he stated this time does not answer the question without further explanation, even when $\frac{4}{n}$ is $> 0$ for all $n > 0$.
I accept his answer, but I would like to understand why is not valid so we can try a different approach that could answer the questions properly.


text:
Q: Forbidden error while describe/scale deployment by user system:node:ip.xx I'm trying to execute K8S kubectl cmds from inside the container(name: autodeploy).
I have configured ClusterRole, ServiceAccount and ClusterRoleBinding. But getting Forbidden error while performing Describe and Scale actions on K8S Deployments.

Error from server (Forbidden): deployments.apps "test-deployment" is
forbidden: User "system:node:ip-xx-xx-xx-xx.ec2.internal" cannot get
resource "deployments" in API group "apps" in the namespace "abc"

autodeploy container also in same namespace abc
ClusterRole:
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: autodeploy
rules:
  - apiGroups: ["*"]
    resources: ["deployments", "deployments/scale", "pods"]
    verbs: ["get", "list", "update"]

ServiceAccount:
apiVersion: v1
kind: ServiceAccount
metadata:
  name: autodeploy
  namespace: abc

ClusterRoleBinding:
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: autodeploy
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: autodeploy
subjects:
  - kind: ServiceAccount
    name: autodeploy
    namespace: abc


text:
Q: Configure Git Remote server with Putty For Windows Pc right now i'm working on my school's development department.
Lately we've gotten a Ubuntu Server, I mean, the school has given us the server with Ubuntu OS.
The last week my boss said that he wanted to use Git on the server, but all our machines have Windows OS.
I've been searching a lot of information about doing this but i noticed that the information is mostly too old and obsolete.
I don't really know the exactly way to to this, i mean, i know that i need to update the server (sudo apt-get update), then install Git and assign the global user email and name, after that, get the ssh keygen but is in this point where i don't know what to do, because in some of the web tutorials they use their machines whit different OS.
Is there any proven new way to solve this problem? ->Configure with windows the private Git server and then use it with windows machines?

A: If you mean setup a Git server on Windows, no need for putty.
Install:

*

*Git for Windows

*Gitea.io (very simple setup: just one exe to copy, that's it)

And you have a Git server on Windows!


text:
Q: How to Create Event for Dynamic Control Array in VB.NET I'm trying to create an array of checkboxes dynamically and also want to put event to those checkboxes. How can I do this?
For example:
I have a array of checkboxes - Chk1, Chk2.
I want it to work this way: When I check Chk1, I want to disable Chk2, and when Chk1 is unchecked, Chk2 is enable, and vice versa.
Your input is greately appreciated.
Thanks,
P.S.: The code is in VB.NET. Thanks.

Thank you all for the inputs. I really appreciated it. Maybe I wasn't very clear on my explanation earlier.
Let's say, I have an array of 6 checkboxes, and I want them to behave in group like this:

*

*When Chk1 is checked, Chk2 is disabled (grey out), and when we uncheck Chk1, Chk2 is enabled, and Vice Versa.

*When Chk3 is checked, Chk4 is disabled, and when we uncheck Chk3, Chk4 is enabled, and Vice Versa.
and so on....
So this is like each pair of checkboxes in the array perform the CheckChanged event upon each other, but not on any other pair. So I think OptionButton is not the case in this situation.
Thanks for any suggestions.

A: Assuming that it is ASP.Net, have a look at this "strange" example to see how it works(take your array instead of my static creation):
Private Sub WebForm1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    For number As Int32 = 1 To 100
        Dim chk As New CheckBox
        chk.ID = "chk" & number
        chk.Text = chk.ID
        chk.AutoPostBack = True
        AddHandler chk.CheckedChanged, AddressOf onCheckedChanged
        Me.MyChkPanel.Controls.Add(chk)
    Next
End Sub

Private Sub onCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim chk As CheckBox = DirectCast(sender, CheckBox)
    Dim number As Int32 = Int32.Parse(chk.ID.Substring("chk".Length))
    Dim otherChk As CheckBox
    If number Mod 2 = 0 Then
        otherChk = DirectCast(Me.MyChkPanel.FindControl("chk" & (number - 1)), CheckBox)
    Else
        otherChk = DirectCast(Me.MyChkPanel.FindControl("chk" & (number + 1)), CheckBox)
    End If
    otherChk.Enabled = Not chk.Checked
End Sub

Apart from that i can subscribe Hans' suggestion to use RadioButtons or at least a CheckBoxList.

A: An RadioButton would do this automatically and is more conventional. For an array of checkboxes, you can use a single handler for the entire array:
Private Sub _CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim i As Integer
If sender.checked Then
  For i = 0 To UBound(chk)
    If chk(i) IsNot sender Then chk(i).Checked = False
  Next i
End If
End Sub

Keep in mind, if you make changes to this handler, that it is called recursively when you set chk(i).checked to false. It doesn't matter in this case, because it skips everything when sender.checked is false.
In case you need it, here is one way to set up the array. (The index property in the designer disappeared in the upgrade from vb6 to .net, so you have to make an array of controls in the code now.)
Public Class Form1
Dim chk(4) As CheckBox

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i, k As Integer
k = 20
For i = 0 To UBound(chk)
  chk(i) = New CheckBox
  Me.Controls.Add(chk(i))
  chk(i).Location = New Point(20, k)
  k = k + chk(0).Height * 1.5 ' or some location
  chk(i).Text = "Checkbox " & i ' some appropriate text
  AddHandler chk(i).CheckedChanged, AddressOf _CheckedChanged
Next i

End Sub


text:
Q: Python list comprehension returns nested list I built this little program to simulate 2 libraries I want to compare files with.
The code is this:
import os

path = "C:\Users\\nelson\Desktop\Lib Check"

pc_path = os.path.join(path, "pc")
phone_path = os.path.join(path, "phone")

pc_lib = [filename for path, dirname, filename in os.walk(pc_path)]

print pc_lib

it returns
[['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '8.txt', '9.txt']]

everything is fine except for the fact that the results are in a nested list. Why?
The only way I can stop this is by using
pc_lib = []
for path, dirname, filename in os.walk(pc_path):
    pc_lib.extend(filename)

A: filename is a list of files (the name you've used is not intuitive), so the results are expected
for root, dirs, files in os.walk('my/home/directory'):
     print(files)
#['close_button.gif', 'close_button_red.gif'],
#['toolbar.js']

extend unwraps the argument list and appends the resulting elements to the list that made the call

A: If you want a list of filenames, I would suggest:
[os.path.join(path, filename)
 for path, dirnames, filenames in os.walk(pc_path)
 for filename in filenames]

A: os.walk(path) returns an iterator over tuples of (root, dirs, files).
Where

*

*root is the path of the current directory relative to the argument of os.walk

*dirs is a list of all the subdirectories in the current directory

*files is a list of all normal files in the current directory

If you want a flat list of all files in a filesystem tree, use:
pc_lib = [
    filename for _, _, files in os.walk(pc_path)
    for filename in files
]

You probably want to retain the absolute path, to get thos use:
pc_lib = [
    os.path.join(root, filename)
    for root, _, files in os.walk(pc_path)
    for filename in files
]


text:
Q: How to seperate UnitTests for Controller Actions from Components in CakePHP 3 In CakePHP 2 it was possible to Mock a Controller like this: https://book.cakephp.org/2.0/en/development/testing.html#a-more-complex-example
and test the action like
$this->testAction('/posts/add', array(
        'method' => 'GET',
        'return' => 'contents'
    ));

In CakePHP 3 official documentation its suggested to put a valid user into the session to call an action.
BUT this makes it very hard to maintain the test. For example if the concept of User-Access-Management changes the "Articles->add" Test fails and I have to change the test.
So what I want is to write a Unit or Functional Test for a Controller-Action.
My idea was to mock the Controller->isAuthorized() method to return always true, but could not figure out how to implement it and still be able to call the action I want to test.
What is a good way of doing this?


text:
Q: ionic 2 stripe payment issue i am developing Hybrid app using ionic-3. i want to make payment with stripe. i am getting token-id from card detail but i don't know how to make charges after getting token-id in angular 2. I did:
npm install stripe

and I got the stripe module into node_modules folder. This is my payment function for get token-id now i want to make charges.
   pay() {
    this.stripe.setPublishableKey('pk_test...');
    this.stripe.createCardToken(this.cardinfo).then((token) => {
    console.log("token.id")
    })
    .catch(error =>
    console.log(error)
  );
  }

A: You need to create charges server-side with your Secret Key, so you'll need to post the Token ID to a server-side endpoint that can do that for you: https://stripe.com/docs/charges
Edit: also, you can't use the Stripe Node library client side; it doesn't have those functions in it.  You need Elements for that part: https://stripe.com/docs/stripe-js


text:
Q: android studio 3.4, não consigo usar celular como emulador Boa noite
Peço ajuda, eu instalei o android studio 3.4, eu não consigo usar o celular como emulador, a versão do meu celular é 8.1.0 samsung, ja habilitei o celular em modo de desenvolvedor, troquei o cabo USB, instalei o intel HAXM, o samsung USB, e nada, ja instalei outras versões do android studio e tbm nada, se algum puder me ajudar eu agradeço.


text:
Q: Как переделать меню? Хочу переделать меню сайта, как на сайте midiltd.ru (Cлева), чтобы при наведении на  категорию выдвигались подменю.
Вот код меню, который стоит на сайте.

#left_block{
 width: 200px;
 float: left;
 position: relative;
 padding: 10px;
    margin-right: 5px;
}

.one_block{
 width: 100%;
 //border: 1px solid #a8a8a8;
 border-radius: 5px;
 background: #efefef;
 box-shadow: 0 0 10px 5px rgba(221, 221, 221, 1);
 margin-bottom: 30px;
}

.block_head{
 padding: 5px 0 0px 0;
 text-align: center;
 font-size: 17px;
 font-weight:bold;
 color: #00007F;
}

.block_body{
 padding: 10px 10px 10px 10px;
}

ol, ul {
 list-style: none;
}

li.menu_catalog{
 padding-bottom: 2px;
 padding-top: 3px;
 color: black;
}

ul.menu{
 list-style: none;
 text-align: center;
 height: 100%;
 width:100%;
}

li.menu{
 display: inline;
 margin-left: 10px;
 margin-right: 50px;
 line-height: 30px;
 font-weight:normal;
}

a.menu, a.menu_curr{
 color: #fff;
 text-decoration: none;
}

div.menu_catalog{
 padding-top: 10px;
}

li.menu_catalog{
 padding-bottom: 2px;
 padding-top: 3px;
 color: black;
}

li.menu:hover, li.menu_curr{
 display: inline;
 margin-left: 10px;
 margin-right: 50px;
 text-decoration: none;
}

li.menu_catalog:hover, li.menu_child_catalog:hover, li.menu_curr_catalog{
 font-weight: bold;
 cursor: pointer;
}

a.menu_catalog, a.menu_curr_catalog, a.menu_child_catalog{
 color: black;
 text-decoration: none;
}

a.menu_catalog{
 color: black;
 text-decoration: none;
}

      Каталог товаров

Китай

Япония

Африка

Австралия

США

Омск

Саратов

Самара

Тепло

- Москва

Россия

Города

- Дома

Самолеты

Вертолеты

Лодки

Мотоциклы

Машины

A: Пример

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.menu {
  max-width: 330px;
}

.menu li {
  border: 1px solid #666;
  background: #fff;
  position: relative;
  list-style: none;
}

.menu a {
  color: #000;
  text-decoration: none;
  display: block;
  padding: 5px;
  font-size: 16px;
}

.submenu {
  opacity: 0;
  z-index: -1;
  position: absolute;
  top: 0;
  left: 100%;
  transform: translateX(20px);
  transition: transform .3s ease, opacity .4s ease;
}

.menu li:hover .submenu {
  opacity: 1;
  z-index: 1;
  transform: translateX(0);
}

.menu a:hover,
.menu > li:hover > a {
  color: #fff;
  background: #00f;
}

Menu

SubMenu

SubMenu

Menu

SubMenu

SubMenu

Menu

SubMenu

SubMenu

Menu

SubMenu

SubMenu

A: Если я правильно понимаю, то Вам нужно, чтобы при на ведении на один список выпадал другой?
В таком случае можно разместить один список внутри другого и скрыть его через display:none;, а затем задать display:block; при наведении на элемент списка, внутри которого находится скрытый список.


text:
Q: Pyparsing: a list of optional elements: weird issue with Optional, Each, and ordering of parser elements I'm trying to parse an XML-like file (with no associated DTD) with pyparsing. Part of each record looks has the following contents:

*

*Something within <L> and <L/> tags,

*One or more things within <pc> and <pc/> tags,

*Optionally, something within <MW> and <MW/> tags,

*Optionally, a literal <mul/>, and optionally a literal <mat/>
The ordering of these elements varies.
So I wrote the following (I'm new to pyparsing; please point out if I'm doing something stupid):
#!/usr/bin/env python

from pyparsing import *

def DumbTagParser(tag):
    tag_close = '</%s>' % tag
    return Group(
             Literal('<') + Literal(tag).setResultsName('tag') + Literal('>')
           + SkipTo(tag_close).setResultsName('contents')
           + Literal(tag_close)
           ).setResultsName(tag)

record1 = Group(ZeroOrMore(DumbTagParser('pc'))).setResultsName('pcs') &\
          DumbTagParser('L') & \
          Optional(Literal('<mul/>')) & \
          Optional(DumbTagParser('MW')) & \
          Optional(Literal('<mat/>'))

record2 = Group(ZeroOrMore(DumbTagParser('pc'))).setResultsName('pcs') &\
          Optional(DumbTagParser('MW')) & \
          Optional(Literal('<mul/>')) & \
          DumbTagParser('L')

def attempt(s):
    print 'Attempting:', s
    match = record1.parseString(s, parseAll = True)
    print 'Match: ', match
    print

attempt('<L>1.1</L>')
attempt('<pc>Page1,1</pc>  <pc>Page1,2</pc> <MW>000001</MW> <L>1.1</L>')
attempt('<mul/><MW>000003</MW><pc>1,1</pc><L>3.1</L>')
attempt('<mul/> <MW>000003</MW> <pc>1,1</pc> <L>3.1</L> ')  # Note end space

Both parsers record1 and record2 fail, with different exceptions. With record1, it fails on the last string (which differs from the penultimate string only in spaces):
pyparsing.ParseException:  (at char 47), (line:1, col:48)

and with record2, it fails on the penultimate string itself:
pyparsing.ParseException: Missing one or more required elements (Group:({"<" "L" ">" SkipTo:("</L>") "</L>"})) (at char 0), (line:1, col:1)

Now what is weird is that if I interchange lines 2 and 3 in the definition of record2, then it parses fine!
record2 = Group(ZeroOrMore(DumbTagParser('pc'))).setResultsName('pcs') &\
          Optional(Literal('<mul/>')) & \
          Optional(DumbTagParser('MW')) & \
          DumbTagParser('L')    # parses my example strings fine

(Yes I realise that record2 doesn't contain any rule for <mat/>. I'm trying to get a minimal example that reflects this sensitivity to reordering.)
I'm not sure if this is a bug in pyparsing or in my code, but my real question is how I should parse the kind of strings I want.

A: I don't know if you still want an answer but here is my bash...
I can see the following problems in your code are as follows :

*

*You've asigned resultsName multiple times to multiple items, as a Dict could eventually be returned you must either add '*' to each occurence of resultsName or drop it from a number of elements. I'll assume you are after the content and not the tags and drop their names. FYI, The shortcut for setting parser.resultsName(name) is parser(name).

*Setting the resultsname to 'Contents' for everything is also a bad idea as we would loose information already available to us. Rather name CONTENTS by it's corresponding TAG.

*You are also making multiple items Optional within the0 ZeroOrMore, they are already 'optional' through the ZeroOrMore, so let's allow them to be variations using the '^' operator as there is no predefined sequence ie. pc tags could precede mul tags or vice versa. It seems reasonable to allow any combintation and collect these as we go by.

*As we also have to deal with multiples of a given tag we append '*' to the CONTENTS' resultsName so that we can collect the results into lists.

First we create a function to create set of opening and closing tags, your DumbTagCreator is now called tagset :
from pyparsing import *

def tagset(str, keywords = False):
 if keywords :
  return [Group(Literal('<') + Keyword(str) + Literal('>')).suppress(),
          Group(Literal('</') + Keyword(str) + Literal('/>')).suppress()]
 else :
  return [Group(Literal('<') + Literal(str) + Literal('>')).suppress(),
          Group(Literal('</') + Literal(str) + Literal('>')).suppress()]

Next we create the parser which will parse <tag\>CONTENT</tag>, where CONTENT is the content we have an interest in, to return a dict so that we have {'pc' : CONTENT, 'MW' : CONTENT, ...}:
tagDict = {name : (tagset(name)) for name in ['pc','MW','L','mul','mat']}

parser = None
for name, tags in tagDict.iteritems() :
 if parser :
  parser = parser ^ (tags[0] + SkipTo(tags[1])(name) + tags[1])
 else :
  parser = (tags[0] + SkipTo(tags[1])(name) + tags[1])

# If you have added the </mul> tag deliberately...
parser = Optional(Literal('<mul/>')) + ZeroOrMore(parser)

# If you have added the </mul> tag by acccident...
parser = ZeroOrMore(parser)

and finally we test :
test = ['<L>1.1</L>',
 '<pc>Page1,1</pc>  <pc>Page1,2</pc> <MW>000001</MW> <L>1.1</L>',
 '<mul/><MW>000003</MW><pc>1,1</pc><L>3.1</L>',
 '<mul/> <MW>000003</MW> <pc>1,1</pc> <L>3.1</L> ']

for item in test :
 print {key:val.asList() for key,val in parser.parseString(item).asDict().iteritems()}

which should produce, assuming you want a dict of lists :
{'L': ['1.1']}
{'pc': ['Page1,1', 'Page1,2'], 'MW': ['000001'], 'L': ['1.1']}
{'pc': ['1,1'], 'MW': ['000003'], 'L': ['3.1']}
{'pc': ['1,1'], 'MW': ['000003'], 'L': ['3.1']}


text:
Q: determine the height of rectangle as function of x My textbook does not give an example of how to solve this problem so I'm not sure how to approach it. The problem asks, "Write the height h of the rectangle as a function of x." The back of the book gives the answer $h = -x^2 + 4x - 3$, which is a variation of the given function in the image, but I have no idea how to arrive at the answer. Any thoughts?

A: I don't know if I understand the request of the problem.
It seems a simple problem: I would say that $h=(-x^2+4x-1)-2=-x^2+4x-3$ in fact $h$ represents the distance between the parabola of equation $y=-x^2+4x-1$ and the line y=2.
Maybe you've to find the equation of the parabola from the graph. In this case you should impose that points $(1,2)$ and $(3,2)$ belong to the curve and that $2=-b/2a$  (vertex condition).


text:
Q: Values of passed variables to php function How do I see all the values passed to a php function ?
I have a custom function which accepts multiple parameters. When I call that  function in a page, I need to see all the values that were passed for each parameter.
function buildPromotionalSection( $f, $a,$b){ echo $f;}

then call to function:
buildPromotionalSection( 'hello', 'world', '876' );

Now I want to see the values that were passed.

A: using the func_get_args() you can get all the argument in a function
function buildPromotionalSection( $f, $a,$b)
{
    echo $f."
 ";
    foreach(func_get_args() as $arg) {
        echo 'This value was passed :'.$arg."
"
    }
}
buildPromotionalSection( 'hello', 'world', '876' );


text:
Q: How to search by member accessor value with std::find_if()? I am learning C++ at the moment and have an example program implemented with an array of objects data store. To make some other operations easier, I have changed the store to a vector. With this change I am now not sure of the best way to search the store to find an object based on a member accessor value.
Initially I used a simple loop:
vector<Composer> composers; // where Composer has a member function get_last_name() that returns a string

Composer& Database::get_composer(string last_name)
{
    for (Composer& c : composers)
        if (c.get_last_name().compare(last_name))
            return c;

    throw std::out_of_range("Composer not found");
}

This works just fine of course, but to experiment I wanted to see if there were vector specific functions that could also do the job. So far I have settled on trying to use find_if() (if there is a better function, please suggest).
However, I am not sure exactly the correct way to use find_if(). Based on code seen in online research I have replaced the above with the following:
vector<Composer> composers; // where Composer has a member function get_last_name() that returns a string

Composer& Database::get_composer(string last_name)
{
    auto found = find_if(composers.begin(), composers.end(),
                [last_name](Composer& c) -> bool {c.get_last_name().compare(last_name);});

    if (found == composers.end())
        throw out_of_range("Composer not found");
    else
        return *found;
}

This does not work. It does find a result, but it is the incorrect one. If an argument that matches, say the third composer's last name the function always returns the first item from the vector (if I pass an argument that doesn't match any last name the function correctly throws an exception)... what am I doing wrong?

A: You are on the right track, your lambda needs return statement. Also in such case you do not have to specify it's return type explicitly, it can be deduced:
find_if(composers.begin(), composers.end(),
            [last_name](const Composer& c) { return c.get_last_name() == last_name);});

you original code should not compile or at least emit warning(s), you should pay attention to them.
Note: it is not clear how your original code worked if you tested it, it should be:
if (c.get_last_name().compare(last_name) == 0 )

or simply:
if (c.get_last_name() == last_name )

as std::string::compare() returns int -1 0 or 1, so your code searches for string that does not match variable last_name

A: With range-v3, you may use projection:
auto it = ranges::find(composers, last_name, &composers::get_last_name);


text:
Q: OpenCV VideoWriter with python gives 5.54kb file I am trying to create a TimeLapse creator in python using OpenCV, and have the following code:
import cv2
import os
import string

directory = (r"C:\Users\Josh\Desktop\20130216")
video = cv2.VideoWriter(r"C:\Users\Josh\Desktop\video.avi", cv2.cv.CV_FOURCC('F','M','P', '4'), 15, (1536, 1536), 1)

for filename in os.listdir(directory):
    if filename.endswith(".jpg"):
        video.write(cv2.imread(filename))

cv2.destroyAllWindows()
video.release()

The folder has 1,440 pictures in it, yet video.avi is only 5.54kb in size, and has an empty output when played. Can anyone see any flaws in my code, and give me any help?

A: I have the same issue because the input video size (width and height) does not match the output file.
Mine shows 6KB.
I believe this is because openCV is not intended to do this kind of job (record/save video)
To fix this, just match the width and height
width, height = frame.shape
out = cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc('M','J','P','G'), fps, (width, height))

A: It seems to be that, you have windows without ffmpeg support.
I had the same problem and OpenCV 2.4 VideoCapture not working on Windows helped me on that.
The opencv246\opencv\3rdparty\ffmpeg\opencv_ffmpeg.dll should be copied to
c:\Python27\opencv_ffmpeg246.dll
Your frame size defined in your code as 1536x1536, so all of your .jpg files should match that size.
video = cv2.VideoWriter(r"C:\Users\Josh\Desktop\video.avi",
cv2.cv.CV_FOURCC('F','M','P', '4'), 15, (1536, 1536), 1)

A: The reason why cv2.VideoWriter can't save the video content with correct code is the output video's width, height size is different with input video's width, height size.
You need to match them


text:
Q: "Undefined index" in php file when using html forms to insert data in to database I am trying to insert data in to my database using html forms. But it is giving me an error as:

Notice: Undefined index: name in
  C:\wamp64\www\testtable\test-table.php on line 7

I am using Wampserver for localhost
Here is my html
spec-table-data.html

<title>Student's Data</title>

<form action="test-table.php" method="post">
    Name:<input type="text" name="name">

    Adress:<input type="text" name="address">

    <input type="submit" name="submit">
</form>

my php - test-table.php
<?php

$con = mysqli_connect("localhost","root","");

mysqli_select_db($con, "testtable");

$Names = $_POST['name'];
$Adresses = $_POST['address'];

$sqltables = "INSERT INTO testtable (Name,Adress) VALUES ('$Names', '$Adresses')";

mysqli_query($con, $sqltables);

mysqli_close($con);


text:
Q: Improve Microsoft cognitive services sentiment analysis? I find sentiment analysis to be frequently off, completely off, of what the sentiment actually should be. Here are some examples,

*

*I told you to not do that - Sentiment 0.81 (positive)  .. how is this positive?

*if you drop the glass i will beat you - Sentiment 0.74 (positive) .. how in the world is beating someone positive?

*You made a mess - Sentiment 0.76 (positive) .. how is this positive?

etc. many other such examples!
Questions,

*

*Is it possible to tweak this per your model?

*Is it possible to have a conversation thread be analyzed for sentiment? For instance,
utterance: you made a mess, it's okay, count to ten ..
.. here count to ten is .. reassuring .. i.e. it's okay, take a deep breath. Sentiment should be positive!

But saying just "count to ten" should be not as positive.
How far can I take Microsoft cognitive services sentiment analysis? Are there better/other options?
Thanks!


text:
Q: How to find the highest point on a lemniscate? A Lemniscate can be described by the following equation :
\begin{equation}
\left(x^{2}+b y^{2}\right)^{2}=2 a^{2}\left(x^{2}-b y^{2}\right)
\label{equa}
\end{equation} where $a,b$ are parameters. (See picture below for the shape)
To find the largest $x$ that is on the curve, we can see that it will be attained in $y=0$, therefore to find $x_\text{max}$ I can simply set $y=0$ in order to find $x_\text{max}$.
How can we find $y_\text{max}$ such that $y_\text{max}$ is the largest value for $y$ that obeys the equation of this curve? Or in simpler terms, how do I compute its half-height?
Any advice or remark is always appreciated, thanks!

A: Hint: Compute $dy/dx$ using implicit differentiation, Then see where that is zero. I'd guess four points (or two depending on how you set it up), compute $y$ values of these, etc.

A: $$(x^2+by^2)^2=2a^2(x^2-by^2)\tag{1}$$
$$2(x^2+by^2)(2x+2byy')=2a^2(2x-2byy')$$
At the point of $y_{max}$ the first derivative is zero so:
$$2(x^2+by^2)(2x)=2a^2(2x)$$
$$x^2+by^2=a^2$$
$$x^2=a^2-by^2\tag{2}$$
Now replace (2) into (1):
$$a^4=2a^2(a^2-2by^2)$$
$$a^2=2a^2-4by^2$$
$$4by^2=a^2$$
$$y=\frac{a}{2\sqrt b}$$


text:
Q: Remover links de imagens em CSS no @media print Meu blog mostra os links quando impressos através do a[href]:after { content:" (" attr(href) ")"; }, entretanto não quero que ele mostre os links de imagens, visto que eu as retirei também do CSS para impressão. Há alguma forma de remover esses links através de algo como o a[href]:after { content:" (" attr(href) ")"; } que mencionei (como, por exemplo, ignorar algo que termine com .jpg ou .png, suponho...)?
Exemplo:
O código aparece, basicamente, assim (um texto seguido de uma imagem):
3. Diligência para se esforçar; pôr uma
força maior do que a que se tem. Não fique parado, zele e proveja.

Quando impresso, sai assim:
 3. Diligência para se esforçar; pôr uma força maior do que a que se tem. Não fique parado, zele e proveja.
(https://4.bp.blogspot.com/-ipbE_b01j_A/Wp_Xj93YDrI/AAAAAAAAE64/hUZW_VqNjpMbL9BanqgF1Db8paRdblYPgCLcBGAs/s320/a-constancia-e-mais.jpg)
A imagem sai em forma de URL porque está configurado assim, mediante o código a[href]:after { content:" (" attr(href) ")"; }. Meu problema é que quero, sim, que os links sejam impressos, exceto os links de imagem.

A: Vitor, pelo que entendi você não vai conseguir fazer isso somente com CSS. Você precisa verificar se a url é uma imagem ou não.
Uma sugestão é adicionar via JS uma class nos elementos onde a url é uma imagem.
 <a class"url-img" href="https://4.bp.blogspot.com/-ipbE_b01j_A/Wp_Xj93...

E com o CSS você remove o content
 @media print { a.url-img[href]:after { content:"" }

A: Vítor isso vai resolver seu problema.
Essa regra vai pegar os termo jpg, png ou gif dentro do link e vai colocar o contente como vazio. Então se no link houver os caracteres jpg etc ele vai aplicar a regra.
a[href*=".jpg"]:after,
a[href*=".png"]:after,
a[href*=".gif"]:after { content:""; }

Veja o exemplo:

@media print {
a[href]:after { content:" (" attr(href) ")"; }

a[href*=".jpg"]:after,
a[href*=".png"]:after,
a[href*=".gif"]:after { content:""; }

img {display:none;}
}
3. Diligência para se esforçar; pôr uma força maior do que a que se tem. Não fique parado, zele e proveja.


text:
Q: Need help/Clarification in Lua Yesterday I have seen a code written in Lua using oop method under "Love Framework"  so I tried to write the same code by changing some variable to understand it better.
Class = require 'lib/class'-- I'm using Class library https://github.com/vrld/hump/blob/master/class.lua

Bala = Class{__includes = Shubham}

-- here I'm Calling Bala Class

chawal = Bala {
           market = "A-Market",
           Rashan = "poha"
        }

-- Here I've initialized Bala Class using 'init' to pass a argument inside it.

function Bala:init(def)
   Shubham.init(self, def)
end

-- Here I've created Shubham class and pass the same argument.
Shubham = Class{}

function Shubham:init(def)
  self.market = def.market
  self.Rashan = def.Rashan
end

print(chawal.market)

The output is table: 00800320

So my question is how to call those argument from Shubham Class by print() and using terminal only
and my 2nd question is why are we using 'self' in Shubham.init(self, def) what's the actual meaning of this line.

A: You have just put your code in the incorrect order.
when executing a lua file you're going to work down it from top to bottom, so if you reference something from a lower section in the file it will not exist/have been loaded yet.
the first example would be here:
chawal = Bala {
           market = "A-Market",
           Rashan = "poha"
        }

-- Here I've initialized Bala Class using 'init' to pass a argument inside it.

function Bala:init(def)
   Shubham.init(self, def)
end

you are doing an action that would call Bala:init before Bala:init is defined, the class library "saves" you from an error, but that just causes you to think the code "worked"
This should be the correct order of the sections:
Class = require 'lib/class'

Shubham = Class{}

function Shubham:init(def)
  self.market = def.market
  self.Rashan = def.Rashan
end

Bala = Class{__includes = Shubham}

function Bala:init(def)
   Shubham.init(self, def)
end

chawal = Bala {
           market = "A-Market",
           Rashan = "poha"
        }

print(chawal.market)

Output:

A-Market