text:
Q: How do I lock the rotation of a grabbed object with Unity Oculus VR For an Oculus Quest game i'm working on, I need to be able to grab an object and not rotate it in any way. I should be able to move it in the x, y and z axes though. I'm doing this in a climbing game and the object is quite big. My player is locked on (0,0,0) and you climb by grabbing the terrain and moving it, giving the illusion that you are climbing.
I am using Unity's Oculus integration asset and I have the OVR Grabbable script on the object I want to be able to grab.
How do I make sure that the object I'm grabbing, doesn't rotate at all?
I've tried using a rigidbody and locking the rotation of the wall I want to climb like that, but that doesn't work. Once I grab it, I can still rotate the object.
I have also tried locking the rotation of the hand rigidbody, but that setting seemed to be ignored, because I could still rotate the hands.
I've also tried adding a bit of code in the script, which would reset the objects rotation in the fixed update. I put this code in the OVR Grabbable script.
void FixedUpdate()
{
    transform.rotation = Quaternion.identity;
}

Using this code didn't keep the wall from rotating, but it did snap back to rotation (0,0,0) every frame. THis caused the wall to function as if it would still rotate, but it looked like it was switching between (0,0,0) and the rotation it would be at in every frame. This is of course also not the desired result.
I am not using VRTK, because that does not work with the type of climbing I'm trying to achieve.
I would like to be able to grab an object, move it in the x, y and z axes, while it doesn't rotate at all. Currently, I can still rotate the object. How would I fix this issue and completely lock the rotation whenever I grab the object?

A: If the object has become a child of the hand and you still want it to move but not rotate. You could add a simple script which scores its default rotation and applies it in LateUpdate.
This is designed for non-physics objects so be sure to remove your test where you added the rigidbody to the wall.
Something simple like this would do the job.
Quaternion defaultRotation;

void Awake()
{
    defaultRotation = transform.rotation;
}

void LateUpdate()
{
    transform.rotation = defaultRotation;
}


text:
Q: Filtration in product page shopify Right now filtration by tag is done by AND..
(mysite.com/collections/product_sub/x+y)
what should i do so that filtration is done by OR i.e suppose
product A has tag x
product B has tag y
product C has tag z
now if user select x and y tags then all product should be shown having any of both tag
any help is greatly appreciated

A: Its not possible in shopify. Shopify will only display the products that has both x and y tags. It will not combine results.
If you want to really achieve this, You need to use ajax. So when someone will select mysite.com/collections/product_sub/x , Your ajax script will retrieve all products from that url.
When user will select another tag which makes the url like mysite.com/collections/product_sub/x+y , ajax script will retrieve all products from mysite.com/collections/product_sub/y and combine in product list ( make sure it remove duplicates if there any )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Got an error in Django view : "NoReverseMatch at /view/" Here are my urls :
root urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('store.urls')),

]
url.py
    urlpatterns = [
    path('',views.store,name='store'),
    path('cart/',views.cart,name='cart'),
    path('checkout/',views.checkout,name='checkout'),
    path('update_item/',views.updateItem,name='update-item'),
    path('process_order/',views.processOrder,name='process-order'),
    path('view/<int:pk>/',views.view,name='view-detail'),
]

Here is the code for the view :
views.py
    def view(request,pk):
        product = Product.objects.get(id=pk)
        return render(request,'store/view.html',{'product':product} )

Here is my template :
template
    View

This output error :

NoReverseMatch at /view/1/ Reverse for 'store' with arguments '(1,)' not found. 1 pattern(s) tried: ['$']

How to resolve this error?

A: template
{% load templatehelpers %}
View

Here we use a new simple tag namely abs_url (absolute url) in templatehelpers.py (Template tag). And app_name is the name of the app.
templatehelpers.py
from django import template
from django.urls import reverse
register = template.Library()

@register.simple_tag
def abs_url(value, request, **kwargs):
    return reverse(value,kwargs=kwargs)


text:
Q: Q: Mobile Push Badge Count (MarketingCloud SDK 6.0) How to manage/display iOS badge number that calculate by myself like
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;?
For now, MarketingCloudSDK will override the result - display unread messages when the app goes to the background.

A: The MobilePush SDK will control badging if the Inbox functionality is enabled in the configuration for the SDK.
If you do not need inbox, set "inbox":"false" in the configuration file and you'll be able to set the badge.
If you are using inbox, you can attempt to set the badge in a delayed fashion in your app's background notification hander. A short dispatch_after in your own handler for UIApplicationDidEnterBackgroundNotification (maybe 1 second) which would then call setApplicationIconBadgeNumber for their own value.
This is untested but should be sufficient.


text:
Q: Change color of left element Status Bar in Sublime Text 3 (English is not my native language, PROMT translate)

In Default.sublime-theme or Soda Dark 3.sublime-theme
 I didn't find the demanded class. I also didn't find required setting me in unofficial documentation. Thanks.

A: That default theme is out of date - in build 3103, this new button was added and the class name for it is panel_button_control.
To see the Default theme that is shipped with your version of ST3:

*

*install PackageResourceViewer from Package Control

*open the Command Palette

*type PRV:

*select PackageResourceViewer: Open Resource

*select Theme - Default

*select Default.sublime-theme

*you will see panel_button_control is there


text:
Q: Retrive values of array from wp_option table of wordpress I added some value in associative array into wp_option table of wordpress. The result is given below.
  array($computer=>$mouse, $mouse=>$keyboard);
  get_option( 'policy_number' );

Output :
  Array
  (
    [0] => Array
        (
            [comoputer1] => mousevalue
            [mousevalue] => keyboardvalue
        )
  )

How can i retrieve value of mousevalue ? Which is keyboardvalue.

A: You have an array within an array. You want the first item (index 0) of the parent array, and you want to return a value by its key:
$values = get_option( 'policy_number' );

foreach ($values as $value) {
    echo $value['mousevalue'];
}


text:
Q: AVAudioPlayer not working anymore This program was working before and I do not believe I changed anything. Here is the code. I get the thrown error : file not found: bgMusic
import SpriteKit
import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {

    var backgroundMusicPlayer = AVAudioPlayer()

    func playBackgroundMusic(filename: String) {
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
        guard let newURL = url else {
            print("Could not find file: \(filename)")
            return
        }
        do {
            backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
            backgroundMusicPlayer.numberOfLoops = -1
            backgroundMusicPlayer.prepareToPlay()
            backgroundMusicPlayer.play()
        } catch let error as NSError {
            print(error.description)
        }
    }

    override init(size: CGSize) {
        super.init(size: size)

        playBackgroundMusic("bgMusic")
}

A: Try getting the file path instead. This works for me everytime.
//Change 'ofType' to whatever the file type is. (.m4a, .mp3, etc.)
let path = NSBundle.mainBundle().pathForResource(filename, ofType: ".mp3")
let url = NSURL.fileURLWithPath(path!)

Then load the url into the AVAudioPlayer.
If that doesn't work, then make sure the filename is correct and that it is added into your project. Best of luck!


text:
Q: How to count in this recursive function? I want to iterate over a nested dictionary (which you can see below):
bsp = {'bewohnen': {'lemma': 'bewohnen', 'pos': 'VFIN', 'attributes': {'type': 'Full', 'person': '3', 'number': 'Pl', 'tense': 'Pres', 'mood': 'Ind'}},
       'bewirtschaften': {'lemma': 'bewirtschaften', 'pos': 'VFIN', 'attributes': {'type': 'Full', 'person': '3', 'number': 'Pl', 'tense': 'Pres', 'mood': 'Ind'}},
       'die': {'lemma': 'die', 'pos': 'ART', 'attributes': {'type': 'Def', 'case': 'Nom', 'number': 'Pl', 'gender': 'Masc'}}, 'vier': {'lemma': 'vier', 'pos': 'CARD', 'attributes': None},
       'Viertel': {'lemma': 'Viertel', 'pos': 'N', 'attributes': {'type': 'Nom', 'case': 'Nom', 'number': 'Pl', 'gender': 'Neut'}}}

#Code:

def iterdict(d, verbs={"all":0,"pres":0}):
        for k,v in d.items():

            if isinstance(v, dict):
               verbs = iterdict(v, verbs)
            elif k == "tense":
                verbs["all"]+= 1
                if v == "Pres":
                    verbs["pres"]+= 1
            return verbs

        return verbs["pres"]//verbs["all"]

print(iterdict(bsp))

I'm interested in counting results (if key gets "tense" and value gets "Pres") in a dictionary, that should be, if recursion-process is finished, returned as
return verbs["pres"]//verbs["all"]

but while troubleshooting I saw, that it doesn't even count properly, the "verbs"-dictionary stays at 0/0.
Something must be wrong with my recursion, I'm a beginner and I just don't know what I should do to get it done.

A: In the following, there are two ways to call iterdict. If you call it without a second argument, it internal initializes the pair of counters to 0. Otherwise, it mutates the given pair of counts.
The initial call to iterdict is made without the counters. The recursive calls take the current pair of counts, which are updated in-place inside the recursive call. The return value of each recursive call isn't really of interest, so it can be ignored.
def iterdict(d, counts=None):
    if counts is None:
        counts = dict(all=0, pres=0)

    for k,v in d.items():

        if isinstance(v, dict):
            iterdict(v, counts)
        elif k == "tense":
            counts["all"] += 1
            if v == "Pres":
                counts["pres"] += 1

    return counts["pres"] // counts["all"]


text:
Q: Get all subsequences of a sequence I have an array and I need all possible subarrays (segments or subsequences) with the exception of the empty one. This is not a power set, since every subarray has only elements that were contiguous in the input array.
For example, for input new int[]{1,2,3}, the output would be:
 new int[]{
   new int[]{1},
   new int[]{1,2},
   new int[]{1,2,3},
   new int[]{2},
   new int[]{2,3},
   new int[]{3}
 }

Note that {1,3} is not there because i don't want all subsets (the power set), just all subsequences.
I would prefer a solution using a single LINQ statement.

A: Assuming your source is a List (if not, convert to a List) then you can do:
var srcl = src.ToList();
var ans = Enumerable.Range(0, srcl.Count).SelectMany(start => Enumerable.Range(1, srcl.Count-start).Select(count => srcl.GetRange(start, count)));

Using a natural ArraySegment extension:
public static class ArrayExt {
    public static IEnumerable<T> Segment<T>(this T[] src, int start, int count) => new ArraySegment<T>(src, start, count);
}

You can have this return an array of arrays:
var ans = Enumerable.Range(0, src.Length).SelectMany(start => Enumerable.Range(1, src.Length-start).Select(count => src.Segment(start, count).ToArray()));

But List is generally preferred.

A: Although NetMage's solution is correct, I ended up writing my own extension method that uses Array.Copy for performance:
/// <summary>
/// Get all subsequences of the given sequence.
/// {1,2,3}=>{{1,2},{1,2,3},{2,3}}
/// </summary>
public static T[][] GetAllSubsequences<T>(this IEnumerable<T> collection)
{
    var list = (collection as T[]) ?? collection.ToArray();
    return list.SelectMany((x, i) => list.Skip(i).Select((z, j) =>
          {
              var arr = new T[j + 1];
              Array.Copy(list, i, arr, 0, j + 1);
              return arr;
          })).ToArray();
}


text:
Q: Template argument deduction/substitution failed: I have a compile error when using "output_array()" in a templated member function, the following code is a simple example:
#include <iostream>

using namespace std;

int menu()
{
    int opt;
    cout << "\n**********MENU**********";
    cout << "\n1. Print the Array in reverse order";
    cin >> opt;
    return opt;
}

void input_array(int b[], int n)
{
    cout << "\nEnter the elements of the array";
    for (int i = 0; i < n; i++)
    {
        cin >> b[i];
    }
    return;
}

void output_array(int c[], int n)
{
    for (int j = 0; j < n; j++)
    {
        cout << c[j] << " ";
    }
    return;
}

void rev_arr(int b[], int n)
{
    int start = 0, end = n - 1;

    cout << "Array before reversing : " << output_array(b, n);

    for (int i = 0; i < n / 2; i++)
    {
        float temp = b[start];
        b[start] = b[end];
        b[end] = temp;
        start++;
        end--;
    }

    cout << "Array after reversing : " << output_array(b, n);
    return;
}

void task(int b[], int n, int opt)
{
    switch (opt)
    {
    case 1:
        rev_arr(b, n);
        break;
    default:
        cout << "!!! Sorry Wrong Choice !!!";
    }
    return;
}

int main()
{
    int size;
    int a[50];
        cout << "\n You can Enter 50 elements in the array.\nHow much you want to enter?";
        cin >> size;

        input_array(a, size);
        int opt = menu();
        task(a, size, opt);

    return 0;
}

A: The output_array(int*, int) is a printing function, not an opertot<< overlaod. Therefore, your can't place output_arrry(b, n) after operator<<. Simple separate into two statments:
Change
cout << "Array after reversing : " << output_array(b, n); // Not good.

into
cout << "Array after reversing : ";  output_array(b, n); // ok.

Or you have to write an operator<< overloading, give rules for operator<< to print you array. But, before doing this, you have to bind the size n in your array (as some kind of structure). The size is needed to be used in the function operator<<.


text:
Q: How to add bootstrap-vue module Laravel Jetstream with InertiaJS? How can I work with bootstrap-vue on Laravel, using Laravel 8, Jetstream and InertiaJS?
import Vue from 'vue'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'

// Import Bootstrap an BootstrapVue CSS files (order is important)
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

// Make BootstrapVue available throughout your project
Vue.use(BootstrapVue)
// Optionally install the BootstrapVue icon components plugin
Vue.use(IconsPlugin)

I don't know where and how to add the app.js file.
app.js:
require('./bootstrap');

// Import modules...
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';

const el = document.getElementById('app');

createApp({
    render: () =>
        h(InertiaApp, {
            initialPage: JSON.parse(el.dataset.page),
            resolveComponent: (name) => require(`./Pages/${name}`).default,
        }),
})
    .mixin({ methods: { route } })
    .use(InertiaPlugin)
    .mount(el);

InertiaProgress.init({ color: '#4B5563' });

This is my css.js.
Here add the CSS libraries.
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

@import 'bootstrap/dist/css/bootstrap.css';
@import 'bootstrap-vue/dist/bootstrap-vue.css';

A: As I can see from your configuration. You are using InertiaJS with Vue3. Right now, BootStrap-Vue components only works with Vue2 (info). So you need first to downgrade InertiaJS from Vue3 to Vue2. With npm
npm uninstall @inertiajs/inertia-vue3 vue @vue/compiler-sfc vue-loader

npm install @inertiajs/inertia-vue vue vue-template-compiler vue-loader

It seems weird to uninstall and reinstall vue and vue-loader, but is the easiest way to properly update the dependencies.
Now you need to put in your app.js.
import Vue from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue';
import BootstrapVue from 'bootstrap-vue';

Vue.use(BootstrapVue);

createInertiaApp({
    resolve: (name) => require(`./Pages/${name}`),
    setup({ el, app, props }) {
        new Vue({
            render: (h) => h(app, props),
        }).$mount(el);
    }
});

The app.css does not need any modification. Unless you need to modify and theme Bootstrap, in that case you must change to SASS.


text:
Q: Replacing all html content with base64 image using Javascript I'm looking for a way to use JS to replace the entire content of the HTML document with a single image, whose source is a base64 string.
When you load up a URL directly in your browser, it exhibits certain properties when it is displayed. For example, the image is aspect-scaled to fit, until clicking the image which enlarges it, if it's bigger than the window size.
However, if I simply do something like...
document.write('<img src="data:image/png;base64,..." />');

...the image will display, but it won't exhibit those "native" characteristics, for lack of a better term.
Is there a way to tell the browser to replace all of its content with a base64-encoded image? Or, alternatively, perhaps some way to mimic the native image behavior as closely as possible?

A: You shouldn't use document.write. First, it results in the problem you're experiencing. Second, it's slow and insecure. Use the DOM when possible like so:
// Store list of all child elements
var list = document.body.children;
// Loop through list
for (var i = 0; i < list.length; i++) {
    // Use native DOM method to remove child
    document.body.removeChild(list[i]);
}
// Use native DOM method to create an image element
var img = document.createChild('IMG');
// Set the src of that image to your string
img.src = 'base64string';
// Use native DOM method to append image to document body
document.body.appendChild(img);


text:
Q: Javascript detect if html elements fit screen Is there a way to use javascript to detect if html content can't fit the screen (is scrollable) to show a "back to top button" only if necessary?

A: Hard to tell, but perhaps you could get the element using document.getElementById(), then use innerHeight (http://www.w3schools.com/jsref/prop_win_innerheight.asp) to determine if the element exceeds the height.
Edit - seems like I might have misread a bit.  If you want to check the entire HTML content on the page, you can use something like scrollHeight (https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight) on document.

A: If you're happy to use jQuery, you could try finding the window height and comparing it to a wrapper element height.  If the element height is greater, show the button.

var x = $(window).height();
if ($('#test').height() > x) {
  alert('scrollable');
  //add in button here
}

A: You can compare the height of the page to the height of your browser:
document.body.offsetHeight < screen.availHeight

That will return true if the page fits. Although for your purpose, why not just show the button if the user is scrolled down at all? Assuming you can use jQuery,
$(window).scroll(function(){
    if ($(document.body).scrollTop() > 0)
    {
        //Add or show button here
    }
})

A: It's not IE supported, but my fave vanilla javascript is always:
var scrollHeight = window.scrollY;
console.log(scrollHeight);


text:
Q: Using a workflow to delete from two calendar lists I am new to SharePoint so please be gentle...
I am trying to create a calendar for a school which has multiple overlays...the reason is each overlay list will have the permission for the intended audience, be it staff or pupils etc...
I am also making a submit entry point so staff can view the fact they have submitted a request which then is copied to another list named pending, this pending list has a few more fields for the approver to edit then once finished modifying the item is then copied to the right calendar list for the overlays...
So here is the fun part...if the approver rejects the event I use the workflow to email the event creator, delete the item from the submit list and then delete the item from pending list...this worked when I used custom lists but now I am using built in calendar list and have as strange result...
My onchange pending list workflow does the following
if Status eqauls reject
  email creator (DOES NOT WORK)
  delete from submit list where submitid equals currentitem submitid (WORKS)
  delete from current list (DOES NOT WORK)

Oh and the submitid value is unique, I create that on the submit list with an oncreate workflow that copies ID to sumbmitid column
The above workflow worked if using custom list but not since I used calendar list...also if I remove actions and try each one on its own then they all work...for some reason when combined only the one deletion works
one more thing, If I am approaching this whole idea in the wrong way then I am happy to be told...will post any more info that is needed to have this moving forward
any pointers appreciated...thanks

A: I can only suppose that you cannot delete the item on which you workflow is running from the workflow itself. But I have another note for you - if you using a workflow only for automatic action where there's no long running operation like interaction with users than it's more appropriate to create an event receiver (here's the another example) for the list - it's designed to make such a short operations. You need to create an event receiver, handle ItemEdited event and do execute your delete logic there.


text:
Q: What are the options SOME and NONE in SML? I am new to SML (and programming, actually).
fun readlist (infile : string) =

  let
  val
      ins = TextIO.openIn infile

      fun loop ins =

      case TextIO.inputLine ins of

      SOME line => line :: loop ins

    | NONE      => []

  in

     loop ins before TextIO.closeIn ins

  end ;

This is a program I encountered here. How do I use SOME and NONE, and how to use 'before'?

A: Some('a) and None are part of the Option datatype. Option is an algebraic or compound data structure found in SML's Basis Library. More on the Option data type at Wikipedia. The big idea is, allow a function to return the value None when it doesn't make sense for the function to return a value of the type which the programmer really cares about.
In the case of your user defined function readlist the important data is the string. But at some point, the program hits the end of the file and reads a value interpreted as EOF instead of a string.
Think about TextIO.openIn as a function that opens a stream and searches it for strings. Each time it finds a string, it returns an option(string). When it does not find a string, it returns None.  Because both are part of the Option(string) datatype, TextIO.openIn only returns a single type.

inputLine strm a stream]
      returns SOME(ln), where ln is the next line of input in the stream strm. Specifically, ln returns all characters from the current
  position up to and including the next newline (#"\n") character. If it
  detects an end-of-stream before the next newline, it returns the
  characters read appended with a newline. Thus, ln is guaranteed to
  always be new-line terminated (and thus nonempty). If the current
  stream position is the end-of-stream, then it returns NONE. It raises
  Size if the length of the line exceeds the length of the longest
  string.

A related concept in SML is user-defined datatypes. Both the option datastructure and user-defined data types provide flexibility within SML's static type system in a somewhat similar manner to the way objects are used in statically typed object oriented languages.

A: The option data type is used if there is a possibility of something having no valid value.
For instance,
fun divide x y = if y == 0 then NONE else SOME (x / y)

could be used if you need to handle the special case of division by zero without resorting to exceptions.
TextIO.inputLine returns NONE when there is nothing more to read, and SOME l, where l is the line it has read, when there is.
before is a low-precedence (the lowest of all) infix function that first evaluates its left hand side, then the right hand side, and then returns the value of the left hand side.
It has type 'a * unit -> 'a, i.e. the right hand side is used only for its side effects.
In this case, it makes the code slightly more readable (and functional-looking) than the equivalent
fun readlist (infile : string) =
  let
      val ins = TextIO.openIn infile
      fun loop indata =
          case TextIO.inputLine indata of
              SOME line => line :: loop indata
            | NONE      => []
      val result = loop ins
  in
     TextIO.closeIn ins;
     result
  end


text:
Q: how to authentication given username password to login in Browserfield in blackberry I am new to blackberry. I want how to authentication in browserfield
    BrowserField web;
    String Usname="yahoo@yahoo.com";
    String password="123456788";
    setTitle("sample");
    String Welcome ="example@example.com/isloginmethod.aspx";
    String logindata ="LoginID="+Usname+"&Password="+password;
    byte[] encodeLogin =Base64OutputStream.encode(logindata.getBytes(),0,logindata.length(), false, false);
    BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
    myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
    web = new BrowserField(myBrowserFieldConfig);
    add(web);
    web.requestContent(Welcome,encodeLogin,null);

A: The web.requestContent method you've used here is for calling the url/posting the data and not for authentication.
HTTP Authentication does not come standard in the BrowserField2 API. You'll have to implement ProtocolHandler and override it for doing authentication.
Check this :
http://208.74.204.192/t5/Java-Development/How-to-enable-HTTP-Authentication-in-your-BrowserField2/ta-p/623025

This will help you implement that.


text:
Q: Typing React components in Flow when passing a component as a prop I want to pass a React component as input prop to another React component. I tried to reference it as React.Component<*, *, *> but when I use the passed component in the render method I get an error. This is how I wrote out my flow code.
/* @flow */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const Input = props =>
Yo

type DefaultProps = {
  InputComponent: Input
};

type Props = {
  InputComponent: React.Component<*, *, *>
};

class App extends Component<DefaultProps, Props, void> {
  static defaultProps = {
    InputComponent: Input
  };

  props: Props;

  render() {
    const { InputComponent } = this.props

    return (

        <InputComponent />

    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)

However in the App render method I get the error
React element `InputComponent` (Expected React component instead of React$Component)

How should I properly type input components?

A: Since v0.59.0, you should use React.Component. For example:
/* @flow */

import React from 'react';

const Input = props =>
Yo

type Props = {
  InputComponent: React.Component<*, *>
};

class App extends React.Component<Props, void> {
  static defaultProps = {
    InputComponent: Input
  };

  render() {
    const { InputComponent } = this.props

    return (

        <InputComponent />

    )
  }
}

Here is a working example for 0.59.0. As mentioned in the comments, there is a description of the changes here.
:: Before v0.59.0 ::
You should use ReactClass<*> instead of React.Component.
Here is a working example, and the documentation is here!
/**
 * Type of a React class (not to be confused with the type of instances of a
 * React class, which is the React class itself). A React class is any subclass
 * of React$Component. We make the type of a React class parametric over Config,
 * which is derived from some of the type parameters (DefaultProps, Props) of
 * React$Component, abstracting away others (State); whereas a React$Component
 * type is useful for checking the definition of a React class, a ReactClass
 * type (and the corresponding React$Element type, see below) is useful for
 * checking the uses of a React class. The required constraints are set up using
 * a "helper" type alias, that takes an additional type parameter C representing
 * the React class, which is then abstracted with an existential type (*). The *
 * can be thought of as an "auto" instruction to the typechecker, telling it to
 * fill in the type from context.
 */
type ReactClass<Config> = _ReactClass<*, *, Config, *>;
type _ReactClass<DefaultProps, Props, Config: $Diff<Props, DefaultProps>, C: React$Component<DefaultProps, Props, any>> = Class<C>;

A: On version Flow 0.93.0, you can do the following.

    import type { Element as ReactElement } from 'react';

    type Props = {
      component: ReactElement
    }


text:
Q: Download multiples documents as zip (Ajax call) not working I'm trying to download multiples documents retrieved from WCF (C#) and passing it through data.Stream. Apparently it works but I'm not able to open the downloaded zip, could someone help me please?
   downloadSelectedItems: function () {
                var selectedDocumentsUrl = [];
                for (var i = 0; i < datatableResult.selected.length; i++) {
                    selectedDocumentsUrl.push(datatableResult.selected[i]["relativeUrlToDocument"]);
                }
                var digest = $('#__REQUESTDIGEST').val();
                $.ajax({
                    type: "POST",
                    url: _spPageContextInfo.webAbsoluteUrl + "/_vti_bin/Infratel.Documentale/_wcf/Documentale.svc/DownloadDocuments",
                    headers: {
                        'Content-Type': 'application/json',
                        "X-RequestDigest": digest
                    },
                    data: JSON.stringify({
                        "selectedDocumentsUrl": selectedDocumentsUrl
                    }),
                    contentType: 'application/zip',
                    dataType: 'json',
                    responseType: 'arraybuffer'
                }).done(function (data, textStatus, jqXHR) {
                var blob = new Blob([JSON.stringify(data.Stream, null, 2)], { type: 'application/zip' });
                var link = document.createElement('a');
                var url = window.URL || window.webkitURL;
                link.href = url.createObjectURL(blob);
                link.download = "ArchiveZip";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });
        }

 public Result DownloadDocuments(DataContract data)
        {
            Result result = new Result { Outcome = OutComeType.KO };

                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    var rootWeb = site.RootWeb;
                    using (MemoryStream stream = new MemoryStream())
                    {
                        using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
                        {
                            foreach (var fileUrl in data.selectedDocumentsUrl)
                            {
                                var item = rootWeb.GetListItem(fileUrl);
                                var demoFile = archive.CreateEntry(item.File.Name);

                                using (var entryStream = demoFile.Open())
                                {
                                    item.File.OpenBinaryStream().CopyTo(entryStream);
                                }
                            }
                            //string filename = DateTime.Now.ToFileTime().ToString() + ".zip";
                            //HttpContext.Current.Response.Clear();
                            //HttpContext.Current.Response.ClearHeaders();
                            //HttpContext.Current.Response.ClearContent();
                            //HttpContext.Current.Response.AddHeader("Content-Length", stream.Length.ToString());
                            //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                            //HttpContext.Current.Response.ContentType = "application/zip";
                            //HttpContext.Current.Response.End();

                            //HttpContext.Current.Response.TransmitFile(filename);
                            //byte[] buffer = new byte[65536];
                            //stream.Position = 0;
                            //int num;
                            //do
                            //{
                            //    num = stream.Read(buffer, 0, buffer.Length);
                            //    HttpContext.Current.Response.OutputStream.Write(buffer, 0, num);
                            //}

                            //while (num > 0);
                            //HttpContext.Current.Response.Flush();
                            stream.Position = 0;
                            result.Stream = stream;
                        }
                    }

                }
                result.Outcome = OutComeType.OK;

            return result;
        }


text:
Q: Weblogic JMS binding issue, class could not be initialized exception Could not initialize class exception is coming when trying to view the jndi bindings for a JMS destination in Weblogic 12c server. I have setup JMS modules with JMS destination queues and connection factory. Below are the things that is deployed in the server :
 JMS Module : MyAppJmsModule (JMSSystemResource)
 JMS Server : MyAppJMSServer (Foreign Server)
 JNDI Initial Context Factory: com.sun.jndi.fscontext.RefFSContextFactory
 JNDI Connection URL: file:///abc/oracle/config/domains/domain_test/jms/MyAppJmsModule/MyAppJMSServer/jms
 In the above path lies the .bindings file

 Destination tab showing Name, Local JNDI name and Remote JNDI name correctly.
 Connection Factories tab also showing the jndi names correctly.
 Local jndi name is prefixed with jms/

Now when I am clicking on the destination inside the JNDI Tree, it gives me the below error:
Unexpected exception: failed to load return type: class java.lang.Object; nested exception is: java.lang.ClassNotFoundException: Failed to load class com.ibm.mq.jms.MQQueue

Error from weblogic log :
An error was generated by the RMI server:
    weblogic.jndi.internal.RootNamingNode.lookup(Ljava.lang.String;Ljava.util.Hashtable;)

java.lang.NoClassDefFoundError: Could not initialize class com.ibm.mq.jms.MQXAQueueConnectionFactory.
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at com.ibm.mq.jms.MQXAQueueConnectionFactoryFactory.class$(MQXAQueueConnectionFactoryFactory.java:58)
    at com.ibm.mq.jms.MQXAQueueConnectionFactoryFactory.getObjectInstance(MQXAQueueConnectionFactoryFactory.java:58)
    at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)

Successful JNDI binding should show something like this :
 Binding Name:      jms.QUEUENAME
 Class:             com.ibm.mq.jms.MQQueue
 Hash Code:         Some Value
 toString Results:  queue://QUEUEMGR/APP.QUEUENAME?persistence=2&expiry=0

I have deployed an appplication which got deployed successfully but in warning state. When I checked the monitoring tab for the application it is showing the below error :
Symtom{MDB,MEDIUM,MyApp-0.0.1-SNAPSHOT,MDB application MyApp-0.0.1-SNAPSHOT is NOT connected to messaging system.}

I have checked few of the classes that got loaded and I found the below relevant classes that is being displayed in application classpath :
~/application/config/com.ibm.mq-9.0.0.jar
~/application/config/com.ibm.mq.headers.jar
~/application/config/com.ibm.mq.jmqi-9.0.0.jar
~/application/config/com.ibm.mq.pcf-6.1.jar
~/application/config/com.ibm.mqjms-9.0.0.jar
~/application/config/commons-codec-1.10.jar
~/application/config/dhbcore.jar
~/application/config/fscontext.jar
~/application/config/javaee-api-5.jar
~/application/config/jms.jar
~/application/config/jndi.jar
~/application/config/providerutil.jar

Please help me to find out what is I am missing in my configurations.

A: The application got successfully deployed and it is connecting to the JMS messaging system. I have removed javaee-api jar as it was already there in the classpath with a different version and added the jms-api jar from weblogic library.
However, the destination in the JNDI tree is still giving the error.


text:
Q: How to load Rtl/Ltr css conditionally in a Components styleUrls attribute What is the correct way to load css files conditionally into a Component in angular 4+ ?
@Component({...
    styleUrls:['./rtl.css','./ltr.css']...
})

In my case I need to load Rtl/Ltr css conditionally depending on a param provided by a service (here called _translateService).
this._translateService.onLangChange.subscribe((event: LangChangeEvent) => {this.lang = event});


text:
Q: Is there a more ergonomic syntax for Either when using futures? Here's an example of using Tokio to run a function that returns a future:
use futures::sync::oneshot;
use futures::Future;
use std::thread;
use std::time::Duration;
use tokio;

#[derive(Debug)]
struct MyError {
    error_code: i32,
}

impl From<oneshot::Canceled> for MyError {
    fn from(_: oneshot::Canceled) -> MyError {
        MyError { error_code: 1 }
    }
}

fn deferred_task() -> impl Future<Item = i32, Error = MyError> {
    let (sx, rx) = oneshot::channel();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(100));
        sx.send(100).unwrap();
    });
    return rx.map_err(|e| MyError::from(e));
}

fn main() {
    tokio::run(deferred_task().then(|r| {
        println!("{:?}", r);
        Ok(())
    }));
}

However, when the function in question (i.e. deferred_task) is non-trivial, the code becomes much more complex when I write it, because the ? operation doesn't seem to easily mix with returning a future:
fn send_promise_to_worker(sx: oneshot::Sender<i32>) -> Result<(), ()> {
    // Send the oneshot somewhere in a way that might fail, eg. over a channel
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(100));
        sx.send(100).unwrap();
    });
    Ok(())
}

fn deferred_task() -> impl Future<Item = i32, Error = MyError> {
    let (sx, rx) = oneshot::channel();
    send_promise_to_worker(sx)?; // <-------- Can't do this, because the return is not a result
    return rx.map_err(|e| MyError::from(e));
}

A Future is a Result, it's meaningless to wrap it in result, and it breaks the impl Future return type.
Instead you get a deeply nested chain of:
fn deferred_task() -> impl Future<Item = i32, Error = MyError> {
    let (sx, rx) = oneshot::channel();
    match query_data() {
        Ok(_i) => match send_promise_to_worker(sx) {
            Ok(_) => Either::A(rx.map_err(|e| MyError::from(e))),
            Err(_e) => Either::B(futures::failed(MyError { error_code: 2 })),
        },
        Err(_) => Either::B(futures::failed(MyError { error_code: 2 })),
    }
}

full code
The more results you have, the deeper the nesting; exactly what the ? operator solves normally.
Am I missing something? Is there some syntax sugar to make this easier?

A: I do not see how async / await syntax will categorically help you with Either. Ultimately, you still need to return a single concrete type, and that's what Either provides. async / await will reduce the need for combinators like Future::map or Future::and_then however.
See also:

*

*Why can impl trait not be used to return multiple / conditional types?

That being said, you don't need to use Either here.
You have consecutive Result-returning functions, so you can borrow a trick from JavaScript and use an IIFE to use use the ? operator. Then, we can "lift up" the combined Result into a future and chain it with the future from the receiver:
fn deferred_task() -> impl Future<Item = i32, Error = MyError> {
    let (tx, rx) = oneshot::channel();

    let x = (|| {
        let _i = query_data().map_err(|_| MyError { error_code: 1 })?;
        send_promise_to_worker(tx).map_err(|_| MyError { error_code: 2 })?;
        Ok(())
    })();

    future::result(x).and_then(|()| rx.map_err(MyError::from))
}

In the future, that IIFE could be replaced with a try block, as I understand it.
You could also go the other way and convert everything to a future:
fn deferred_task() -> impl Future<Item = i32, Error = MyError> {
    let (tx, rx) = oneshot::channel();

    query_data()
        .map_err(|_| MyError { error_code: 1 })
        .into_future()
        .and_then(|_i| {
            send_promise_to_worker(tx)
                .map_err(|_| MyError { error_code: 2 })
                .into_future()
        })
        .and_then(|_| rx.map_err(MyError::from))
}

This would be helped with async / await syntax:
async fn deferred_task() -> Result<i32, MyError> {
    let (tx, rx) = oneshot::channel();

    query_data().map_err(|_| MyError { error_code: 1 })?;

    send_promise_to_worker(tx).map_err(|_| MyError { error_code: 2 })?;

    let v = await! { rx }?;

    Ok(v)
}

I have also seen improved syntax for constructing the Either by adding left and right methods to the Future trait:
foo.left();
// vs
Either::left(foo);

However, this doesn't appear in any of the current implementations.

A Future is a Result

No, it is not.
There are two relevant Futures to talk about:

*

*From the futures 0.1 crate

*From the (nightly) standard library
Notably, Future::poll returns a type that can be in two states:

*

*Complete

*Not complete

In the futures crate, "success" and "failure" are tied to "complete", whereas in the standard library they are not. In the crate, Result implements IntoFuture, and in the standard library you can use future::ready. Both of these allow converting a Result into a future, but that doesn't mean that Result is a future, no more than saying that a Vec<u8> is an iterator, even though it can be converted into one.
It's possible that the ? operator (powered by the Try trait), will be enhanced to automatically convert from a Result to a specific type of Future, or that Result will even implement Future directly, but I have not heard of any such plans.

A:
Is there some syntax sugar to make this easier?

Yes, it's called async/await, but it's not quite ready for wide consumption. It is only supported on nightly, it uses a slightly different version of futures that Tokio only supports via an interop library that causes additional syntactic overhead, and documentation for the whole thing is still spotty.
Here are some relevant links:
What is the purpose of async/await in Rust?
https://jsdw.me/posts/rust-asyncawait-preview/
https://areweasyncyet.rs/


text:
Q: Gutenberg repeater blocks using ESNEXT I've been working on creating my own custom Gutenberg repeater block with a text & link input field. I've only seen ES5 samples like this and this. I've been working on creating my own version of those samples for close to 8 hours now and I'm stuck.
I'm here because I want to be pointed in the right direction (help is greatly needed).
Here is the code I currently have. I don't know where to start with the ES5 -> ESNEXT conversion.
Edit: I forgot to say that I'm trying to avoid using ACF for this
// Importing code libraries for this block
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { RichText, MediaUpload, InspectorControls } from '@wordpress/block-editor';
import { Button, ColorPicker, ColorPalette, Panel, PanelBody, PanelRow } from '@wordpress/components';

registerBlockType('ccm-block/banner-block', {
    title: __('Banner Block'),
    icon: 'format-image', // from Dashicons → https://developer.wordpress.org/resource/dashicons/.
    category: 'layout', // E.g. common, formatting, layout widgets, embed.
    keywords: [
        __('Banner Block'),
        __('CCM Blocks'),
    ],
    attributes: {
        mediaID: {
            type: 'number'
        },
        mediaURL: {
            type: 'string'
        },
        title: {
            type: 'array',
            source: 'children',
            selector: 'h1'
        },
        content: {
            type: 'array',
            source: 'children',
            selector: 'p'
        },
        bannerButtons: {
            type: 'array',
            source: 'children',
            selector: '.banner-buttons',
        },
        items: {
            type: 'array',
            default: []
        }
    },

    /**
     * The edit function relates to the structure of the block when viewed in the editor.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Component.
     */
    edit: (props) => {

        const {
            attributes: { mediaID, mediaURL, title, content, bannerButtons },
            setAttributes, className
        } = props;

        const onSelectImage = (media) => {
            setAttributes({
                mediaURL: media.url,
                mediaID: media.id,
            });
        };

        const onChangeTitle = (value) => {
            setAttributes({ title: value });
        };

        const onChangeContent = (value) => {
            setAttributes({ content: value });
        };

        const onChangeBannerButtons = (value) => {
            setAttributes({ bannerButtons: value });
        };

        // console.log(items);
        // var itemList = items.sort

        return (

                    <MediaUpload
                        onSelect={onSelectImage}
                        allowedTypes="image"
                        value={mediaID}
                        render={({ open }) => (
                            <Button className={mediaID ? 'image-button' : 'button button-large'} onClick={open}>
                                {!mediaID ? __('Upload Image', 'ccm-blocks') : }
                            </Button>
                        )}
                    />

                    <RichText
                        tagName="h1"
                        placeholder={__('Insert Title Here', 'ccm-blocks')}
                        className={className}
                        onChange={onChangeTitle}
                        value={title}
                    />

                    <RichText
                        tagName="p"
                        placeholder={__('Insert your short description here...', 'ccm-blocks')}
                        className={className}
                        onChange={onChangeContent}
                        value={content}
                    />

                    <RichText
                        tagName="ul"
                        multiline="li"
                        className="banner-buttons"
                        placeholder={ __('Add a banner button link (max of 2)', 'ccm-blocks') }
                        onChange={ onChangeBannerButtons }
                        value={ bannerButtons }
                    />

        );
    },

    /**
     * The save function determines how the different attributes should be combined into the final markup.
     * Which is then serialised into the post_content.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Frontend HTML.
     */
    save: (props) => {
        return (

                <div id="home-banner" style={{backgroundImage: `url(${ props.attributes.mediaURL })`}}>

                                    <RichText.Content tagName="h1" className={ props.className } value={ props.attributes.title } />
                                    <RichText.Content tagName="p" className={ props.className } value={ props.attributes.content } />
                                    <RichText.Content tagName="ul" className="banner-buttons" value={ props.attributes.bannerButtons } />

        );
    },
});

Edit 2: Here's my failed take on it
// Importing code libraries for this block
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { RichText, MediaUpload, InspectorControls } from '@wordpress/block-editor';
import { Button, ColorPicker, ColorPalette, Panel, PanelBody, PanelRow } from '@wordpress/components';

/**
 * Register the Block
 *
 * @link https://wordpress.org/gutenberg/handbook/block-api/
 * @param  {string}   name     name.
 * @param  {Object}   settings settings.
 * @return {?WPBlock}          The block, otherwise `undefined`.
 */
registerBlockType('ccm-block/banner-block', {
    title: __('Banner Block'),
    icon: 'format-image', // from Dashicons → https://developer.wordpress.org/resource/dashicons/.
    category: 'layout', // E.g. common, formatting, layout widgets, embed.
    keywords: [
        __('Banner Block'),
        __('CCM Blocks'),
    ],
    attributes: {
        mediaID: {
            type: 'number'
        },
        mediaURL: {
            type: 'string'
        },
        title: {
            type: 'array',
            source: 'children',
            selector: 'h1'
        },
        content: {
            type: 'array',
            source: 'children',
            selector: 'p'
        },
        bannerButtons: {
            type: 'array',
            source: 'children',
            selector: '.banner-buttons',
        },
        items: {
            source: 'query',
            default: [],
            selector: '.item',
            query: {
                title: {
                    type: 'string',
                    source: 'text',
                    selector: '.title'
                },
                index: {
                    type: 'number',
                    source: 'attribute',
                    attribute: 'data-index'
                }
            }
        }
    },

    /**
     * The edit function relates to the structure of the block when viewed in the editor.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Component.
     */
    edit: (props) => {

        const {
            attributes: { mediaID, mediaURL, title, content, bannerButtons, items },
            setAttributes, className
        } = props;

        const onSelectImage = (media) => {
            setAttributes({
                mediaURL: media.url,
                mediaID: media.id,
            });
        };

        const onChangeTitle = (value) => {
            setAttributes({ title: value });
        };

        const onChangeContent = (value) => {
            setAttributes({ content: value });
        };

        const onChangeBannerButtons = (value) => {
            setAttributes({ bannerButtons: value });
        };

        // Clone an array of objects
        function _cloneArray(arr) {
            if (Array.isArray(arr)) {
              for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
                arr2[i] = arr[i];
              }
              return arr2;
            } else {
              return Array.from(arr);
            }
        }
        // return repeater items
        var itemList = items.sort(function(a, b){
            return a.index - b.index;
        }).map(function(item){
            console.log(item);
            return(
                <RichText
                    tagName="h1"
                    placeholder={ __('Test', 'ccm-blocks') }
                    value={ item.title }
                    onChange={ function(value){
                        var newObject = Object.assign({}, item, {
                            title: value
                        });
                        setAttributes({
                            items: [].concat(_cloneArray(items.filter(function(itemFilter){
                                return itemFilter.index != item.index;
                            })), [newObject])
                        });
                    } }
                />
            );
        });

        //
        console.log(itemList);

        return (

                    <RichText
                        className="item-list"
                        tagName="h1"
                        value={ itemList }
                    />

                    <Button
                        className="button add-row"
                        onClick={ function(){
                            setAttributes({
                                items: [].concat(_cloneArray(items), [{
                                    index: items.length,
                                    title: ""
                                }])
                            });
                        } }
                    >
                        Add a button
                    </Button>

                    <MediaUpload
                        onSelect={onSelectImage}
                        allowedTypes="image"
                        value={mediaID}
                        render={({ open }) => (
                            <Button className={mediaID ? 'image-button' : 'button button-large'} onClick={open}>
                                {!mediaID ? __('Upload Image', 'ccm-blocks') : }
                            </Button>
                        )}
                    />

                    <RichText
                        tagName="h1"
                        placeholder={__('Insert Title Here', 'ccm-blocks')}
                        className={className}
                        onChange={onChangeTitle}
                        value={title}
                    />

                    <RichText
                        tagName="p"
                        placeholder={__('Insert your short description here...', 'ccm-blocks')}
                        className={className}
                        onChange={onChangeContent}
                        value={content}
                    />

                    <RichText
                        tagName="ul"
                        multiline="li"
                        className="banner-buttons"
                        placeholder={ __('Add a banner button link (max of 2)', 'ccm-blocks') }
                        onChange={ onChangeBannerButtons }
                        value={ bannerButtons }
                    />

        );
    },

    /**
     * The save function determines how the different attributes should be combined into the final markup.
     * Which is then serialised into the post_content.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Frontend HTML.
     */
    save: (props) => {
        return (

                <div id="home-banner" style={{backgroundImage: `url(${ props.attributes.mediaURL })`}}>

                                    <RichText.Content tagName="h1" className={ props.className } value={ props.attributes.title } />
                                    <RichText.Content tagName="p" className={ props.className } value={ props.attributes.content } />
                                    <RichText.Content tagName="ul" className="banner-buttons" value={ props.attributes.bannerButtons } />

        );
    },
});

A: I've figured it out!! After countless hours of tinkering with it here's what I came up with. It's a rough version of what I want but it definitely works! Here's a link for one of the tutorials I found link.
// Importing code libraries for this block
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { RichText } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';

// Register the block
registerBlockType( 'test-block/custom-repeater-block', {
    title: __('Repeater Block'),
    icon: 'layout',
    category: 'layout',
    keywords: [
        __('Custom Block'),
    ],
    attributes: {
        info: {
            type: 'array',
            selector: '.info-wrap'
        }
    },

    // edit function
    edit: (props) => {
        const {
            attributes: { info = [] },
            setAttributes, className
        } = props;

        const infoList = (value) => {
            return(
                value.sort((a, b) => a.index - b.index).map(infoItem => {
                    return(

                            <Button
                                className="remove-item"
                                onClick={ () => {
                                    const newInfo = info.filter(item => item.index != infoItem.index).map(i => {
                                        if(i.index > infoItem.index){
                                            i.index -= 1;
                                        }
                                        return i;
                                    } );
                                    setAttributes({ info: newInfo });
                                } }
                            >×</Button>

Number {infoItem.index}

                            <RichText
                                tagName="h4"
                                className="info-item-title"
                                placeholder="Enter the title here"
                                value={infoItem.title}
                                style={{ height: 58 }}
                                onChange={ title => {
                                    const newObject = Object.assign({}, infoItem, {
                                        title: title
                                    });
                                    setAttributes({
                                        info: [...info.filter(
                                            item => item.index != infoItem.index
                                        ), newObject]
                                    });
                                } }
                            />
                            <RichText
                                tagName="p"
                                className="info-item-description"
                                placeholder="Enter description"
                                value={infoItem.description}
                                style={{ height: 58 }}
                                onChange={ description => {
                                    const newObject = Object.assign({}, infoItem, {
                                        description: description
                                    });
                                    setAttributes({
                                        info: [...info.filter(
                                            item => item.index != infoItem.index
                                        ), newObject]
                                    });
                                } }
                            />

                    )
                })
            )
        }

        return(

{infoList(info)}

                <Button onClick={title => {
                    setAttributes({
                        info: [...info, {
                            index: info.length,
                            title: "",
                            description: ""
                        }]
                    });
                }}>Add Item</Button>

        );
    },

    // save function
    save: (props) => {
        const info = props.attributes.info;
        const displayInfoList = (value) => {
            return(
                value.map( infoItem => {
                    return(

                            <RichText.Content
                                tagName="h4"
                                className="info-item-title"
                                value={infoItem.title}
                                style={{ height: 58 }}
                            />

                    )
                } )
            )
        }

        return(

{ displayInfoList(info) }

        );
    }
} )

A: I just created an example with the query attribute, you can find it here: github repo
I believe that query is the right way to go when working on more complex blocks.
So first attribute part:
attributes: {
        services: {
            type: "array",
            source: "query",
            default: [],
            selector: "section .card-block",
            query: {
                index: {
                    type: "number",
                    source: "attribute",
                    attribute: "data-index",
                },
                headline: {
                    type: "string",
                    selector: "h3",
                    source: "text",
                },
                description: {
                    type: "string",
                    selector: ".card-content",
                    source: "text",
                },
            },
        },
    },

Then edit.js part:
import produce from "immer";
import { __ } from "@wordpress/i18n";
import "./editor.scss";

import { RichText, PlainText } from "@wordpress/block-editor";
// import { useState } from "@wordpress/element";

export default function Edit({ attributes, setAttributes, className }) {
    const services = attributes.services;

    const onChangeContent = (content, index, type) => {
        const newContent = produce(services, (draftState) => {
            draftState.forEach((section) => {
                if (section.index === index) {
                    section[type] = content;
                }
            });
        });
        setAttributes({ services: newContent });
    };
    return (
        <>
            {services.map((service) => (
                <>
                    <RichText
                        tagName="h3"
                        className={className}
                        value={service.headline}
                        onChange={(content) =>
                            onChangeContent(content, service.index, "headline")
                        }
                    />
                    <PlainText
                        className={className}
                        value={service.description}
                        onChange={(content) =>
                            onChangeContent(content, service.index, "description")
                        }
                    />
                </>
            ))}
            <input
                className="button button-secondary"
                type="button"
                value={__("Add Service", "am2-gutenberg")}
                onClick={() =>
                    setAttributes({
                        services: [
                            ...attributes.services,
                            { headline: "", description: "", index: services.length },
                        ],
                    })
                }
            />
        </>
    );
}

and finally, saving part:
export default function save({ attributes, className }) {
    const { services } = attributes;

    return (

            {services.length > 0 &&
                services.map((service) => {
                    return (

{service.headline}

{service.description}

                    );
                })}

    );
}


text:
Q: BJT with collector base or base emitter shorted People have been using BJTs in various configurations with either of the junctions shorted. The following queries persist for these configurations. Links to previous questions are added
1)Base collector shorted
This configuration is used when the bjt is to be configured as a diode. Now, what would be the ratio of the base current to the collector current is this configuration and does this have any relation to the standard Hfe
2)Base emitter shorted
Mentioned as an alternative to using zeners. In that case can I use a BJT with base-collector shorted and reverse biased in replacement for a low voltage zener. (in place of standard zeners which have a soft knee, saw this link which mentions a sharp knee for this config). Say for example I use a BC817 as a replacement for a 5V zener. And in this case I expect the current rating to be the lower of Ic and that dictated by the power rating of the device

A: With Base connected to Collector the transistor is on the knee going into the saturation zone. Depending on knee voltage the current gain may be a bit lower than HFE at standard Collector voltage.
With Base connected to Emitter the transistor is turned off unless the polarity is reversed, and then the Collector and Emitter swap roles. The current gain is very low in this mode but it still acts like the other case.
If the Base is not connected to the Emitter then the B-E reverse bias breakdown voltage can be exploited. The problem with this mode is that it is outside the absolute maximum specification (so if it damages anything it's your fault). The actual breakdown voltage is not usually specified either, so it cannot be relied on.


text:
Q: How to debug an Angular app that require remote assets with login I have an angular app that downloads resources from Cloudflare in order to get it up and running. The problem is that you have to login.
So when I run the debug mode in VSCode, the Chrome window that opens goes blank with the error:
arg1:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: 'OK', url: 'https://xxxx.cloudflareaccess.com/cdn-cgi/acce…xxxxxXvzw', ok: false, …}
defaultErrorLogger @ c:\Users\xxxxxxx\workspace\xxxx\xxxx\node_modules\@angular\core\fesm2015\core.mjs:6461

To resolve that and continue debugging, I need to open another window in the Chrome that was opened for debugging, login, return to the app window, and refresh.
I have to do that every day.
Isn't there a way to add the accesses in the launch.json so that it does it automatically?
It's quite annoying.
My actual launch.json is :
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Chrome",
      "request": "launch",
      "type": "chrome",
      "url": "http://localhost:4200",
      "webRoot": "${workspaceFolder}"
    }
  ]
}

A: You need to be authenticated and logged in to run remote resources. You could create SSH tunnel:

Cloudflare can be used to create a zero trust configuration for the SSH connection between your local machine and the VM in Azure. To get started, create a free Cloudflare account, set up a domain, and enable the Access and Argo Tunnel products in your account.

https://developers.cloudflare.com/cloudflare-one/tutorials/ssh
https://bradyjoslin.com/blog/remote-vs-code/#vs-code-remote-ssh-extension


text:
Q: How to delete REG_DWORD registry value where registry value like '*String*' using PowerShell? PowerShell is presenting registry values (and their registry data) as an array in $\_.Property in their parent registry key. How do I select and delete only the registry values where the value is like \*String\* ?
I have tried searching high and low on StackOverflow and on Google trying many combinations that involve Get-Item, Get-ItemProperty, Get-ChildItem, Select-Object (including -ExpandProperty parameter), and Where-Object to select the registry values that I want (prior to moving on to incorporating deletion). I am now at a point where I am entirely clueless and unable to figure out how to simply find registry values like \*Text\* existing at a particular registry key and delete them. Something so simple seems so difficult! I do not know how to work with data in arrays!
Get-Item -Path HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\SharedDLLs

Every registry value is being listed as part of an array under $\_.Property for registry key HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\SharedDLLs. I was expecting results where I could do something roughly like $\_.RegistryValue -Like '\*Text\*' | Remove-Item to delete the registry values matching \*Text\*.
For clarification to ensure correct technical usage of certain vocabulary, a "registry key" appears as a folder in regedit.exe.
A "registry value" is an entry of any type such as REG\_SZ, REG\_DWORD, REG\_MZ, and so on. A registry value contains "registry data", and depending on the registry type, it may be a string, an 32-bit value (sometimes expressed as either 1, 0, or 0x000000, 0x000001).
We often refer to "registry values" as 'registry keys' (which is incorrect technical usage) and the "registry data" as 'registry values' (also incorrect technical usage), and "registry keys" as folders/location/"this place in the registry".

A: Removing registry values by value name filter only:
Update, based on your own simplification:
# The target registry key's full path.
$keyPath = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\SharedDLLs'

# Pass the value name pattern to Remove-ItemProperty's -Name parameter.
# Remove `-WhatIf` if the preview suggests that the operation works as intended.
Remove-ItemProperty -Path $keyPath -Name *Text* -WhatIf

Pitfall: If you want to use a wildcard expression such as *Text* with -Name, you must combine it with -Path rather than -LiteralPath, even if the key path is itself not a wildcard; with -LiteralPath, -Name too is then taken literally (verbatim).
If you do need to use -LiteralPath (e.g., if the literal path contains a * character, such as in HKEY_CLASSES_ROOT\*):
# The target registry key's full path.
$keyPath = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\SharedDLLs'

# Get an array of all value names that match the name wildcard pattern.
$valueNames = (Get-Item -LiteralPath $keyPath).Property -like '*Text*'

# Pass the array of value names to Remove-ItemProperty's -Name parameter.
# Remove `-WhatIf` if the preview suggests that the operation works as intended.
if ($valueNames) {
  Remove-ItemProperty -LiteralPath $keyPath -Name $valueNames -WhatIf
}

Note the use of Get-Item rather than Get-ItemProperty.[1]
Get-Item returns an object representing the entire key that is of type [Microsoft.Win32.RegistryKey], which PowerShell decorates with a .Property note property that contains an array  of all the key's value names.
Important: In the .Property array, PowerShell translates the default value name, which is the empty string ('') at the API level, into name '(default)'.
Applying operator -like to an array LHS makes it act as a filter that only returns a sub-array of matching items.
Remove-ItemProperty's -Name parameter directly accepts an array of property (registry value) names to remove from the target key.

Removing values by value name and/or data filter:
Note: Due to use of the -PipelineVariable common parameter, this solution requires PSv4+.
# The target registry key's full path.
$keyPath = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\SharedDLLs'

$pattern = '*Text*'

# Look for $pattern in both the name and the data.
# Remove `-WhatIf` if the preview suggests that the operation works as intended.
Get-Item -LiteralPath $keyPath -PipelineVariable key |
  ForEach-Object Property |
    Where-Object {
      $valueName = ($_, '')[$_ -eq '(default)'] # translate '(default)' to '' for API
      $valueName -like $pattern -or $key.GetValue($valueName) -like $pattern
    } |
      Remove-ItemProperty -LiteralPath $keyPath -WhatIf

*

*-PipelineVariable key stores the [Microsoft.Win32.RegistryKey] instance returned by Get-Item in variable $key for later use in the pipeline.

*ForEach-Object Property enumerates the target key's value names (via the .Property note property PowerShell adds to the output [Microsoft.Win32.RegistryKey] instance, as discussed).

*Inside the Where-Object script block, $_ then refers to the value name at hand, and $key.GetValue(<valueName>) is used to retrieve the associated data.

*

*Important: In the .Property array, PowerShell translates the default value name, which is the empty string ('') at the API level, into name '(default)'; thus, if $_ is '(default)', you must translate it to '' before calling $_.GetValue(<valueName>), which is what ($_, '')[$_ -eq '(default)'] does.

*Whatever value names match the criteria are then piped to Remove-ItemProperty, which implicitly binds these names to its -Name parameter.
If you simply want to list matching values and their data, see this answer.

[1] Get-ItemProperty -Path $keyPath -Name *Text* technically works too, but the output is a single object of type [pscustomobject], whose properties you have to enumerate via reflection, because the property names reflect the matching value names; while doing so via .psobject.properties as shown in this answer works and allows you to filter by data too, the pitfall is that PowerShell's registry provider automatically adds its own properties to the collection of properties, namely PSPath, PsParentPath, PSChildName, PSDrive, PSProvider, which means that a wildcard expression that filters by name can accidentally include them or, worse, if values by the same name happen to exist on the key (even though unlikely), the provider properties overrides them.

A: The registry provider is horrible.  I just wish get-itemproperty worked like this:
# get-itemproperty2.ps1

# get-childitem skips top level key, use get-item
# can't remove default name
param([parameter(ValueFromPipeline)]$key)

process {
  $valuenames = $key.getvaluenames()

  if ($valuenames) {
    $valuenames | foreach {
      $value = $_
      [pscustomobject] @{
        Path = $key -replace 'HKEY_CURRENT_USER',
          'HKCU:' -replace 'HKEY_LOCAL_MACHINE','HKLM:'
        Name = $Value
        Value = $Key.GetValue($Value)
        Type = $Key.GetValueKind($Value)
      }
    }
  } else {
    [pscustomobject] @{
      Path = $key -replace 'HKEY_CURRENT_USER',
        'HKCU:' -replace 'HKEY_LOCAL_MACHINE','HKLM:'
        Name = ''
        Value = ''
        Type = ''
    }
  }
}

Then you could just do things like:
PS C:\users\me> get-item hkcu:\key1 | get-itemproperty2

Path       Name  Value    Type
----       ----  -----    ----
HKCU:\key1 name1 value1 String
HKCU:\key1 name2 value2 String

PS C:\users\me> get-item hkcu:\key1 | get-itemproperty2 | where name -eq name1

Path       Name  Value    Type
----       ----  -----    ----
HKCU:\key1 name1 value1 String

PS C:\users\me> get-item hkcu:\key1 | get-itemproperty2 | where name -eq name1 | Remove-ItemProperty -whatif
What if: Performing the operation "Remove Property" on target "Item: HKEY_CURRENT_USER\key1 Property: name1".

PS C:\users\me> get-childitem -recurse hkcu:\key1 | get-itemproperty2

Path                      Name  Value     Type
----                      ----  -----     ----
HKCU:\key1\key2           name2 value2  String
HKCU:\key1\key2                 default String
HKCU:\key1\key2\key3      name3 value3  String
HKCU:\key1\key2\key3\key4


text:
Q: Multiple delete rows in radgrid
My problem :
I want to delete all selected records using checkbox in RadGrid..
How to write the code for this..
I have a code for simple GridView But its not working in RadGrid.

A: Please try with below code snippet.
Method1
.aspx
 <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False"
        OnNeedDataSource="RadGrid1_NeedDataSource">
        <MasterTableView DataKeyNames="ID">
            <Columns>

                <telerik:GridBoundColumn DataField="Name" UniqueName="Name" HeaderText="Name">
                </telerik:GridBoundColumn>
                <telerik:GridTemplateColumn>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridEditCommandColumn>
                </telerik:GridEditCommandColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>

.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
    foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
    {
        CheckBox CheckBox1 = item.FindControl("CheckBox1") as CheckBox;
        if (CheckBox1 != null && CheckBox1.Checked)
        {
            // Access data key
            string strID = item.GetDataKeyValue("ID").ToString();
            // Access column
            string strName = item["Name"].Text; // "Name" is column unique name

            // delete logic comes here
        }
    }
}

Method2
.aspx
  <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False"
        OnNeedDataSource="RadGrid1_NeedDataSource"
        AllowMultiRowSelection="true">
        <MasterTableView DataKeyNames="ID">
            <Columns>
                <telerik:GridClientSelectColumn>
                </telerik:GridClientSelectColumn>
                <telerik:GridBoundColumn DataField="Name" UniqueName="Name" HeaderText="Name">
                </telerik:GridBoundColumn>
                <telerik:GridEditCommandColumn>
                </telerik:GridEditCommandColumn>
            </Columns>
        </MasterTableView>
        <ClientSettings>
            <Selecting AllowRowSelect="true" />
        </ClientSettings>
    </telerik:RadGrid>

.aspx.cs
 protected void Button1_Click(object sender, EventArgs e)
{
    foreach (GridDataItem item in RadGrid1.SelectedItems)
    {
        if (item.Selected)
        {
            // Access data key
            string strID = item.GetDataKeyValue("ID").ToString();
            // Access column
            string strName = item["Name"].Text; // "Name" is column unique name

            // delete logic comes here
        }
    }
}

Common code for both of above method.
.aspx
 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

.aspx.cs
 protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    dynamic data = new[] {
        new { ID = 1, Name ="Name1",path="1.jpg"},
        new { ID = 2, Name = "Name2",path="2.jpg"},
        new { ID = 3, Name = "Name3",path="3.jpg"},
         new { ID = 4, Name = "Name4",path="2.jpg"},
        new { ID = 5, Name = "Name5",path="3.jpg"}
    };
    RadGrid1.DataSource = data;
}


text:
Q: ¿Cómo puedo guardar múltiples archivos con un mismo ID? Tengo un problema al intentar insertar los archivos en la base de datos. Me los ingresa de esta manera:

Lo que necesito es que ingresen todos con el mismo id. Ejemplo:
id   file
15   bd1(Autoguardado).xlsx, Captura.JPG, combox filtro.JPG

Aquí está el código:

//Iniciamos nuestra función jquery.
$(function(){
 $('#enviar').click(SubirFotos);
});

function SubirFotos(){
  var archivos = document.getElementById("archivos");
  var archivo = archivos.files;
  var archivos = new FormData();

  for(i=0; i<archivo.length; i++){
  archivos.append('archivo'+i,archivo[i]);  }

  /*Ejecutamos la función ajax de jQuery*/
  $.ajax({
   url:'subir.php',
   type:'POST',
   contentType:false,
   data:archivos,
   processData:false,
   cache:false
  }).done(function(msg){
   MensajeFinal(msg)
  });
 }

function MensajeFinal(msg){
 $('.mensage').html(msg);
 $('.mensage').show('slow');//Mostramos el div.
}

Subir.php
<?php

require_once "conexion.php";
$conexion=conexion();
$ruta = './Files/';
$mensage = '';
foreach ($_FILES as $key)
{
    if($key['error'] == UPLOAD_ERR_OK )
        {
            $NombreOriginal = $key['name'];
            $temporal = $key['tmp_name'];
            $Destino = $ruta.$NombreOriginal;

            move_uploaded_file($temporal, $Destino);
        }

    if ($key['error']=='')
        {
            $mensage .= '-> Archivo '.$NombreOriginal.' Subido correctamente.
';
        }
    if ($key['error']!='')
        {
            $mensage .= '-> No se pudo subir el archivo '.$NombreOriginal.' debido al siguiente Error: \n'.$key['error'];
        }
    $sql="INSERT into imagen (file) values('$NombreOriginal')";
    echo $result=mysqli_query($conexion,$sql);
}

echo $mensage;
?>

A: Te quería poner un comentario, pero me resulta difícil siendo que no se puede poner código. Solo tienes que declarar una variable fuera y antes del for en dónde ir guardando las imágenes y luego, al salir del for, realizar el insert una sola vez:
<?php
    require_once "conexion.php";
    $conexion = conexion();
    $ruta = './Files/';
    $mensage = '';
    $files = "";
    foreach ($_FILES as $key) {
        if($key['error'] == UPLOAD_ERR_OK ) {
            $NombreOriginal = $key['name'];
            $temporal = $key['tmp_name'];
            $Destino = $ruta.$NombreOriginal;
            move_uploaded_file($temporal, $Destino);
        }
        if ($key['error']=='') {
            $mensage .= '-> Archivo '.$NombreOriginal.' Subido correctamente.
';
        }
        if ($key['error']!='') {
            $mensage .= '-> No se pudo subir el archivo '.$NombreOriginal.' debido al siguiente Error: \n'.$key['error'];
        }
        $files .= $NombreOriginal . ", ";
    }
    $files = trim($files, ", "); // Quito la última ", " de la cadena
    $sql="INSERT into imagen (file) values('$files')";
    echo $result=mysqli_query($conexion,$sql);
    echo $mensage;
?>

A: En la forma en la que tienes el diseño, es muy dificil hacer lo que pretendes.  Como la columna id es AUTO_INCREMENT, siempre te va a generar un id nuevo para cada INSERT.  La unica forma de hacerlo seria concatenando los nombres de los archivos separados por comas, pero como ya te explicaron, esto no es un buen diseño porque viola la primera forma normal.
Si la razon por la que quieres tener el mismo id es porque los archivos estan relacionados con alguna otra entidad, digamos un usuario, la forma correcta de hacerlo seria agregar una llave foranea que apunte a dicho usuario.  De esa forma, puedes relacionar los archivos que pertenezcan a un usuario con la misma llave foranea.


text:
Q: Можно ли выполнять таски в Celery по очереди? Всем привет! У меня есть две таски download_and_send_youtube_video и clear_cache_youtube_video. Код:
@celery.task
def clear_cache_youtube_video(video_path: Path):
    """Clear YouTube video from cache"""
    if os.path.exists(video_path):
        os.remove(video_path)

@celery.task
@inject
def download_and_send_youtube_video(
        chat_id: int,
        link: str,
        redis_client: Redis = Provide[WorkerContainer.redis_client]
Provide[WorkerContainer.assistant_grpc_client]  # Передаётся через dependency injector
):
    assistant_grpc_client = AssistantGrpcClient(ASSISTANT_GRPC_ADDR)

    try:
        yt = YouTube(link)
    except pytube.exceptions.VideoUnavailable:
        logger.info(f'{link}: video is unavailable')
        return

    if yt.length >= YT_MAX_VIDEO_LENGTH:
        logger.info(f'{link} video too long')
        return

    # forward message if it's existing in cache
    yt_cached_msg_id = f'youtube:{yt.video_id}'
    if redis_client.exists(yt_cached_msg_id):
        chat_message_id = redis_client.get(yt_cached_msg_id).decode()
        from_chat_id, message_id = map(int, chat_message_id.split(':'))
        req = ForwardMessagesRequest(
            from_chat_id=from_chat_id,
            chat_id=chat_id,
            disable_notification=True
        )
        req.message_ids.append(message_id)
        assistant_grpc_client.stub.forward_messages(req)
        return

    stream = yt.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution()
    if stream is None:
        logger.warning(f'{link}: stream is not available')
        return

    out_filename = yt.video_id
    video_path = stream.download(YT_OUT_DIR, out_filename)

    caption = remove_hashtags(yt.title).strip()
    req = SendVideoRequest(
        chat_id=chat_id,
        video_path=video_path,
        caption=caption,
        disable_notification=True
    )
    result_msg = assistant_grpc_client.stub.send_video(req)

    video_ttl = timedelta(seconds=YT_VIDEO_TTL)
    # cache message id in Redis store
    redis_client.set(yt_cached_msg_id, f'{chat_id}:{result_msg.id}', video_ttl)

    release_date = datetime.now() + video_ttl
    clear_cache_youtube_video.apply_async((video_path,), eta=release_date)

...

@bot.on_message
async def handle_new_message(client: Client, link: str):
     await chat_id = client.get_chat_id();
     download_and_send_youtube_video.delay(chat_id, link)

clear_cache_youtube_video удаляет видео из кеша.
download_and_send_youtube_video вызывается, когда пользователь отправляет кому-нибудь сообщение.
Внутри download_and_send_youtube_video:
Есть ли видео в кеше?
  Пересылаем сообщение из другого диалога.
Иначе:
  Скачиваем видео.
  Отправляем пользователю.
  Сохраняем на несколько минут в Redis информацию ключ: youtube_video_id, значение: "chat_id:message_id".
  Создаём таску clear_cache_youtube_video на удаление видео через 3 минуты.

Если запустить воркер со стандартным значением concurrency = 8 и запустить одновременно (почти), например, три таски download_and_send_youtube_video, то видео будет скачиваться в трёх тасках и после загрузки создастся три таски clear_cache_youtube_video для удаление видео из кеша. Это плохо с точки зрения производительности, так как видео скачивается в пустую 3 раза и 3 раза удаляться.
В данному случае лучше исполнять таски download_and_send_youtube_video последовательно. Тогда в примере с 3-мя тасками видео будет скачиваться один раз, 2 раза пересылаться сообщение из чата со скачанным видео, 1 раз удалится видео из кеша. Это можно сделать, если установить concurrency = 1, но тогда все таски в Celery будут исполняться по очереди. Мне бы хотелось сделать так, чтобы только таски download_and_send_youtube_video исполнялись по очереди. Можете, пожалуйста, подсказать, как можно так сделать в Celery?
Примечание:
download_and_send_youtube_video исполняю в воркере для того, чтобы не стопить поток обработки сообщений (функция handle_new_message).

A: Чтоб ограничить одновременное исполнение задач используйте маршрутизацию.
Создайте специальный маршрут для download_and_send_youtube_video так, чтоб все задачи download_and_send_youtube_video  попадали в отдельную очередь, которую будет обрабатывать только один процесс. Для этого в конфигурацию celery добавьте параметр task_routes:
task_routes = {'path.to.tasks.download_and_send_youtube_video': {'queue': 'downloads'}}

Теперь вам нужно запустить обработчики (celery worker) два раза, один для очереди по умолчанию (если не меняли названия то она называется celery) с нужной вам concurrency, и второй для очереди downloads с concurrency=1:
celery -A myproj worker -Q celery --concurrency=10
celery -A myproj worker -Q downloads --concurrency=1

Но конкретно для вашей задачи это не лучшее решение, так как будет заблокированно одновременное скачивание разных видео. Лучшее решение, это разделить задачу на две: отдельно задача на скачивание, отдельно - на посылку.
Задача на скачивание, должна записать в redis признак того, что она собирается скачивать такое то видео, проверив сначала, что этот признак не установлен. Если признак уже установлен, т.е. другая задача уже скачивает, то качать заново не нужно, нужно только сохранить информацию о том, кому нужно будет послать файл по окончанию скачивания. Опять же это можно сохранить в redis. После того, как файл скачался, нужно разослать его всем кому нужно.


text:
Q: Kotlin set two different text styles to dynamically changing text in a text view using SpannableString I have a text view with a value that can change. For example, it's Pressure. It can have different length - i.e. 999.1 or 1010.2 hPa.
The text looks like this:

I need to set different text styles for the first part of the text (the number - 1024.12) and the second part of the text (the unit of measurement).
So far I have tried:

*

*Using SpannableString and set spans to the same scannable string.

*Creating two scannable strings, setting spans on them separately, joining two scannable strings and setting that joined scannable strings as text to text view:
//the value of measurement
val spannable1 = SpannableString(button.customView.tvBottom.text.split(" ")[0])
//the unit of measurement
val spannable2 = SpannableString(button.customView.tvBottom.text.split(" ")[1])

spannable1.setSpan(R.style. Bold20Dark, 0, spannable1.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
spannable2.setSpan(R.style. Regular12Dark, 0, spannable2.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

val spannableString = spannable1.toString() + spannable2.toString()
button.customView.tvBottom.setText(spannableString)

What stops me is the dynamic change of the number and its length, so I cannot figure out how to set a stable range if it constantly changes.
By different text styles I mean following styles:
 <style name="Bold20Dark">
        <item name="android:textSize">20sp</item>
        <item name="android:lineSpacingExtra">3sp</item>
        <item name="android:textColor">@color/dark</item>
        <item name="android:fontFamily">@font/fonr_bold</item>
    </style>

    <style name="Regular12Dark">
        <item name="android:gravity">center_horizontal</item>
        <item name="android:textSize">12sp</item>
        <item name="android:lineSpacingExtra">4sp</item>
        <item name="android:fontFamily">@font/font_regular</item>
        <item name="android:textColor">@color/grey</item>
    </style>

Is there a way to set two text styles if the range is changeable? Thank you.

A: You can make a spannable factory, override the newSpannable method and set it to the TextView. You just have to make sure you call the setText as setText(string, BufferType.SPANNABLE)
val spannableFactory = object : Spannable.Factory() {
    override fun newSpannable(source: CharSequence?): Spannable {
        val spannable = source!!.toSpannable()
        val len1 = source.split(" ")[0].length
        val len2 = source.split(" ")[1].length

        spannable.setSpan(ForegroundColorSpan(Color.RED), 0, len1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannable.setSpan(ForegroundColorSpan(Color.BLUE), len1, len1+len2+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spannable
    }
}
button.customView.tvBottom.setSpannableFactory(spannableFactory)
button.customView.tvBottom.setText("1010.2 hPa", TextView.BufferType.SPANNABLE)

A: I followed @GregotRant's answer and it worked. However, it turned out that SpannableFactory is not supported for a majority of Android devices, so I came up with another solution, inspired by the accepted answer:
private fun setUnitTextStyle(button: CustomButton) {
        val spanText = SpannableString(button.bottomText)
        val value = spanText.split(" ")[0].length
        val unit = spanText.split(" ")[1].length

        spanText.setSpan(TextAppearanceSpan(button.context, R.style. Regular12Dark),
            value, value+unit+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        button.tvBottom.setText(spanText, TextView.BufferType.SPANNABLE)
}

A: you can bold and resize a part of your string in kotlin
val s = SpannableStringBuilder()
.append("First Part Not Bold And No Resize ")
.bold { scale(1.5f, { append("Second Part By Bold And Resize " }) }
.append("Third Part Not Bold And No Resize")

yourTextview.text = s

A: This may help you..
TextView txtView = (TextView) findViewById(R.id.text);
        String number ="1024.12";
        String unit = " hPa";

        SpannableString spannableString = new SpannableString(number+unit);
        spannableString.setSpan( new BottomAlignSuperscriptSpan( (float)0.35 ), number.length(), number.length()+unit.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
        txtView.setText(spannableString);

BottomAlignSuperscriptSpan.java
import android.text.TextPaint;
import android.text.style.SuperscriptSpan;

public class BottomAlignSuperscriptSpan extends SuperscriptSpan {

    //divide superscript by this number
    protected int fontScale = 2;
    //shift value, 0 to 1.0
    protected float shiftPercentage = 0;
    //doesn't shift
    BottomAlignSuperscriptSpan() {}
    //sets the shift percentage
    BottomAlignSuperscriptSpan( float shiftPercentage ) {
        if( shiftPercentage > 0.0 && shiftPercentage < 1.0 )
            this.shiftPercentage = shiftPercentage;
    }
    @Override
    public void updateDrawState( TextPaint tp ) {
        //original ascent
        float ascent = tp.ascent();
        //scale down the font
        tp.setTextSize( tp.getTextSize() / fontScale );
        //get the new font ascent
        float newAscent = tp.getFontMetrics().ascent;
        //move baseline to top of old font, then move down size of new font
        //adjust for errors with shift percentage
//        tp.baselineShift += ( ascent - ascent * shiftPercentage )
//                - (newAscent - newAscent * shiftPercentage );
    }
    @Override
    public void updateMeasureState( TextPaint tp ) {
        updateDrawState( tp );
    }
}

A: The cleanest way in Kotlin is by using Span
val myTitleText = "1024.12hPa"

val spannable = SpannableString(myTitleText)
spannable.setSpan(
    TextAppearanceSpan(context, R.style.myFontSize),
    8, // beginning of hPa
    myTitleText.length, // end of string
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
tvMytitle.text = spannable

See my original post: https://stackoverflow.com/a/69404934/3792198


text:
Q: numpy vectorizing a function slows it down? I'm writing a program in which I'm trying to see how well a given redshift gets a set of lines detected in an spectrum to match up to an atomic line database. The closer the redshift gets the lines to overlap, the lower the "score" and the higher the chance that the redshift is correct.
I do this by looping over a range of possible redshifts, calculating the score for each. Within that outer loop, I was looping within each line in the set of detected lines to calculate its sub_score, and summing that inner loop to get the overall score.
I tried to vectorize the inner loop with numpy, but surprisingly it actually slowed down the execution. In the example given, the nested for loop takes ~2.6 seconds on my laptop to execute, while the single for loop with numpy on the inside takes ~5.3 seconds.
Why would vectorizing the inner loop slow things down? Is there a better way to do this that I'm missing?
import numpy as np
import time

def find_nearest_line(lines, energies):
    # Return the indices (from the lines vector) that are closest to the energies vector supplied
    # Vectorized with help from https://stackoverflow.com/a/53111759
    energies = np.expand_dims(energies, axis=-1)
    idx = np.abs(lines / energies - 1).argmin(axis=-1)
    return idx

def calculate_distance_to_line(lines, energies):
    # Returns distance between an array of lines and an array of energies)
    z = (lines / energies) - 1
    return z

rng = np.random.default_rng(2021)
det_lines = rng.random(1000)
atom_lines = rng.random(10000)

redshifts = np.linspace(-0.1, 0.1, 100)

# loop version
start=time.time()
scores = []
for redshift in redshifts:
    atom_lines_shifted = atom_lines * (1 + redshift)
    score = 0
    for det_line in det_lines:
        closest_atom_line = find_nearest_line(atom_lines_shifted, det_line)
        score += abs(calculate_distance_to_line(atom_lines_shifted[closest_atom_line], det_line))
    scores.append(score)
print(time.time()-start)
print(scores)

# (semi)-vectorized version
start=time.time()
scores = []
for redshift in redshifts:
    atom_lines_shifted = atom_lines * (1 + redshift)
    closest_atom_lines = find_nearest_line(atom_lines_shifted, det_lines)
    score = np.sum(np.abs(calculate_distance_to_line(atom_lines_shifted[closest_atom_lines], det_lines)))
    scores.append(score)
print(time.time()-start)
print(scores)

A: Numpy codes generally creates many temporary arrays. This is the case for your function find_nearest_line for example. Working on all the items of det_lines simultaneously would results in the creation of many relatively big arrays (1000 * 10_000 * 8 = 76 MiB per array). The thing is big array often do not fit in CPU caches. If so, the array needs to be stored in RAM with a much lower throughput and much higher latency. Moreover, allocating/freeing bigger array takes more time and results often in more page faults (due to the actual implementation of most default standard allocators). It is sometimes faster to use big array because the overhead of the CPython interpreter is huge but both strategies are inefficient in practice.
The thing is that the algorithm is not efficient. Indeed, you can sort the array and use a binary search to find the closest value much more efficiently. np.searchsorted does most of the work but it only returns the index of the closest value greater (or equal) than the target value. Thus, there is some additional operation to do to get the closest value (possibly greater or lesser than the target value). Note that this algorithm do not generate huge array thanks to the binary search.
scores = []
n = atom_lines.size
m = det_lines.size
line_idx = np.arange(m)

for redshift in redshifts:
    atom_lines_shifted = atom_lines * (1 + redshift)
    sorted_atom_lines_shifted = np.sort(atom_lines_shifted)
    close_idx = np.searchsorted(sorted_atom_lines_shifted, det_lines)
    lower_bound = sorted_atom_lines_shifted[np.maximum(close_idx - 1, 0)]
    upper_bound = sorted_atom_lines_shifted[np.minimum(close_idx, n - 1)]
    bounds = np.hstack((lower_bound[:, None], upper_bound[:, None]))
    closest_bound_idx = find_nearest_line(bounds, det_lines)
    close_values = bounds[line_idx, closest_bound_idx]
    score = np.sum(np.abs(calculate_distance_to_line(close_values, det_lines)))
    scores.append(score)

Since atom_lines is not modified and the multiplication preserve the order, the algorithm can be further optimized by sorting atom_lines directly:
scores = []
n = atom_lines.size
m = det_lines.size
line_idx = np.arange(m)
sorted_atom_lines = np.sort(atom_lines)

for redshift in redshifts:
    sorted_atom_lines_shifted = sorted_atom_lines * (1 + redshift)
    close_idx = np.searchsorted(sorted_atom_lines_shifted, det_lines)
    lower_bound = sorted_atom_lines_shifted[np.maximum(close_idx - 1, 0)]
    upper_bound = sorted_atom_lines_shifted[np.minimum(close_idx, n - 1)]
    bounds = np.hstack((lower_bound[:, None], upper_bound[:, None]))
    closest_bound_idx = find_nearest_line(bounds, det_lines)
    close_values = bounds[line_idx, closest_bound_idx]
    score = np.sum(np.abs(calculate_distance_to_line(close_values, det_lines)))
    scores.append(score)

This last implementation is about 300 times faster on my machine.