问:
Laravel 9.42 Facing problems routing to the correct page below is my code instead of saving to db when i press button input fields are cleared
When i press the store button instead of posting to the db its clearing the input fileds  when i press the button store the information must be posted to the database and the redirects to the admin.menus.index but when i press the store button the input filelds are only cleraed

My Controller

```<code><?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Menu;
use App\Models\Category;
use App\Http\Requests\MenuStoreRequest;
use Illuminate\Support\Facades\Storage;

class MenuController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $menus = Menu::all();
        return view('admin.menus.index',compact('menus'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        $categories = Category::all();
        return view('admin.menus.create',compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(MenuStoreRequest $request)
    {
        $image = $request->file('image')->store('public/menus');

        Menu::create([

            'name' => $request->name,
            'description' => $request->description,
            'image' => $image,
            'price' => $request->price

        ]);

        return to_route('admin.menus.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

</code>```

My blade file

```<code><x-admin-layout>
  <x-slot name="header">
      <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
          {{ __('Dashboard') }}
      </h2>
  </x-slot>

  <div class="py-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">

          <div class=" flex justify-items-end m-2 p-2">
              <a href="{{ route('admin.menus.index') }}" class="px-4 py-2 bg-indigo-500 hover:bg-indigo-600 rounded-lg text-white">Menus Index</a>
          </div>

          <div class="m-2 p-2 bg-slate-100 rounded">
              <div class="space-y-8 divide-y divide-gray-200 w-1/2 mt-10">
                  <form  method="POST" action="{{ route('admin.menus.store') }}" enctype="multipart/form-data">
                    @csrf

                    <div class="sm:col-span-6">
                      <label for="name" class="block text-sm font-medium text-gray-700"> Name </label>
                      <div class="mt-1">
                        <input type="text" id="name"  name="name"
                        class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
                      </div>
                    </div>
                    <div class="sm:col-span-6">
                      <label for="image" class="block text-sm font-medium text-gray-700"> Image </label>
                      <div class="mt-1">
                        <input type="file" id="image" " name="image" class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
                      </div>
                    </div>
                    <div class="sm:col-span-6 pt-5">
                      <label for="body" class="block text-sm font-medium text-gray-700">Price</label>
                      <div class="mt-1">
                        <input type="number"  min ="0.00" max ="10000.00" step="0.01" id="price" wire:model.lazy="price" name="price" class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
                      </div>
                    </div>

                    <div class="sm:col-span-6 pt-5">
                      <label for="body" class="block text-sm font-medium text-gray-700">Description</label>
                      <div class="mt-1">
                        <textarea id="body" rows="3" wire:model.lazy="body" class="shadow-sm focus:ring-indigo-500 appearance-none bg-white border  py-2 px-3 text-base leading-normal transition duration-150 ease-in-out focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"></textarea>
                      </div>
                    </div>

                    <div class="sm:col-span-6 pt-5">
                      <label for="body" class="block text-sm font-medium text-gray-700">Categories</label>
                      <div class="mt-1">
                         <select id="categories" name="categories[]" class="form-multiselect block w-full mt-1"
                          multiple>

                            @foreach ($categories as $category)
                            <option>{{ $category->name }}</option>
                            @endforeach
                         </select>
                      </div>
                    </div>

                    <div class="mt-6 p-4">

                      <button type="submit"
                      class="py-2 px-4  bg-indigo-500 hover:bg-indigo-700 rounded-lg text-white">
                          Store
                      </button>

                    </div>

                  </form>
                </div>

          </div>

      </div>
  </div>
</x-admin-layout>

</code>```

My Request

```<code><?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MenuStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name' =>['required'],
            'description' =>['required'],
            'price' =>['required'],
            'image' =>['required','image'],

        ];
    }
}
</code>```

Body:
When i press the store button instead of posting to the db its clearing the input fileds  when i press the button store the information must be posted to the database and the redirects to the admin.menus.index but when i press the store button the input filelds are only cleraed

My Controller

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Menu;
use App\Models\Category;
use App\Http\Requests\MenuStoreRequest;
use Illuminate\Support\Facades\Storage;

class MenuController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $menus = Menu::all();
        return view('admin.menus.index',compact('menus'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        $categories = Category::all();
        return view('admin.menus.create',compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(MenuStoreRequest $request)
    {
        $image = $request->file('image')->store('public/menus');

        Menu::create([

            'name' => $request->name,
            'description' => $request->description,
            'image' => $image,
            'price' => $request->price

        ]);

        return to_route('admin.menus.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

My blade file

<x-admin-layout>
  <x-slot name="header">

          {{ __('Dashboard') }}

  </x-slot>

              Menus Index

                  <form  method="POST" action="{{ route('admin.menus.store') }}" enctype="multipart/form-data">
                    @csrf

                       Name

                        <input type="text" id="name"  name="name"
                        class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />

                       Image

                        <input type="file" id="image" " name="image" class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />

                      Price

                        <input type="number"  min ="0.00" max ="10000.00" step="0.01" id="price" wire:model.lazy="price" name="price" class="block w-full  appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />

                      Description

                        <textarea id="body" rows="3" wire:model.lazy="body" class="shadow-sm focus:ring-indigo-500 appearance-none bg-white border  py-2 px-3 text-base leading-normal transition duration-150 ease-in-out focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"></textarea>

                      Categories

                         <select id="categories" name="categories[]" class="form-multiselect block w-full mt-1"
                          multiple>

                            @foreach ($categories as $category)
                            <option>{{ $category->name }}</option>
                            @endforeach
                         </select>

                      <button type="submit"
                      class="py-2 px-4  bg-indigo-500 hover:bg-indigo-700 rounded-lg text-white">
                          Store
                      </button>

                  </form>

</x-admin-layout>

My Request

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MenuStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name' =>['required'],
            'description' =>['required'],
            'price' =>['required'],
            'image' =>['required','image'],

        ];
    }
}


来源: stackexchange

问:
Fulfillment with "location_id" in latest 2023 -01 API
"Create a new Fulfillment API" available in API version 2022 - 04,
using this API we create the fulfillment with "location_id" now Shopify removed this API endpoint on 2022-07 API,

Please mention which API call was used to create the fulfillment order using "location_id" in the latest 2023 -01 API.

ContentLicense: CC BY-SA 4.0


问:
Django Admin custom field in ModelForm is displayed as blank after being set in get_readonly_fields
I am using python 3.10 and Django 4.1
The model I'm making an admin panel for has a JSONField that will hold values from dynamically created form fields in the Admin panel. The issue is that I should be able to also dynamically set them to readonly from the AdminModel using the get_readonly_fields method.

To do that I made a custom ModelForm which adds new fields inside the _init_ method.

```<code>class CustomForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CustomForm, self).__init__(*args, **kwargs)
        for name in dynamic_fields_names():
            self.fields[name] = forms.ChoiceField(choices=dynamic_fields_values(name))

    def clean(self):
        cleaned_data = super(ExecutionAdminForm, self).clean()
        for name in dynamic_fields_names():
            self.instance.description_fields[name] = cleaned_data.pop(name)

    class Meta:
        model = Execution
        fields = "__all__"

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = CustomForm

    def get_form(self, request, obj=None, **kwargs):
        kwargs["fields"] = admin.utils.flatten_fieldsets(self.fieldsets)
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

    def get_fieldsets(self, request, obj):
         return (
            (None, {"fields": ("user", "status")}),
            ("Description", {"fields": dynamic_fields_names()})
        )

    def get_readonly_fields(self, request, obj):
        if can_change_dynamic_fields:
            return []
        return dynamic_fields_names()
</code>```

When I set them to readonly using get_readonly_fields they are rendered as empty inside the browser

Not set as readonly

Set as readonly

Body:
I am using python 3.10 and Django 4.1
The model I'm making an admin panel for has a JSONField that will hold values from dynamically created form fields in the Admin panel. The issue is that I should be able to also dynamically set them to readonly from the AdminModel using the get_readonly_fields method.

To do that I made a custom ModelForm which adds new fields inside the _init_ method.

class CustomForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CustomForm, self).__init__(*args, **kwargs)
        for name in dynamic_fields_names():
            self.fields[name] = forms.ChoiceField(choices=dynamic_fields_values(name))

    def clean(self):
        cleaned_data = super(ExecutionAdminForm, self).clean()
        for name in dynamic_fields_names():
            self.instance.description_fields[name] = cleaned_data.pop(name)

    class Meta:
        model = Execution
        fields = "__all__"

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    form = CustomForm

    def get_form(self, request, obj=None, **kwargs):
        kwargs["fields"] = admin.utils.flatten_fieldsets(self.fieldsets)
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

    def get_fieldsets(self, request, obj):
         return (
            (None, {"fields": ("user", "status")}),
            ("Description", {"fields": dynamic_fields_names()})
        )

    def get_readonly_fields(self, request, obj):
        if can_change_dynamic_fields:
            return []
        return dynamic_fields_names()

When I set them to readonly using get_readonly_fields they are rendered as empty inside the browser

Not set as readonly

Set as readonly


问:
PHP-AJAX, load more data on scroll: what if there's more data available but no need for scrolling?
I've got a working load more data on scrolling using PHP and Jquery.
It fetches 10 rows of data and displays them in a scrollable div container, which is 90% of the viewport in height.
On scrolling the next set of 10 rows is loaded.

My question: what if the available height of the scrollable div container is greater than the height required by the first 10 rows of data?
In this case there'll be no need for scrolling (in fact there isn't even a scrollbar present) and no more data, however available, can be loaded.
How would you tackle this problem?
Many thanks for your support.


问:
Sharing cookies between domain and subdomain and viceversa
I have two different web applications: one is hosted on example.com and the other one is hosted on subdomain.example.com. I want to do so that if user enters one of them for the first time, a cookies banner appears and cookie preferences become same for both applications. In other words, I'd like to share cookies between example.com and subdomain.example.com and viceversa. I know that it should be possible to share cookies with websites hosted on subdomains. But the possibility of sharing cookies with the root domain from subdomain is still not clear to me.

So if users enters subdomain.example.com, can its cookies be sent to example.com? And viceversa?


问:
Why am not able to move content elements after installing tx:container together with tx:gridelements in TYPO3 10?
[See solution below]

To move a TYPO3 10 website from tx:gridelements to tx:container I installed tx:container and configured it as it should be. Everything works like a charm.
But when I try to move an element (id: 203) into a container-element there occurs an error:

```<code>2: SQL error: 'Data truncated for column 'colPos' at row 1' (tt_content:203)
</code>```

When I then copy the same element and paste it into the container-element it is shown and works like a charm.

[SOLUTION]
There was also a module called paste_reference installed and after updating it everything works as it should.

Body:
[See solution below]

To move a TYPO3 10 website from tx:gridelements to tx:container I installed tx:container and configured it as it should be. Everything works like a charm.
But when I try to move an element (id: 203) into a container-element there occurs an error:

2: SQL error: 'Data truncated for column 'colPos' at row 1' (tt_content:203)

When I then copy the same element and paste it into the container-element it is shown and works like a charm.

[SOLUTION]
There was also a module called paste_reference installed and after updating it everything works as it should.


问:
difference protobuf & non-protobuf methods
I want to understand the difference between protobuf & non-protobuf methods with respect to grpc with some example

understand the difference between protobuf & non-protobuf methods with respect to grpc with some example


问:
The line for router-dom does not work in React. I don't know what the problem is, PhpStorm emphasizes in italics
{publicRoutes.map(({path, Container}) => <Route key={path} path={path} element={Container} exact/> )}
is Auth is a variable that is responsible for checking whether the user is authorized or not
publicRoutes is an array that has a path- the path of the address bar and a Container that launches the desired js component
For example:
export const SHOP_ROUTE = './shop' export const publicRoutes = [ { path: SHOP_ROUTE, Container: Shop },

Why that code doesn't work?
I don't understand why PhpStorm emphasizes it in italics, but it doesn't work on the site itself
It does not give errors

And also, I studied by video, according to the old version of router-dom, now I'm adapting, maybe that's the point?


问:
Error When Reading File Using plpython3u in PostgreSQL on Windows
I am working on a project where I need to move PostgreSQL from Linux to Windows and upgrade it to version 14.  Most of it seems to work and I was able to get plpython3u added.  I am running into two issues though.

I am getting a permission denied error.  If I give "everyone" read permissions I can access the file.  Obviously, I don't want to give every file these permissions, but I can't find any documentation on what PostgreSQL is using, through plpython3u, to access the file system so that I can give it the appropriate permissions.

Even after I get around the permissions issue I run into this error.

[38000] ERROR: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position X: character maps to  Where: Traceback (most recent call last):

When I look into the issue people suggest setting the encoding, but since I am doing a binary read, there is no way to set an encoding.  So, at this point, I am stumped about what is happening.  I did run the code outside of PostgreSQL and I didn't get any errors at all.  Here is the code in question:

```<code>fo = open(filetoforward, 'rb')
fr = fo.read()
msgtoforward = email.message_from_bytes(fr)
fo.close()
</code>```

Body:
I am working on a project where I need to move PostgreSQL from Linux to Windows and upgrade it to version 14.  Most of it seems to work and I was able to get plpython3u added.  I am running into two issues though.

I am getting a permission denied error.  If I give "everyone" read permissions I can access the file.  Obviously, I don't want to give every file these permissions, but I can't find any documentation on what PostgreSQL is using, through plpython3u, to access the file system so that I can give it the appropriate permissions.

Even after I get around the permissions issue I run into this error.

[38000] ERROR: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position X: character maps to  Where: Traceback (most recent call last):

When I look into the issue people suggest setting the encoding, but since I am doing a binary read, there is no way to set an encoding.  So, at this point, I am stumped about what is happening.  I did run the code outside of PostgreSQL and I didn't get any errors at all.  Here is the code in question:

fo = open(filetoforward, 'rb')
fr = fo.read()
msgtoforward = email.message_from_bytes(fr)
fo.close()


问:
Vue3 leaflet TypeError: Icon is undefined
I'm trying to make a map on my vue3 project but vue-leaflet is throwing me the following error even with the most basic map component (I tried with the one from the doc).

TypeError: Icon is undefined

I don't know what I'm doing wrong with my setup and I can't find any issues about this problem on their git page. Did someone else encounter this issue ?

My package.json :

```<code>{
  "name": "map-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "axios": "^1.2.2",
    "@vue-leaflet/vue-leaflet": "0.6.1",
    "leaflet": "^1.7.1",
    "leaflet.markercluster": "^1.5.3",
    "pinia": "^2.0.28",
    "vue": "^3.2.45",
    "vue-router": "^4.1.6",
    "vuetify": "^3.1.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.0.0",
    "vite": "^4.0.0"
  }
}
</code>```

My map component Carte.vue (from the official doc) :

```<code><template>
  <div>
    <l-map ref="map" v-model:zoom="zoom" :center="[47.41322, -1.219482]">
      <l-tile-layer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          layer-type="base"
          name="OpenStreetMap"
      ></l-tile-layer>
    </l-map>
  </div>
</template>

<script>
import "leaflet/dist/leaflet.css";
import { LMap , LTileLayer } from "@vue-leaflet/vue-leaflet";
export default {
  name: "Carte",
  components: {
    LMap,
    LTileLayer,
  },
  data() {
    return {
      zoom: 2,
    };
  },
}
</script>
</code>```

Body:
I'm trying to make a map on my vue3 project but vue-leaflet is throwing me the following error even with the most basic map component (I tried with the one from the doc).

TypeError: Icon is undefined

I don't know what I'm doing wrong with my setup and I can't find any issues about this problem on their git page. Did someone else encounter this issue ?

My package.json :

{
  "name": "map-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "axios": "^1.2.2",
    "@vue-leaflet/vue-leaflet": "0.6.1",
    "leaflet": "^1.7.1",
    "leaflet.markercluster": "^1.5.3",
    "pinia": "^2.0.28",
    "vue": "^3.2.45",
    "vue-router": "^4.1.6",
    "vuetify": "^3.1.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.0.0",
    "vite": "^4.0.0"
  }
}

My map component Carte.vue (from the official doc) :

<template>

    <l-map ref="map" v-model:zoom="zoom" :center="[47.41322, -1.219482]">
      <l-tile-layer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          layer-type="base"
          name="OpenStreetMap"
      ></l-tile-layer>
    </l-map>

</template>


问:
gym_recording does not get imported at all ! I have tried everything
```<code>import os
import numpy as np
import gym
from gym import wrappers
from gym_recording.wrappers import Monitor
# import pybullet_envs

ENV_NAME = 'BipedalWalker-v3'
# ENV_NAME = 'HalfCheetahBulletEnv-v0'

class Hp():
    # Hyperparameters
    def __init__(self,
                 nb_steps=1000,
                 episode_length=2000,
                 learning_rate=0.02,
                 num_deltas=16,
                 num_best_deltas=16,
                 noise=0.03,
                 seed=1,
                 env_name='BipedalWalker-v2',
                 record_every=50):

        self.nb_steps = nb_steps
        self.episode_length = episode_length
        self.learning_rate = learning_rate
        self.num_deltas = num_deltas
        self.num_best_deltas = num_best_deltas
        assert self.num_best_deltas <= self.num_deltas
        self.noise = noise
        self.seed = seed
        self.env_name = env_name
        self.record_every = record_every

class Normalizer():
    # Normalizes the inputs
    def __init__(self, nb_inputs):
        self.n = np.zeros(nb_inputs)
        self.mean = np.zeros(nb_inputs)
        self.mean_diff = np.zeros(nb_inputs)
        self.var = np.zeros(nb_inputs)

    def observe(self, x):
        self.n += 1.0
        last_mean = self.mean.copy()
        self.mean += (x - self.mean) / self.n
        self.mean_diff += (x - last_mean) * (x - self.mean)
        self.var = (self.mean_diff / self.n).clip(min = 1e-2)

    def normalize(self, inputs):
        obs_mean = self.mean
        obs_std = np.sqrt(self.var)
        return (inputs - obs_mean) / obs_std

class Policy():
    def __init__(self, input_size, output_size, hp):
        self.theta = np.zeros((output_size, input_size))
        self.hp = hp

    def evaluate(self, input, delta = None, direction = None):
        if direction is None:
            return self.theta.dot(input)
        elif direction == "+":
            return (self.theta + self.hp.noise * delta).dot(input)
        elif direction == "-":
            return (self.theta - self.hp.noise * delta).dot(input)

    def sample_deltas(self):
        return [np.random.randn(*self.theta.shape) for _ in range(self.hp.num_deltas)]

    def update(self, rollouts, sigma_rewards):
        # sigma_rewards is the standard deviation of the rewards
        step = np.zeros(self.theta.shape)
        for r_pos, r_neg, delta in rollouts:
            step += (r_pos - r_neg) * delta
        self.theta += self.hp.learning_rate / (self.hp.num_best_deltas * sigma_rewards) * step

class ArsTrainer():
    def __init__(self,
                 hp=None,
                 input_size=None,
                 output_size=None,
                 normalizer=None,
                 policy=None,
                 monitor_dir=None):

        self.hp = hp or Hp()
        np.random.seed(self.hp.seed)
        self.env = gym.make(self.hp.env_name)
        if monitor_dir is not None:
            should_record = lambda i: self.record_video
            self.env = Monitor(self.env, monitor_dir, video_callable=should_record, force=True)
        self.hp.episode_length = self.env.spec.timestep_limit or self.hp.episode_length
        self.input_size = input_size or self.env.observation_space.shape[0]
        self.output_size = output_size or self.env.action_space.shape[0]
        self.normalizer = normalizer or Normalizer(self.input_size)
        self.policy = policy or Policy(self.input_size, self.output_size, self.hp)
        self.record_video = False

    # Explore the policy on one specific direction and over one episode
    def explore(self, direction=None, delta=None):
        state = self.env.reset()
        done = False
        num_plays = 0.0
        sum_rewards = 0.0
        while not done and num_plays < self.hp.episode_length:
            self.normalizer.observe(state)
            state = self.normalizer.normalize(state)
            action = self.policy.evaluate(state, delta, direction)
            state, reward, done, _ = self.env.step(action)
            reward = max(min(reward, 1), -1)
            sum_rewards += reward
            num_plays += 1
        return sum_rewards

    def train(self):
        for step in range(self.hp.nb_steps):
            # initialize the random noise deltas and the positive/negative rewards
            deltas = self.policy.sample_deltas()
            positive_rewards = [0] * self.hp.num_deltas
            negative_rewards = [0] * self.hp.num_deltas

            # play an episode each with positive deltas and negative deltas, collect rewards
            for k in range(self.hp.num_deltas):
                positive_rewards[k] = self.explore(direction="+", delta=deltas[k])
                negative_rewards[k] = self.explore(direction="-", delta=deltas[k])

            # Compute the standard deviation of all rewards
            sigma_rewards = np.array(positive_rewards + negative_rewards).std()

            # Sort the rollouts by the max(r_pos, r_neg) and select the deltas with best rewards
            scores = {k:max(r_pos, r_neg) for k,(r_pos,r_neg) in enumerate(zip(positive_rewards, negative_rewards))}
            order = sorted(scores.keys(), key = lambda x:scores[x], reverse = True)[:self.hp.num_best_deltas]
            rollouts = [(positive_rewards[k], negative_rewards[k], deltas[k]) for k in order]

            # Update the policy
            self.policy.update(rollouts, sigma_rewards)

            # Only record video during evaluation, every n steps
            if step % self.hp.record_every == 0:
                self.record_video = True
            # Play an episode with the new weights and print the score
            reward_evaluation = self.explore()
            print('Step: ', step, 'Reward: ', reward_evaluation)
            self.record_video = False

def mkdir(base, name):
    path = os.path.join(base, name)
    if not os.path.exists(path):
        os.makedirs(path)
    return path

# Main code
if __name__ == '__main__':
    videos_dir = mkdir('.', 'videos')
    monitor_dir = mkdir(videos_dir, ENV_NAME)
    hp = Hp(seed=1946, env_name=ENV_NAME)
    trainer = ArsTrainer(hp=hp, monitor_dir=monitor_dir)
    trainer.train()

</code>```

but when i run the code this error comes

```<code>ModuleNotFoundError: No module named 'gym_recording'
</code>```

This is my code, I want installed gym_recording using

```<code>pip install gym_recording
</code>```

and it worked. When I type

```<code>pip3 show gym-recording
</code>```

it gives

```<code>Name: gym-recording
Version: 0.0.1
Summary: UNKNOWN
Home-page: UNKNOWN
Author:
Author-email:
License: UNKNOWN
Location: /home/snigdh/.local/lib/python3.10/site-packages
Requires: boto3, gym
Required-by:
</code>```

I even tried including the code

```<code>import sys
sys.path.append('/home/snigdh/.local/lib/python3.10/site-packages')
</code>```

but it did not work. What should I do? I am stuck. I asked open chat gpt, and tried all the thing it told me to try like but none of it worked. By the way, I am not using a virtual environment, I am doing this in VS studio as a simple project.

Body:
import os
import numpy as np
import gym
from gym import wrappers
from gym_recording.wrappers import Monitor
# import pybullet_envs

ENV_NAME = 'BipedalWalker-v3'
# ENV_NAME = 'HalfCheetahBulletEnv-v0'

class Hp():
    # Hyperparameters
    def __init__(self,
                 nb_steps=1000,
                 episode_length=2000,
                 learning_rate=0.02,
                 num_deltas=16,
                 num_best_deltas=16,
                 noise=0.03,
                 seed=1,
                 env_name='BipedalWalker-v2',
                 record_every=50):

        self.nb_steps = nb_steps
        self.episode_length = episode_length
        self.learning_rate = learning_rate
        self.num_deltas = num_deltas
        self.num_best_deltas = num_best_deltas
        assert self.num_best_deltas <= self.num_deltas
        self.noise = noise
        self.seed = seed
        self.env_name = env_name
        self.record_every = record_every

class Normalizer():
    # Normalizes the inputs
    def __init__(self, nb_inputs):
        self.n = np.zeros(nb_inputs)
        self.mean = np.zeros(nb_inputs)
        self.mean_diff = np.zeros(nb_inputs)
        self.var = np.zeros(nb_inputs)

    def observe(self, x):
        self.n += 1.0
        last_mean = self.mean.copy()
        self.mean += (x - self.mean) / self.n
        self.mean_diff += (x - last_mean) * (x - self.mean)
        self.var = (self.mean_diff / self.n).clip(min = 1e-2)

    def normalize(self, inputs):
        obs_mean = self.mean
        obs_std = np.sqrt(self.var)
        return (inputs - obs_mean) / obs_std

class Policy():
    def __init__(self, input_size, output_size, hp):
        self.theta = np.zeros((output_size, input_size))
        self.hp = hp

    def evaluate(self, input, delta = None, direction = None):
        if direction is None:
            return self.theta.dot(input)
        elif direction == "+":
            return (self.theta + self.hp.noise * delta).dot(input)
        elif direction == "-":
            return (self.theta - self.hp.noise * delta).dot(input)

    def sample_deltas(self):
        return [np.random.randn(*self.theta.shape) for _ in range(self.hp.num_deltas)]

    def update(self, rollouts, sigma_rewards):
        # sigma_rewards is the standard deviation of the rewards
        step = np.zeros(self.theta.shape)
        for r_pos, r_neg, delta in rollouts:
            step += (r_pos - r_neg) * delta
        self.theta += self.hp.learning_rate / (self.hp.num_best_deltas * sigma_rewards) * step

class ArsTrainer():
    def __init__(self,
                 hp=None,
                 input_size=None,
                 output_size=None,
                 normalizer=None,
                 policy=None,
                 monitor_dir=None):

        self.hp = hp or Hp()
        np.random.seed(self.hp.seed)
        self.env = gym.make(self.hp.env_name)
        if monitor_dir is not None:
            should_record = lambda i: self.record_video
            self.env = Monitor(self.env, monitor_dir, video_callable=should_record, force=True)
        self.hp.episode_length = self.env.spec.timestep_limit or self.hp.episode_length
        self.input_size = input_size or self.env.observation_space.shape[0]
        self.output_size = output_size or self.env.action_space.shape[0]
        self.normalizer = normalizer or Normalizer(self.input_size)
        self.policy = policy or Policy(self.input_size, self.output_size, self.hp)
        self.record_video = False

    # Explore the policy on one specific direction and over one episode
    def explore(self, direction=None, delta=None):
        state = self.env.reset()
        done = False
        num_plays = 0.0
        sum_rewards = 0.0
        while not done and num_plays < self.hp.episode_length:
            self.normalizer.observe(state)
            state = self.normalizer.normalize(state)
            action = self.policy.evaluate(state, delta, direction)
            state, reward, done, _ = self.env.step(action)
            reward = max(min(reward, 1), -1)
            sum_rewards += reward
            num_plays += 1
        return sum_rewards

    def train(self):
        for step in range(self.hp.nb_steps):
            # initialize the random noise deltas and the positive/negative rewards
            deltas = self.policy.sample_deltas()
            positive_rewards = [0] * self.hp.num_deltas
            negative_rewards = [0] * self.hp.num_deltas

            # play an episode each with positive deltas and negative deltas, collect rewards
            for k in range(self.hp.num_deltas):
                positive_rewards[k] = self.explore(direction="+", delta=deltas[k])
                negative_rewards[k] = self.explore(direction="-", delta=deltas[k])

            # Compute the standard deviation of all rewards
            sigma_rewards = np.array(positive_rewards + negative_rewards).std()

            # Sort the rollouts by the max(r_pos, r_neg) and select the deltas with best rewards
            scores = {k:max(r_pos, r_neg) for k,(r_pos,r_neg) in enumerate(zip(positive_rewards, negative_rewards))}
            order = sorted(scores.keys(), key = lambda x:scores[x], reverse = True)[:self.hp.num_best_deltas]
            rollouts = [(positive_rewards[k], negative_rewards[k], deltas[k]) for k in order]

            # Update the policy
            self.policy.update(rollouts, sigma_rewards)

            # Only record video during evaluation, every n steps
            if step % self.hp.record_every == 0:
                self.record_video = True
            # Play an episode with the new weights and print the score
            reward_evaluation = self.explore()
            print('Step: ', step, 'Reward: ', reward_evaluation)
            self.record_video = False

def mkdir(base, name):
    path = os.path.join(base, name)
    if not os.path.exists(path):
        os.makedirs(path)
    return path

# Main code
if __name__ == '__main__':
    videos_dir = mkdir('.', 'videos')
    monitor_dir = mkdir(videos_dir, ENV_NAME)
    hp = Hp(seed=1946, env_name=ENV_NAME)
    trainer = ArsTrainer(hp=hp, monitor_dir=monitor_dir)
    trainer.train()

but when i run the code this error comes

ModuleNotFoundError: No module named 'gym_recording'

This is my code, I want installed gym_recording using

pip install gym_recording

and it worked. When I type

pip3 show gym-recording

it gives

Name: gym-recording
Version: 0.0.1
Summary: UNKNOWN
Home-page: UNKNOWN
Author:
Author-email:
License: UNKNOWN
Location: /home/snigdh/.local/lib/python3.10/site-packages
Requires: boto3, gym
Required-by:

I even tried including the code

import sys
sys.path.append('/home/snigdh/.local/lib/python3.10/site-packages')

but it did not work. What should I do? I am stuck. I asked open chat gpt, and tried all the thing it told me to try like but none of it worked. By the way, I am not using a virtual environment, I am doing this in VS studio as a simple project.


问:
requires android.permission.BLUETOOTH_CONNECT
I'm facing this error for Android 12 or higher.

BLUETOOTH_CONNECT permission was also added in androidManifest.xml still error coming.

My current React Native version is 0.59.9.
I'm using third-party library to request Bluetooth permission(react-native-bluetooth-escpos-printer)

```<code>Permission Denial: starting Intent { act=android.bluetooth.adapter.action.REQUEST_ENABLE
cmp=com.android.settings/.bluetooth.RequestPermissionActivity } from ProcessRecord{df6b879 25469:com.app/u0a151} (pid=25469, uid=10151)
requires android.permission.BLUETOOTH_CONNECT
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app">
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
   <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
   <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
   <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
 </manifest>
</code>```
```<code>  React Native Environment Info:
    System:
      OS: macOS 12.5
      CPU: (8) arm64 Apple M2
      Memory: 99.52 MB / 16.00 GB
      Shell: 5.8.1 - /bin/zsh
    Binaries:
      Node: 19.2.0 - /opt/homebrew/bin/node
      Yarn: 1.22.19 - /opt/homebrew/bin/yarn
      npm: 8.19.3 - /opt/homebrew/bin/npm
      Watchman: 2022.11.14.00 - /opt/homebrew/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: DriverKit 22.1, iOS 16.1, macOS 13.0, tvOS 16.1, watchOS 9.1
    IDEs:
      Android Studio: 2021.3 AI-213.7172.25.2113.9123335
      Xcode: 14.1/14B47b - /usr/bin/xcodebuild
    npmPackages:
      react: 16.8.3 => 16.8.3
      react-native: 0.59.9 => 0.59.9
</code>```

Body:
I'm facing this error for Android 12 or higher.

BLUETOOTH_CONNECT permission was also added in androidManifest.xml still error coming.

My current React Native version is 0.59.9.
I'm using third-party library to request Bluetooth permission(react-native-bluetooth-escpos-printer)

Permission Denial: starting Intent { act=android.bluetooth.adapter.action.REQUEST_ENABLE
cmp=com.android.settings/.bluetooth.RequestPermissionActivity } from ProcessRecord{df6b879 25469:com.app/u0a151} (pid=25469, uid=10151)
requires android.permission.BLUETOOTH_CONNECT

AndroidManifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app">
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
   <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
   <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
   <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
 </manifest>

  React Native Environment Info:
    System:
      OS: macOS 12.5
      CPU: (8) arm64 Apple M2
      Memory: 99.52 MB / 16.00 GB
      Shell: 5.8.1 - /bin/zsh
    Binaries:
      Node: 19.2.0 - /opt/homebrew/bin/node
      Yarn: 1.22.19 - /opt/homebrew/bin/yarn
      npm: 8.19.3 - /opt/homebrew/bin/npm
      Watchman: 2022.11.14.00 - /opt/homebrew/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: DriverKit 22.1, iOS 16.1, macOS 13.0, tvOS 16.1, watchOS 9.1
    IDEs:
      Android Studio: 2021.3 AI-213.7172.25.2113.9123335
      Xcode: 14.1/14B47b - /usr/bin/xcodebuild
    npmPackages:
      react: 16.8.3 => 16.8.3
      react-native: 0.59.9 => 0.59.9


问:
Converting series of numbers into array
i am trying to convert a string(series of numbers) into array.

I want to convert bigNumbers variable to array, so it will be [50, 50, 70, 90, 710], and i always get ['5','0'] and similiar, but i can't get it into actual array.

My code:

```<code>let arr = [5, 12, 5, 10, 4, 26, 7, 9, 71];

/*sort numbers from lower to higher,
log the numbers,
log only even numbers,
multiply odd numbers by ten,
find biggest number,
turn multiplied odd numbers into array,
*/

arr.sort(function(a, b) { return a - b});
console.log(arr);

let numbers = "";
for(let i = 0; i < arr.length; i ++) {
numbers += arr[i] + " ";
} console.log(numbers);
let evenNumbers = "";
for(let j = 0; j < arr.length; j++) {
if(arr[j] % 2 === 0) {
    evenNumbers += arr[j] + " ";
}
}
console.log(evenNumbers);

let bigNumbers = "";
for(let k = 0; k < arr.length; k++) {
if(arr[k] % 2 !== 0) {
    bigNumbers += arr[k] * 10 + " ";
}
}
console.log(bigNumbers);

console.log(typeof(bigNumbers));
</code>```

Title: Converting series of numbers into array

Body:
i am trying to convert a string(series of numbers) into array.

I want to convert bigNumbers variable to array, so it will be [50, 50, 70, 90, 710], and i always get ['5','0'] and similiar, but i can't get it into actual array.

My code:

let arr = [5, 12, 5, 10, 4, 26, 7, 9, 71];

/*sort numbers from lower to higher,
log the numbers,
log only even numbers,
multiply odd numbers by ten,
find biggest number,
turn multiplied odd numbers into array,
*/

arr.sort(function(a, b) { return a - b});
console.log(arr);

let numbers = "";
for(let i = 0; i < arr.length; i ++) {
numbers += arr[i] + " ";
} console.log(numbers);
let evenNumbers = "";
for(let j = 0; j < arr.length; j++) {
if(arr[j] % 2 === 0) {
    evenNumbers += arr[j] + " ";
}
}
console.log(evenNumbers);

let bigNumbers = "";
for(let k = 0; k < arr.length; k++) {
if(arr[k] % 2 !== 0) {
    bigNumbers += arr[k] * 10 + " ";
}
}
console.log(bigNumbers);

console.log(typeof(bigNumbers));


问:
Angular library : use exported scss files from one module into other library modules

EDIT :

I realized that my angular project folder (what I called "library") was not composed of several modules like utils or breadcrumb but that they were in fact libraries... So instead of import modules in my parent app, I imported libraries... Due to this point, it was normal I can't share things between my libraries like I asked to.

I've recreated ONE library with expected modules and now everything works like a charm : I succeed to share styles across all my library (by specifiing the path of my scss files), and from my library to parent app like explained below.

I am building an Angular library with couple of modules, all generated with command ng generate library <module-name>. One of these modules is utils and contains some methods, service and scss files. I was able to export the scss file thanks to this topic (see Orson's answer). In my case, scss files are located in module's root (on the same level as package.json).

ng-package.json of utils :

```<code>{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../dist/utils",
  "lib": {
    "entryFile": "src/public-api.ts"
  },
  "assets": ["styles.scss", "variables.scss", "components.scss"]
}
</code>```

package.json of utils :

```<code>{
  "name": "utils",
  "version": "1.0.6",
  "peerDependencies": {
    "@angular/common": "^13.3.0",
    "@angular/core": "^13.3.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "exports": {
    "./ics-styles": {
      "sass": "./styles.scss"
    }
  }
}
</code>```

When I build utils, I see styles.scss, variables.scss and components.scss files into dist folder.

In parallel, I have an Angular application (let's call it "parent app") which use many modules from the library :

```<code>Angular CLI: 13.3.5
Node: 18.12.1 (Unsupported)
Package Manager: npm 8.8.0
OS: win32 x64

Angular: 13.3.8
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1303.5
@angular-devkit/build-angular   13.3.5
@angular-devkit/core            13.3.5
@angular-devkit/schematics      13.3.5
@angular/cdk                    13.3.7
@angular/cli                    13.3.5
@schematics/angular             13.3.5
ng-packagr                      13.3.1
rxjs                            7.5.5
typescript                      4.6.4
</code>```

Parent app has a SharedModule which import UtilsModule. I am able to import and use scss from utils thanks to this import in scss files : @import 'utils/ics-styles';. It works perfectly, all variables and mixins from UtilsModule are available.

Now, I want to use exported scss files from UtilsModule into another module of the library, let's say BreadcrumbModule. I proceeded in the same way, importing UtilsModule in breadcrumb.module.ts :

```<code>import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { UtilsModule } from 'utils';
import { BreadcrumbComponent } from './breadcrumb.component';

@NgModule({
  declarations: [BreadcrumbComponent],
  imports: [CommonModule, RouterModule, TranslateModule, UtilsModule],
  exports: [BreadcrumbComponent],
})
export class BreadcrumbModule {}
</code>```

Then, in breadcrumb.component.scss, I use @import 'utils/ics-styles'; but it gives me the following error on serve or build :

```<code>./projects/breadcrumb/src/lib/breadcrumb.component.scss?ngResource - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
  ╷
1 │ @import 'utils/ics-styles';
  │         ^^^^^^^^^^^^^^^^^^
  ╵
  projects\breadcrumb\src\lib\breadcrumb.component.scss 1:9  root stylesheet

× Failed to compile.
</code>```

I tried to change scss import with @import '~utils/ics-styles'; or @import '~@utils/ics-styles'; but got the same error message.

Any idea to make scss file from utils useable into other library modules would be appreciated. Thanks !

Body:
EDIT :

I realized that my angular project folder (what I called "library") was not composed of several modules like utils or breadcrumb but that they were in fact libraries... So instead of import modules in my parent app, I imported libraries... Due to this point, it was normal I can't share things between my libraries like I asked to.

I've recreated ONE library with expected modules and now everything works like a charm : I succeed to share styles across all my library (by specifiing the path of my scss files), and from my library to parent app like explained below.

I am building an Angular library with couple of modules, all generated with command ng generate library <module-name>. One of these modules is utils and contains some methods, service and scss files. I was able to export the scss file thanks to this topic (see Orson's answer). In my case, scss files are located in module's root (on the same level as package.json).

ng-package.json of utils :

{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../dist/utils",
  "lib": {
    "entryFile": "src/public-api.ts"
  },
  "assets": ["styles.scss", "variables.scss", "components.scss"]
}

package.json of utils :

{
  "name": "utils",
  "version": "1.0.6",
  "peerDependencies": {
    "@angular/common": "^13.3.0",
    "@angular/core": "^13.3.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "exports": {
    "./ics-styles": {
      "sass": "./styles.scss"
    }
  }
}

When I build utils, I see styles.scss, variables.scss and components.scss files into dist folder.

In parallel, I have an Angular application (let's call it "parent app") which use many modules from the library :

Angular CLI: 13.3.5
Node: 18.12.1 (Unsupported)
Package Manager: npm 8.8.0
OS: win32 x64

Angular: 13.3.8
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1303.5
@angular-devkit/build-angular   13.3.5
@angular-devkit/core            13.3.5
@angular-devkit/schematics      13.3.5
@angular/cdk                    13.3.7
@angular/cli                    13.3.5
@schematics/angular             13.3.5
ng-packagr                      13.3.1
rxjs                            7.5.5
typescript                      4.6.4

Parent app has a SharedModule which import UtilsModule. I am able to import and use scss from utils thanks to this import in scss files : @import 'utils/ics-styles';. It works perfectly, all variables and mixins from UtilsModule are available.

Now, I want to use exported scss files from UtilsModule into another module of the library, let's say BreadcrumbModule. I proceeded in the same way, importing UtilsModule in breadcrumb.module.ts :

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { UtilsModule } from 'utils';
import { BreadcrumbComponent } from './breadcrumb.component';

@NgModule({
  declarations: [BreadcrumbComponent],
  imports: [CommonModule, RouterModule, TranslateModule, UtilsModule],
  exports: [BreadcrumbComponent],
})
export class BreadcrumbModule {}

Then, in breadcrumb.component.scss, I use @import 'utils/ics-styles'; but it gives me the following error on serve or build :

./projects/breadcrumb/src/lib/breadcrumb.component.scss?ngResource - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
  ╷
1 │ @import 'utils/ics-styles';
  │         ^^^^^^^^^^^^^^^^^^
  ╵
  projects\breadcrumb\src\lib\breadcrumb.component.scss 1:9  root stylesheet

× Failed to compile.

I tried to change scss import with @import '~utils/ics-styles'; or @import '~@utils/ics-styles'; but got the same error message.

Any idea to make scss file from utils useable into other library modules would be appreciated. Thanks !


问:
React / CSS: If content is larger than its container
I have a menuList, in that list are items, those text items (label) are X in length. The container is overflow wrapping the item.

```<code>    container: {
      minHeight: 'auto',
      overflow: 'hidden',
    },
    label: {
      whiteSpace: 'nowrap',
      overflow: 'wrap',
      overflowWrap: 'break-word',
      '@keyframes scrollText': {
        '0%': { transform: 'translate(0%, 0)' },
        '100%': { transform: 'translate(-100%, 0)' },
      },
      '&:hover': {
        animation: 'scrollText 4s linear infinite',
      },
    },
</code>```

When the text is larger than the container i want to translate through, but only where the text is overflowing... i.e. it would look silly to rotate text on hover where there is no need to.

So how in the react application / css file do i determine if the text is overflowing / needs to transform. I can pass a var to the style sheet to apply different rules, but how to determine if the text if overflowing?

```<code>const TextMenuItem: TextMenuItemType = (props) => {
  const { text, selected, onSelect } = getTextMenuItemProps(props);

  const styles = useTextMenuItemStyles();

  return (
    <MenuItem
      data-testid="text-menu-item"
      sx={styles.container}
      selected={selected}
      onClick={onSelect}
    >
      <Typography sx={styles.label}>{text}</Typography>
    </MenuItem>
  );
};
</code>```

Body:
I have a menuList, in that list are items, those text items (label) are X in length. The container is overflow wrapping the item.

    container: {
      minHeight: 'auto',
      overflow: 'hidden',
    },
    label: {
      whiteSpace: 'nowrap',
      overflow: 'wrap',
      overflowWrap: 'break-word',
      '@keyframes scrollText': {
        '0%': { transform: 'translate(0%, 0)' },
        '100%': { transform: 'translate(-100%, 0)' },
      },
      '&:hover': {
        animation: 'scrollText 4s linear infinite',
      },
    },

When the text is larger than the container i want to translate through, but only where the text is overflowing... i.e. it would look silly to rotate text on hover where there is no need to.

So how in the react application / css file do i determine if the text is overflowing / needs to transform. I can pass a var to the style sheet to apply different rules, but how to determine if the text if overflowing?

const TextMenuItem: TextMenuItemType = (props) => {
  const { text, selected, onSelect } = getTextMenuItemProps(props);

  const styles = useTextMenuItemStyles();

  return (
    <MenuItem
      data-testid="text-menu-item"
      sx={styles.container}
      selected={selected}
      onClick={onSelect}
    >
      <Typography sx={styles.label}>{text}</Typography>
    </MenuItem>
  );
};


问:
How to use Eigen::Ref with STL Vector?
currently, I'm working on a specific problem where I have an STL vector with several mapped Eigen vectors of different sizes which I would like to keep.
When writing a function to accept my stl vector with mapped eigen vectors, I always encounter a compiler error, stating that conversion could not be performed.

When simply working without the surrounding STL vector (i.e. Eigen::Ref<Eigen::VectorXd>), everything works fine. However, once the STL vector comes into play, the given compiler error occurs:
My mwe looks as follows:

```<code>#include <iostream>
#include <vector>
#include <Eigen/Core>

void EigenRefFunction(const std::vector<Eigen::Ref<Eigen::VectorXd>>& vec)
{
    for(int i=0;i<vec.size();++i)
    {
        for(int j=0;j<vec[i].rows();++j)
        {
                    std::cout << i << "," << "j:\t" << vec[i](j) << std::endl;
        }
    }
}

int main()
{
    //Examplary vector to map
    std::vector<double> vec1(10, 1.0);

    //Mapped vector
    std::vector<Eigen::Map<Eigen::VectorXd>> vec_map;
    vec_map.push_back(Eigen::Map<Eigen::VectorXd>(vec1.data(), vec1.size()));

    //Call to function
    EigenRefFunction(vec_map);
}
</code>```

This results in compiler error C2665 on Visual Studio v142.

Edit: Sorry, just copied the generic translation. Here is the full error message from godbolt (thanks @Marek R):

: In function 'int main()': :26:22: error: invalid
initialization of reference of type 'const
std::vector > >&' from
expression of type 'std::vector, 0, Eigen::Stride > >'    26 |     EigenRefFunction(vec_map);
      |                      ^~~~~~~ :5:71: note: in passing argument 1 of 'void EigenRefFunction(const
std::vector > >&)'
    5 | void EigenRefFunction(const std::vector>& vec)

If, for any reason, this is not resolvable: Is there another efficient way to store several differently sized mapped Eigen vectors in a data structure which is flexible to be extended to different sizes at runtime?

Any help would be much appreciated, thank you!

Edit:
Thanks for all the very quick answers. Marek R provided the code to resolve my issue by simply changing the provided parameter to the function call. The resulting copy is not an issue for me:

```<code>EigenRefFunction({ vec_map.begin(), vec_map.end() });
</code>```

Title: How to use Eigen::Ref with STL Vector?

Body:
currently, I'm working on a specific problem where I have an STL vector with several mapped Eigen vectors of different sizes which I would like to keep.
When writing a function to accept my stl vector with mapped eigen vectors, I always encounter a compiler error, stating that conversion could not be performed.

When simply working without the surrounding STL vector (i.e. Eigen::Ref<Eigen::VectorXd>), everything works fine. However, once the STL vector comes into play, the given compiler error occurs:
My mwe looks as follows:

#include <iostream>
#include <vector>
#include <Eigen/Core>

void EigenRefFunction(const std::vector<Eigen::Ref<Eigen::VectorXd>>& vec)
{
    for(int i=0;i<vec.size();++i)
    {
        for(int j=0;j<vec[i].rows();++j)
        {
                    std::cout << i << "," << "j:\t" << vec[i](j) << std::endl;
        }
    }
}

int main()
{
    //Examplary vector to map
    std::vector<double> vec1(10, 1.0);

    //Mapped vector
    std::vector<Eigen::Map<Eigen::VectorXd>> vec_map;
    vec_map.push_back(Eigen::Map<Eigen::VectorXd>(vec1.data(), vec1.size()));

    //Call to function
    EigenRefFunction(vec_map);
}

This results in compiler error C2665 on Visual Studio v142.

Edit: Sorry, just copied the generic translation. Here is the full error message from godbolt (thanks @Marek R):

: In function 'int main()': :26:22: error: invalid
initialization of reference of type 'const
std::vector > >&' from
expression of type 'std::vector, 0, Eigen::Stride > >'    26 |     EigenRefFunction(vec_map);
      |                      ^~~~~~~ :5:71: note: in passing argument 1 of 'void EigenRefFunction(const
std::vector > >&)'
    5 | void EigenRefFunction(const std::vector>& vec)

If, for any reason, this is not resolvable: Is there another efficient way to store several differently sized mapped Eigen vectors in a data structure which is flexible to be extended to different sizes at runtime?

Any help would be much appreciated, thank you!

Edit:
Thanks for all the very quick answers. Marek R provided the code to resolve my issue by simply changing the provided parameter to the function call. The resulting copy is not an issue for me:

EigenRefFunction({ vec_map.begin(), vec_map.end() });


问:
only my banner ads work but when i upload the game same only banners are working not rewarded and intersitials
I am using Google ad mob In unity all my test ads are working but when I get the build and test it only my banner ads work but when I thought that these are test ids lets upload the game and see but when I upload the game same only banners are working not rewarded and interstitials even 10 days i have uploaded the game only banner are working
I changed the code as well still after every try just banner ads are working even on my build test devices not rewarded and interstitial</p>


问:
How to change Android DatePicker month navigation chevron/arrow color
I am using the DateTimePicker component of the Material Dialog library. I want to change the color of the left arrow "<" and also the text color of the future day number (Marked in red color in the attached image). I am able to update TimePicker but no luck with DatePicker.


问:
Cannot append localStorage data to an existing div class
Currently making a quick journal entry app in HTML, CSS, and JS. User inputs and submits text data along with the time and date. I'm trying to take that data from the localStorage to put inside an existing div class. Any advice?

This is the HTML code.

```<code><div class="background-journal">
        <button class="button-journal" onclick="openPopup()" id="entrybtn">New Entry</button>
        <br><br><br><br><br><br><br>
        <button class="show-journal" onclick="recallEntries()" id="showbtn">View Previous Entries</button>
        <div class="journal-visual" id="data-viz">

        </div>
    <div id="popup" class="popup">
    <form id="form" class="form">
        <br>
        <label for="journal-entry">何を勉強していますか？</label><br><br>
        <textarea class="add-entry" id="journal-entry" rows="6" cols="150"></textarea><br>
        <button type="submit" onclick="submitJournalEntry()">Submit</button>
        <button type="button" onclick="closePopup()">Close</button>
        </form>
    </div>
</code>```

This is the CSS code.

```<code>.background-journal{
  position:absolute;
  top: 35%;
  left: 9.6%;
  background-color:rgba(255,255,255,0);
  z-index:1001;
  width: 80%;
  height: 600px;
  overflow-y: auto;
  overflow-x: hidden;
}

.button-journal {
  background-color: #fff;
  border: none;
  color: #000;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
  cursor: pointer;
  width: 90%;
  height: 100px;
  left: 4.5%;
  position: absolute;
  box-shadow: 3px 5px #888888;
}

.show-journal{
  background-color: #fff;
  border: none;
  color: #000;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
  cursor: pointer;
  width: 90%;
  height: 100px;
  left: 4.5%;
  position: absolute;
  box-shadow: 3px 5px #888888;
}

.journal-visual{
  background-color: #fff;
  z-index:1003;
  width: 70%;
  height: 450px;
  overflow-y: auto;
  overflow-x: hidden;
  margin-left: auto;
  margin-right: auto;
  display: none;
  position: relative;
  color: #000;
  text-align: center;
}

.button-popup-journal{
  position: relative;
}

.popup {
  display: none;
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 200px;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;
  box-shadow: 3px 5px #000;
}

.popup form{
  margin: auto;
}

.add-entry{
  margin: auto;
  overflow: auto;
  position:inherit;
  left: 5%;
}

.background-journal label{
  color: white;
  opacity: 70%;
}
</code>```

and this is the JS code.

```<code>    // Journal Function

  function openPopup() {
    document.getElementById("popup").style.display = "block";
    document.getElementById("entrybtn").style.display = "none";
    document.getElementById("showbtn").style.display = "none";
  }

  function closePopup() {
    document.getElementById("popup").style.display = "none";
    document.getElementById("entrybtn").style.display = "block";
    document.getElementById("showbtn").style.display = "block";
  }

  function submitJournalEntry() {
    var journalEntry = document.getElementById("journal-entry").value;

  var date = new Date();
  var timestamp = date.toString();

  localStorage.setItem(timestamp, journalEntry);

    closePopup();
  }

  function recallEntries() {
    document.getElementById("entrybtn").style.display = "none";
    document.getElementById("showbtn").style.display = "none";
    document.getElementById("data-viz").style.display = "block";
    var keys = Object.keys(localStorage);

    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var journalEntry = localStorage.getItem(key);
      var viz = document.getElementById('data-viz');
      div.innerHTML = '<p><strong>' + key + '</strong>: ' + journalEntry + '</p>';
      document.body.appendChild(viz);
  }
  }

</code>```

I was expecting the text to show up in the div class="journal-entry" id="data-viz" but nothing is there. Any ideas?

Body:
Currently making a quick journal entry app in HTML, CSS, and JS. User inputs and submits text data along with the time and date. I'm trying to take that data from the localStorage to put inside an existing div class. Any advice?

This is the HTML code.

        <button class="button-journal" onclick="openPopup()" id="entrybtn">New Entry</button>

        <button class="show-journal" onclick="recallEntries()" id="showbtn">View Previous Entries</button>

    <form id="form" class="form">

        何を勉強していますか？

        <textarea class="add-entry" id="journal-entry" rows="6" cols="150"></textarea>

        <button type="submit" onclick="submitJournalEntry()">Submit</button>
        <button type="button" onclick="closePopup()">Close</button>
        </form>

This is the CSS code.

.background-journal{
  position:absolute;
  top: 35%;
  left: 9.6%;
  background-color:rgba(255,255,255,0);
  z-index:1001;
  width: 80%;
  height: 600px;
  overflow-y: auto;
  overflow-x: hidden;
}

.button-journal {
  background-color: #fff;
  border: none;
  color: #000;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
  cursor: pointer;
  width: 90%;
  height: 100px;
  left: 4.5%;
  position: absolute;
  box-shadow: 3px 5px #888888;
}

.show-journal{
  background-color: #fff;
  border: none;
  color: #000;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
  cursor: pointer;
  width: 90%;
  height: 100px;
  left: 4.5%;
  position: absolute;
  box-shadow: 3px 5px #888888;
}

.journal-visual{
  background-color: #fff;
  z-index:1003;
  width: 70%;
  height: 450px;
  overflow-y: auto;
  overflow-x: hidden;
  margin-left: auto;
  margin-right: auto;
  display: none;
  position: relative;
  color: #000;
  text-align: center;
}

.button-popup-journal{
  position: relative;
}

.popup {
  display: none;
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 200px;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;
  box-shadow: 3px 5px #000;
}

.popup form{
  margin: auto;
}

.add-entry{
  margin: auto;
  overflow: auto;
  position:inherit;
  left: 5%;
}

.background-journal label{
  color: white;
  opacity: 70%;
}

and this is the JS code.

    // Journal Function

  function openPopup() {
    document.getElementById("popup").style.display = "block";
    document.getElementById("entrybtn").style.display = "none";
    document.getElementById("showbtn").style.display = "none";
  }

  function closePopup() {
    document.getElementById("popup").style.display = "none";
    document.getElementById("entrybtn").style.display = "block";
    document.getElementById("showbtn").style.display = "block";
  }

  function submitJournalEntry() {
    var journalEntry = document.getElementById("journal-entry").value;

  var date = new Date();
  var timestamp = date.toString();

  localStorage.setItem(timestamp, journalEntry);

    closePopup();
  }

  function recallEntries() {
    document.getElementById("entrybtn").style.display = "none";
    document.getElementById("showbtn").style.display = "none";
    document.getElementById("data-viz").style.display = "block";
    var keys = Object.keys(localStorage);

    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var journalEntry = localStorage.getItem(key);
      var viz = document.getElementById('data-viz');
      div.innerHTML = '
' + key + ': ' + journalEntry + '
';
      document.body.appendChild(viz);
  }
  }

I was expecting the text to show up in the div class="journal-entry" id="data-viz" but nothing is there. Any ideas?


问:
Microsoft Project Server 2019 on premise: ServiceModel.CommunicationObjectAbortedException in Project Update queue job created using CSOM
I have a code that makes a few simple changes to a project using CSOM:

    projContext.Load(this.projContext.Projects, pj => pj.Where(p => p.Id == projId));
    projContext.ExecuteQuery();

    var proj = projContext.Projects.SingleOrDefault(p => p.Id == projId);
    var draft = proj.CheckOut();

    projContext.Load(draft, p => p.Owner);
    projContext.ExecuteQuery();

    draft.Owner = managerUser;

    var tasks = draft.Tasks;
    projContext.Load(tasks, tsk => tsk.IncludeWithDefaultProperties(t => t.Id, t => t.StatusManager));
    projContext.ExecuteQuery();

    var newTaskId = Guid.NewGuid();
    var newTask = new PS.TaskCreationInformation {
        Id = Guid.NewGuid(),
        Name = "New task",
        StatusManager = managerUser,
    };
    tasks.Add(newTask);
    draft.Assignments.Add(new PS.AssignmentCreationInformation {
        TaskId = newTaskId,
        ResourceId = managerId,
    });

    var qJob = draft.Update();
    var jobState = projContext.WaitForQueue(qJob, TimeoutSeconds);
```
<p>It works well in development environment, but the Update job in queue fails with internal exception in production environment. This happens only with projects that were created a certain way:</p>
<ul>
<li>Fresh enterprise project in PWA;</li>
<li>Enterprise project created by importing a local project to server using Project Professional.</li>
</ul>
<p>Here is the queue error:</p>
<blockquote>
<p>Your Project Update job failed. Its current state is failed. It was 0
complete. It entered the queue on 12/08/2022 16:24:05 Error ID: 9133
Error ID: 26000</p>
<p>Detailed error below – send it to the administrator for more detailed
troubleshooting.</p>
</blockquote>
```<?xml version="1.0" encoding="utf-16"?> <errinfo><general><class name="Project"><error id="9133" name="ProjectSchedulingEngineException" uid="2d0b12df-fb76-ed11-95ef-005056b6871f" exception="System.ServiceModel.CommunicationObjectAbortedException: The communication object,  System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it has  been Aborted. Server stack trace: at System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposedOrNotOpen() at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at Microsoft.Office.Project.Server.BusinessLayer.ProjectEngineUpdate.UpdateProjectWithPCS(IPlatformContext context, ProjectDataSet dataset, Guid projectUid, Guid sessionUid, Boolean inVisibilitySyncMode, Boolean skipEventHandlers, Boolean skipPostSSPUpdate) at Microsoft.Office.Project.Server.BusinessLayer.ProjectMain.HandleProject2(MessageContext mContext, ProjectDataSet dataset, Guid projectUid, Guid sessionUid, Boolean inVisibilitySyncMode)" /></class><class name="Queue"><error id="26000" name="GeneralQueueJobFailed" uid="2e0b12df-fb76-ed11-95ef-005056b6871f" JobUID="c3f6fcdb-fb76-ed11-95ef-005056b6871f" ComputerName="7e53cc63-ebbd-427f-bde0-d1db317abacd" GroupType="ProjectUpdate" MessageType="ProjectUpdate2Message" MessageId="1" Stage="" CorrelationUID="704180a0-0676-40da-abac-d2a039c9acc3" /></class></general> </errinfo>
```

You can do the following:

Try troubleshooting using the error IDs, error XML.

Contact administrator with your jobID (db6df25a-d4c1-4631-b7a1-2e7aae9f5c16) and error XML.

Tried to reproduce the problem on Project Server used for development, no luck yet. Looks like Microsoft is totally responsible for the issue, but maybe someone knows a workaround?

Body:
I have a code that makes a few simple changes to a project using CSOM:

    projContext.Load(this.projContext.Projects, pj => pj.Where(p => p.Id == projId));
    projContext.ExecuteQuery();

    var proj = projContext.Projects.SingleOrDefault(p => p.Id == projId);
    var draft = proj.CheckOut();

    projContext.Load(draft, p => p.Owner);
    projContext.ExecuteQuery();

    draft.Owner = managerUser;

    var tasks = draft.Tasks;
    projContext.Load(tasks, tsk => tsk.IncludeWithDefaultProperties(t => t.Id, t => t.StatusManager));
    projContext.ExecuteQuery();

    var newTaskId = Guid.NewGuid();
    var newTask = new PS.TaskCreationInformation {
        Id = Guid.NewGuid(),
        Name = "New task",
        StatusManager = managerUser,
    };
    tasks.Add(newTask);
    draft.Assignments.Add(new PS.AssignmentCreationInformation {
        TaskId = newTaskId,
        ResourceId = managerId,
    });

    var qJob = draft.Update();
    var jobState = projContext.WaitForQueue(qJob, TimeoutSeconds);

It works well in development environment, but the Update job in queue fails with internal exception in production environment. This happens only with projects that were created a certain way:

Fresh enterprise project in PWA;

Enterprise project created by importing a local project to server using Project Professional.

Here is the queue error:

Your Project Update job failed. Its current state is failed. It was 0
complete. It entered the queue on 12/08/2022 16:24:05 Error ID: 9133
Error ID: 26000

Detailed error below – send it to the administrator for more detailed
troubleshooting.

<?xml version="1.0" encoding="utf-16"?> <errinfo><general><class name="Project"><error id="9133" name="ProjectSchedulingEngineException" uid="2d0b12df-fb76-ed11-95ef-005056b6871f" exception="System.ServiceModel.CommunicationObjectAbortedException: The communication object,  System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it has  been Aborted. Server stack trace: at System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposedOrNotOpen() at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at Microsoft.Office.Project.Server.BusinessLayer.ProjectEngineUpdate.UpdateProjectWithPCS(IPlatformContext context, ProjectDataSet dataset, Guid projectUid, Guid sessionUid, Boolean inVisibilitySyncMode, Boolean skipEventHandlers, Boolean skipPostSSPUpdate) at Microsoft.Office.Project.Server.BusinessLayer.ProjectMain.HandleProject2(MessageContext mContext, ProjectDataSet dataset, Guid projectUid, Guid sessionUid, Boolean inVisibilitySyncMode)" /></class><class name="Queue"><error id="26000" name="GeneralQueueJobFailed" uid="2e0b12df-fb76-ed11-95ef-005056b6871f" JobUID="c3f6fcdb-fb76-ed11-95ef-005056b6871f" ComputerName="7e53cc63-ebbd-427f-bde0-d1db317abacd" GroupType="ProjectUpdate" MessageType="ProjectUpdate2Message" MessageId="1" Stage="" CorrelationUID="704180a0-0676-40da-abac-d2a039c9acc3" /></class></general> </errinfo>

You can do the following:

Try troubleshooting using the error IDs, error XML.

Contact administrator with your jobID (db6df25a-d4c1-4631-b7a1-2e7aae9f5c16) and error XML.

Tried to reproduce the problem on Project Server used for development, no luck yet. Looks like Microsoft is totally responsible for the issue, but maybe someone knows a workaround?