text:
Q: How to execute a lambda function which copies objects from one S3 bucket to another via Step functions? I was able to perform the task to copy data from the source bucket to a destination bucket using lambda function, however, I got an error while executing the lambda function in Step functions. Below are the steps I followed from the scratch.

*

*Region chosen is ap-south-1

*Created 2 buckets. Source bucket: start.bucket    &   Destination bucket: final.bucket

*Created a Lambda function with the following information:

*

*Author from scratch

*Function name: CopyCopy

*Runtime: Python 3.8

*Had created a lambda IAM role: LambdaCopy and gave the necessary policies(S3 full access and Step functions full access) and attached it to the function.

*Added a trigger and chose:

*

*S3

*Bucket: start.bucket

*Event type: All object create events

*I found a python code in GeeksforGeeks and applied in the code section.

import json
import boto3
s3_client=boto3.client('s3')

# lambda function to copy file from 1 s3 to another s3
def lambda_handler(event, context):
    #specify source bucket
    source_bucket_name=event['Records'][0]['s3']['bucket']['name']
    #get object that has been uploaded
    file_name=event['Records'][0]['s3']['object']['key']
    #specify destination bucket
    destination_bucket_name='final.bucket'
    #specify from where file needs to be copied
    copy_object={'Bucket':source_bucket_name,'Key':file_name}
    #write copy statement
    s3_client.copy_object(CopySource=copy_object,Bucket=destination_bucket_name,Key=file_name)

    return {
        'statusCode': 3000,
        'body': json.dumps('File has been Successfully Copied')
    }

- I deployed the code and it worked. Uploaded a csv file in start.bucket and it was copied to final.bucket.

Then, I created a State machine in Step functions with the following information:

*

*Design your workflow visually

*Type: Standard

*Dragged the AWS Lambda between the Start and End state.

*

*Changed its name to LambdaCopy

*Integration type: Optimized

*Under API Parameters, Function name(I chose the Lambda function that I had created): CopyCopy:$LATEST

*Next State: End

*Next and then again Next

*State machine name: StepLambdaCopy

*

*IAM Role: Create a new role (Later gave it S3 full access, Lambdafullaccess and Step function fullaccess too).

It showed error when I tried to execute it.
I know I am missing out on something. I would really appreciate the help.

A: Step functions now allows you to utilize the S3 Copy SDK directly completely bypassing the need for Lambda and boto3.  Take a look here for more information.
So in your case you would need a simple task that looks like this:
{
  "Comment": "A description of my state machine",
  "StartAt": "CopyObject",
  "States": {
    "CopyObject": {
      "Type": "Task",
      "End": true,
      "Parameters": {
        "ServerSideEncryption": "AES256",
        "Bucket.$": "$.destination_bucket",
        "CopySource.$": "$.source_path",
        "Key.$": "$.key"
      },
      "Resource": "arn:aws:states:::aws-sdk:s3:copyObject"
    }
  }
}

Then your input state will need to feed in the parameters you would normally use to copy a file with the copy command.  Source Path, Destination Bucket, and Object Key exactly the same as the boto3 command.
Note: Your state machine IAM role will need direct S3 permissions and will need to be in the same region as the buckets.

A: It's always confusing what exactly you have to pass as parameters. Here is a template I use to copy the output of an Athena query. You can adapt it to your needs:
"athena_score": {
  "Type": "Task",
  "Resource": "arn:aws:states:::athena:startQueryExecution.sync",
  "Parameters": {
    "QueryExecutionContext": {
      "Catalog": "${AthenaCatalog}",
      "Database": "${AthenaDatabase}"
    },
    "QueryString": "SELECT ...",
    "WorkGroup": "${AthenaWorkGroup}",
    "ResultConfiguration": {
      "OutputLocation": "s3://${BucketName}/${OutputPath}"
    }
  },
  "TimeoutSeconds": 300,
  "ResultPath": "$.responseBody",
  "Next": "copy_csv"
},
"copy_csv": {
  "Type": "Task",
  "Resource": "arn:aws:states:::aws-sdk:s3:copyObject",
  "Parameters": {
    "Bucket": "${BucketName}",
    "CopySource.$": "States.Format('/${BucketName}/${OutputPath}/{}.csv', $.responseBody.QueryExecution.QueryExecutionId)",
    "Key": "${OutputPath}/latest.csv"
  },
  "ResultPath": "$.responseBody.CopyObject",
  "Ent": "true"
}


text:
Q: How to force the re-login to all users when roles are changed using Symfony2 and FOSUserBundle? I have a question about how can I force a re-login for all users when I execute a process that reloads all user roles.
Is possible do that? I'm using FOSUserBundle as user provider.
Thank you!

A: I never used FosUserBundle but one simple way to do this is in your User Class implementing the EquatableInterface and inserting in the isEqualTo method something like:
# this comparison is ONLY indicative

if ($this->roles !== $user->getRoles()) {
    return false;
}

PS: At any request Symfony checks that assigned roles are not changed (but you can add also other fields to check like Email, Username, etc...), otherwise the user is automatically disconnected (but without printing a friendly message to the user)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best practice for error handling anon functions I'm working on some large Go projects but I wanted to ask a question about best practice on error handling. As far as I'm aware errors shouldn't be hidden / "caught" but I could be wrong.
In a lot of the projects I'm working on I'm seeing a lot of this in http handlers. Sometimes with about 8 function calls
func FooHandler(w http.ResponseWriter, r *http.Request) {
    if err := func() error {
        var1, err := doSomething1()
        if err != nil {
             return fmt.Error("some error")
        }

        var2, err := doSomething2()
        if err != nil {
             return fmt.Error("some error")
        }

        var3, err := doSomething3()
        if err != nil {
             return fmt.Error("some error")
        }

        var4, err := doSomething4()
        if err != nil {
             return fmt.Error("some error")
        }
    }(); err != nil {
        // build error response here
    }
    // do successful response here
}

This seems like doing try / catch in Go, but it would be good to know if this is accepted practice or not. The alternative would be if err != nil then using a function to write the error response, but would be repeating code.

A: The above approach is completely fine and not "catching" anything in the sense of try .. catch as other languages would do.
The main reason for the anonymous function is to write the error specific response only once. There are other ways to do it if you don't like that approach.
handle error function
For example you could have a function to handle / return the error so this code does not clutter the handler:
func handleErr(w http.ResponseWriter, err error, statusCode int) {
    log.Printf("statusCode: %d; error: %s", statusCode, err)

    w.WriteHeader(statusCode)

    bts, err := json.Marshal(struct {
        Error string
    }{
        Error: err.Error(),
    })
    if err != nil {
        _, _ = w.Write([]byte(`{"Error":"error while marshalling error response"`))
    }

    _, _ = w.Write(bts)
}

A handler would then look like this:
func FooHandler(w http.ResponseWriter, r *http.Request) {
    var1, err := doSomething1()
    if err != nil {
        handleErr(w, err, http.StatusBadRequest, "some user error msg")
        return
    }

    var2, err := doSomething2()
    if err != nil {
        handleErr(w, err, http.StatusUnauthorized, "some user error msg")
        return
    }

    var3, err := doSomething3()
    if err != nil {
        handleErr(w, err, http.StatusInternalServerError, "some user error msg")
        return
    }

    var4, err := doSomething4()
    if err != nil {
        handleErr(w, err, http.StatusInternalServerError, "some user error msg")
        return
    }

    // do successful response here
}

using a middleware
As @mkopriva suggested in the comments, you can also use a wrapper for the handlers:
func handleErr(f func(w http.ResponseWriter, r *http.Request) (int, error)) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        statusCode, err := f(w, r)
        if err != nil {
            return
        }

        log.Printf("statusCode: %d; error: %s", statusCode, err)

        w.WriteHeader(statusCode)

        bts, err := json.Marshal(struct {
            Error string
        }{
            Error: err.Error(),
        })
        if err != nil {
            _, _ = w.Write([]byte(`{"Error":"error while marshalling error response"`))
        }

        _, _ = w.Write(bts)
    }
}

It will get wrapped when registering the handler:
http.Handle("/foo", handleErr(FooHandler))

The FooHandler can now return statusCode and error:
func FooHandler(w http.ResponseWriter, r *http.Request) (int, error) {
    var1, err := doSomething1()
    if err != nil {
        return http.StatusBadRequest, fmt.Error("some error")
    }

    var2, err := doSomething2()
    if err != nil {
        return http.StatusUnauthorized, fmt.Error("some error")
    }

    var3, err := doSomething3()
    if err != nil {
        return http.StatusInternalServerError, fmt.Error("some error")
    }

    var4, err := doSomething4()
    if err != nil {
        return http.StatusInternalServerError, fmt.Error("some error")
    }

    // do successful response here
    return http.StatusOK, nil
}


text:
Q: Should I include /dev in backups? After searching this site, and reading the Ubuntu community documentation, I've decided to use a simple tar command such as
sudo tar -cvpzf serverbackupMMDDYYYY.tgz --exclude=/proc --exclude=/lost+found --exclude=/mnt --exclude=/sys --exclude=/media --exclude=/backups --exclude=/boot --exclude=/dev  --exclude=/home -exclude=/tmp --exclude=serverbackupMMDDYYYY.tgz /

To backup my system. While researching how to backup my system it seemed some people recommended excluding /dev (as I'm doing above) and others warned that there could be problems doing that (but they didn't elaborate).
What are the pros and cons of including or excluding /dev in a backup?
I tested a full backup/restore and didn't run into any problems excluding /dev myself, but I also think I took more steps than necessary to restore. After inserting a non broken hard drive I reinstalled Ubuntu and then extracted the backup over the fresh install.

A: Some directories are irrelevant into a backup. For example:

*

*/dev/*

*/proc/*

*/sys/*

*/tmp/*

**lost+found

They are created during the boot, and are related specific with your devices and/or your running processes.
While its irrelevant to backup or not - your kernel will recreate those directories when boot from restored backup - you probably will save a little time if you do not backup it.

A: *

*None of the nodes in dev are real files, and none of them contain much that isn't generated.


text:
Q: AzureDevops publish publishes too many zip files Apologies if this is a stpuid question but I have been struggling with this for several weeks now and making no progress. I have a build step for my .Net project in Azure Devops with the following parameters:
/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\\"

Although it says package as single file. I get the following in the drop folder:
Orchard.Autoroute.deploy-readme.txt
Orchard.Autoroute.deploy.cmd
Orchard.Autoroute.SetParameters.xml
Orchard.Autoroute.SourceManifest.xml
Orchard.Autoroute.zip
Orchard.Azure.deploy-readme.txt
Orchard.Azure.deploy.cmd
Orchard.Azure.MediaServices.deploy-readme.txt
Orchard.Azure.MediaServices.deploy.cmd
Orchard.Azure.MediaServices.SetParameters.xml
Orchard.Azure.MediaServices.SourceManifest.xml
Orchard.Azure.MediaServices.zip
Orchard.Azure.SetParameters.xml
Orchard.Azure.SourceManifest.xml
Orchard.Azure.zip
Orchard.Blogs.deploy-readme.txt
Orchard.Blogs.deploy.cmd
Orchard.Blogs.SetParameters.xml
Orchard.Blogs.SourceManifest.xml
Orchard.Blogs.zip
Orchard.Caching.deploy-readme.txt
Orchard.Caching.deploy.cmd
Orchard.Caching.SetParameters.xml
Orchard.Caching.SourceManifest.xml
Orchard.Caching.zip
Orchard.CodeGeneration.deploy-readme.txt
Orchard.CodeGeneration.deploy.cmd
Orchard.CodeGeneration.SetParameters.xml
Orchard.CodeGeneration.SourceManifest.xml
Orchard.CodeGeneration.zip
Orchard.Comments.deploy-readme.txt
Orchard.Comments.deploy.cmd
Orchard.Comments.SetParameters.xml
Orchard.Comments.SourceManifest.xml
Orchard.Comments.zip
Orchard.Conditions.deploy-readme.txt
Orchard.Conditions.deploy.cmd
Orchard.Conditions.SetParameters.xml
Orchard.Conditions.SourceManifest.xml
Orchard.Conditions.zip
Orchard.ContentPermissions.deploy-readme.txt
Orchard.ContentPermissions.deploy.cmd
Orchard.ContentPermissions.SetParameters.xml
Orchard.ContentPermissions.SourceManifest.xml
Orchard.ContentPermissions.zip
Orchard.ContentPicker.deploy-readme.txt
Orchard.ContentPicker.deploy.cmd
Orchard.ContentPicker.SetParameters.xml
Orchard.ContentPicker.SourceManifest.xml
Orchard.ContentPicker.zip
Orchard.ContentTypes.deploy-readme.txt
Orchard.ContentTypes.deploy.cmd
Orchard.ContentTypes.SetParameters.xml
Orchard.ContentTypes.SourceManifest.xml
Orchard.ContentTypes.zip
Orchard.Core.deploy-readme.txt
Orchard.Core.deploy.cmd
Orchard.Core.SetParameters.xml
Orchard.Core.SourceManifest.xml
Orchard.Core.zip
Orchard.CustomForms.deploy-readme.txt
Orchard.CustomForms.deploy.cmd
Orchard.CustomForms.SetParameters.xml
Orchard.CustomForms.SourceManifest.xml
Orchard.CustomForms.zip
Orchard.Dashboards.deploy-readme.txt
Orchard.Dashboards.deploy.cmd
Orchard.Dashboards.SetParameters.xml
Orchard.Dashboards.SourceManifest.xml
Orchard.Dashboards.zip
Orchard.DesignerTools.deploy-readme.txt
Orchard.DesignerTools.deploy.cmd
Orchard.DesignerTools.SetParameters.xml
Orchard.DesignerTools.SourceManifest.xml
Orchard.DesignerTools.zip
Orchard.DynamicForms.deploy-readme.txt
Orchard.DynamicForms.deploy.cmd
Orchard.DynamicForms.SetParameters.xml
Orchard.DynamicForms.SourceManifest.xml
Orchard.DynamicForms.zip
Orchard.Email.deploy-readme.txt
Orchard.Email.deploy.cmd
Orchard.Email.SetParameters.xml
Orchard.Email.SourceManifest.xml
Orchard.Email.zip
Orchard.Fields.deploy-readme.txt
Orchard.Fields.deploy.cmd
Orchard.Fields.SetParameters.xml
Orchard.Fields.SourceManifest.xml
Orchard.Fields.zip
Orchard.Forms.deploy-readme.txt
Orchard.Forms.deploy.cmd
Orchard.Forms.SetParameters.xml
Orchard.Forms.SourceManifest.xml
Orchard.Forms.zip
Orchard.ImageEditor.deploy-readme.txt
Orchard.ImageEditor.deploy.cmd
Orchard.ImageEditor.SetParameters.xml
Orchard.ImageEditor.SourceManifest.xml
Orchard.ImageEditor.zip
Orchard.ImportExport.deploy-readme.txt
Orchard.ImportExport.deploy.cmd
Orchard.ImportExport.SetParameters.xml
Orchard.ImportExport.SourceManifest.xml
Orchard.ImportExport.zip
Orchard.Indexing.deploy-readme.txt
Orchard.Indexing.deploy.cmd
Orchard.Indexing.SetParameters.xml
Orchard.Indexing.SourceManifest.xml
Orchard.Indexing.zip
Orchard.JobsQueue.deploy-readme.txt
Orchard.JobsQueue.deploy.cmd
Orchard.JobsQueue.SetParameters.xml
Orchard.JobsQueue.SourceManifest.xml
Orchard.JobsQueue.zip
Orchard.jQuery.deploy-readme.txt
Orchard.jQuery.deploy.cmd
Orchard.jQuery.SetParameters.xml
Orchard.jQuery.SourceManifest.xml
Orchard.jQuery.zip
Orchard.Layouts.deploy-readme.txt
Orchard.Layouts.deploy.cmd
Orchard.Layouts.SetParameters.xml
Orchard.Layouts.SourceManifest.xml
Orchard.Layouts.zip
Orchard.Lists.deploy-readme.txt
Orchard.Lists.deploy.cmd
Orchard.Lists.SetParameters.xml
Orchard.Lists.SourceManifest.xml
Orchard.Lists.zip
Orchard.Localization.deploy-readme.txt
Orchard.Localization.deploy.cmd
Orchard.Localization.SetParameters.xml
Orchard.Localization.SourceManifest.xml
Orchard.Localization.zip
Orchard.Media.deploy-readme.txt
Orchard.Media.deploy.cmd
Orchard.Media.SetParameters.xml
Orchard.Media.SourceManifest.xml
Orchard.Media.zip
Orchard.MediaLibrary.deploy-readme.txt
Orchard.MediaLibrary.deploy.cmd
Orchard.MediaLibrary.SetParameters.xml
Orchard.MediaLibrary.SourceManifest.xml
Orchard.MediaLibrary.zip
Orchard.MediaPicker.deploy-readme.txt
Orchard.MediaPicker.deploy.cmd
Orchard.MediaPicker.SetParameters.xml
Orchard.MediaPicker.SourceManifest.xml
Orchard.MediaPicker.zip
Orchard.MediaProcessing.deploy-readme.txt
Orchard.MediaProcessing.deploy.cmd
Orchard.MediaProcessing.SetParameters.xml
Orchard.MediaProcessing.SourceManifest.xml
Orchard.MediaProcessing.zip
Orchard.MessageBus.deploy-readme.txt
Orchard.MessageBus.deploy.cmd
Orchard.MessageBus.SetParameters.xml
Orchard.MessageBus.SourceManifest.xml
Orchard.MessageBus.zip
Orchard.Migrations.deploy-readme.txt
Orchard.Migrations.deploy.cmd
Orchard.Migrations.SetParameters.xml
Orchard.Migrations.SourceManifest.xml
Orchard.Migrations.zip
Orchard.Modules.deploy-readme.txt
Orchard.Modules.deploy.cmd
Orchard.Modules.SetParameters.xml
Orchard.Modules.SourceManifest.xml
Orchard.Modules.zip
Orchard.MultiTenancy.deploy-readme.txt
Orchard.MultiTenancy.deploy.cmd
Orchard.MultiTenancy.SetParameters.xml
Orchard.MultiTenancy.SourceManifest.xml
Orchard.MultiTenancy.zip
Orchard.OutputCache.deploy-readme.txt
Orchard.OutputCache.deploy.cmd
Orchard.OutputCache.SetParameters.xml
Orchard.OutputCache.SourceManifest.xml
Orchard.OutputCache.zip
Orchard.Packaging.deploy-readme.txt
Orchard.Packaging.deploy.cmd
Orchard.Packaging.SetParameters.xml
Orchard.Packaging.SourceManifest.xml
Orchard.Packaging.zip
Orchard.Pages.deploy-readme.txt
Orchard.Pages.deploy.cmd
Orchard.Pages.SetParameters.xml
Orchard.Pages.SourceManifest.xml
Orchard.Pages.zip
Orchard.Projections.deploy-readme.txt
Orchard.Projections.deploy.cmd
Orchard.Projections.SetParameters.xml
Orchard.Projections.SourceManifest.xml
Orchard.Projections.zip
Orchard.PublishLater.deploy-readme.txt
Orchard.PublishLater.deploy.cmd
Orchard.PublishLater.SetParameters.xml
Orchard.PublishLater.SourceManifest.xml
Orchard.PublishLater.zip
Orchard.Recipes.deploy-readme.txt
Orchard.Recipes.deploy.cmd
Orchard.Recipes.SetParameters.xml
Orchard.Recipes.SourceManifest.xml
Orchard.Recipes.zip
Orchard.Redis.deploy-readme.txt
Orchard.Redis.deploy.cmd
Orchard.Redis.SetParameters.xml
Orchard.Redis.SourceManifest.xml
Orchard.Redis.zip
Orchard.Resources.deploy-readme.txt
Orchard.Resources.deploy.cmd
Orchard.Resources.SetParameters.xml
Orchard.Resources.SourceManifest.xml
Orchard.Resources.zip
Orchard.Roles.deploy-readme.txt
Orchard.Roles.deploy.cmd
Orchard.Roles.SetParameters.xml
Orchard.Roles.SourceManifest.xml
Orchard.Roles.zip
Orchard.Rules.deploy-readme.txt
Orchard.Rules.deploy.cmd
Orchard.Rules.SetParameters.xml
Orchard.Rules.SourceManifest.xml
Orchard.Rules.zip
Orchard.Scripting.CSharp.deploy-readme.txt
Orchard.Scripting.CSharp.deploy.cmd
Orchard.Scripting.CSharp.SetParameters.xml
Orchard.Scripting.CSharp.SourceManifest.xml
Orchard.Scripting.CSharp.zip
Orchard.Scripting.deploy-readme.txt
Orchard.Scripting.deploy.cmd
Orchard.Scripting.Dlr.deploy-readme.txt
Orchard.Scripting.Dlr.deploy.cmd
Orchard.Scripting.Dlr.SetParameters.xml
Orchard.Scripting.Dlr.SourceManifest.xml
Orchard.Scripting.Dlr.zip
Orchard.Scripting.SetParameters.xml
Orchard.Scripting.SourceManifest.xml
Orchard.Scripting.zip
Orchard.Search.deploy-readme.txt
Orchard.Search.deploy.cmd
Orchard.Search.SetParameters.xml
Orchard.Search.SourceManifest.xml
Orchard.Search.zip
Orchard.SecureSocketsLayer.deploy-readme.txt
Orchard.SecureSocketsLayer.deploy.cmd
Orchard.SecureSocketsLayer.SetParameters.xml
Orchard.SecureSocketsLayer.SourceManifest.xml
Orchard.SecureSocketsLayer.zip
Orchard.Setup.deploy-readme.txt
Orchard.Setup.deploy.cmd
Orchard.Setup.SetParameters.xml
Orchard.Setup.SourceManifest.xml
Orchard.Setup.zip
Orchard.Tags.deploy-readme.txt
Orchard.Tags.deploy.cmd
Orchard.Tags.SetParameters.xml
Orchard.Tags.SourceManifest.xml
Orchard.Tags.zip
Orchard.TaskLease.deploy-readme.txt
Orchard.TaskLease.deploy.cmd
Orchard.TaskLease.SetParameters.xml
Orchard.TaskLease.SourceManifest.xml
Orchard.TaskLease.zip
Orchard.Taxonomies.deploy-readme.txt
Orchard.Taxonomies.deploy.cmd
Orchard.Taxonomies.SetParameters.xml
Orchard.Taxonomies.SourceManifest.xml
Orchard.Taxonomies.zip
Orchard.Templates.deploy-readme.txt
Orchard.Templates.deploy.cmd
Orchard.Templates.SetParameters.xml
Orchard.Templates.SourceManifest.xml
Orchard.Templates.zip
Orchard.Themes.deploy-readme.txt
Orchard.Themes.deploy.cmd
Orchard.Themes.SetParameters.xml
Orchard.Themes.SourceManifest.xml
Orchard.Themes.zip
Orchard.Tokens.deploy-readme.txt
Orchard.Tokens.deploy.cmd
Orchard.Tokens.SetParameters.xml
Orchard.Tokens.SourceManifest.xml
Orchard.Tokens.zip
Orchard.Users.deploy-readme.txt
Orchard.Users.deploy.cmd
Orchard.Users.SetParameters.xml
Orchard.Users.SourceManifest.xml
Orchard.Users.zip
Orchard.Warmup.deploy-readme.txt
Orchard.Warmup.deploy.cmd
Orchard.Warmup.SetParameters.xml
Orchard.Warmup.SourceManifest.xml
Orchard.Warmup.zip
Orchard.Web.deploy-readme.txt
Orchard.Web.deploy.cmd
Orchard.Web.SetParameters.xml
Orchard.Web.SourceManifest.xml
Orchard.Web.zip

etc and many more
In my release step I have an Azure App Service Deployment step with the following parameter:
$(System.DefaultWorkingDirectory)/**/Orchard.Web.zip

But it only deploys the code for the website, none of the modules of Orchard so the website does not work. I cannot specify this:
$(System.DefaultWorkingDirectory)/**/*.zip

Otherwise I get this error:
Error: More than one package matched with specified pattern: D:\a\r1\a***.zip. Please restrain the search pattern.
Currently the website publishes correctly if I publish from visual studio, but not through AzureDevops.
Do I need a deployment step for each module?
Why can't I do a deployment step just like in VS but through AzureDevops?
What combination of build and release steps do I need to do a WebDeploy which will deploy all of the code?
A tutorial would be ideal.
Edit:
I have also raised this issue here:
https://developercommunity.visualstudio.com/content/problem/408833/azuredevops-publish-publishes-too-many-zip-files.html


text:
Q: View Key value observations How do I know what items my object is key-value observing?
The only way I've been able to find out if I'm already observing is to try to remove the observation. If an exception is thrown, then I wasn't observing.
for (AVPlayerItem *item in itemsToRemove) {
    @try{
        [item removeObserver:self forKeyPath:@"status" context:(__bridge void *)(foo)];
    }@catch(id anException){
        //wasn't observing
    }
}

EDIT: I'm considering using my own dictionary to track observation but that seems redundant since a KVO Dictionary does exist somewhere. Unfortunately there is no API access.

A: It seems there is no other option than catching the exception, even NSHipster recommends to do so. However, at least in my case, it was hardly ever needed to do the check. After all, you are the one who controls the observers.
You can use a wrapper (like FBKVOController) which adds more sanity to the raw KVO (and makes observing a lot easier, allowing to use blocks). Among other features, it doesn't crash when trying to remove a nonexistent observer:
 @discussion If not observing object key path, or unobserving nil, this method results in no operation.
 */
- (void)unobserve:(id)object keyPath:(NSString *)keyPath;

A: There is no way to know that until you add some boolean flag to your controller and use it to mark and check if your registered for KVO. Normally you should balance out registration and unregistration from KVO observation.
Using exception under ARC is bad and may lead to memory leaks until you use -fobjc-arc-exceptions.
Long story short: Exceptions are expensive, that's why ARC does not properly handle them until you explicitly ask. There is an explanation to that: https://stackoverflow.com/a/4649234/351305


text:
Q: How can I incporporate a Geolocation lookup into a switch? In my Wordpress theme I have a function that looks a bit like this:
function variable($value) {
    switch ($value) {
        case 'prem_no':
            $prem_no_uk  = '0906 636 4355';
            $prem_no_aus = '';
            $prem_no_us  = '';
            return $prem_no;
            break;
    }
}

On the page I am calling:
echo variable('prem_no');

I want to use this script to get the users location, and depending on the returning location, return one of the three variables listed in the case above.
http://www.hostip.info/use.html
the problem I have, is I've looked on that site, and it just gives a URL. I don't know how to write an IF statement, or whatever is needed.
I think logically, I want to only have one call for the main location finder, then store that value as a variable elsewhere on the site.
Then in the return for the cases add a suffix at the end of prem_no that would match the cases above.
Is that along the right tracks?
UPDATE:
Right I'll try and have a go in a slightly different direction.
At the top of the header file I've got this:
require_once 'geoip.inc';
$gi = geoip_open('GeoIP.dat',GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);

I'm getting a error message saying:

Warning: fopen(GeoIP.dat): failed to open stream: No such file or directory in C:\wamp\www\clairvoyant\wp-content\themes\clairvoyant\geoip.inc on line 314

What I don't get is that the path is absolutely correct, the file is there. So why can't it find it?

A: Okay, so I've managed to partly fix my issues here.
I put the switch and the code into a single function like this:
function variable($value) {
$country_code = '';
require_once("geoip.inc");
$gi = geoip_open(dirname(__FILE__)."/GeoIP.dat",GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
switch ($value) {
    case 'prem_no':
        if ($country_code == 'US') { $prem_no = '888-888-8888'; }
        elseif ($country_code == 'AU') { $prem_no = '1900 000 000'; }
        else { $prem_no  = '0906 636 4355'; }
        return $prem_no;
        break;

    case 'prem_rate':
        if ($country_code == 'US') { $prem_rate = '$3.50'; }
        elseif ($country_code == 'AUS') { $prem_rate = '$3.96'; }
        else { $prem_rate  = '£1.53'; }
        return $prem_rate;
        break;

    case 'local_no':
        if ($country_code == 'US') { $local_no = '755-555-5555'; }
        elseif ($country_code == 'AUS') { $local_no = '1800 000 000'; }
        else { $local_no  = '0207 111 6311'; }
        return $local_no;
        break;

    case 'sms_no':
        if($country_code == 'AUS') { $sms_no = '1977 1977'; }
        else { $sms_no  = '78887'; }
        return $sms_no;
        break;

    case 'sms_rate':
        if($country_code == 'AUS') { $sms_rate = '25c'; }
        else { $sms_rate  = '£1.50'; }
        return $sms_rate;
        break;

    case 'helpline':
        if($country_code == 'US') { $helpline = '700-777-7777'; }
        elseif ($country_code == 'AUS') { $helpline = '1700 000 000'; }
        else { $helpline  = '0207 111 6210'; }
        return $helpline;
        break;

    default:
        break;
}
}

The file GeoIP.dat loads perfectly fine on every normal page, except when looking at the blog pages. (I'm assuming it must read functions differently or something? The error I get when trying to view the Blog loop articles is:

Warning: fopen(GeoIP.dat): failed to open stream: No such file or directory in C:\wamp\www\clairvoyant\wp-content\themes\clairvoyant\geoip.inc on line 314

then at the bottom of the trace table it says

Can not open GeoIP.dat

I just can't work out why it's working fine for normal pages, but not for blogs. Can anyone shed any light?
UPDATE:
It turns out Wordpress uses different pages for blog and normal pages. So I just needed to edit the other pages to match the initial ones, and it all seems to be working now.
Thanks for all of those who took the time to read my questions, sorry if it wasn't too clear or logical. But thanks anyway. All is good!


text:
Q: How to display web page properly on mobile So I have a table and an image, on pc It works fine, they are next to each other, but on mobile, the image should be under the table, but it either overlays the table or stays next to it. How can I fix this? I have made the table with bootstrap 4, which is required. I tried fixing the position of the table, but that overlays the image on top of the table, when I remove the fixing, they stay on the same row and you have to scroll left or right.
HTML:

DONNEES DE MARCHE

                    COURS
                    38,40
                    DATE
                    38,40

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

CSS:
body{
font-family: Helvetica, sans-serif;
background-color: rgb(38, 68, 105);
 }
#top_row h3{

color: rgb(71, 147, 176);
float: left;
}
#top_row h2{

padding-left: 20%;
float: center;

}
#top_row h5{

float: right;

}
#top_row{
clear: both;

}

}
#bottom_row{
clear: both;
}

#graph_img{

padding-left: 55%;
height: 400px;

}

#graph{
padding-top: 80px;
}

table{
font-size: 18px;
margin: 0;

}
img{
width: 100%;
}

.border-3{
border-width:3px !important;
}

A:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

DONNEES DE MARCHE

                    COURS
                    38,40
                    DATE
                    38,40

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

                    LOREM IPSUM
                    XX,XX
                    LOREM IPSUM
                    XX,XX

I have added the text-align property into the image style as well as the height to make it responsive and position into the code.


text:
Q: Handling transactions/data lost in ZeroMQ? I couldn't tell from looking at the FAQ and documentation. What happens if the power goes out? Does zeromq forget everything? Are all messages stored on the harddrive as transactions? Lets say I have a site with source code. Lets say 5 people clicked on download zip on 5 different large projects and it will take me a while to zip it. Lets say I forward them to a page saying we'll email you when it's ready. There is a power surge and the machine reboots at this point.
How do I recover and process these messages? In my head I think 1) I have to send the message 2) ZeroMQ must store it somehow 3) A client must take a message and mark it as pending 4) Another client should take a different message to work on 5) The client either finishes sending data/a reply or dies which zeromq changes pending to not-processed.
How do I handle data that shouldn't be lost? I don't think I'm suppose to store it in an ACID db?

A: ZeroMQ doesn't persist messages to a storage device, partly because that would be very inefficient, so you must handle this yourself.
If a downstream connection dies (loss of power, network failure, etc) then ZeroMQ will buffer the data until the connection is restored. However, buffer space is finite, and depending on your throughput, may not be at all sufficient. The company I work for needed to solve this problem, so we used a memory mapped file for buffering data, which works very well.
Your best option to avoid any kind of data loss is probably to take a similar route to what we did. Using request / reply is the best way to guarantee that a sent message was received downstream.
If data loss is mission critical then there are a bevy of UPS solutions that can help mitigate power outages, and as long as the program and the memory are kept alive, ZeroMQ is generally very good at handling error scenarios.


text:
Q: Problem Updating Item of a Certain Content Type (deriving from Folder) I'm encountering some problems updating some items in my Event Handler.
I have a Document Library in which I have folders, items and folder of content type PRATICA, which derives from folder and has the same attribute of the other items in the list.
So... The code I've written is invoked by an Event Handler and want to apply mods on all items under a certain folder..
This works for items (like files etc). When it analize a SubFolder and find it of the right content type tries to modify the column but no modify has been applied (without exception and debugging every instruction is passed!!)
Any suggesion?
Thank you!
private void RecursiveUpdateItemCliente(SPFolder folder, string RagioneSociale, Guid fieldRS)
   {
       foreach (SPFile spfile in folder.Files)
       {
           this.EventFiringEnabled = false;
           spfile.Item[fieldRS] = RagioneSociale;
           spfile.Item.SystemUpdate();
           this.EventFiringEnabled = true;
       }

       foreach (SPFolder spfolder in folder.SubFolders)
       {
           if ((spfolder.Name != "Forms") && (spfolder.Item.ContentTypeId.IsChildOf(new SPContentTypeId(PRATICA))))
           {
               this.EventFiringEnabled = false;
               folder.Item[fieldRS] = RagioneSociale;
               folder.Item.SystemUpdate();
               this.EventFiringEnabled = true;
           }
           RecursiveUpdateItemCliente(spfolder, RagioneSociale, fieldRS);            }
   }

A: private void RecursiveUpdateItemCliente(SPFolder folder, string RagioneSociale, Guid fieldRS)
 {
     foreach (SPFile spfile in folder.Files)
   {
       this.EventFiringEnabled = false;
       spfile.Item[fieldRS] = RagioneSociale;
       spfile.Item.SystemUpdate();
       this.EventFiringEnabled = true;
   }

   foreach (SPFolder spfolder in folder.SubFolders)
   {
       if ((spfolder.Name != "Forms") && (spfolder.Item.ContentTypeId.IsChildOf(new SPContentTypeId(PRATICA))))
       {
           //I MUST GET SPFOLDER and NOT folder element...
           this.EventFiringEnabled = false;
           spfolder.Item[fieldRS] = RagioneSociale;
           spfolder.Item.SystemUpdate();
           this.EventFiringEnabled = true;
       }
       RecursiveUpdateItemCliente(spfolder, RagioneSociale, fieldRS);            }

}


text:
Q: inputText and convertDateTime error I have an h:inputText field which I use to enter a date. I am using the f:convertDateTime but I get errors.
Here is the situation:
<h:inputText value="#{listModel.creationDate}" valueChangeListener="#{listController.filterFieldChanged}">
    <f:convertDateTime type="date" pattern="yyyy-MM-dd"/>
</h:inputText>

If I enter "2011-11-23" I get the following error:

"...[exec] sourceId=j_idt3[severity=(ERROR 2), summary=(Conversion Error setting value 'Wed Nov 23 01:00:00 CET 2011' for 'null Converter'. ), detail=(Conversion Error setting value 'Wed Nov 23 01:00:00 CET 2011' for 'null Converter'. )]|#]"  (besides, where does 01:00:00 come from??)

If I remove the type="date" and leave only pattern="yyyy-MM-dd" and enter the same date, I get the same error.
If I remove the pattern and leave only type="date" and enter the same date, I get the following error:

"[exec] sourceId=searchForm:j_idt72[severity=(ERROR 2), summary=(searchForm:j_idt72: '2011-11-23' could not be understood as a date.), detail=(searchForm:j_idt72: '2011-11-23' could not be understood as a date. Example: 23.11.2011 )]|#]"

I am a little confused. If I define the pattern yyyy-MM-dd why "2011-11-23" isn't accepted?
Info added:
value="#{listModel.creationDate}"
public Date getCreationDate()
{
    return creationDate;
}

This is the getter for creationDate in the class ListModel. (it is a java.Util.Date)
valueChangeListener="#{listController.filterFieldChanged}"
public void filterFieldChanged( ValueChangeEvent event )
{
    // Note: value change events are handled in the PROCESS_VALIDATIONS
    // phase by default. The problem is that the model values are not
    // updated until later, so any changes we make here would normally be
    // overwritten.
    // By requeueing the event and targeting it to the UPDATE_MODEL_VALUES
    // phase we can make the model changes without them being overwritten.
    if ( event.getPhaseId().equals( PhaseId.ANY_PHASE ) )
    {
        event.setPhaseId( PhaseId.UPDATE_MODEL_VALUES );
        event.queue();
    }
    else
    {
        // reset the paging any time a filter field was changed
        listModel.setFirstResult( 0 );
    }
}

I hope this is useful...


text:
Q: Find place for callback function I can't find where i can put my own code on resize and reposition. I need to find where to insert the callback, this is the only bit i should be looking at and i just can't find where to insert the callback function on resize
  $.Isotope.prototype._getCenteredMasonryColumns = function() {
    this.width = this.element.width();
    var parentWidth = this.element.parent().width();

    // i.e. options.masonry && options.masonry.columnWidth
    var colW = this.options.masonry && this.options.masonry.columnWidth ||
    // or use the size of the first item
    this.$filteredAtoms.outerWidth(true) ||
    // if there's no items, use size of container
    parentWidth;

    var cols = Math.floor( parentWidth / colW );
    cols = Math.max( cols, 1 );

    // i.e. this.masonry.cols = ....
    this.masonry.cols = cols;
    // i.e. this.masonry.columnWidth = ...
    this.masonry.columnWidth = colW;
  };

  $.Isotope.prototype._masonryReset = function() {
    // layout-specific props
    this.masonry = {};
    // FIXME shouldn't have to call this again
    this._getCenteredMasonryColumns();
    var i = this.masonry.cols;
    this.masonry.colYs = [];
    while (i--) {
      this.masonry.colYs.push( 0 );
    }
  };

  $.Isotope.prototype._masonryResizeChanged = function() {
    var prevColCount = this.masonry.cols;
    // get updated colCount
    this._getCenteredMasonryColumns();
    return ( this.masonry.cols !== prevColCount );
  };

  $.Isotope.prototype._masonryGetContainerSize = function() {
     var unusedCols = 0,
    i = this.masonry.cols;
    // count unused columns
    while ( --i ) {
      if ( this.masonry.colYs[i] !== 0 ) {
      break;
    }
    unusedCols++;
  }

   return {
      height : Math.max.apply( Math, this.masonry.colYs ),
      // fit container to columns that have been used;
      width : (this.masonry.cols - unusedCols) * this.masonry.columnWidth
    }
   };

Any idea?

A: Solution was to simply do a window.resize an apply a timer in it:
 var delay = (function(){
   var timer = 0;
   return function(callback, ms){
     clearTimeout (timer);
      timer = setTimeout(callback, ms);
   };
 })();

 $(window).resize(function() {
   delay(function(){
     if ($("#head").width() != $("#container").width()){
        var myLeft = $("#container").offset().left;
        var newWidth = $("#container").innerWidth();
        var myRight = $("#container").offset().left + $("#container").outerWidth();
        $("#head").animate({ width: newWidth, marginLeft: myLeft, marginRight: myRight }, "fast");
    }
  }, 800);
});


text:
Q: Error while comparing data fetched from the table I am not sure what's wrong, but it gives the error message- Error1: "Notice: Undefined index: user_type" and Error2: "Notice: Undefined index: user_approved", while there exists a table userdetails which has columns with the name user_type and user_approved.
NOTE: The code may be incomplete, but it has nothing to do with the error, I have only pasted the code for reference, the concern is the error.
 if(isset($_POST['login_btn'])){

                // define variables and set to empty values
                $email = $pwd = "";
                $query1 = $result1 = "";
                $error = FALSE;
                $usertype = $status = "";
                $combo = FALSE;

                $email = validate_input($_POST['user_name']);
                $pwd = validate_input($_POST['user_pwd']);

                include_once("includes/connection.php");

                $query1 = "SELECT * FROM userdetails WHERE user_email='$email' AND user_pwd='$pwd'";

                $result1 = mysqli_query($con,$query1);

                if (!$result1) {
                    echo 'Could not run query: ' . mysql_error();
                    exit;
                }
                else{
                    while($array1= mysqli_fetch_row($result1)){
                        $combo=TRUE;
                        $usertype=$array1['user_type']; **//Error1**
                        $status=$array1['user_approved']; **//Error2**
                    };
                }

A: If you want to use the name of the table columns in your $array1 you have to use
$array1 = mysqli_fetch_assoc($result1)

A: Better use mysqli_fetch_assoc()
eg:
while($array1= mysqli_fetch_assoc($result1)){
   $combo=TRUE;
   $usertype=$array1['user_type']; **//Error1**
   $status=$array1['user_approved']; **//Error2**
};

For your question, see http://php.net/manual/en/mysqli-result.fetch-row.php

Fetches one row of data from the result set and returns it as an
  enumerated array, where each column is stored in an array offset
  starting from 0 (zero). Each subsequent call to this function will
  return the next row within the result set, or NULL if there are no
  more rows.

So it stored as index as 0, 1, 2 etc...
while($array1= mysqli_fetch_row($result1)){
   $combo=TRUE;
    $usertype=$array1[0];
    $status=$array1[1];
};

See http://php.net/manual/en/mysqli-result.fetch-row.php

A: mysqli_fetch_row return  result row as an enumerated array
you can use mysqli_fetch_assoc to get
while($array1= mysqli_fetch_assoc($result1)){

A: select the exact columns in query instead of * and then use below.
$usertype=$array1[0];
 $status=$array1[1];
Or you need to use the index of those columns for e.g. if thye are 3rd and 4th columns of your sql result then use $array1[2] and $array1[3]


text:
Q: iisnode does not store cookie in Chrome I have an nodejs/expressjs Web API project setup that works perfectly fine when I test locally. But when I test by making a request to the API hosted in IIS, Google Chrome doesn't save the cookie. Otherwise with Firefox, where I make a request to log in, but it does not save the cookie, however I can request resources protected by authentication. With Postman, I have no problem.
   <system.webServer>
   <handlers>
      <add name="iisnode" path="app.js" verb="*" modules="iisnode" />
    </handlers>
     <rewrite>
       <rules>
         <rule name="api">
           <match url="api/*" />
           <action type="Rewrite" url="app.js" />
         </rule>
       </rules>
     </rewrite>
     <iisnode
       enableXFF="true"
       nodeProcessCommandLine=""%programfiles%\nodejs\node.exe""
       interceptor=""%programfiles%\iisnode\interceptor.js"" />
    <httpErrors existingResponse="PassThrough" />
   </system.webServer>
</configuration>

This is the app.js
app.set('trust proxy', 1)
app.use(
    cors({
        credentials: true,
        origin: true
    })
);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(keys.mongodb.dbURI, { useNewUrlParser: true });

app.use(session({
    proxy: true,
    secret: keys.session.cookieKey,
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 1 * 60000, httpOnly: false },
    store: new MongoStore({
        mongooseConnection: mongoose.connection
    })
}));

This is a portion of code making a post request to iisnode
      axios.defaults.withCredentials = true;
      axios
        .post("http://xxx.xxx.xxx.xxx//api/login", {
          email: this.email,
          password: this.password,
          withCredentials: true
      })
   .then(response => {


text:
Q: How do I map a SQL Server login to a user that already exists in a read-only database? One of our database users complains that they can't select from one of the databases in this particualr instance while they have no problems in accessing others in this very same instance. The one that they have access problems is shown as "Standby / Read-Only". The others are just normal.
So, I checked the Security -> Logins for the given principal and looked at the principal's properties to see if there were any user mappings to the read-only database for this login. There were no such mappings for that particular db while there were mappings for other databases and all with "db_datareader" role membership. Initially, I wanted to add a user mapping for this db as well; However, it failed with the below message:

"Failed to update database X because the database is read-only"

Then, I checked the read-only database and found that a user exists in there with the same name as the account that had this issue. It also had "db_datareader" role membership. So, I guess I just need to link the two; however, I don't know how. Please help me! Thanks.

A: Since the status of the database is Standby, I'm assuming this database is a Log Shipping secondary. If that's the case, the database cannot be written to at all on the secondary (making it writable would break Log Shipping).
Also, since you said that other databases (presumably not read-only) have correct mappings, I'm assuming you're using a SQL login. If that's the case, all you should have to do is recreate the login on the secondary server using CREATE LOGIN ... WITH SID to match the SID from the primary (look in sys.server_principals on the primary server to find it).
On the other hand, if you're using Active Directory for the login, you'll have to add the user principal to the primary database so that when it comes across to the secondary in a log backup, there's no need to do any remapping (note: depending on the situation, this may be a lot easier said than done!).

A: running this will normally map SQL user SPIDs but you will need to make the DB read/write for a while, preferably in single user mode.
Declare @SQL nvarchar(max)
Declare @Database nvarchar(max)

Declare @DBs table
(DBName nvarchar(100))

Declare @Databases varchar (max)
set @Databases = ''

select @Databases = coalesce (case when @Databases = ''
                            then name
                            else @Databases + ',' + name end,'')

from sys.databases Where database_id > 4 and name not like '%$%'
and name in ('MyDatabase')

Set @SQL = 'Select ''' + Replace(@Databases, ',', ''' Union Select ''') + ''''

Insert into @DBs
EXEC SP_ExecuteSql @SQLToExecute = @SQL

Declare @Logins table
(DB varchar(100)
,UserName sysname
,UserSID varbinary(85))

Declare @TempLogins table
(UserName sysname
,UserSID varbinary(85))

---
While Exists(Select * From @DBs)
Begin
    Set @Database = (Select Top 1 DBName From @DBs)

    Print 'Checking ' + @Database
    Set @SQL = 'exec [' + @Database + ']..sp_change_users_login @Action=''Report'' '

    Delete From @TempLogins
    Insert into @TempLogins
    EXEC SP_ExecuteSql @SQLToExecute = @SQL

    Insert into @Logins
    Select @Database, l.*
    From @TempLogins l

    Delete From @DBs Where DBName = @Database
End

Declare @User nvarchar(100)

While Exists(Select * From @Logins)
Begin
    Select Top 1 @Database = DB, @User = UserName From @Logins

    Set @SQL = 'exec [' + @Database + ']..sp_change_users_login @Action=''Auto_fix'', @UserNamePattern = ''' + @User + ''' '

    Begin Try
        EXEC SP_ExecuteSql @SQLToExecute = @SQL
        Print 'Mapped ' + @User + ' in ' + @Database
    End Try
    Begin Catch
        Print 'Failed to map ' + @User + ' in ' + @Database
    End Catch

    Delete From @Logins Where DB = @Database and UserName = @User
End

Or you could remove the user from the DB and re-map it.


text:
Q: gRPC forking in Python + server-client implemented in C++ with python bindings I have a server - client app written in C++ using gRPC C++ library.
My library has C++ bindings for Python API as well, using pybind11.
I know there is no support for c++ forking in gRPC but there is support for python forking, as explained in https://github.com/grpc/grpc/blob/master/doc/fork_support.md .
As far as I saw the env vars mentioned are used only in gRPC C
++ code.
If I am following the instructions of turning on the env vars in my CMakeLists:
export GRPC_ENABLE_FORK_SUPPORT=true
export GRPC_POLL_STRATEGY=poll

It does not solve the forking issue where I am getting into a deadlock once I forked. Is there a way to solve this issue and enable forking in python while the server-client is implemented in gRPC c++?
grpc version:  1.46.0
pybind11 version: 2.10.1


text:
Q: Sharepoint 2010 : web.ProcessBatchData is throwing the error i am facing an issue while trying to migrate the data from one list to other, the list is having custom columns which are of type "Single line of Text","Multiple line of Text","Person or Group","Datetime","Integer".
i am getting the below error after execution of the statement "Web.ProcessBatchData"
.....

The operation failed because an unexpected error occurred.
(Result Code: 0x80020005)
The operation failed because an unexpected error occurred.
(Result Code: 0x800704c7)

2147023673">
......
Can someone please help me to resolve the same.


text:
Q: local host site, outputting random text I started to do some updates to a site this morning, and when I went to run it, I am getting random text instead of the site.
The site is setup on a local url, mysite.local, with an entry in hosts to map it to my PC.
I have tried a "clean and rebuild" in VS, IIS Reset, Recycling the app pool, re booting the PC, and even creating a new entry in IIS, but nothing solves it.
It only appears to be happening on aspx pages, as I can load .htm pages without error.
I need to get some updates done today, so any help would be fantastic!
Here is the text it's outputting
���`I�%&/m�{J�J��t��`$ؐ@�������iG#)�*��eVe]f@�흼��{����{����;�N'���?\fdl��J�ɞ!���?~|?"��Ey�')=��y6�����h���ly���,�&?�O�t�-���7������bU���'/���lR��_�|�fm�&_��W���fmQ-��Ǐ� 0z�^��jv����j�n�g���~��O��,[f��Wyq1o-�z���QS� �����iUV��I�M���ԃ�z�>�EV_���Z=J���������T���������f�����Z���gir�k�ܷ ��ZPWu������e�   �tU� \g�a��_��y��� �J�����ߵ۳|Z��B��e��P�y��W�/�/��:l��uE})�'U�V�G����]�ݻU��e��F�v{^/gy]�{�#����.���u��su�S��]���U1�?��'賏��E�d�� B����w�^�5�;=������������������vwv~���ٮ��YS���������|�(}\|S�^a�{�c�� �Lϳi��G�u�����9!��Q�y��/�����u�l�_��2�Gi����.���&G�Ӽ���J8������2]/1#%�F�n��wi5�ɂ���u��H�yN��ӵ|{�pB�*��u���yӎӗe�59�}Y�Wܬi�_Ӷ������")���*�M�u+]��6��^ξ��K��-ۄ������[u�j�ܢ�?���eA��v����hp�t1�6��|x����ٚѯ�[���.i�����bU���f]���6����M���<|x�40b�gŲh��,ǹ���A���ClY�y��_2�����t���������$h�[��홈�zD�pM���ziI��f��r*��=|x��!��b�$\�����ҧ�c�(����w<[�y��JE�E���u^_o��v:A���l���M��X�����M�u���x���|2~�7�S�{�613C�   L �h�C��Š�䧍��r�i4��)�����   �����?�����;����-%q1�����buHF,I����:��j ��*g����#MW�m�̷�ݶ+��;yO��N60�Ì���C�:!����!�.�+����nF����j�.sR��&�e4�B�����踾h���F�>�{�-��W�.���ϲ�rk~�.��F���6�ʭ1��pUn�y�Q��yK�u}�����ug�V7:2���z��qanD��p`"�t�oΝ�Eg��f�<��8��>�P=�j

The latest thing I have tried is to bring down the code from svn into a brand new folder, create a new entry in IIS and point at this. I am still getting the same issue after this!!
Also, other sites running locally are not getting the error.

A: Looks like you have enabled gzip.
In your Application_Error make sure you remove the custom response filter:
protected void Application_Error(Object sender, EventArgs e)
{
    HttpApplication app = sender as HttpApplication;
    app.Response.Filter = null;
}

Rick Strahl described the problem in more details in his blog post.

A: Right, problem solved!
I turned out to be an issue with my session tables.
I followed the steps outlined in this post, and it solved my problem:
http://forums.asp.net/t/1313929.aspx/1


text:
Q: Killing a JavaScript function which runs infinite As an example
var runInfinite = function(){
    while(1)
    {
       // Do stuff;
    }
};

setTimeout(runInfinite, 0);

Is it possible to break this runInfinite function form running infinite? I mean is it possible to kill this function from another function without using a flag or return statement?

A: The answer is no. Since JavaScript is single-threaded ( unless you are using some less common implementation which I doubt ) nothing can break a loop ( or any other block of code ) from outside.

A: There is no direct way to "kill" a running javascript function.
Possible workaround, although you need to replace the while(1) loop:
var i = 0; // for testing purposes

var toCall = "runInfinite()";
function runInfinite(){
    // do stuff
    console.log(i++);
    setTimeout(function(){ eval(toCall); }, 100); // or whatever timeout you want
}

setTimeout(function(){ eval(toCall); }, 0); // start the function
setTimeout(function(){ toCall = ""; }, 5000); // "kill" the function

I know using eval() is considered to be bad practice, however the idea should be clear. The function calls itself (not recursive, therefore the setTimeout()) using the toCall variable. Once this variable is unset, you kill it from outside.
You could wrap these variables and functions in a class so you can implement your "kill" function.

A: I've just tested on my browser.
AFAIK, the while(1) block will literally block the thread and not allow anything else to run. I don't have sources other than experience, but using the Chrome developer toolkit thing ctrl+shift+i typing while(1){} will block everything else due to the fact that browser-javascript is single threaded.
However, if you're using node.js, you may be able to as it has multithreading capabilities.  If anyone is familiar enough with node.js and is willing to answer/edit, go for it.  I've never quite used it.

A: The whay you want not really. But maybe you're doing it wrong. Try not to use while(1) if possible and at the end of the function call the function again if the outside flag triggered but some break button is not set, or return if otherwise

A: I admit this is not exactly the same, but, there are the Javascript generators and Javascript iterators in ECMA-262. If you can replace your function with a generator function, then, you can implement the breakable feature easily.

function execWithTimeout(iter, timeout = 100) {
    const limit = Date.now() + timeout
    for (const output of iter) {
        console.log(output)
        if (Date.now() > limit) throw(new Error("Timeout reached"))
    }
}

let runInfinite = function * () {
    let i = 0
    while (1) {
        yield i++
    }
}

execWithTimeout(runInfinite())

A: return  can be used to stop a function from its current execution but not in your case.
In your case you could try  to your function are wrapped in a try / catch block, you can find it out when your function gonna infinite ,based on that you can terminate its current execution.


text:
Q: First argument of bash is different when parameter is passed or not There are two bash usages:
$ bash -c 'echo $0'
bash

$bash -c 'echo $0' "text"
text

Why in the first case parameter $0 holds the program name but in second the first parameter?

A: Per the bash man page:

   -c        If the -c option is present, then commands are read from  the
             first non-option argument command_string.  If there are argu‐
             ments after the command_string,  they  are  assigned  to  the
             positional parameters, starting with $0.

And further down:

   If arguments remain after option processing, and neither the -c nor the
   -s option has been supplied, the first argument is assumed  to  be  the
   name  of  a file containing shell commands.  If bash is invoked in this
   fashion, $0 is set to the name of the file, and the positional  parame‐
   ters  are set to the remaining arguments.

In short, $0's behaviour varies depending on how bash is invoked.


text:
Q: function to calculate Target after joining ration from other data farame I Have two data frames for is sales data with many different columns and another is incentive scale data .
I am trying to map scale against goals in sales data , then I am trying to recalculate Target columns against incentive scale . but unable to create the perfect logic to do this .
df <- data.frame(Name = c("ABC",    "DCA",  "GOL",  "LAM",  "MNA",  "BVA",  "VAN"),
                 Goal =c("published",   "pending",  "not designed",NA,  "pending",  "pending",  "not designed"),
                 Target_1 = c(3734, 2639,   2604,   NA, 2793,   2688,   2403),
                 Target_2 = c(3322, 2016,   2310,   NA, 3236,   3898,   2309),
                 Target_3 = c(3785, 2585,   3750,   NA, 2781,   3589,   2830))

df1 <- data.frame(Goals = c("published",    "pending",  "not designed"),
                  Incentive =c(1.4,1.1,0.5))
df <- left_join(df,df1,by=c("Goal"="Goals")) %>% relocate(Incentive,.after = Goal) %>%
  mutate(colnames(contains("Target")) =  colnames(contains("Target"))*Incentive)

A: You can use across -
library(dplyr)

left_join(df,df1,by=c("Goal"="Goals"))  %>%
  mutate(across(contains("Target"), ~. * Incentive))

#  Name         Goal Target_1 Target_2 Target_3 Incentive
#1  ABC    published   5227.6   4650.8   5299.0       1.4
#2  DCA      pending   2902.9   2217.6   2843.5       1.1
#3  GOL not designed   1302.0   1155.0   1875.0       0.5
#4  LAM         <NA>       NA       NA       NA        NA
#5  MNA      pending   3072.3   3559.6   3059.1       1.1
#6  BVA      pending   2956.8   4287.8   3947.9       1.1
#7  VAN not designed   1201.5   1154.5   1415.0       0.5


text:
Q: Create JUnit test for a method covering all its invocations in Eclipse workspace Lets assume following Java class:
class MyClass {
   public String methodA( String data, String expression ) {
      // expression is evaluated using data
      // ...
      // this leads to a result which is returned
      return result;
   }
}

Note, that expression is an instance of an expression language (DSL). Thus, the evaluation of expression using data depends on the combination of both. Normally, expression is a fixed value which does not change often and data can change throughout all invocations.
Well, sometime later a bug is found in MyClass.methodA(String,String). The bug resides in some underlying class and only occurs for some special combination of expression and data. A JUnit test is easily written for this special case and can be fixed.
Unfortunately, this method is used frequently across the whole project. Eclipse call hierarchy identifies more than 97 other methods where this method is used. I now fear regression, if I just apply the bugfix. To feel more safe, I would like to do some regression testing.
Normally, unit tests should consider all important types of invocations, especially border cases. But, as expression is a DSL which can vary highly, it's not easy to test-cover all potential usage. Additionally, those tests would not identify false usage relying on the bug.
So my idea is to proceed in the following way:

*

*Find all invocations of this method (like using "Call hierarchy" in Eclipse) and extract all the values for expression.

*Sample enough real-life values for data (e.g. from database) and cross-evaluate all expressions from the first step on it using the original version of MyClass.methodA(String,String). Save the triples (data, expression, result) to a file.

*Implement bugfix.

*Test method MyClass.methodA(String,String) using the above file to assert that the results have not changed.
Following questions:
What do you think of this approach?
Using call hierarchy in Eclipse I can only copy and paste the calling methods but not the exact invocation including arguments to clipboard (cf. step 1). I would have to copy the invoking call by hand for each method found. How do I extract the invocations in a convenient way (in the complete Eclipse workspace, thus in several projects)?
IMHO I am only testing one single method, thus the tests covers only one unit. Is it ok to use JUnit for step 4 or is there something more sophisticated?

A: As the expected additional value by Testing your software is to cover the most circumstances with lowest costs and maximum outcome, I would agree with your approach.
Collecting reallife samplevalues from your software and save them to a representative file should not be that complex to realize and seems to me as the best way to analyze this thing. Even if you have to copy it manually.


text:
Q: Image getting cached in Angular I am using angular version 9. I have 2 components. 1 to search a car make, model and 2nd component to load the details of the car that is selected from component 1. I pass the image link for the car from the car that is selected from component 1 to component 2 and load that image in component 2. This works fine..
When I browse to some other page in my application and again go to the component 1 and select a different car and go to component 2, the image of the previously selected car shows for around 1-2 seconds and then my new image is shown. This looks like a browser caching problem. I have tried to load a loader image initially till my new image completes loading and then show the newly loaded image but it does not work. What I have tried is as below.
<img *ngIf="isLoading" [src]="loadingimage.png" />
<img [hidden]="isLoading" [src]="carModelImage" (load)="isLoading = false"/>

What I have noticed is, the moment component 2 is opened the (load) event on the img tag fires and changes the isLoading value to false even without waiting for the new carModelImage to load and thus the previous image shows for some time.
My component code looks like below.
@Component({
selector: 'app-request-summary',
templateUrl: './request-summary.component.html',
styleUrls: ['./request-summary.component.scss']
})

export class RequestSummaryComponent implements OnInit, OnDestroy {
    public carModelImage: string = '';
    public isLoading: boolean = true;

   constructor() {
     this.carModelImage = '';
     this.isLoading = true;
   }

   ngOnInit() {
   this.requestSummaryService.carData
    .pipe(takeUntil(this.ngUnsubscribe))
    .subscribe((data) => {
      this.carModelImage = data[0].carModelImage ? data[0].carModelImage
      :'http://nocarimage.png';
    }
   }

   ngOnDestroy() {
     this.isLoading = true;
     this.carModelImage = '';
     this.ngUnsubscribe.next();
     this.ngUnsubscribe.complete();
   }
}

I am struglling due to this issue since quite a long. Any help will be highly appreciated.

A: Well, I don't have much to go on here, but I'll share a simple pattern with you.
When your image is no longer being displayed null it out.
For example somewhere in your code you probably write this:
carModelImage = "your-image";

When you are sure you no longer need this var anymore, null it out.
carModelImage = null;

Post more code if you want help specific to your issue.

A: How do you assign carmodelImage variable . The carmodelImage is responsible for showing the previous image,  if you could nullify it on destroy may be it should help
Assuming you said ngondestroy is being called


text:
Q: GNU Parallel not work (parallel_20120422-1_a in Ubuntu 16.04.5)
*

*I use parallel_20120422-1_a in Ubuntu 16.04.5. It was used to run very well.

*But recently, even "parallel --version" dose not work. After I typed "parallel --version" and return, no response at all and stuck.

*I re-install parallel_20120422-1_a again "sudo apt install parallel".
It dose the same. Might anyone provide me some suggestions to fix this? Thank you very much!


text:
Q: Making line graphs in black and white Say I'm making a line graph with about ten lines or so, and I want each line to be distinguishable in black and white.  Is there a way to "automatically" give each grouping a different line structure (i.e. dashed, dotted, thickness), similar to how you could do the same thing with different colors?  It doesn't matter what these are, just something to make them distinguishable.
Edit: I'm looking for something a little better than
aes(linetype=group)


text:
Q: How to create Skewed transition effect on hover as moving water? can somebody help me to create slider with ripple effect like this. as you slide hover horizontally, it ripple. I need it exact.

this


text:
Q: Django Migrations not detecting is_active column I created a custom user model using the AbstractBaseUser class (see source code below). However, after realising that the column I needed in the table should be called "is_active" not "active", I renamed the column in the models file, however, the migrations only removed the "active" column but didn't create an "is_active" column. Any ideas?
class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(max_length=50, null=True)
    last_name = models.CharField(max_length=100, null=True)
    is_active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)  # a admin user; non super-user
    date_joined = models.DateTimeField(auto_now_add=True)
    manager_access = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    # Email & Password are required by default.
    REQUIRED_FIELDS = ['first_name', 'last_name']
    objects = UserManager()

    def get_full_name(self):
        return self.first_name + self.last_name

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.is_superuser

    @property
    def is_active(self):
        "Is the user active?"
        return self.is_active

A: I ended up removing this chunk of code:
  @property
def is_active(self):
    "Is the user active?"
    return self.is_active

After doing this and rerunning the migrations, the is_active column was added.


text:
Q: mySql is not creating new table on the fly Why do I need to reload / refresh / run this script TWICE
to get the new table under the new database that have just been created ?
IOW... This script is working perfectly but not on first run.
Only after refresh it creates the new table.
<?php

$dbhost = '127.0.0.1';
$dbusername = 'root';
$dbuserpass = '';
$dbname = 'newDatabase';

$link_id = mysql_connect ($dbhost, $dbusername, $dbuserpass);
if (!mysql_select_db($dbname, $link_id)){mysql_query('CREATE DATABASE '.$dbname, $link_id);}

$sql = "CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(255) NOT NULL default '',
`email` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8";

mysql_query($sql);

?>

A: Probably, if the database didn't exist then it wouldn't select it so the CREATE TABLE would fail.
Try changing the $sql query to:
$sql = "CREATE TABLE IF NOT EXISTS `" . $dbname . "`.`users` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(255) NOT NULL default '',
`email` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8";

EDIT:
As others have suggested, another possible solution would be to call mysql_select_db (or your your favourite newer alternative to the mysql_* functions) but this involves more data transfer to the database so using this method will be slightly more efficient. Although that efficiency will be negligible in this scenario probably!

A: When the mysql_select_db errors because the database doesn't exist, the CREATE DATABASE statement is executed.
Following that, there's no second call to mysql_select_db to change to the newly created database.
The CREATE TABLE statement is likely encountering a "no database selected" type error.
Those calls to mysql_query can raise SQL errors; it's a good idea to check for successful completion, rather than just assuming that everything went to plan.

And, for the love of all that is good and beautiful in this world, don't use the mysql_ interface for new development. Use mysqli or PDO instead.

A: <?php

$link_id = mysql_connect ($dbhost, $dbusername, $dbuserpass);
if (!mysql_select_db($dbname, $link_id)){
mysql_query('CREATE DATABASE '.$dbname, $link_id);
mysql_select_db($dbname, $link_id); //add this
}

You basically create the database (when it doesnt exist) but dont then connect to it te first time around - adding that line should fix it.


text:
Q: Запретить повторную отправку формы На странице имеется форма добавления информации о себе, которая отправляется на сервер Ajax'м.
При успехе на страницу возвращается alert уведомление. Если нажать снова кнопку "Отправить", эта форма повторно добавится в БД и так далее.
Что можно в этом случае сделать?
A: На выбор:

*

*
После нажатия на кнопку "отправить" блокировать ее до получения ОТРИЦАТЕЛЬНОГО ответа от сервака или редактирования формы.

*
После успешной отправки очищать форму.

*
После отправки переводить форму из состояния create в состояние update.

*
Проверять дубликаты в бд при добавлении.

*
Редиректить на страницу просмотра добавленной записи, а уже там выдавать сообщение.

Есть еще пара способов, типа передавать уникальный код транзакции, чтобы наверняка определить отправку одних и тех же данных, но они сложнее в реализации.
A: От хороших идей к худшим:

*

*скрыть форму;

*выполнить reset для формы;

*установить disabled = true для кнопки type="send" после отправки, и в случае ошибки disabled = false;

*установить disabled = true для кнопки type="send" после успешного получения ответа;

*проверять дублирование данных.

Но идеально будет дисаблить кнопку после нажатия, если возникнит ошибка раздисаблить, если успешно, скрыть форму и показать типа "спасибо" или что вы там в алерте выводите.


text:
Q: how to open browser in action result? i have a action tresult method and in it i want to open a url in new window or new tab how can i handel it ?
in my code it works not i mean redirect it to member account and do not open my url
public ActionResult myactionresult()
    {
         Response.Write("<script language=\"javascript\">");
         Response.Write("window.open('" + "http://www.xxx.com" + ,'_blank')");
         Response.Write("</script>");

       return RedirectToAction("Index", "MembersAccount");
      }

A: Try this instead :
Controller
public ActionResult myactionresult()
{
    String jScript = String.Empty;
    jScript = "<script language=\"javascript\">";
    jScript += "window.open('http://www.xxx.com' ,'_blank')";
    jScript += "</script>";

    ViewBag.jScript = jScript;

    return RedirectToAction("Index", "MembersAccount");
}

View : Any where in view's body
@ViewBag.jScript

This will fix your problem;


text:
Q: Tab files into pandas dataframe according to columns with missing headers How can I turn a tab file, with empty columns headers, into a dataframe?  More specifically, how can I fill this dataframe only with values that correspond with a letter in the adjacent unlabeled column, in this case 'P'?
This is a representation of the tab file I'm using.  Note the lack of headers over the A or P columns.
gene   cell_1      cell_2
MYC    5.0     P   4.0     A
AKT    3.0     A   1.0     P

The desired dataframe would look like this:
gene   cell_1   cell_2
MYC    5.0      NaN
AKT    NaN      1.0

What is the best way to tackle this problem using pandas?

A: For your example data, pandas's read_fwf() function (for "fixed-width format") does a good job of guessing the columns:
s = """gene   cell_1      cell_2
MYC    5.0     P   4.0     A
AKT    3.0     A   1.0     P"""

import pandas as pd
from io import StringIO
in_file = StringIO(s)

pd.read_fwf(in_file)
Out[6]:
  gene  cell_1 Unnamed: 2  cell_2 Unnamed: 4
0  MYC     5.0          P     4.0          A
1  AKT     3.0          A     1.0          P

A: # Read the dataframe.
filename = '...'
df = pd.read_csv(filename, skiprows=1, header=None, sep=" ", skipinitialspace=True)
df = df.rename(columns={0: 'gene', 1: 'cell_1', 2:'a_p', 3: 'cell_2', 4: 'p_a'})

# Changes adjacent 'A' values to NaN.
df.loc[df.a_p == 'P', 'cell_2'] = None
df.loc[df.p_a == 'P', 'cell_1'] = None

>>> df[['gene', 'cell_1', 'cell_2']]
  gene  cell_1  cell_2
0  MYC       5     NaN
1  AKT     NaN       1

A: I tried to implement a few different approaches that show fancy indexing and masking methods. Let me know if you have any questions
#Load Data
string_data = "gene cell_1  cell_2 \nMYC 5.0 P 4.0 A\nAKT 3.0 A 1.0 P"
A_pre = np.array([row.split(" ") for row in string_data.split("\n")])
DF_data = pd.DataFrame(A_pre[1:,1:],
                       index=pd.Series(A_pre[1:,0],name=A_pre[0,0]),
                       columns=A_pre[0,1:])

A_data = DF_data.as_matrix() #Set the data array b/c it's quicker to slice than DF
rowLabels, colLabels = DF_data.index, DF_data.columns

# #Get blank columns
gene_idx = np.where(np.array(colLabels) != "")[0] #Used later
numColBlank = len(colLabels) - len(gene_idx)

# #Placeholder to fill
DF_placeholder = pd.DataFrame(np.zeros((DF_data.shape[0],DF_data.shape[1] - numColBlank)),
                              index = DF_data.index,
                              columns = DF_data.columns[gene_idx]
                              )
DF_data

#Populate matrix
query = "P"
for i in range(DF_data.shape[0]):
    for j in range(DF_data.shape[1]):
        if colLabels[j] == "":
            if A_data[i,j] == query:
                cell = colLabels[j-1]
                gene = rowLabels[i]
                metric = A_data[i,j-1]
                DF_placeholder.loc[gene,cell] = metric

#I just found out about masks they are useful
mask = DF_placeholder == 0.0
DF_placeholder[mask] = np.nan
DF_processed = DF_placeholder
DF_processed


text:
Q: Warning: Can't perform a React state update on an unmounted component , method needs to run only one time I'm trying to fetch the advertisers list when the component mounts, but it is causing me memory leak,
Any suggestions ? i'll be grateful :)
 useEffect(() => {
    const fetchData = async () => {
      const list = await Api.listAdvertisers();
      setAdvertisers(list);
    };
    fetchData();
  }, []);

A: You can declare your fetchData function on main scope and you can check the function if it is called or not by declaring a didMount variable in useEffect scope.
const didMount = useRef(false);

const fetchData = async () => {
      const list = await beeswaxService.listAdvertisers();
      setAdvertisers(list);
      return;
    };

useEffect(() => {
    if(!didMount.current){
       didMount.current = true;
       fetchData();
    }

  }, []);

A: Maybe the function inside the useEffect is causing memory leak, try this?
const fetchData = async () => {
      const list = await beeswaxService.listAdvertisers();
      setAdvertisers(list);
      return;
    };

useEffect(() => {
    fetchData();
  }, []);


text:
Q: How to sort string with mixed characters Please check code bellow:
https://codepen.io/Whity/pen/XWNVqvP?editors=1010;
Result:
[">20Y", {…}]
["5Y", {…}]
["6M", {…}]
["7Y", {…}]
["10Y", {…}]
["14D", {…}]
["15Y", {…}]
["20Y", {…}]

I need to have the element with the '>' symbol last, not first. How can I achieve that?

A: You could sort by numbers and if a comparison sign is available, then take for the same numerical value the delta of both offsets, which reflects the order of comparison, see my answer with comparison signs.
To get numerical value, just get the digits from the string.

const
    data = [[">20Y", {}], ["5Y", {}], ["6M", {}], ["7Y", {}], ["10Y", {}], ["14D", {}], ["15Y", {}], ["20Y", {}]];

data.sort(([a], [b]) => {
    function getV(s) {
        return {
            value: s.match(/\d+/),
            offset: { '<': -2, '<=': -1, null: 0, '>=': 1, '>': 2 }[s.match(/[<>]={0,1}(?=\s*\d)/)]
        };
    }
    var aa = getV(a),
        bb = getV(b);

    return aa.value - bb.value || aa.offset - bb.offset;
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: When using dictionaries doesn't really make sense to sort by keys, but here you go.
var data = {
  "6M": {},
  "14D": {},
  "7Y": {},
  "10Y": {},
  "5Y": {},
  "15Y": {},
  ">20Y": {},
  "20Y": {}
};

function sortOnKeys(dict) {
    var sorted = [];
    for(var key in dict) {
        sorted[sorted.length] = key;
    }
    sorted.sort(function(a,b) {
        return a.replace(/^\W+/, 'z').localeCompare(b.replace(/^\W+/, 'z'));
    });

    var tempDict = {};
    for(var i = 0; i < sorted.length; i++) {
        tempDict[sorted[i]] = dict[sorted[i]];
    }

    return tempDict;
}

data = sortOnKeys(data);

console.log(data)

A: Keep it simple. notes are in the comments section in the example.

var obj = {
  "6M": {},
  "14D": {},
  "7Y": {},
  "10Y": {},
  "5Y": {},
  "15Y": {},
  ">20Y": {},
  "20Y": {}
};

//Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object

//sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

//reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

console.log(Object.keys(obj).sort().reduce(function (result, key) {
        result[key] = obj[key];
        return result;
    }, {}));

//just throwing in another variant if you really need numbers to be in right sort order. This  becuase above sort does string comparision. What if comaprision had to be on numaeric base.

console.log(Object.keys(obj).sort((a, b) => a.localeCompare(b, 'en', { numeric: true })));


text:
Q: Magento 2 Associate Certified Developer Progtis Ended? Anyone known that adobe ended the Magento Associated Certification Program?(Magento 2 Associate Certified Developer Exam).
If Not, Then guide me which program is alternate of Magento 2 Associate Certified Developer Exam?
Thanks...

A: Associate Developer is now called Adobe Certified Professional
.
They changed the names of the certifications (see this article update from AUGUST 17, 2020 'Certification name change').
Please check the list https://learning.adobe.com/certification.html?solution=Adobe%20Magento%20Commerce of all available certifications on Magento.

A: You can check that on learning.adobe.com/certification.html? website

A: the name has been changed to adobe certified professional - magento commerce developer


text:
Q: XSLT 2 Support in IntelliJ IDEA I have a problem with viewing XSLT 2 styled XML file in IntelliJ. I've added Saxon HE dependency and I know that it works because build completes with a success (it isn't without this dependency)
Connecting to XSLT runner on localhost/127.0.0.1:62573
Connected to XSLT runner.

Process finished with exit code 0

In XSLT output I can see fully created HTML that I can put in .html file and it will work fine. The problem is when I want to see this HTML through server hosted by my application e.g. localhost:8080/sampleFile.xml. This is the problem with exactly this tag
<xsl:for-each select="tokenize(@inputDomain, ',')">
...
</xsl:for-each>

When I remove this tag, I can see the whole HTML as I want to. I think it's the problem with starting tags on those files but I don't know and I can't find any answer.
XML file starts with
<?xml version="1.0"?>
<?xml-stylesheet href="./interpreter.xsl" type="text/xsl" ?>
...

XSL file starts with
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

A: The problem is that browsers only support XSLT version 1.0 and fn:tokenize(...) is an XSLT-2.0 function. So, unfortunately, you are restricted to version 1.0 if you want to run your stylesheet in the browser.
The only alternative would be using Saxon-JS:

Saxon-JS is an XSLT 3.0 run-time written in pure JavaScript. It's designed to execute Stylesheet Export Files (SEFs) compiled by Saxon-EE.

But it is not free, so you'd have to buy a license.


text:
Q: Using scraping api throw error while scraping amazon product details? I tried to scrape amazon product details using scraping api but it shows me following error:
"message": "Error: getaddrinfo ENOTFOUND api.scrapapi.com",
"cause": {
"errno": -3008,
"code": "ENOTFOUND",
"syscall": "getaddrinfo",
"hostname": "api.scrapapi.com"
 },

My whole code snippet is given below. Please help me to fix this problem
const { response } = require('express');
const express = require('express');
const { reset } = require('nodemon');
const request = require('request-promise');

const app = express();
const PORT = process.env.PORT || 5500;

const apiKey = "api_key";
const apiUrl = `http://api.scrapapi.com?api_key=${apiKey}&autoparse=true`;

app.use(express.json());

app.get('/',(req,res) =>{
res.send('Daraz api scraper');
});

//get product id
app.get('/products/:productId',async(req,res)=>{
const {productId} = req.params;
try {
    const response = await
    request(`${apiUrl}&url=https://www.amazon.com/dp/${productId}`);
    res.json(JSON.parse(response));
} catch (error) {
    res.json(error);
}

});

A: I have already sorted it out.
My code was right but all was the silly mistake that i did in my code that i wrote the wrong scrapeerapi thats why unknown hostname responded with error.


text:
Q: Symfony2 ORM schema update with 2 FK hi i'm trying to link a class test with 2 entities, the Administrator that post the test and the competence (subject of the test ), but whatever i do i only get 1 index FK on my database after schema update
namespace Admin\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Test
 *
 * @ORM\Table(name="test")
 * @ORM\Entity
 */
class Test
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

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

    /**
     * @var integer
     * @ORM\ManyToOne(targetEntity="ProjetCompetenceListe")
     * @ORM\JoinColumn(name="id_competence", referencedColumnName="id")
     */
    private $idCompetence;

    /**
     * @var \Administrateur
     *
     * @ORM\ManyToOne(targetEntity="Administrateur")
     * @ORM\JoinColumn(name="id_administrateur", referencedColumnName="id")
     */
    private $idAdministrateur;

please can any one tell me why ?

A: You may need to clear doctrine meta data :
php app/console doctrine:cache:clear-metadata

Otherwise do a :
php app/console doctrine:schema:validate

to check if the relations are correct.

A: Have you tried creating indexes with @index annotation, maybe you should give it a try. Ref
add index with @index annotation and then run schema update command


text:
Q: Higher order partial derivative of vector function Let $$f(x_1,x_2)=\begin{bmatrix}x_1x_2\sin x_1\\x_2\cos x_1-x_1\end{bmatrix}$$
Now I need to find $\frac {\partial^2 f(x)}{\partial x^2}$. I have no idea how I should find this. The first order partial should be the jacobian but what is the 2nd order partial derivative? And how can I find a bilinear map $\frac {\partial^2 f(x)}{\partial x^2}(p,q)$? Any help is appreciated. Thank you.

A: Observe $f: \mathbb{R}^2\rightarrow \mathbb{R}^2$ which means $Df: \mathbb{R}^2 \rightarrow L(\mathbb{R}^2; \mathbb{R}^2)$ and $D^2f:\mathbb{R}^2 \rightarrow L(\mathbb{R}^2; L(\mathbb{R}^2; \mathbb{R}^2))$ where $L(\mathbb{R}^2; \mathbb{R}^2)$ is the space of linear maps from $\mathbb{R}^2 \rightarrow \mathbb{R}^2$; likewise, $L(\mathbb{R}^2; L^2(\mathbb{R}^2; \mathbb{R}^2))$ is the space of linear maps from $\mathbb{R}^2$ to the linear space of linear maps.
In short $Df$ maps $(x_1, x_2)$ to a matrix $Df(x_1, x_2)$ which in this case  is
\begin{align}
Df(x_1, x_2)=
\begin{pmatrix}
\frac{\partial f_1}{\partial x_1} & \frac{\partial f_1}{\partial x_2}\\
\frac{\partial f_2}{\partial x_1} & \frac{\partial f_2}{\partial x_2}
\end{pmatrix}
 =
\begin{pmatrix}
x_2\sin x_1+ x_1x_2\cos x_1 & x_1\sin x_1\\
-x_2\sin x_1-1 & \cos x_1
\end{pmatrix}.
\end{align}
Alternative, we could say that $Df$ is a (1, 1)-tensor since it takes in a vector and a co-vector, i.e. $Df(x_1, x_2)[v^T, w]$. Hence, we can write $Df$ as
\begin{align}
Df =&\ \sum_{i, j}\frac{\partial f_i}{\partial x_j}\  e_i\otimes dx_j\\
=&\ (x_2\sin x_1+ x_1x_2\cos x_1)\ e_1\otimes dx_1+ (x_1\sin x_1)\ e_1\otimes dx_2\\
&-\ (x_2\sin x_1+1)\ e_2\otimes dx_1+ (\cos x_2)\ e_2\otimes dx_2.
\end{align}
For the second derivative of $f$, $D^2f$, we get a $(1, 2)$-tensor where the "matrix" components are given by
\begin{align}
(D^2f)_{jk}^i = \frac{\partial^2 f_i}{\partial x_j\partial x_k}
\end{align}
which means
\begin{align}
D^2f =&\  \sum_{i, j , k}\frac{\partial^2 f_i}{\partial x_j\partial x_k}\ e_i\otimes dx_j\otimes dx_k\\
=&\ (2x_2\cos x_1-x_1x_2\sin x_1)\ e_1\otimes dx_1\otimes dx_1+(\sin x_1+x_1\cos x_1)\ e_1\otimes dx_1\otimes dx_2\\
&+(\sin x_1 +x_1\cos x_1)\ e_1\otimes dx_2\otimes dx_1 + (0)\ e_1\otimes dx_2\otimes dx_2\\
&-(x_2\cos x_1)\ e_2\otimes dx_1\otimes dx_1 - (\sin x_1)\ e_2\otimes dx_1\otimes dx_2\\
&-(\sin x_1)\ e_2\otimes dx_2\otimes dx_1+(0)\ e_2\otimes dx_2\otimes dx_2
\end{align}
Edit: One should note that
\begin{align}
L(V; W) \cong V^\ast\otimes W
\end{align}
which means
\begin{align}
L(\mathbb{R}^2; L(\mathbb{R}^2; \mathbb{R}^2))\cong (\mathbb{R}^2)^\ast\otimes (\mathbb{R}^2)^\ast\otimes \mathbb{R}^2.
\end{align}

A: To get the second partial derivative, you literally need to differentiate twice:
$$ f = \left[ \begin{array}{c} x_1 x_2 \sin x_1 \\ x_2 \cos x_1 - x_1 \end{array}\right] \implies \frac{\partial f}{\partial x_1} = \left[ \begin{array}{c} x_2 \sin x_1 + x_1 x_2 \cos x_1 \\ - x_2 \sin x_1 - 1 \end{array}\right]$$
$$ \implies \frac{\partial^2 f}{\partial x_1^2} = \left[ \begin{array}{c} 2 x_2 \cos x_1  -  x_1 x_2 \sin x_1  \\ - x_2 \cos x_1 \end{array}\right].$$
To write the second derivative as a bilinear map $D^2 f: \mathbb R^2 \times \mathbb R^2 \to \mathbb R^2$, you first need to work out all four second derivatives. Then, if $v_i, w_i \in \mathbb R^2$ are a pair of directional vectors, the map $D^2 f$ is defined by:
$$ D^2 f(v, w) = \sum_{i=1}^2 \sum_{j=1}^2 v_i w_j \frac{\partial^2 f}{\partial x_i  \partial x_j} .$$


text:
Q: How to zoom Quartz Composer's viewer? I would like to zoom in and out in the viewer, my iPhone screens won't fit in my MB screen, and it seems impossible. Is there a way?

A: There isn't a way to zoom in Quartz Composer's Viewer window.
However, there's a workaround:

*

*Select all your patches, copy them to the clipboard, and delete them.

*Create a Render in Image patch and a Billboard patch.  Connect the Image port.

*Double-click on the Render in Image patch to go inside it.  Create a Clear patch, then paste your patches from the clipboard.

*Select the menu item Editor > Edit Parent.

Now you can adjust the Billboard's Width port to change the size of the Viewer's output.


text:
Q: add 2 :before's :after's on same div to create 2 triangles I have the following, where I am creating a triangle (that looks like it has a border) with css.
I want to create another triangle, exactly the same, but about 50px to the right of the 1st one.
How would you do these 2 :before's :after's ???
JSfiddle Here
HTML

Register Here

It's quick and easy and you'll be the first to know about new bits we release.
Register Now

CSS
.section-module-light:after,
.section-module-light:before {
    content: '';
    position: absolute;
}
/* Styling block element */
.my-account .section-module-light {
    position: relative;
    margin-bottom: 2em;
    padding: 1em;
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    background-color: transparent;
    color: #444;
}
/* Stroke */
.my-account .section-module-light:before {
    bottom: -0px;
    left: 150px;
    border-width: 36px;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-bottom: 20px solid #ccc;
}
/* Fill */
.my-account .section-module-light:after {
    bottom: -1px;
    left: 150px;
    border-width: 34px;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-bottom: 20px solid white;
}

JSfiddle Here

A: you do not need to create the triangle with separate stroke and fill, use css3 transform rotate. Then you can use before for one triangle and after for the second one.
display: block;
width: 34px;
height: 34px;

transform: rotate(45deg);
border-left: 1px solid #ccc;
border-top: 1px solid #ccc;
background: white;

see the whole code here: http://jsfiddle.net/07jfLdwL/

A: You can use CSS3 transform rotate properties. See documentations.


text:
Q: Moving code to older version of ECMAScript I am completely new to ECMA script and also JavaScript in general.
I'm trying to convert my code to work on an older version of ECMA script (I think).
The following code
Unit.prototype.getItems = function (...args) {
        let item = this.getItem.apply(this, args), items = [];

        if (item) {
            do {
                items.push(copyUnit(item));
            } while (item.getNext());
        }

        return items;
    };

Returns:
SyntaxError: missing formal parameter on the first line.

What does the ...args argument mean? What code can I replace it with to be compatible with the older version of ECMA script.


text:
Q:  блок с текстом по середине и плюсом "fa fa-plus" справа Как видите текст не по центру, нужна помощь. Из-за "плюса" текст съезжает левее.

A:

.elem {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 200px;
  background: #857bfe;
  color: #fff;
  padding: 5px;
}

.elem > span {
  display: block;
  width: 100%;
  padding-left: 16px;
  text-align: center;
}
<link href="https://use.fontawesome.com/releases/v5.13.1/css/all.css" rel="stylesheet"/>

  Название колонки

A: Иконке плюс присвойте position: absolute, тексту установите отступы по бокам соответсвующие размеру иконки, чтобы при изменении размера кнопки не наложились друг на друга.


text:
Q: save image to sql server 2012 using c# My aim is to insert images into my sql server database.
image column in database defined as varbinary(max) type
but when I execute the command, the Image column contains only the first value in the byte array!
Insert Image Script:
public void InsertImage()
    {
        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

        Image img = Image.FromFile(@"D:\MyProjects\Registry Biometrics Insight\FingerPrintImages\1_2.bmp");
        byte[] arr;
        using (MemoryStream ms = new MemoryStream())
        {
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            arr = ms.ToArray();
        }

        DBLayer dblayer = new DBLayer(CS);

        SqlParameter[] sqlParams = new SqlParameter[1];
        sqlParams[0] = new SqlParameter("@Image", SqlDbType.VarBinary);
        sqlParams[0].Value = arr;

        dblayer.M_ExecuteSQLCommand("prc_Fingers_InsertImage", sqlParams);
    }

ExecuteSQLCommand Script:
public int M_ExecuteSQLCommand(string StoredProcedureName, SqlParameter[] Parameters)
    {
        SqlCommand comm;
        try
        {
            using (SqlConnection conn = new SqlConnection(_P_ConnectionString))
            {

                comm = new SqlCommand();
                comm.Connection = conn;

                comm.CommandType = System.Data.CommandType.StoredProcedure;
                comm.CommandText = StoredProcedureName;
                comm.CommandTimeout = 0;

                comm.Parameters.Clear();
                for (int i = 0; i < Parameters.Length; i++)
                {
                    comm.Parameters.Add( Parameters[i] );
                }

                conn.Open();
                comm.ExecuteNonQuery();

                return 1;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

My Sorted Procedure:
Procedure [dbo].[prc_Fingers_InsertImage]
(@Image varbinary = null)
 as
 begin

INSERT INTO [dbo].[Fingers]
           ([Image])
     VALUES
           (@Image)
 end

Why did I get this result instead of saving all values from byte array??

A: You might want to use the method "Read" to convert the stream into an array of bytes
ms.Read(arr, 0, ms.Length);

I would even go as far as declare the size of the "arr" byte array just before, you read the stream into the array
arr = new byte[ms.length];

You might also have to reset the stream pointer, since after the Save method, the pointer is at the end of the stream:
ms.Seek(0, SeekOrigin.Begin);

The final code block would result in replacing
arr = ms.ToArray();

with
ms.Seek(0, SeekOrigin.Begin);
arr = new byte[ms.length];
ms.Read(arr, 0, ms.Length);


text:
Q: select top 1 or get first record using FMDB I am using FMDB and I just want to select a single record using TOP 1 - can you do this using FMDB?  I have Googled and I haven't found this mentioned anywhere - seems like a pretty common usage scenario.
Anyone?

A: I don't know about fmdb, but it seems to use raw/prepared sql statements, so you can use the SQLite documentation:
http://www.sqlite.org/lang_select.html
You can see that it uses LIMIT 1 (like MySQL) instead of TOP 1 (like MS SQL)


text:
Q: 50 People All over the World hit web app versus 50 people on the Same LAN? Any difference? At my office we use a LAN (connected to internet through Comcast) and 30-50 people all accessed a web app (on Heroku) simultaneously. The server responded as if it had been hit by 50K people. Am I barking up the wrong tree, or would it make a difference if 50 people on an office network hit an app at the same time versus 50 people spread across the globe?
Apologies for such a vague question, but it only just occurred to me as a possibility.
Thanks in advance.

A: Probably barking up the wrong tree.  It would make no difference at all.
Sounds like a bug in your webapp if it's reporting 50k instead of correctly reporting 50.  Although you haven't really said what is reporting this exactly.
In which case if it's a code problem you need to post some code over at stackoverflow.

A: You should be able to tell what happened from the heroku logs. Depending on the app if the logs are not showing that the web&worker processes are the problem you may need to shard the database layer.


text:
Q: image doesn't send to serveur from ionic3 I try upload multiple images from ionic3 to serveur php but I have error images doesn't send to backend.. I use imagepicker plugin to select multiple images ..
code angular:
testfile(){

  for (var l of this.images)
  {
    if(l !== 'K' && l !== 'O')
    {
           this.base64.encodeFile(l).then((base64File: string) => {
    var formData = new FormData();
  formData.append('photo',base64File);

   this.http.post('url api',formData, {responseType: 'text'}).subscribe(res =>

 alert(res),
        err => {
          this.presentToast(err);
        });
  }

  , (err) => {
  this.presentToast(err);
  this.presentToast('error encode');
});
}
}
}

also I try send base64File without append to formData and also I try send l (get in loop) but also error in all cases

A: Try using Camera plugin and set
Camera.PictureSourceType: PHOTOLIBRARY


text:
Q: Rotated Element creates issues with adorner I have a problem with my adorner which is supposed to preview the destination of my drag & drop operation,
everything is working fine until i rotate the adorned element.
My adorner is a rectangle which is filled with a visual brush of the adorned element, so if the element is rotated the adorner gets the correct (already rotated) image. But because the rectangle has to be rotated too the image gets rotated once more which isn't supposed to happen. Can I somehow exclude the brush  of the transformation so it will not rotate again or is there another solution for my problem?
Thanks

A: You can override the GetDesiredTransform method in the adorner class and manipulate the transforms applied to the adorner's children (the rectangle with the visual brush in your case).

A: Finally I have a solution to this problem:
with this small algorythm link I've created a copy of the UI element, set its rendertransform property to null and used it as a visualbrush instead of the original element which also allowed me to set the original element to invisible!