问:
how to compare an objects array and a nested objects array?
I have only been programming for a short time and I am faced with a data structure that is difficult to understand.I have a function where I get an array of objects, representing products added to a cart.

```<code>  getAllAddedItems(addedItems) {

    this.fullInfoAddedItems.push(addedItems);
    const filtered = this.fullInfoAddedItems.reduce((filtered, item) => {
      if ( !filtered.some(filteredItem => JSON.stringify(filteredItem) === JSON.stringify(item)) ) {
        filtered.push(item);
      }
      return filtered;
    }, []);
    this.fullInfoAddedItems = filtered;
}

</code>```

As a result I get the following array of objects

```<code>[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4
  }
]
</code>```

The problem is that I need a data "name" that is in an array of nested objects to complete the view information.

This would be the structure of the array

```<code>[

{
  "name": "Articles funeraires",
  "functional_id": "funeral",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Boîte de sympathie",
      "id": 27,
      "path": "",
      "items": [
        {
          "name": "1 boîte",
          "price": 0,
          "functional_id": "boite_de_sympathie_1_boite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Coffret empreinte rouge",
      "id": 8,
      "path": "",
      "items": [
        {
          "name": "Carton de 10 coffrets",
          "price": 140,
          "functional_id": "carton_de_10_coffrets_2_recharges_argile_offertes_coloris_rouge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "AfuBOX",
      "id": 10,
      "path": "",
      "items": [
        {
          "name" : "PACK N°1 comprenant :",
          "price": 30,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 4
        },
        {
          "name" : "PACK N°2 comprenant :",
          "price": 70,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 6
        }

      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2200
},
  {
  "name": "Documents",
  "functional_id": "incineris_doc",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Carnet de conventions",
      "id": 17,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "carnet_de_conventions",
          "quantity": 3
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Affiches procédure",
      "description": "De prise en charge et de crémation des animaux",
      "id": 18,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "affiches_procedure_de_prise_en_charge_et_de_cremation_des_animaux"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Dépliants services de crémation",
      "description": "Pour animaux de compagnie",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "depliants_services_incinération",
          "quantity": 4
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2400
},
{
  "name": "Matériel crémation",
  "functional_id": "furniture",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Sacs blancs",
      "description": "Pour les crémations Plurielles",
      "id": 11,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_petit_modele_par_25"
        },
        {
          "name": "Moyen modèle",
          "description": "Par 20",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_moyen_modele_par_20"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bordeaux",
      "description": "Pour les crémations Référence",
      "id": 12,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_petit_modele_par_10"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs verts",
      "description": "Pour les crémations Privées",
      "id": 13,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_petit_modele_unite"
        },
        {
          "name": "Moyen modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_moyen_modele_unite"
        },
        {
          "name": "Grand modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_grand_modele_unite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bleus",
      "description": "Pour pièces anatomiques",
      "id": 14,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bleus_pour_pieces_anatomiques_standard_par_25"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Etiquettes d'identification",
      "id": 15,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "etiquettes_identification_et_colliers_de_serrages_standard_par_50"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Colliers de serrages",
      "id": 16,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "distributeurs_pour_sacs_housse_par_5"
        }
      ]
    }
  ],
  "sorting": 2300
}
]
</code>```

```<code>[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3,
    "name": "Carnet de conventions"
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4,
    "name": "Dépliants services de crémation"
  }
]

</code>```

I attach a stacblitz link simulating what I'm trying to do to compare by "functional_id" to get "name" from the array of nested objects and push to the first array

https://stackblitz.com/edit/angular-ivy-3wfgme

Someone to give me an effective option to get it.
Thank you in advance.

what I try to do is go through the second array to compare the "functional_id" of the original product with the "functional_id" of the product added to the first array, so I can extract the "name" in the first array and push it into the first array

```<code>this.market.forEach(function(item: any, i) {
      item.products.forEach(function(products: any, i) {
      products.items.forEach(function(sale: any, i) {
        let saleId = sale.functional_id;
        console.log(sale);
        console.log(saleId);

      });

      });
    });
</code>```

This is what I'm trying to do, but I don't see how I can compare the two arrays

答:
Iterate over the addedItems array and for each item in this array, iterate over the products array in each object inside product array and check if any of the item inside current items array has a functional_id equal to the functional_id of the current item from the addedItems array

```<code>getAllAddedItems(addedItems) {

  addedItems.forEach(item => {
     this.product.forEach(({products}) => {
        products.forEach(({name, items}) => {
           const index = items.findIndex(i => i.functional_id === item.functional_id);
           if (index > -1) item.name = name;
        })
     })
  })

  console.log(addedItems);
}
</code>```

Here's a stackblitz demo. Open the console to see the output of the function

Body:
I have only been programming for a short time and I am faced with a data structure that is difficult to understand.I have a function where I get an array of objects, representing products added to a cart.

  getAllAddedItems(addedItems) {

    this.fullInfoAddedItems.push(addedItems);
    const filtered = this.fullInfoAddedItems.reduce((filtered, item) => {
      if ( !filtered.some(filteredItem => JSON.stringify(filteredItem) === JSON.stringify(item)) ) {
        filtered.push(item);
      }
      return filtered;
    }, []);
    this.fullInfoAddedItems = filtered;
}

As a result I get the following array of objects

[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4
  }
]

The problem is that I need a data "name" that is in an array of nested objects to complete the view information.

This would be the structure of the array

[

{
  "name": "Articles funeraires",
  "functional_id": "funeral",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Boîte de sympathie",
      "id": 27,
      "path": "",
      "items": [
        {
          "name": "1 boîte",
          "price": 0,
          "functional_id": "boite_de_sympathie_1_boite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Coffret empreinte rouge",
      "id": 8,
      "path": "",
      "items": [
        {
          "name": "Carton de 10 coffrets",
          "price": 140,
          "functional_id": "carton_de_10_coffrets_2_recharges_argile_offertes_coloris_rouge"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "AfuBOX",
      "id": 10,
      "path": "",
      "items": [
        {
          "name" : "PACK N°1 comprenant :",
          "price": 30,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 4
        },
        {
          "name" : "PACK N°2 comprenant :",
          "price": 70,
          "functional_id": "afubox_6_petits_modeles_4_moyens_modeles",
          "quantity": 6
        }

      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2200
},
  {
  "name": "Documents",
  "functional_id": "incineris_doc",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Carnet de conventions",
      "id": 17,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "carnet_de_conventions",
          "quantity": 3
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Affiches procédure",
      "description": "De prise en charge et de crémation des animaux",
      "id": 18,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "affiches_procedure_de_prise_en_charge_et_de_cremation_des_animaux"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Dépliants services de crémation",
      "description": "Pour animaux de compagnie",
      "id": 19,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "depliants_services_incinération",
          "quantity": 4
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Catalogue d'urnes décoratives",
      "id": 20,
      "path": "",
      "items": [
        {
          "price": 0,
          "functional_id": "catalogue_urnes_decoratives"
        }
      ]
    }
  ],
  "sorting": 2400
},
{
  "name": "Matériel crémation",
  "functional_id": "furniture",
  "generic": "incineris",
  "products": [
    {
      "file": "data:image/;base64,",
      "name": "Sacs blancs",
      "description": "Pour les crémations Plurielles",
      "id": 11,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_petit_modele_par_25"
        },
        {
          "name": "Moyen modèle",
          "description": "Par 20",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_moyen_modele_par_20"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_blancs_pour_les_cremations_plurielles_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bordeaux",
      "description": "Pour les crémations Référence",
      "id": 12,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_petit_modele_par_10"
        },
        {
          "name": "Grand modèle",
          "description": "Par 10",
          "price": 0,
          "functional_id": "sacs_bordeaux_pour_les_cremations_reference_grand_modele_par_10"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs verts",
      "description": "Pour les crémations Privées",
      "id": 13,
      "path": "",
      "items": [
        {
          "name": "Petit modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_petit_modele_unite"
        },
        {
          "name": "Moyen modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_moyen_modele_unite"
        },
        {
          "name": "Grand modèle",
          "description": "A l'unité",
          "price": 0,
          "functional_id": "sacs_verts_pour_les_cremations_privees_grand_modele_unite"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Sacs bleus",
      "description": "Pour pièces anatomiques",
      "id": 14,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 25",
          "price": 0,
          "functional_id": "sacs_bleus_pour_pieces_anatomiques_standard_par_25"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Etiquettes d'identification",
      "id": 15,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "etiquettes_identification_et_colliers_de_serrages_standard_par_50"
        }
      ]
    },
    {
      "file": "data:image/;base64,",
      "name": "Colliers de serrages",
      "id": 16,
      "path": "",
      "items": [
        {
          "name": "Standard",
          "description": "Par 50",
          "price": 0,
          "functional_id": "distributeurs_pour_sacs_housse_par_5"
        }
      ]
    }
  ],
  "sorting": 2300
}
]

[
  {
    "price": 0,
    "functional_id": "carnet_de_conventions",
    "quantity": 3,
    "name": "Carnet de conventions"
  },
  {
    "price": 0,
    "functional_id": "depliants_services_incinération",
    "quantity": 4,
    "name": "Dépliants services de crémation"
  }
]

I attach a stacblitz link simulating what I'm trying to do to compare by "functional_id" to get "name" from the array of nested objects and push to the first array

https://stackblitz.com/edit/angular-ivy-3wfgme

Someone to give me an effective option to get it.
Thank you in advance.

what I try to do is go through the second array to compare the "functional_id" of the original product with the "functional_id" of the product added to the first array, so I can extract the "name" in the first array and push it into the first array

this.market.forEach(function(item: any, i) {
      item.products.forEach(function(products: any, i) {
      products.items.forEach(function(sale: any, i) {
        let saleId = sale.functional_id;
        console.log(sale);
        console.log(saleId);

      });

      });
    });

This is what I'm trying to do, but I don't see how I can compare the two arrays

Body:
Iterate over the addedItems array and for each item in this array, iterate over the products array in each object inside product array and check if any of the item inside current items array has a functional_id equal to the functional_id of the current item from the addedItems array

getAllAddedItems(addedItems) {

  addedItems.forEach(item => {
     this.product.forEach(({products}) => {
        products.forEach(({name, items}) => {
           const index = items.findIndex(i => i.functional_id === item.functional_id);
           if (index > -1) item.name = name;
        })
     })
  })

  console.log(addedItems);
}

Here's a stackblitz demo. Open the console to see the output of the function


来源: stackexchange

问:
UIButton dynamic width using autolayout
I am having a button which has two different text in selected state and normal state, When I change state of button programatically button is not getting resized so text is not appearing properly, which is the best way to do this with autolayout?

I know one way setting outlet to UIButton's width constraint and change it manually but I am looking for better way

答:
An alternate way for shrinking/expanding width of UIButton using autolayout is to add a width constraint and then change the priority of width constraint to less than Content Hugging Priority and Content Compression Resistance Priority.

In case we only want to expand the button based on their title, we can set the width constraint to the minimum value and the priority of width constraint to less than Content Compression Resistance Priority but more than Content Hugging Priority.

In the above cases we only need to

```<code>btn.setTitle("SomeTitle", for: .normal)
</code>```

in the code and auto layout will take care of the rest.

Attached is a screenshot

ContentLicense: CC BY-SA 3.0

Title: UIButton dynamic width using autolayout

Body:
An alternate way for shrinking/expanding width of UIButton using autolayout is to add a width constraint and then change the priority of width constraint to less than Content Hugging Priority and Content Compression Resistance Priority.

In case we only want to expand the button based on their title, we can set the width constraint to the minimum value and the priority of width constraint to less than Content Compression Resistance Priority but more than Content Hugging Priority.

In the above cases we only need to

btn.setTitle("SomeTitle", for: .normal)

in the code and auto layout will take care of the rest.

Attached is a screenshot

ContentLicense: CC BY-SA 4.0


问:
hide debug information in dev environnement
I'am working on web app with symfony4.

by default in developement environnement Symfony catches all the exceptions and displays a special exception page with lots of debug information to help you discover the root problem.my question is to know how can I desable or hide details informations

答:
If you mean that you want to disable the Profiler Debug Bar on the Bottom Screen you can do this with editing for the DEV Environment:

```<code># config/packages/dev/web_profiler.yaml
web_profiler:
  toolbar: false # set to false to disable
</code>```

As stated on the comment by ehymel you should want this information if you are working on the DEV Environment.

The only use case i can imagine is when disabling this is for an automatic test run while still having the dev environment on.

Body:
If you mean that you want to disable the Profiler Debug Bar on the Bottom Screen you can do this with editing for the DEV Environment:

# config/packages/dev/web_profiler.yaml
web_profiler:
  toolbar: false # set to false to disable

As stated on the comment by ehymel you should want this information if you are working on the DEV Environment.

The only use case i can imagine is when disabling this is for an automatic test run while still having the dev environment on.


问:
How to integrate inspinia into rails 6
My problem is with the inspinia.js file in rails 6.

I have the file inspinia.js and application.js in :-

app / javascript / pack

Try to integrate it in the following ways:

```<code>import 'inspinia'
require ("inspinia")
</code>```

and in some other ways that didn't help me either.
If someone has already done it or knows how to do it, I would appreciate your help.

答:
Well, you said that you've put it in the app/javascript/packs directory.
All you have to do is require it in application.js like:

require ("packs/inspinia");

```

<p>You can also include it in the the <code>index.html.erb</code> like:</p>

<pre class="lang-rb prettyprint-override"><code><%= javascript_pack_tag 'inspinia', 'data-turbolinks-track': 'reload'  %>
</code>```

Title: How to integrate inspinia into rails 6

Body:
My problem is with the inspinia.js file in rails 6.

I have the file inspinia.js and application.js in :-

app / javascript / pack

Try to integrate it in the following ways:

import 'inspinia'
require ("inspinia")

and in some other ways that didn't help me either.
If someone has already done it or knows how to do it, I would appreciate your help.

Body:
Well, you said that you've put it in the app/javascript/packs directory.
All you have to do is require it in application.js like:

require ("packs/inspinia");

You can also include it in the the index.html.erb like:

<%= javascript_pack_tag 'inspinia', 'data-turbolinks-track': 'reload'  %>


问:
How to use Jbuilder to save output for later
I want to save json into a database field for later use.  How should I go about that with Jbuilder?

I want to use an item's show template, passing in the object, @item to save the output for that Item into the database for later use.

I got some output with the following code:

```<code>view_paths = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
av_helper = ActionView::Base.new view_paths
include Rails.application.routes.url_helpers
@job = Job.find(239)
output = av_helper.render(file: '/api/jobs/show.jbuilder', locals: {:@job => @job})
</code>```

How can I render the saved json directly from the controller?

Add this for the action code in the controller

```<code>def show
   @job = Job.find(params[:id])
   render :inline => @job.json_output
end
</code>```

答:
render_to_string

Raw rendering of a template to a string.

It is similar to render, except that it does not set the response_body
  and it should be guaranteed to always return a string.

Also if you're doing it from a controller there you can just use the controller to render it:

```<code>class JobsController
  def create
    @job = Job.new(item_params) do |job|
      job.my_json_attribute = render_to_string(:show, locals: { :@job => job})
    end
    if @job.save
      redirect_to @job
    else
      render :new
    end
  end
end
</code>```

But this seems like a pretty overcomplicated and flawed way to handle something that can be done with e-tag caching and a reverse proxy or even low level caching. Especially since you would have to repeat the logic when updating the item.

Body:
I want to save json into a database field for later use.  How should I go about that with Jbuilder?

I want to use an item's show template, passing in the object, @item to save the output for that Item into the database for later use.

I got some output with the following code:

view_paths = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
av_helper = ActionView::Base.new view_paths
include Rails.application.routes.url_helpers
@job = Job.find(239)
output = av_helper.render(file: '/api/jobs/show.jbuilder', locals: {:@job => @job})

How can I render the saved json directly from the controller?

Add this for the action code in the controller

def show
   @job = Job.find(params[:id])
   render :inline => @job.json_output
end

Body:
render_to_string

Raw rendering of a template to a string.

It is similar to render, except that it does not set the response_body
  and it should be guaranteed to always return a string.

Also if you're doing it from a controller there you can just use the controller to render it:

class JobsController
  def create
    @job = Job.new(item_params) do |job|
      job.my_json_attribute = render_to_string(:show, locals: { :@job => job})
    end
    if @job.save
      redirect_to @job
    else
      render :new
    end
  end
end

But this seems like a pretty overcomplicated and flawed way to handle something that can be done with e-tag caching and a reverse proxy or even low level caching. Especially since you would have to repeat the logic when updating the item.


问:
Delete table row using "isempty"
Can someone please tell me why, when I run this code, it skips the tbl.Range.Rows(i).Delete line when there are rows in my table which are empty?

Many thanks

Debbie

Dim i As Long
Dim tbl As Table

```<code>Set tbl = ActiveDocument.Tables(2)

For i = tbl.Range.Rows.Count To 1 Step -1
  With tbl
    If IsEmpty(tbl.Range.Rows(i)) = True Then
      tbl.Range.Rows(i).Delete
    End If
  End With
Next
</code>```

答:
The simple answer is that, in Word, a row is never empty - it always contains end-of-cell and end-of-row characters. Try:

```<code>Dim r As Long
With ActiveDocument.Tables(2)
  For r = .Rows.Count To 1 Step -1
    With .Rows(r)
      If Len(.Range.Text) = .Cells.Count * 2 + 2 Then .Delete
    End With
  Next r
End With
</code>```

Note that the above code won't work if the table has vertically-merged/split cells.

Title: Delete table row using "isempty"

Body:
Can someone please tell me why, when I run this code, it skips the tbl.Range.Rows(i).Delete line when there are rows in my table which are empty?

Many thanks

Debbie

Dim i As Long
Dim tbl As Table

Set tbl = ActiveDocument.Tables(2)

For i = tbl.Range.Rows.Count To 1 Step -1
  With tbl
    If IsEmpty(tbl.Range.Rows(i)) = True Then
      tbl.Range.Rows(i).Delete
    End If
  End With
Next

Body:
The simple answer is that, in Word, a row is never empty - it always contains end-of-cell and end-of-row characters. Try:

Dim r As Long
With ActiveDocument.Tables(2)
  For r = .Rows.Count To 1 Step -1
    With .Rows(r)
      If Len(.Range.Text) = .Cells.Count * 2 + 2 Then .Delete
    End With
  Next r
End With

Note that the above code won't work if the table has vertically-merged/split cells.


问:
open new browser window within dialog ajax call - jquery NOT popup
I am stumped.  How do I open a link "go" in this situation using jquery?

Opened a dialog and when click on activate button. The link should open a new browser window / tab the same as clicking on a link "go" with target=_blank.

```<code><div id="dialog">
<a href="http://stackoverflow.com" target="_blank" >go</a>
</div>
<script type="text/javascript">
$( "#dialog" ).dialog({buttons: {
"Activate": function(event) {
    $.get("404.html").error(function(){
    $("#dialog a").click(); //doesnt work
    $("#dialog a").trigger("click"); //doesnt work
    window.open("http://stackoverflow.com",'_blank'); //opens a popup, not what i need
    window.location.href //is not what i need since its in same window/tab
       });
    }
}});
</script>
</code>```

答: you can try window.open('http://stackoverflow.com', '_newtab');. Keep in mind this behaviour is mostly controlled by the browser so the results may vary.

Body:
I am stumped.  How do I open a link "go" in this situation using jquery?

Opened a dialog and when click on activate button. The link should open a new browser window / tab the same as clicking on a link "go" with target=_blank.

go


问:
Parsing Data from Access to Excel via vba code to split onto sheets based on field contents
I have been trying to find a way to adapt the code i have written (based heavily on the Youtube video and coding provided by Access Jitsu to split my data across mutliple sheets based on the value in one field.
I have a number of fields and the purpose is for a comparison between invoicing and costs which i want to split by years onto separate sheets in excel.

Can anyone assist with how i would parse the field to split the data onto individual sheets based on the Year (in the code [Yr]) field.

many thanks in advance.

Code below. couldnt get it to display as all one entry

```<code>Private Sub Command2_Click()
On Error GoTo SubError

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim SQL As String
Dim rs1 As DAO.Recordset
Dim i As Integer

'Show user work is being performed
DoCmd.Hourglass (True)

'*********************************************
'              RETRIEVE DATA
'*********************************************
'SQL statement to retrieve data from database
SQL = "SELECT [Job Opened], [Job Number], [Job Title], " & _
"[ProposalRef], [QuotedValue], [Invoiced], " & _
"[Uplifted Cost], [Profit], [Diff], [Last Date Worked], [Reason], [Status], [Yr]" & _
"FROM [BIID] " & _
"ORDER BY [Job Number] "

'Execute query and populate recordset
Set rs1 = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)

'If no data, don't bother opening Excel, just quit
If rs1.RecordCount = 0 Then
    MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
    GoTo SubExit
End If

'*********************************************
'             BUILD SPREADSHEET
'*********************************************
'Create an instance of Excel and start building a spreadsheet

'Early Binding
Set xlApp = Excel.Application

xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

With xlSheet
    .Name = "BIID-All"
    .Cells.Font.Name = "Calibri"
    .Cells.Font.Size = 10

    'Set column widths
    .Columns("A").ColumnWidth = 11
    .Columns("B").ColumnWidth = 10
    .Columns("C").ColumnWidth = 40
    .Columns("D").ColumnWidth = 16
    .Columns("E").ColumnWidth = 14
    .Columns("F").ColumnWidth = 12
    .Columns("G").ColumnWidth = 12
    .Columns("H").ColumnWidth = 12
    .Columns("I").ColumnWidth = 10
    .Columns("J").ColumnWidth = 15
    .Columns("K").ColumnWidth = 45
    .Columns("L").ColumnWidth = 8
    .Columns("M").ColumnWidth = 5

    'Format columns
    .Columns("A").NumberFormat = "dd/mm/yyyy"
    .Columns("J").NumberFormat = "dd/mm/yyyy"
    .Columns("F").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("G").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("H").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("I").NumberFormat = "#,###,##0.00%;-#,###,##0.00%"

    'Column Headings
    .Range("A2").Value = "Date Opened"
    .Range("B2").Value = "Job Number"
    .Range("C2").Value = "Job Title"
    .Range("D2").Value = "Proposal Ref."
    .Range("E2").Value = "Quoted Value"
    .Range("F2").Value = "Total Invoiced"
    .Range("G2").Value = "Uplifted Cost"
    .Range("H2").Value = "Proft"
    .Range("I2").Value = "Difference"
    .Range("J2").Value = "Last Date Worked"
    .Range("K2").Value = "Reason"
    .Range("L2").Value = "Status"
    .Range("M2").Value = "Year"

    .Range("A1").Value = "Date Updated"
    .Range("B1").Value = Date

    'Format Column Headings
    .Range("A2:M2").Cells.Font.Bold = True
    .Range("A2:M2").Cells.Font.Color = RGB(68, 84, 106)
    .Range("A2:B2").HorizontalAlignment = xlCenter
    .Range("E2:J2").HorizontalAlignment = xlCenter

    'provide initial value to row counter
    i = 3
    'Loop through recordset and copy date from recordset to sheet
    Do While Not rs1.EOF

        .Range("A" & i).Value = rs1![Job Opened]
        .Range("B" & i).Value = rs1![Job Number]
        .Range("C" & i).Value = rs1![Job Title]
        .Range("D" & i).Value = rs1![ProposalRef]
        .Range("E" & i).Value = rs1![QuotedValue]
        .Range("F" & i).Value = rs1![Invoiced]
        .Range("G" & i).Value = rs1![Uplifted Cost]
        .Range("H" & i).Value = rs1![Profit]
        .Range("I" & i).Value = rs1![Diff]
        .Range("J" & i).Value = rs1![Last Date Worked]
        .Range("K" & i).Value = rs1![Reason]
        .Range("L" & i).Value = rs1![Status]
        .Range("M" & i).Value = rs1![Yr]

        i = i + 1
        rs1.MoveNext

        Loop

        'Total Average %
        .Range("F" & i).HorizontalAlignment = xlRight
        .Range("F" & i, "H" & i).Merge
        .Range("F" & i).Value = "Average % Profit (Billed vs Uplifted Cost)"
        .Range("F" & i).Cells.Font.Bold = True
        .Range("I" & i).Formula = "=AVERAGE(I3:I" & i - 1

        'Add borders
        .Range("A2:M2").Borders(xlEdgeTop).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M2").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:A" & i - 1).Borders(xlEdgeLeft).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeRight).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlInsideVertical).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous

        'Add Conditional formatting
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlGreater, 0)
            .Font.Color = RGB(0, 176, 80)
        End With
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlLess, 0)
            .Font.Color = vbRed
        End With

    End With

SubExit:
On Error Resume Next
DoCmd.Hourglass False
xlApp.Visible = True
rs1.Close
Set rs1 = Nothing
Exit Sub

 SubError:
MsgBox "Error Number: " & Err.Number & "= " & Err.Description, vbCritical + vbOKOnly, _
    "An error occurred"
GoTo SubExit
 End Sub
</code>```

答:
What you need to do is to introduce a new recordset that has a list of the distinct years in. You then loop this recordset, adding a new worksheet for each year, and then your original recordset is opened, but has a WHERE clause in the SQL to just show data for the year in question. Some abridged VBA to do this is below:

```<code>Sub sSampleExport()
    On Error GoTo E_Handle
    Dim db As DAO.Database
    Dim rsYear As DAO.Recordset
    Dim rsData As DAO.Recordset
    Dim strSQL As String
    Dim objXL As New Excel.Application
    Dim objXLBook As Excel.Workbook
    Dim objXLSheet As Excel.Worksheet
    Dim lngLoop1 As Long
    Set db = DBEngine(0)(0)
    strSQL = "SELECT DISTINCT Yr FROM BIID ORDER BY Yr ASC;"
    Set rsYear = db.OpenRecordset(strSQL)
    If Not (rsYear.BOF And rsYear.EOF) Then
        Set objXLBook = objXL.Workbooks.Add
        Do
            Set objXLSheet = objXLBook.Worksheets.Add(After:=objXLBook.Worksheets(objXLBook.Worksheets.Count))
            With objXLSheet
                .name = rsYear!Yr
                strSQL = "SELECT [Job Opened], [Job Number], [Job Title] " _
                    & " FROM BIID " _
                    & " WHERE Yr=" & rsYear!Yr
                Set rsData = db.OpenRecordset(strSQL)
                If Not (rsData.BOF And rsData.EOF) Then
                    .Cells(1, 1).CopyFromRecordset rsData
                End If
            End With
            rsYear.MoveNext
        Loop Until rsYear.EOF
        For lngLoop1= objXLBook.Worksheets.Count To 1 Step -1
            If Left(objXLBook.Worksheets(lngLoop1).Name, 5) = "Sheet" Then
                objXLBook.Worksheets(lngLoop1).Delete
            End If
        Next lngLoop1
        objXLBook.Worksheets(1).Select
        objXLBook.SaveAs "J:\downloads\test.xlsx"
    End If
sExit:
    On Error Resume Next
    rsData.Close
    rsYear.Close
    Set rsData = Nothing
    Set rsYear = Nothing
    Set db = Nothing
    Set objXLSheet = Nothing
    objXLBook.Close
    Set objXLBook = Nothing
    objXL.Quit
    Set objXL = Nothing
    Exit Sub
E_Handle:
    MsgBox Err.Description & vbCrLf & vbCrLf & "sSampleExport", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume sExit
End Sub
</code>```

Regards,

Body:
I have been trying to find a way to adapt the code i have written (based heavily on the Youtube video and coding provided by Access Jitsu to split my data across mutliple sheets based on the value in one field.
I have a number of fields and the purpose is for a comparison between invoicing and costs which i want to split by years onto separate sheets in excel.

Can anyone assist with how i would parse the field to split the data onto individual sheets based on the Year (in the code [Yr]) field.

many thanks in advance.

Code below. couldnt get it to display as all one entry

Private Sub Command2_Click()
On Error GoTo SubError

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim SQL As String
Dim rs1 As DAO.Recordset
Dim i As Integer

'Show user work is being performed
DoCmd.Hourglass (True)

'*********************************************
'              RETRIEVE DATA
'*********************************************
'SQL statement to retrieve data from database
SQL = "SELECT [Job Opened], [Job Number], [Job Title], " & _
"[ProposalRef], [QuotedValue], [Invoiced], " & _
"[Uplifted Cost], [Profit], [Diff], [Last Date Worked], [Reason], [Status], [Yr]" & _
"FROM [BIID] " & _
"ORDER BY [Job Number] "

'Execute query and populate recordset
Set rs1 = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)

'If no data, don't bother opening Excel, just quit
If rs1.RecordCount = 0 Then
    MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
    GoTo SubExit
End If

'*********************************************
'             BUILD SPREADSHEET
'*********************************************
'Create an instance of Excel and start building a spreadsheet

'Early Binding
Set xlApp = Excel.Application

xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

With xlSheet
    .Name = "BIID-All"
    .Cells.Font.Name = "Calibri"
    .Cells.Font.Size = 10

    'Set column widths
    .Columns("A").ColumnWidth = 11
    .Columns("B").ColumnWidth = 10
    .Columns("C").ColumnWidth = 40
    .Columns("D").ColumnWidth = 16
    .Columns("E").ColumnWidth = 14
    .Columns("F").ColumnWidth = 12
    .Columns("G").ColumnWidth = 12
    .Columns("H").ColumnWidth = 12
    .Columns("I").ColumnWidth = 10
    .Columns("J").ColumnWidth = 15
    .Columns("K").ColumnWidth = 45
    .Columns("L").ColumnWidth = 8
    .Columns("M").ColumnWidth = 5

    'Format columns
    .Columns("A").NumberFormat = "dd/mm/yyyy"
    .Columns("J").NumberFormat = "dd/mm/yyyy"
    .Columns("F").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("G").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("H").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("I").NumberFormat = "#,###,##0.00%;-#,###,##0.00%"

    'Column Headings
    .Range("A2").Value = "Date Opened"
    .Range("B2").Value = "Job Number"
    .Range("C2").Value = "Job Title"
    .Range("D2").Value = "Proposal Ref."
    .Range("E2").Value = "Quoted Value"
    .Range("F2").Value = "Total Invoiced"
    .Range("G2").Value = "Uplifted Cost"
    .Range("H2").Value = "Proft"
    .Range("I2").Value = "Difference"
    .Range("J2").Value = "Last Date Worked"
    .Range("K2").Value = "Reason"
    .Range("L2").Value = "Status"
    .Range("M2").Value = "Year"

    .Range("A1").Value = "Date Updated"
    .Range("B1").Value = Date

    'Format Column Headings
    .Range("A2:M2").Cells.Font.Bold = True
    .Range("A2:M2").Cells.Font.Color = RGB(68, 84, 106)
    .Range("A2:B2").HorizontalAlignment = xlCenter
    .Range("E2:J2").HorizontalAlignment = xlCenter

    'provide initial value to row counter
    i = 3
    'Loop through recordset and copy date from recordset to sheet
    Do While Not rs1.EOF

        .Range("A" & i).Value = rs1![Job Opened]
        .Range("B" & i).Value = rs1![Job Number]
        .Range("C" & i).Value = rs1![Job Title]
        .Range("D" & i).Value = rs1![ProposalRef]
        .Range("E" & i).Value = rs1![QuotedValue]
        .Range("F" & i).Value = rs1![Invoiced]
        .Range("G" & i).Value = rs1![Uplifted Cost]
        .Range("H" & i).Value = rs1![Profit]
        .Range("I" & i).Value = rs1![Diff]
        .Range("J" & i).Value = rs1![Last Date Worked]
        .Range("K" & i).Value = rs1![Reason]
        .Range("L" & i).Value = rs1![Status]
        .Range("M" & i).Value = rs1![Yr]

        i = i + 1
        rs1.MoveNext

        Loop

        'Total Average %
        .Range("F" & i).HorizontalAlignment = xlRight
        .Range("F" & i, "H" & i).Merge
        .Range("F" & i).Value = "Average % Profit (Billed vs Uplifted Cost)"
        .Range("F" & i).Cells.Font.Bold = True
        .Range("I" & i).Formula = "=AVERAGE(I3:I" & i - 1

        'Add borders
        .Range("A2:M2").Borders(xlEdgeTop).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M2").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:A" & i - 1).Borders(xlEdgeLeft).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeRight).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlInsideVertical).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous

        'Add Conditional formatting
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlGreater, 0)
            .Font.Color = RGB(0, 176, 80)
        End With
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlLess, 0)
            .Font.Color = vbRed
        End With

    End With

SubExit:
On Error Resume Next
DoCmd.Hourglass False
xlApp.Visible = True
rs1.Close
Set rs1 = Nothing
Exit Sub

 SubError:
MsgBox "Error Number: " & Err.Number & "= " & Err.Description, vbCritical + vbOKOnly, _
    "An error occurred"
GoTo SubExit
 End Sub

Body:
What you need to do is to introduce a new recordset that has a list of the distinct years in. You then loop this recordset, adding a new worksheet for each year, and then your original recordset is opened, but has a WHERE clause in the SQL to just show data for the year in question. Some abridged VBA to do this is below:

Sub sSampleExport()
    On Error GoTo E_Handle
    Dim db As DAO.Database
    Dim rsYear As DAO.Recordset
    Dim rsData As DAO.Recordset
    Dim strSQL As String
    Dim objXL As New Excel.Application
    Dim objXLBook As Excel.Workbook
    Dim objXLSheet As Excel.Worksheet
    Dim lngLoop1 As Long
    Set db = DBEngine(0)(0)
    strSQL = "SELECT DISTINCT Yr FROM BIID ORDER BY Yr ASC;"
    Set rsYear = db.OpenRecordset(strSQL)
    If Not (rsYear.BOF And rsYear.EOF) Then
        Set objXLBook = objXL.Workbooks.Add
        Do
            Set objXLSheet = objXLBook.Worksheets.Add(After:=objXLBook.Worksheets(objXLBook.Worksheets.Count))
            With objXLSheet
                .name = rsYear!Yr
                strSQL = "SELECT [Job Opened], [Job Number], [Job Title] " _
                    & " FROM BIID " _
                    & " WHERE Yr=" & rsYear!Yr
                Set rsData = db.OpenRecordset(strSQL)
                If Not (rsData.BOF And rsData.EOF) Then
                    .Cells(1, 1).CopyFromRecordset rsData
                End If
            End With
            rsYear.MoveNext
        Loop Until rsYear.EOF
        For lngLoop1= objXLBook.Worksheets.Count To 1 Step -1
            If Left(objXLBook.Worksheets(lngLoop1).Name, 5) = "Sheet" Then
                objXLBook.Worksheets(lngLoop1).Delete
            End If
        Next lngLoop1
        objXLBook.Worksheets(1).Select
        objXLBook.SaveAs "J:\downloads\test.xlsx"
    End If
sExit:
    On Error Resume Next
    rsData.Close
    rsYear.Close
    Set rsData = Nothing
    Set rsYear = Nothing
    Set db = Nothing
    Set objXLSheet = Nothing
    objXLBook.Close
    Set objXLBook = Nothing
    objXL.Quit
    Set objXL = Nothing
    Exit Sub
E_Handle:
    MsgBox Err.Description & vbCrLf & vbCrLf & "sSampleExport", vbOKOnly + vbCritical, "Error: " & Err.Number
    Resume sExit
End Sub

Regards,


问:
How to optimize queryset filtering
I have a little bit of code as follows:

```<code>    for prop in Property.objects.all():
        for platform_device in prop.platformdevice_set.all():
            if platform_device.platform == cur_platform:
                if platform_device.applicable_devices.filter(name=cur_device).exists():
                    if platform_device.applicable_events.filter(name=cur_event).exists():
                        print("Found my correct even and need to continue processing.")
                    else:
                        for group in platform_device.event_group.all():
                            if group.applicable_events.filter(name=cur_event).exists():
                                print("Found my correct even and need to continue processing.")
</code>```

It is a bit messy but it is working so far. Where I am stuck at is this portion:

```<code>                    if platform_device.applicable_events.filter(name=cur_event).exists():
                        print("Found my correct even and need to continue processing.")
                    else:
                        for group in platform_device.event_group.all():
                            if group.applicable_events.filter(name=cur_event).exists():
                                print("Found my correct even and need to continue processing.")
</code>```

Basically what I am doing is checking the platform_device.applicable_events to check if inside of that contains my cur_event. If it does then I need to continue processing from that point.

Else

I am going to look through a event_group (which is just a grouping of events) and checking if cur_event is inside of one of those groups and then continue processing.

My question is how can I make both of those avenues end up in the same spot. I am just trying to prevent having the same code in both of those locations.

答:
I would try to do as much work in the database as possible. Instead of "filtering" the queryset in python, filter it in the db.

```<code>for prop in Property.objects.filter(
    platformdevice__platform=cur_platform,
    platformdevice__applicable_devices=cur_device,
).filter(
    Q(platformdevice__applicable_events=cur_event)
    | Q(platform_device__event_group__applicable_events__name=cur_event)
):
    #continue processing
</code>```

the foo__bar=baz filters a related table foo for column bar with value baz. To filter for value A or B you can use Q-expressions

or: Q(..) | Q(..)

and: Q(..) & Q(..)  (same as normal filter)

Title: How to optimize queryset filtering

Body:
I have a little bit of code as follows:

    for prop in Property.objects.all():
        for platform_device in prop.platformdevice_set.all():
            if platform_device.platform == cur_platform:
                if platform_device.applicable_devices.filter(name=cur_device).exists():
                    if platform_device.applicable_events.filter(name=cur_event).exists():
                        print("Found my correct even and need to continue processing.")
                    else:
                        for group in platform_device.event_group.all():
                            if group.applicable_events.filter(name=cur_event).exists():
                                print("Found my correct even and need to continue processing.")

It is a bit messy but it is working so far. Where I am stuck at is this portion:

                    if platform_device.applicable_events.filter(name=cur_event).exists():
                        print("Found my correct even and need to continue processing.")
                    else:
                        for group in platform_device.event_group.all():
                            if group.applicable_events.filter(name=cur_event).exists():
                                print("Found my correct even and need to continue processing.")

Basically what I am doing is checking the platform_device.applicable_events to check if inside of that contains my cur_event. If it does then I need to continue processing from that point.

Else

I am going to look through a event_group (which is just a grouping of events) and checking if cur_event is inside of one of those groups and then continue processing.

My question is how can I make both of those avenues end up in the same spot. I am just trying to prevent having the same code in both of those locations.

Body:
I would try to do as much work in the database as possible. Instead of "filtering" the queryset in python, filter it in the db.

for prop in Property.objects.filter(
    platformdevice__platform=cur_platform,
    platformdevice__applicable_devices=cur_device,
).filter(
    Q(platformdevice__applicable_events=cur_event)
    | Q(platform_device__event_group__applicable_events__name=cur_event)
):
    #continue processing

the foo__bar=baz filters a related table foo for column bar with value baz. To filter for value A or B you can use Q-expressions

or: Q(..) | Q(..)

and: Q(..) & Q(..)  (same as normal filter)


问:
C Program : Array example
I read somewhere that i should be able to initialize the array like that. but why isn't it working.

```<code>#include<stdio.h>

main()
{
   char s[10];
   s[10]="pen";
   printf("%s\n",s[10]);
}
</code>```

output:
NULL

答:
After the array is declared, it is no longer an "initialization".

You are attempting an assignment.

But you cannot assign an entire array using the syntax: s[10]="pen";

```<code>main()
{
   char s[10] = "pen";    // Initialization
   printf("%s\n",s);
}
</code>```

Title: C Program : Array example

Body:
I read somewhere that i should be able to initialize the array like that. but why isn't it working.

#include<stdio.h>

main()
{
   char s[10];
   s[10]="pen";
   printf("%s\n",s[10]);
}

output:
NULL

Body:
After the array is declared, it is no longer an "initialization".

You are attempting an assignment.

But you cannot assign an entire array using the syntax: s[10]="pen";

main()
{
   char s[10] = "pen";    // Initialization
   printf("%s\n",s);
}


问:
Which JavaScript (ECMAScript) version does Java's Rhino implementation implement (and what's the update policy?)
Which version of the ECMAScript standard does Java's JavaScript engine Rhino support, how much work is going into fixing bugs and keeping the implementation in sync with the latest standardized version?</p>

答:
About the compatilibity with ES2015/ES6 only, you have this webpage from the Mozilla's official repository :

https://mozilla.github.io/rhino/compat/engines.html


问:
OpenMP Offloading with Private Arrays of Unknown Size at Compile Time
I am trying to offload several  nested for loops in fortran using OpenMP, XL compiler suite. 90% of the routines are straight forward, but a handful of the loops involve private 1D arrays that are of unknown size at compile time, but will always be on ~O(10), which is very manageable in terms of thread stack memory. Here is an example loop

```<code>implicit none
real, dimension(1:nseq) :: yy    !nseq is a global variable, usually 1-10,

!$omp target teams distribute parallel do collapse(3) schedule (static,1) &
!$omp& private(i, j, k) &
!$omp& private( yy )&
!omp& shared( ne )
do k=1,30
do j=1,30
do i=1,30

 yy = dummy_array(i,j,k,6:ne)  ! nseq is equal to ne-6... ne is a global variable
                               ! dummy_array is an allocatable array that exists persistently on
                               ! the GPU
  ...
  do stuff with yy
  ...
end do
end do
end do
</code>```

With this standard method, I get a lot of memory issues, varying between "out of memory errors" and  "an illegal memory access was encountered"

If I go in and hard code what I know the values of nseq will be ahead of time, i.e.

```<code>implicit none
real, dimension(1:10) :: yy
</code>```

Then I have no issues at all, so I am not ACTUALLY running out of memory on the GPU. This is obviously bad practice as these values change from case to case and are run time parameters.

I have experimented with ENV variables such as OMP_HEAPSIZE and OMP_STACKSIZE with no luck.

Thanks for taking a look!

答:
This turns out to be a compiler quirk/bug with the IBM XL compiler suite I was using.

A workaround that is not very desirable, but is effective, is to manually privitize the temporary array, i.e.

```<code>real, dimension(30,30,30,1:nseq) :: yy

!$omp target teams distribute parallel do collapse(3) schedule (static,1) &
!$omp& private(i, j, k) &
!$omp& private( yy )&
!omp& shared( ne )
do k=1,30
do j=1,30
do i=1,30

 yy(i,j,k,:) = dummy_array(i,j,k,6:ne)

  ...
  do stuff with yy
  ...
end do
end do
end do
</code>```

Body:
I am trying to offload several  nested for loops in fortran using OpenMP, XL compiler suite. 90% of the routines are straight forward, but a handful of the loops involve private 1D arrays that are of unknown size at compile time, but will always be on ~O(10), which is very manageable in terms of thread stack memory. Here is an example loop

implicit none
real, dimension(1:nseq) :: yy    !nseq is a global variable, usually 1-10,

!$omp target teams distribute parallel do collapse(3) schedule (static,1) &
!$omp& private(i, j, k) &
!$omp& private( yy )&
!omp& shared( ne )
do k=1,30
do j=1,30
do i=1,30

 yy = dummy_array(i,j,k,6:ne)  ! nseq is equal to ne-6... ne is a global variable
                               ! dummy_array is an allocatable array that exists persistently on
                               ! the GPU
  ...
  do stuff with yy
  ...
end do
end do
end do

With this standard method, I get a lot of memory issues, varying between "out of memory errors" and  "an illegal memory access was encountered"

If I go in and hard code what I know the values of nseq will be ahead of time, i.e.

implicit none
real, dimension(1:10) :: yy

Then I have no issues at all, so I am not ACTUALLY running out of memory on the GPU. This is obviously bad practice as these values change from case to case and are run time parameters.

I have experimented with ENV variables such as OMP_HEAPSIZE and OMP_STACKSIZE with no luck.

Thanks for taking a look!

Body:
This turns out to be a compiler quirk/bug with the IBM XL compiler suite I was using.

A workaround that is not very desirable, but is effective, is to manually privitize the temporary array, i.e.

real, dimension(30,30,30,1:nseq) :: yy

!$omp target teams distribute parallel do collapse(3) schedule (static,1) &
!$omp& private(i, j, k) &
!$omp& private( yy )&
!omp& shared( ne )
do k=1,30
do j=1,30
do i=1,30

 yy(i,j,k,:) = dummy_array(i,j,k,6:ne)

  ...
  do stuff with yy
  ...
end do
end do
end do


问:
Deserializing json in unity returns nothing
I'm using Jsonutility, the json file is read correctly but when checking the values of the class I get 0. I looked around similar questions but the result is the same, I either get 0 or null whenever I check the values after Deserializing. I think the problem is with how the json is formatted.

here's my json :

```<code>    {
   "StatsValues":{
      "HealthStat":{
         "_Min":700,
         "_Max":1200,
         "_Color":"255,255,255",
         "_Opacity":0.1
      },
      "SickStat":[
         {
            "name":"Sickness 1 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         },
         {
            "name":"Sickness 2 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         },
         {
            "name":"Sickness 3 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         },
         {
            "name":"Sickness 4 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         }
      ]
   }
}
</code>```

and My code :

```<code>StatsValues _stats = JsonUtility.FromJson<StatsValues>(jsonFile);

    [System.Serializable]
public class StatsValues
{
    public HealthStat _healthStats;
    public List<SickStat> _sickStats;
}

[System.Serializable]
public class HealthStat
{
    public int _Min;
    public int _Max;
    public string _Color;
    public float _Opacity;
}

[System.Serializable]
public class SickStat
{
    public string name;
    public int _Min;
    public int _Max;
    public string _Color;
    public float _Opacity;
}
</code>```

答:
You have one more nest level in your JSON since the "StatsValues" object is wrapped within additional { } so there is one more type object around it

Your classes' field names have to match exactly the field names in JSON. (The class names do not matter.)

You have "HealthStat" : ... and "SickStat" : ...

so it should be:

```<code>Data _stats = JsonUtility.FromJson<Data>(jsonFile);
var _healthStat = _stats.StatsValues.HealthStat;

[Serializable]
public class Data
{
    public StatsValues StatsValues;
}

[Serializable]
public class StatsValues
{
    public HealthStat HealthStat;
    public List<SickStat> SickStat;
}
</code>```

and in order to be a bit more c# like you could also do

```<code>[Serializable]
public class StatsValues
{
    public Stat HealthStat;
    public List<SickStat> SickStat;
}

[Serializable]
public class Stat
{
    public int _Min;
    public int _Max;
    public string _Color;
    public float _Opacity;
}

[Serializable]
public class SickStat : Stat
{
    public string name;
}
</code>```

Body:
I'm using Jsonutility, the json file is read correctly but when checking the values of the class I get 0. I looked around similar questions but the result is the same, I either get 0 or null whenever I check the values after Deserializing. I think the problem is with how the json is formatted.

here's my json :

    {
   "StatsValues":{
      "HealthStat":{
         "_Min":700,
         "_Max":1200,
         "_Color":"255,255,255",
         "_Opacity":0.1
      },
      "SickStat":[
         {
            "name":"Sickness 1 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         },
         {
            "name":"Sickness 2 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         },
         {
            "name":"Sickness 3 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         },
         {
            "name":"Sickness 4 name",
            "_Min":700,
            "_Max":1200,
            "_Color":"255,255,255",
            "_Opacity":0.1
         }
      ]
   }
}

and My code :

StatsValues _stats = JsonUtility.FromJson<StatsValues>(jsonFile);

    [System.Serializable]
public class StatsValues
{
    public HealthStat _healthStats;
    public List<SickStat> _sickStats;
}

[System.Serializable]
public class HealthStat
{
    public int _Min;
    public int _Max;
    public string _Color;
    public float _Opacity;
}

[System.Serializable]
public class SickStat
{
    public string name;
    public int _Min;
    public int _Max;
    public string _Color;
    public float _Opacity;
}

Body:
You have one more nest level in your JSON since the "StatsValues" object is wrapped within additional { } so there is one more type object around it

Your classes' field names have to match exactly the field names in JSON. (The class names do not matter.)

You have "HealthStat" : ... and "SickStat" : ...

so it should be:

Data _stats = JsonUtility.FromJson<Data>(jsonFile);
var _healthStat = _stats.StatsValues.HealthStat;

[Serializable]
public class Data
{
    public StatsValues StatsValues;
}

[Serializable]
public class StatsValues
{
    public HealthStat HealthStat;
    public List<SickStat> SickStat;
}

and in order to be a bit more c# like you could also do

[Serializable]
public class StatsValues
{
    public Stat HealthStat;
    public List<SickStat> SickStat;
}

[Serializable]
public class Stat
{
    public int _Min;
    public int _Max;
    public string _Color;
    public float _Opacity;
}

[Serializable]
public class SickStat : Stat
{
    public string name;
}


问:
A Frame Image displaying flat
I am trying to use  and  to track a marker used in a QR code, and when the marker is captured on the camera it shows an image on top. My code is able to recognise the marker and display the image, but the image is flatten and it only shows a thin line, even though I have set width and height to 4 (meters). Below is my source code and a screenshot of how the image is currently displaying on the camera. I have circled in red the line that corresponds to the image on camera.

```<code><!-- we add detectionMode and matrixCodeType to tell AR.js to recognize barcode markers -->
<a-scene embedded="" vr-mode-ui="enabled: false" arjs="sourceType: webcam; debugUIEnabled: false; detectionMode: mono_and_matrix; matrixCodeType: 3x3;">

<a-assets>
    <a-asset-item id="animated-asset" src="https://raw.githubusercontent.com/nicolocarpignoli/nicolocarpignoli.github.io/master/ar-playground/models/CesiumMan.gltf"></a-asset-item>
</a-assets>

<a-marker type="barcode" value="7">
    <a-image src="https://ewouk.com.au/wp-content/uploads/2020/04/cropped-Screen-Shot-2020-04-10-at-12.48.46-pm.png" width="4" height="4"></a-image>
</a-marker>

<a-marker id="animated-marker" type="barcode" value="6">
    <a-entity animation-mixer="" gltf-model="#animated-asset" scale="2 2 2">
    </a-entity>
</a-marker>

<a-entity camera=""></a-entity>
</a-scene>
</code>```

Screenshot:

答: I guess you need to rotate the image (something like <a-image rotation="90 0 0" ...).

Title: A Frame Image displaying flat

Body:
I am trying to use  and  to track a marker used in a QR code, and when the marker is captured on the camera it shows an image on top. My code is able to recognise the marker and display the image, but the image is flatten and it only shows a thin line, even though I have set width and height to 4 (meters). Below is my source code and a screenshot of how the image is currently displaying on the camera. I have circled in red the line that corresponds to the image on camera.

Screenshot:


答:
This is initialization: char s[10] = "pen";

This is assignment (and invalid syntax): s[10]="pen";

Similar syntax but different terms. Initialization is done together with the variable declaration. Generally, initialization could be carried out before the program is launched. Had you for example written const char s[10] = "pen";, then the string could be pre-loaded into the variable before the program starts.

Since s[10]="pen"; is invalid C but your compiler let it through with a warning (which you probably didn't read), consider compiling with stricter compiler settings. On gcc this means compiling with -pedantic-errors -Werror, which I strongly recommend beginners to use.

Title: C Program : Array example


问:
Android studio- disable donwload button/Activity when internet not availabe
I have a download button configured in my app. When I click the download button when the internet is not available, the button is getting clicked. When the internet is available, this download activity begins and the file is downloaded no of the times I clicked when the internet was offline.

Is there any way I can disable by download activity when internet is unavailable by giving a message check your internet connection'.

MainActivity

```<code>
public class Download_Activity extends AppCompatActivity {

    FirebaseFirestore downdb;
    RecyclerView downRecyclerView;
    ArrayList<Downloadsmodel> downloadsmodelArrayList=new ArrayList<>();
    DownloadsAdapter downloadsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_);

        setUpRV();
        setUpFB();
        dataFromFirebase();
    }

    private void dataFromFirebase() {
        downdb.collection("Downloads").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                for(DocumentSnapshot documentSnapshot: task.getResult()){

                    Downloadsmodel downloadsmodel= new Downloadsmodel(documentSnapshot.getString("name")
                            ,documentSnapshot.getString("link"),documentSnapshot.getString("fileextension"),documentSnapshot.getString("uploaddate"),documentSnapshot.getString("icon"));
                    downloadsmodelArrayList.add(downloadsmodel);
                }
                downloadsAdapter= new DownloadsAdapter(Download_Activity.this,downloadsmodelArrayList);
                downRecyclerView.setAdapter(downloadsAdapter);
            }
        })

                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(Download_Activity.this,"Error",  Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void setUpFB() {
        downdb=FirebaseFirestore.getInstance();
    }

    private void setUpRV() {
        downRecyclerView=findViewById(R.id.drecyclerdownloads);
        downRecyclerView.setHasFixedSize(true);
        downRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

}

</code>```

Download Adapter

```<code>
public class DownloadsAdapter extends RecyclerView.Adapter<Downloadsviewholder> {

    Download_Activity download_activity;
    ArrayList<Downloadsmodel> downloadsmodels;

    public DownloadsAdapter(Download_Activity download_activity, ArrayList<Downloadsmodel> downloadsmodels) {
        this.download_activity = download_activity;
        this.downloadsmodels = downloadsmodels;
    }

    @NonNull
    @Override
    public Downloadsviewholder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        LayoutInflater layoutInflater = LayoutInflater.from(download_activity.getBaseContext());
        View view = layoutInflater.inflate(R.layout.downloads_elements,null,false);
        return new Downloadsviewholder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final Downloadsviewholder downloadsviewholder, final int i) {
        downloadsviewholder.dName.setText(downloadsmodels.get(i).getName());
        downloadsviewholder.dUploaddate.setText(downloadsmodels.get(i).getUploaddate());
        downloadsviewholder.dExtension.setText(downloadsmodels.get(i).getFileextension());
        Picasso.get().load(downloadsmodels.get(i).getIcon()).into(downloadsviewholder.dIcon);
        downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dowloadFile(downloadsviewholder.dName.getContext(),downloadsmodels.get(i).getName(),downloadsmodels.get(i).getFileextension()
                        ,DIRECTORY_DOWNLOADS,downloadsmodels.get(i).getLink());

            }
        });

    }

    public void dowloadFile (Context context,String filename, String fileextension, String destinationdirectory, String url){

        DownloadManager downloadManager=(DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
        Uri uri=Uri.parse(url);
        DownloadManager.Request request=new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, destinationdirectory, filename+fileextension);
        downloadManager.enqueue(request);

    }

    @Override
    public int getItemCount() {
        return downloadsmodels.size();
    }
}

</code>```

答:
Use this function to check the internet connectivity

```<code>   protected boolean isInternetConnected() {
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        } else {
            return false;
        }
    }

</code>```

Inside your BindViewHolder use like this:

```<code>   downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                     if(isInternetConnected()){

               dowloadFile(downloadsviewholder.dName.getContext(),downloadsmodels.get(i).getName(),downloadsmodels.get(i).getFileextension()
                        ,DIRECTORY_DOWNLOADS,downloadsmodels.get(i).getLink());
               } else {

                    //Change your button color so it looks like disable if you want
                }

            }
        });
</code>```

Body:
I have a download button configured in my app. When I click the download button when the internet is not available, the button is getting clicked. When the internet is available, this download activity begins and the file is downloaded no of the times I clicked when the internet was offline.

Is there any way I can disable by download activity when internet is unavailable by giving a message check your internet connection'.

MainActivity

public class Download_Activity extends AppCompatActivity {

    FirebaseFirestore downdb;
    RecyclerView downRecyclerView;
    ArrayList<Downloadsmodel> downloadsmodelArrayList=new ArrayList<>();
    DownloadsAdapter downloadsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_);

        setUpRV();
        setUpFB();
        dataFromFirebase();
    }

    private void dataFromFirebase() {
        downdb.collection("Downloads").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                for(DocumentSnapshot documentSnapshot: task.getResult()){

                    Downloadsmodel downloadsmodel= new Downloadsmodel(documentSnapshot.getString("name")
                            ,documentSnapshot.getString("link"),documentSnapshot.getString("fileextension"),documentSnapshot.getString("uploaddate"),documentSnapshot.getString("icon"));
                    downloadsmodelArrayList.add(downloadsmodel);
                }
                downloadsAdapter= new DownloadsAdapter(Download_Activity.this,downloadsmodelArrayList);
                downRecyclerView.setAdapter(downloadsAdapter);
            }
        })

                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(Download_Activity.this,"Error",  Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void setUpFB() {
        downdb=FirebaseFirestore.getInstance();
    }

    private void setUpRV() {
        downRecyclerView=findViewById(R.id.drecyclerdownloads);
        downRecyclerView.setHasFixedSize(true);
        downRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

}

Download Adapter

public class DownloadsAdapter extends RecyclerView.Adapter<Downloadsviewholder> {

    Download_Activity download_activity;
    ArrayList<Downloadsmodel> downloadsmodels;

    public DownloadsAdapter(Download_Activity download_activity, ArrayList<Downloadsmodel> downloadsmodels) {
        this.download_activity = download_activity;
        this.downloadsmodels = downloadsmodels;
    }

    @NonNull
    @Override
    public Downloadsviewholder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        LayoutInflater layoutInflater = LayoutInflater.from(download_activity.getBaseContext());
        View view = layoutInflater.inflate(R.layout.downloads_elements,null,false);
        return new Downloadsviewholder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final Downloadsviewholder downloadsviewholder, final int i) {
        downloadsviewholder.dName.setText(downloadsmodels.get(i).getName());
        downloadsviewholder.dUploaddate.setText(downloadsmodels.get(i).getUploaddate());
        downloadsviewholder.dExtension.setText(downloadsmodels.get(i).getFileextension());
        Picasso.get().load(downloadsmodels.get(i).getIcon()).into(downloadsviewholder.dIcon);
        downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dowloadFile(downloadsviewholder.dName.getContext(),downloadsmodels.get(i).getName(),downloadsmodels.get(i).getFileextension()
                        ,DIRECTORY_DOWNLOADS,downloadsmodels.get(i).getLink());

            }
        });

    }

    public void dowloadFile (Context context,String filename, String fileextension, String destinationdirectory, String url){

        DownloadManager downloadManager=(DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
        Uri uri=Uri.parse(url);
        DownloadManager.Request request=new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, destinationdirectory, filename+fileextension);
        downloadManager.enqueue(request);

    }

    @Override
    public int getItemCount() {
        return downloadsmodels.size();
    }
}

Body:
Use this function to check the internet connectivity

   protected boolean isInternetConnected() {
        ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        } else {
            return false;
        }
    }

Inside your BindViewHolder use like this:

   downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                     if(isInternetConnected()){

               dowloadFile(downloadsviewholder.dName.getContext(),downloadsmodels.get(i).getName(),downloadsmodels.get(i).getFileextension()
                        ,DIRECTORY_DOWNLOADS,downloadsmodels.get(i).getLink());
               } else {

                    //Change your button color so it looks like disable if you want
                }

            }
        });


问:
How to get permalink of a review/rating from Facebook Graph API?
We are implementing a review system in our app and pulling Yelp, Facebook reviews for certain businesses from their respective pages.

With Yelp a permalink is included in data for each review so that we link back the user to the Yelp page.

We want to do the same with Facebook (Single View that lists Yelp and Facebook reviews for the business - the only problem is we are unable to get the permalink for the review from Facebook Graph API Data.

Found a Facebook Developer Community question requesting the same (asked 4 months ago) but no answer till date.

Is there any way that a Facebook Page Review's permalink can be obtained?

Any help is greatly appreciated.

答:
After a lot of googling and digging through docs and forums, we couldn't find a way to get the link from API data.

As a workaround, the URL(permalink) can be constructed from review data.

```<code>https://facebook.com/ + review_object.id
</code>```

So from graph API data, it would be - open_graph_story.id

NOTE: This approach would break if Facebook decides to change the URL structure in the future. So, be mindful of changes by Facebook.

Answer Credits: Kalidas M, my teammate.

Body:
After a lot of googling and digging through docs and forums, we couldn't find a way to get the link from API data.

As a workaround, the URL(permalink) can be constructed from review data.

https://facebook.com/ + review_object.id

So from graph API data, it would be - open_graph_story.id

NOTE: This approach would break if Facebook decides to change the URL structure in the future. So, be mindful of changes by Facebook.

Answer Credits: Kalidas M, my teammate.


问:
browser version - expressjs / morgan
I need to collect the user access log in the application, mainly the name and version of the browser he is using. However, morgan is bringing many details that I don't need, can you help me?

Currently:

Firefox

::1 - OPTIONS - /signin - 204 - 0 - 0.126 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0 -

Chrome

::1 - POST - /signin - 200 - 545 - 106.758 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 -

::1 - OPTIONS - /signin - 204 - 0 - 0.163 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 -

Expected:

Firefox

::1 - OPTIONS - /signin - 204 - 0 - 0.126 ms http://localhost:8080/auth - Firefox/76.0 -

Chrome

::1 - POST - /signin - 200 - 545 - 106.758 ms http://localhost:8080/auth -
Chrome/83.0.4103.61 -

My code:

```<code>app.use((req,res,next) => {
    const logger = morgan(function (tokens, req, res) {
        return [
            tokens['remote-addr'](req, res), '-',
            tokens.method(req, res), '-',
            tokens.url(req, res), '-',
            tokens.status(req, res), '-',
            tokens.res(req, res, 'content-length'), '-',
            tokens['response-time'](req, res), 'ms',
            tokens.referrer(req, res), '-',
            tokens['user-agent'](req, res), '-',
            ].join(' ')
        })
    logger(req,res,next)
})
</code>```

答:
I'm use a component called:
app.use(require('express-useragent').express())

const navigator = req.useragent.browser

Title: browser version - expressjs / morgan

Body:
I need to collect the user access log in the application, mainly the name and version of the browser he is using. However, morgan is bringing many details that I don't need, can you help me?

Currently:

Firefox

::1 - OPTIONS - /signin - 204 - 0 - 0.126 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0 -

Chrome

::1 - POST - /signin - 200 - 545 - 106.758 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 -

::1 - OPTIONS - /signin - 204 - 0 - 0.163 ms http://localhost:8080/auth - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 -

Expected:

Firefox

::1 - OPTIONS - /signin - 204 - 0 - 0.126 ms http://localhost:8080/auth - Firefox/76.0 -

Chrome

::1 - POST - /signin - 200 - 545 - 106.758 ms http://localhost:8080/auth -
Chrome/83.0.4103.61 -

My code:

app.use((req,res,next) => {
    const logger = morgan(function (tokens, req, res) {
        return [
            tokens['remote-addr'](req, res), '-',
            tokens.method(req, res), '-',
            tokens.url(req, res), '-',
            tokens.status(req, res), '-',
            tokens.res(req, res, 'content-length'), '-',
            tokens['response-time'](req, res), 'ms',
            tokens.referrer(req, res), '-',
            tokens['user-agent'](req, res), '-',
            ].join(' ')
        })
    logger(req,res,next)
})


问:
Not able to execute the sql file script from docker compose
I am trying to execute the sql files from docker compose.

My compose file is:

```<code>    - ../folder:/docker-entrypoint-initdb.d/folder1/
    - ../folder2:/docker-entrypoint-initdb.d/folder2/
</code>```

The sql files are in folder named folder.

Docker file is:

```<code>COPY init.sh /docker-entrypoint-initdb.d/init.sh
</code>```

init.sh file:

```<code>"${psql[@]}" -f folder1/*.sql
"${psql[@]}" -f folder2/*.sql

</code>```

I am getting :

postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1
postgres_1  |
postgres_1  | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sh
postgres_1  | /docker-entrypoint-initdb.d/init.sh: line : -f: command not found

答:
The code you have in the init.sh isn't standard Bourne shell syntax.  I believe that expansion will look for an environment variable named psql[@], and when no environment variable with that name exists (including the punctuation as part of the variable name), you will get an empty string (hence the -f option being interpreted as the command).

If you put your SQL initialization files directly in the container's /docker-entrypoint-initdb.d directory, the container startup will run them for you.  It's reasonable to inject these using a bind mount; you do not need a derived image.

version: '3'
services:
  db:
    # Stock PostgreSQL image, not something locally built
    image: postgres:12
    volumes:
      - pgdata:/var/lib/postgresql/data
      # Bind-mount init scripts directly into init directory
      - ./folder:/docker-entrypoint-initdb.d
volumes:
  pgdata:
```

<p>If you do want to store these files in the image, <code>COPY</code> the SQL scripts (and not the Bourne shell wrapper) into the init directory</p>

<pre class="lang-sh prettyprint-override"><code>COPY folder/*.sql /docker-entrypoint-initdb.d
</code>```

You need to do one or the other, but not both.

Body:
I am trying to execute the sql files from docker compose.

My compose file is:

    - ../folder:/docker-entrypoint-initdb.d/folder1/
    - ../folder2:/docker-entrypoint-initdb.d/folder2/

The sql files are in folder named folder.

Docker file is:

COPY init.sh /docker-entrypoint-initdb.d/init.sh

init.sh file:

"${psql[@]}" -f folder1/*.sql
"${psql[@]}" -f folder2/*.sql

I am getting :

postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1
postgres_1  |
postgres_1  | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sh
postgres_1  | /docker-entrypoint-initdb.d/init.sh: line : -f: command not found

Body:
The code you have in the init.sh isn't standard Bourne shell syntax.  I believe that expansion will look for an environment variable named psql[@], and when no environment variable with that name exists (including the punctuation as part of the variable name), you will get an empty string (hence the -f option being interpreted as the command).

If you put your SQL initialization files directly in the container's /docker-entrypoint-initdb.d directory, the container startup will run them for you.  It's reasonable to inject these using a bind mount; you do not need a derived image.

version: '3'
services:
  db:
    # Stock PostgreSQL image, not something locally built
    image: postgres:12
    volumes:
      - pgdata:/var/lib/postgresql/data
      # Bind-mount init scripts directly into init directory
      - ./folder:/docker-entrypoint-initdb.d
volumes:
  pgdata:

If you do want to store these files in the image, COPY the SQL scripts (and not the Bourne shell wrapper) into the init directory

COPY folder/*.sql /docker-entrypoint-initdb.d

You need to do one or the other, but not both.


答:
Strictly speaking this statement

```<code>s[10]="pen";
</code>```

is not an initialization. It is an assignment. You are trying to assign the string literal "pen" having the type char * to a non-existent element of the type char of the array s with the index 10.

So the both these statements

```<code>s[10]="pen";
printf("%s\n",s[10]);
</code>```

invoke undefined behavior.

Pay attention to that arrays have no the assignment operator. Arrays are non-modifiable lvalues. If you will write for example

```<code>s = "pen";
</code>```

the compiler will issue an error.

What you need is the following

```<code>char s[10] = "pen";
printf("%s\n",s);
</code>```

That is in this case the array s will be initialized with elements of the string literal. All elements that do not have a corresponding initializer of the string literal will be zero-initialized.

If to use assignments instead of the initialization then this declaration

```<code>char s[10] = "pen";
</code>```

is equivalent to

```<code>char s[10];
s[0] = 'p';
s[1] = 'e';
s[2] = 'n';
s[3] = '\0';
s[4] = '\0';
s[5] = '\0';
s[6] = '\0';`
s[7] = '\0';
s[8] = '\0';
s[9] = '\0';
</code>```

`

Title: C Program : Array example

Body:
Strictly speaking this statement

s[10]="pen";

is not an initialization. It is an assignment. You are trying to assign the string literal "pen" having the type char * to a non-existent element of the type char of the array s with the index 10.

So the both these statements

s[10]="pen";
printf("%s\n",s[10]);

invoke undefined behavior.

Pay attention to that arrays have no the assignment operator. Arrays are non-modifiable lvalues. If you will write for example

s = "pen";

the compiler will issue an error.

What you need is the following

char s[10] = "pen";
printf("%s\n",s);

That is in this case the array s will be initialized with elements of the string literal. All elements that do not have a corresponding initializer of the string literal will be zero-initialized.

If to use assignments instead of the initialization then this declaration

char s[10] = "pen";

is equivalent to

char s[10];
s[0] = 'p';
s[1] = 'e';
s[2] = 'n';
s[3] = '\0';
s[4] = '\0';
s[5] = '\0';
s[6] = '\0';`
s[7] = '\0';
s[8] = '\0';
s[9] = '\0';

`


问:
Spring data neo4j change of database context at runtime
I am having a really hard time using spring-data-neo4j using neo4j 4.0.0. With this version of Neo4j, there is a possibility to switch between databases, and I need to do this to implement a multi-tenancy system where each tenant has its own database.

However, spring-data-neo4j doesn't seem to provide any way to switch of database at runtime with the latest version (this also have to be thread-safe).

What I thought of is to create a single sessionFactory per tenant doing so

    val sessionFactory = createTenantSessionFactory()
    val session = sessionFactory.openSession()
    val factory = Neo4jRepositoryFactory(session, mappingContext)
    val repository = factory.getRepository(DesiredNeo4jRepository::class.java)
```

However, with this solution, I am experiencing problems of concurrency, even though requests are executed one after the other in a single thread, the result in the database end up wrong.

I figured out that this might probably be because I am not using transaction management support offered by spring with this solution, because Neo4jTransactionManager is not created.

I realise this is really complex question, but did I take a good approach for the problem, or is there a better alternative I haven't seen?

If there is no better way, how can I support transaction management with this solution?

Thank you for your help!

答:
I finally figured out how to fix it for now using the solution from https://community.neo4j.com/t/spring-data-neo4j-4-0-release-multi-tenant/12920

So I implemented an TenantContext

object ApplicationContext {

    private val currentTenant = ThreadLocal<String>()

    fun setCurrentTenant(tenantName: String) {
        currentTenant.set(tenantName)
    }

    fun getCurrentTenant(): String? {
        return currentTenant.get()
    }

    // Just a utility function
    fun withTenantContext(tenant: String, handler: (() -> Unit)) {
        val currentTenant = getCurrentTenant()
        setCurrentTenant(tenant)
        handler()

        if (currentTenant != null) {
            setCurrentTenant(currentTenant)
        } else {
            clearTenant()
        }
    }

    fun clearTenant() {
        currentTenant.remove()
    }
}

```

<p>And override the session factory. Unfortunately, <code>SessionFactory</code> doesn't expose an interface, so I had to override it and pass a fake package and an empty driver (Just implement <code>org.neo4j.ogm.driver.Driver</code> class and leave it empty). </p>

<p>This is more a hotfix than a real solution while waiting for a solution from <code>spring-data-neo4j</code>, but it works in a multi-thread context and suits my needs.</p>

<pre class="lang-kotlin prettyprint-override"><code>class MultiTenantSessionFactory(private val sessionFactories: ConcurrentMap<String, SessionFactory>) : SessionFactory(EmptyDriver(), "fake.package") {

    override fun openSession(): Session {
        return getSessionFactory(getCurrentTenantOrThrow()).openSession()
    }

    override fun close() {
        getSessionFactory(getCurrentTenantOrThrow()).close()
    }

    private fun getSessionFactory(tenantName: String): SessionFactory {
        return sessionFactories[tenantName] ?: throw UnregisteredSessionFactoryException(tenantName)
    }

    private fun getCurrentTenantOrThrow(): String {
        return ApplicationContext.getCurrentTenant() ?: throw EmptyTenantContextException()
    }
}
</code>```

Finally, just create a bean for this session factory while using @EnableNeo4jRepositories

    @Bean
    fun sessionFactory(tenantRepository: TenantRepository): SessionFactory {
        return MultiTenantSessionFactory(
                tenantRepository.findAll()
                        .map { tenant -> tenant.name to initTenantSessionFactory(tenant) }
                        .toMap(ConcurrentHashMap())
        )
    }

```

You should now be able to use all your Neo4jRepository transparently in a multi-tenant context. Hope this helps someone!

Body:
I am having a really hard time using spring-data-neo4j using neo4j 4.0.0. With this version of Neo4j, there is a possibility to switch between databases, and I need to do this to implement a multi-tenancy system where each tenant has its own database.

However, spring-data-neo4j doesn't seem to provide any way to switch of database at runtime with the latest version (this also have to be thread-safe).

What I thought of is to create a single sessionFactory per tenant doing so

    val sessionFactory = createTenantSessionFactory()
    val session = sessionFactory.openSession()
    val factory = Neo4jRepositoryFactory(session, mappingContext)
    val repository = factory.getRepository(DesiredNeo4jRepository::class.java)

However, with this solution, I am experiencing problems of concurrency, even though requests are executed one after the other in a single thread, the result in the database end up wrong.

I figured out that this might probably be because I am not using transaction management support offered by spring with this solution, because Neo4jTransactionManager is not created.

I realise this is really complex question, but did I take a good approach for the problem, or is there a better alternative I haven't seen?

If there is no better way, how can I support transaction management with this solution?

Thank you for your help!

Body:
I finally figured out how to fix it for now using the solution from https://community.neo4j.com/t/spring-data-neo4j-4-0-release-multi-tenant/12920

So I implemented an TenantContext

object ApplicationContext {

    private val currentTenant = ThreadLocal<String>()

    fun setCurrentTenant(tenantName: String) {
        currentTenant.set(tenantName)
    }

    fun getCurrentTenant(): String? {
        return currentTenant.get()
    }

    // Just a utility function
    fun withTenantContext(tenant: String, handler: (() -> Unit)) {
        val currentTenant = getCurrentTenant()
        setCurrentTenant(tenant)
        handler()

        if (currentTenant != null) {
            setCurrentTenant(currentTenant)
        } else {
            clearTenant()
        }
    }

    fun clearTenant() {
        currentTenant.remove()
    }
}

And override the session factory. Unfortunately, SessionFactory doesn't expose an interface, so I had to override it and pass a fake package and an empty driver (Just implement org.neo4j.ogm.driver.Driver class and leave it empty).

This is more a hotfix than a real solution while waiting for a solution from spring-data-neo4j, but it works in a multi-thread context and suits my needs.

class MultiTenantSessionFactory(private val sessionFactories: ConcurrentMap<String, SessionFactory>) : SessionFactory(EmptyDriver(), "fake.package") {

    override fun openSession(): Session {
        return getSessionFactory(getCurrentTenantOrThrow()).openSession()
    }

    override fun close() {
        getSessionFactory(getCurrentTenantOrThrow()).close()
    }

    private fun getSessionFactory(tenantName: String): SessionFactory {
        return sessionFactories[tenantName] ?: throw UnregisteredSessionFactoryException(tenantName)
    }

    private fun getCurrentTenantOrThrow(): String {
        return ApplicationContext.getCurrentTenant() ?: throw EmptyTenantContextException()
    }
}

Finally, just create a bean for this session factory while using @EnableNeo4jRepositories

    @Bean
    fun sessionFactory(tenantRepository: TenantRepository): SessionFactory {
        return MultiTenantSessionFactory(
                tenantRepository.findAll()
                        .map { tenant -> tenant.name to initTenantSessionFactory(tenant) }
                        .toMap(ConcurrentHashMap())
        )
    }

You should now be able to use all your Neo4jRepository transparently in a multi-tenant context. Hope this helps someone!


问:
Why does question mark get interpreted as "z" in Ruby
Why does this line output "z" instead of "?"

$ ruby -e 'puts %x[ echo #{"?"} ]'

Suppose the expression inside the #{...} is a variable that may have the value of "?". How should I modify this script so that the question mark is outputted instead of "z"?

(Please forgive the title of this question -- I don't yet understand what is going on here well enough to provide a more descriptive title.)

答:
It's not ruby, it's your shell.

Many shells expand the ? character to match a single character in command line arguments.
It's useful, if you have a bunch of files name tempA,temp1,tempB,...,temp9 that you want to delete, but you don't want to delete 'temple'

```<code>% rm temp?
</code>```

So I'm guessing you have a file or directory in your working directory named 'z', and the ? matches that, so it gets replaced by the shell.

Normally, when inside single quotes (like your ruby script) it wouldn't get expanded, but since you're passing the question mark to a shell command, it gets expanded there.

```<code>% ruby -e 'puts %x[ echo ? ]'
z
%
</code>```

Should show you the same behaviour.

Also, if you touch a couple other single character filenames like a b c d, those should show up too:

```<code>% touch a b c
% ruby -e 'puts %x[ echo ? ]'
a b c z
%
</code>```

If you want to avoid this when calling exterior shell commands from within ruby, you'll have to escape any strings you pass out.  For most purposes String#inspect should give a good enough escaping.

ContentLicense: CC BY-SA 2.5

Body:
It's not ruby, it's your shell.

Many shells expand the ? character to match a single character in command line arguments.
It's useful, if you have a bunch of files name tempA,temp1,tempB,...,temp9 that you want to delete, but you don't want to delete 'temple'

% rm temp?

So I'm guessing you have a file or directory in your working directory named 'z', and the ? matches that, so it gets replaced by the shell.

Normally, when inside single quotes (like your ruby script) it wouldn't get expanded, but since you're passing the question mark to a shell command, it gets expanded there.

% ruby -e 'puts %x[ echo ? ]'
z
%

Should show you the same behaviour.

Also, if you touch a couple other single character filenames like a b c d, those should show up too:

% touch a b c
% ruby -e 'puts %x[ echo ? ]'
a b c z
%

If you want to avoid this when calling exterior shell commands from within ruby, you'll have to escape any strings you pass out.  For most purposes String#inspect should give a good enough escaping.

OwnerDisplayName: rampion

LastEditorDisplayName: rampion


问:
what is parse error: naked expression at top level?
I was trying to get the length of each element, given a nested list; and I also I want to get rid of the repeated length.

For example, a nested list [[1],[1,2],[4..5]] should give me [1,2].

I can do it in the interactive by nub (map  length  [[1],[1,2],[4..5]]). But if I write a file with the following code:

```<code>Import Data.List
getLen :: [[a]] ->[Int]
getLen xs = nub (map length xs)
</code>```

I got the error saying:

"Parse error: naked expression at top level"

What does this error mean and how can I fix this?

答: Simple change: it's import not Import.

Body:
I was trying to get the length of each element, given a nested list; and I also I want to get rid of the repeated length.

For example, a nested list [[1],[1,2],[4..5]] should give me [1,2].

I can do it in the interactive by nub (map  length  [[1],[1,2],[4..5]]). But if I write a file with the following code:

Import Data.List
getLen :: [[a]] ->[Int]
getLen xs = nub (map length xs)

I got the error saying:

"Parse error: naked expression at top level"

What does this error mean and how can I fix this?

Body: Simple change: it's import not Import.


问:
Wordpress Avada Theme remove border
How do I remove in Wordpress Avada Theme the top borders, which automatically appear everywhere and look like this:

I can remove them in Chrome dev tools just like this:

But if I put e.g. this css code inside the Avada themes custom css, it is still there:

```<code>#main .fusion-row {
    border-top: 0px !important;
}
</code>```

答:
The solution was to consider the page id in the css:

```<code>.page-id-xxxx #main .fusion-row {
    border: none;
}
</code>```

Title: Wordpress Avada Theme remove border

Body:
How do I remove in Wordpress Avada Theme the top borders, which automatically appear everywhere and look like this:

I can remove them in Chrome dev tools just like this:

But if I put e.g. this css code inside the Avada themes custom css, it is still there:

#main .fusion-row {
    border-top: 0px !important;
}

Body:
The solution was to consider the page id in the css:

.page-id-xxxx #main .fusion-row {
    border: none;
}