问:
Telerik Captcha control validation
I am using Telerik captcha control without textbox and now i want to validate this with my own textbox value.

my code is this

```<code><telerik:RadCaptcha ID="RadCaptcha" runat="server" EnableRefreshImage="true" CaptchaTextBoxCssClass="text"
                                                                ProtectionMode="Captcha" Display="Dynamic" ErrorMessage="Invaid Code" CaptchaImage-TextColor="Black"
                                                                CaptchaImage-RenderImageOnly="true" CaptchaImage-Width="219" CaptchaImage-TextChars="CustomCharSet"
                                                                CaptchaImage-CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
                                                                CaptchaImage-ImageCssClass="captchIMG" CaptchaImage-Height="36" CaptchaImage-BackgroundNoise="None"
                                                                CaptchaImage-LineNoise="High" />
</code>```

and a single seperate text box for validate its value

```<code><asp:TextBox ID="txtCaptcha" runat="server" CssClass="text" />
</code>```

Now on button click event i want to validate this captcha text but how???

答:
There is a demo on the Telerik site that shows how to use an external textbox to validate the captcha - http://demos.telerik.com/aspnet-ajax/captcha/examples/refreshimage/defaultcs.aspx
I think you will be able to use its code.</p>

Title: Telerik Captcha control validation

Body:
I am using Telerik captcha control without textbox and now i want to validate this with my own textbox value.

my code is this

<telerik:RadCaptcha ID="RadCaptcha" runat="server" EnableRefreshImage="true" CaptchaTextBoxCssClass="text"
                                                                ProtectionMode="Captcha" Display="Dynamic" ErrorMessage="Invaid Code" CaptchaImage-TextColor="Black"
                                                                CaptchaImage-RenderImageOnly="true" CaptchaImage-Width="219" CaptchaImage-TextChars="CustomCharSet"
                                                                CaptchaImage-CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
                                                                CaptchaImage-ImageCssClass="captchIMG" CaptchaImage-Height="36" CaptchaImage-BackgroundNoise="None"
                                                                CaptchaImage-LineNoise="High" />

and a single seperate text box for validate its value

<asp:TextBox ID="txtCaptcha" runat="server" CssClass="text" />

Now on button click event i want to validate this captcha text but how???


来源: stackexchange

问:
Whatsapp message requests without Selenium
Simple project. Send, receive or generally simplify your life by automating messages. For example, I need to send "Happy new Year!" message to certain group of people. Heck, I'll go step further and make  programmable messages: "Happy new year, {name}!" .

But there is a constraint, I can't use Selenium based api nor webhook. That'd be too easy!

My question is, is there any free tool or api in any programming language that can send, receive WhatsApp messages?

To have an idea of the project, here is a little sketch. Note: I'm not the best designer.

答:
I can suggest this one, which I made. You can send messages, files and images.

Here is the Github location: https://github.com/ammarayh89/whatsapp-web-api-using-python

ContentLicense: CC BY-SA 4.0


问:
What is the name of the this sorting method?
I am learning sorting. but I don't know what this sorting method is called.

class Solution {
    public void sort(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (nums[i] > nums[j]) {
                    swap(nums, i, j);
                }
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
```

答:
It should be bubble sort.

But you have wrong implementation.

Take a look on:

https://www.geeksforgeeks.org/bubble-sort/


问:
Symfony Form with Doctrine Class Table Inheritance (CTI)
In a previous question I ask how to handle large forms, outcome was Single Table Inheritance (STI) or CTI, Inheritance mapping. I've has chosen for CTI.

Now i'm dealing how to create the form with CTI. A quick overview what kind or relation there are.

Each inspection could have one or more surfaces. Each surface consists of many sub entities, like: surface_leakage, surface_tension or surface_slope. As you could see surface has the CTI with sub entities. Some fields overlap (put them in parent), some don't (put them in child). But in the end I need one form with all the fields grouped by surfaces then by child (maybe Bootrap collapse).

Setting up the relation was not that hard, but to use it into a form is difficult and I'm not sure how I could handle this. See below code with in code two approuches

```<code><?php
class Inspection
{
    /**
     * @OneToMany(targetEntity="App\Entity\Surface", mappedBy="inspection")
     */
    protected $surfaces;
}

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"surface" = "Surface", "surface_leagage" = "SurfaceLeakage", ...})
 */
class Surface
{
    protected $inpection;
    protected $description;
}

class SurfaceLeakage extends Surface
{
    protected $leakageLevel;
}

// .. other child classes (SurfaceTension, SurfaceSlope, ...)

class InspectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...

        $builder->add('surfaces', CollectionType::class, [
            'entry_type' => SurfaceType::class,
        ]);
    }
}

// Approach 1, where each child is added to the SurfaceType
// with this approach data should be mapped false
// This approach ensures that I only have to call SurfaceType once and all fields are loaded, but
// could not make this work with data from DB through CIT.
// Also this method does not allow me to add field description (from parent) to all childTypes
class SurfaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('leakage', SurfaceLeakageType::class, array('mapped' => false));
        $builder->add('tension', SurfaceTensionType::class, array('mapped' => false));
        //  ...
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Surface::class,
        ]);
    }
}

class SurfaceLeakageType extends AbstractType
{

}

// Approach 2, where each childFormType could extend SurfaceType, like below but how to call/create the
// form and handling the data.
// With this approuch i could parent fields to the child
class SurfaceLeakageType extends SurfaceType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('description', TextareaType::class); // field from parent or ...
        parent::buildForm($builder, $options);

        $builder->add('leakageLevel', IntegerType::class); // own field
        //  ...
    }
}
</code>```

Then there is form inherit_data

```<code>// Approach 3, inherit data, now each child should add this as a field like below,
// but how the only thing I'm doing on InspectionType build Surfaces as collection so
// i think inherit data also doesn't work
class SurfaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('description', TextareaType::class);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'inherit_data' => true,
        ]);
    }
}

class SurfaceLeakageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // inherit fields
        $builder->add('leakage', SurfaceType::class, [
            'data_class' => SurfaceLeakage::class,
        ]);

        $builder->add('leakageLevel', IntegerType::class); // own field
    }
}
</code>```

Hope someone could help me out

答:
Another option is by calling the base-type buildForm-function:</p>
```<code>class SurfaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('description', TextareaType::class);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Surface::class,
        ]);
    }
}

class SurfaceLeakageType extends AbstractType
{
    /**
    * @var SurfaceType
    */
    private $surfaceType;

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $this->surfaceType->buildForm($builder, $options);

        $builder->add('leakageLevel', IntegerType::class); // own field
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => SurfaceLeakage::class,
        ]);
    }
}
</code>```

Body:
In a previous question I ask how to handle large forms, outcome was Single Table Inheritance (STI) or CTI, Inheritance mapping. I've has chosen for CTI.

Now i'm dealing how to create the form with CTI. A quick overview what kind or relation there are.

Each inspection could have one or more surfaces. Each surface consists of many sub entities, like: surface_leakage, surface_tension or surface_slope. As you could see surface has the CTI with sub entities. Some fields overlap (put them in parent), some don't (put them in child). But in the end I need one form with all the fields grouped by surfaces then by child (maybe Bootrap collapse).

Setting up the relation was not that hard, but to use it into a form is difficult and I'm not sure how I could handle this. See below code with in code two approuches

<?php
class Inspection
{
    /**
     * @OneToMany(targetEntity="App\Entity\Surface", mappedBy="inspection")
     */
    protected $surfaces;
}

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"surface" = "Surface", "surface_leagage" = "SurfaceLeakage", ...})
 */
class Surface
{
    protected $inpection;
    protected $description;
}

class SurfaceLeakage extends Surface
{
    protected $leakageLevel;
}

// .. other child classes (SurfaceTension, SurfaceSlope, ...)

class InspectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...

        $builder->add('surfaces', CollectionType::class, [
            'entry_type' => SurfaceType::class,
        ]);
    }
}

// Approach 1, where each child is added to the SurfaceType
// with this approach data should be mapped false
// This approach ensures that I only have to call SurfaceType once and all fields are loaded, but
// could not make this work with data from DB through CIT.
// Also this method does not allow me to add field description (from parent) to all childTypes
class SurfaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('leakage', SurfaceLeakageType::class, array('mapped' => false));
        $builder->add('tension', SurfaceTensionType::class, array('mapped' => false));
        //  ...
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Surface::class,
        ]);
    }
}

class SurfaceLeakageType extends AbstractType
{

}

// Approach 2, where each childFormType could extend SurfaceType, like below but how to call/create the
// form and handling the data.
// With this approuch i could parent fields to the child
class SurfaceLeakageType extends SurfaceType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('description', TextareaType::class); // field from parent or ...
        parent::buildForm($builder, $options);

        $builder->add('leakageLevel', IntegerType::class); // own field
        //  ...
    }
}

Then there is form inherit_data

// Approach 3, inherit data, now each child should add this as a field like below,
// but how the only thing I'm doing on InspectionType build Surfaces as collection so
// i think inherit data also doesn't work
class SurfaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('description', TextareaType::class);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'inherit_data' => true,
        ]);
    }
}

class SurfaceLeakageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // inherit fields
        $builder->add('leakage', SurfaceType::class, [
            'data_class' => SurfaceLeakage::class,
        ]);

        $builder->add('leakageLevel', IntegerType::class); // own field
    }
}

Hope someone could help me out

Body:
Another option is by calling the base-type buildForm-function:

class SurfaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('description', TextareaType::class);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Surface::class,
        ]);
    }
}

class SurfaceLeakageType extends AbstractType
{
    /**
    * @var SurfaceType
    */
    private $surfaceType;

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $this->surfaceType->buildForm($builder, $options);

        $builder->add('leakageLevel', IntegerType::class); // own field
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => SurfaceLeakage::class,
        ]);
    }
}


问:
HaxeDevelop Problem "Binary stream '0' does not contain a valid BinaryHeader"
I'm currently new in Haxe, when i open up HaxeDevelop software it shows this error code:

Binary stream '0' does not contain a valid BinaryHeader. Possible
causes are invalid stream or object version change between
serialization and deserialization.

at
System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()

at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler
handler, __BinaryParser serParser, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage)    at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream, HeaderHandler handler, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage)    at
PluginCore.Utilities.ObjectSerializer.InternalDeserialize(String file,
Type type)    at
PluginCore.Utilities.ObjectSerializer.Deserialize(String file, Object
obj, Boolean checkValidity)

Can someone help me?

Here's the Window Image

I also did trying reinstalling it several times, it does not work.

答: What version you're using? Try to download dev version of HaxeDevelop or FlashDevelop (it should work same)</p>


问:
Redirect to old page at logout in PHP
I am developing a CMS. I have three scripts, and 2 session variables

```<code> $_SESSION['logged']
 $_SESSION['redirect']
</code>```

"auth.inc.php" - Run every time a user requests a page. It checks if $_SESSION['logged'] is set and equal to 1. If it isn't redirects ti main page using

```<code>header(location:index.php)
</code>```

and the page referrer link is saved in $_SESSION['redirect']. If $_SESSION['logged'] is set  inactivity time is less than a required value it redirects to the requested page other wise it redirects to logout.php

"index.php" - checks for user name and password. I successful sets

```<code>$_SESSION['logged']=1
</code>```

If  $_SESSION['redirect'] is set it redirects to that page otherwise to deafult page

"logout.php" - Its unsets and destroys the session using

```<code>session_unset();
session_destroy();
</code>```

But I want if user is logged out due to session timeout then after login it should be redirected to old page. Since I was unsetting the session  $_SESSION['redirect'] was lost. So instead of using  session_unset() I only unset $_SESSION['logged']

```<code>unset($_SESSION['logged']);
session_destroy();
</code>```

but still I am not able to retrieve $_SESSION['redirect'] after session_destroy(). The variable is still not set. How should I redirect to old page after logout due to session expire

答:
session_destroy() will, in fact, destroy the data for the current session. To use any value you set, you have to session_start() again.

Furthermore, if the session expires, nothing you have set as a session cookie will be valid.

The best thing you could do is to save your last page or whatever in the database, since you said the users can log in. Then fetch that value upon login, and redirect to it.

Good luck!

ContentLicense: CC BY-SA 3.0

Title: Redirect to old page at logout in PHP

Body:
I am developing a CMS. I have three scripts, and 2 session variables

 $_SESSION['logged']
 $_SESSION['redirect']

"auth.inc.php" - Run every time a user requests a page. It checks if $_SESSION['logged'] is set and equal to 1. If it isn't redirects ti main page using

header(location:index.php)

and the page referrer link is saved in $_SESSION['redirect']. If $_SESSION['logged'] is set  inactivity time is less than a required value it redirects to the requested page other wise it redirects to logout.php

"index.php" - checks for user name and password. I successful sets

$_SESSION['logged']=1

If  $_SESSION['redirect'] is set it redirects to that page otherwise to deafult page

"logout.php" - Its unsets and destroys the session using

session_unset();
session_destroy();

But I want if user is logged out due to session timeout then after login it should be redirected to old page. Since I was unsetting the session  $_SESSION['redirect'] was lost. So instead of using  session_unset() I only unset $_SESSION['logged']

unset($_SESSION['logged']);
session_destroy();

but still I am not able to retrieve $_SESSION['redirect'] after session_destroy(). The variable is still not set. How should I redirect to old page after logout due to session expire


问:
How to elegantly represent finite Haskell recursive datastructure in Python?
Let's have some finite recursive datastructure in Haskell. Eg.

```<code>data Tree = Node Tree Tree | Nil
</code>```

I need to be able to load such datastructure from Haskell to Python, change it and return it back to Haskell.

Is there some standard/elegant way how to do it without much pain? Eg. using some directory like objects?

答:
The easiest option is probably to go via JSON, because Haskell has easy support for saving data as JSON and Python can directly load it as dicts.

```<code>{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}

import GHC.Generics

import Data.Aeson
import Data.Aeson.TH

data Tree = Node Tree Tree | Nil
 deriving (Generic, FromJSON, ToJSON)
</code>```

This generates rather awkward JSON though, like, Node (Node Nil Nil) Nil becomes

```<code>        "tag": "Node",
        "contents": [
            {
                "tag": "Node",
                "contents": [
                    {
                        "tag": "Nil"
                    },
                    {
                        "tag": "Nil"
                    }
                ]
            },
            {
                "tag": "Nil"
            }
        ]
</code>```

It gets much more compact with

```<code>data TreeNode = Node { lSubtree, rSubtree :: Tree }
 deriving (Generic, FromJSON, ToJSON)

type Tree = Maybe TreeNode
</code>```

where the equivalent Node (Just (Node Nothing Nothing)) Nothing is now saved as

```<code>        {
            "rSubtree": null,
            "lSubtree": {
                "rSubtree": null,
                "lSubtree": null
            }
        }
</code>```

Body:
Let's have some finite recursive datastructure in Haskell. Eg.

data Tree = Node Tree Tree | Nil

I need to be able to load such datastructure from Haskell to Python, change it and return it back to Haskell.

Is there some standard/elegant way how to do it without much pain? Eg. using some directory like objects?

Body:
The easiest option is probably to go via JSON, because Haskell has easy support for saving data as JSON and Python can directly load it as dicts.

{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}

import GHC.Generics

import Data.Aeson
import Data.Aeson.TH

data Tree = Node Tree Tree | Nil
 deriving (Generic, FromJSON, ToJSON)

This generates rather awkward JSON though, like, Node (Node Nil Nil) Nil becomes

        "tag": "Node",
        "contents": [
            {
                "tag": "Node",
                "contents": [
                    {
                        "tag": "Nil"
                    },
                    {
                        "tag": "Nil"
                    }
                ]
            },
            {
                "tag": "Nil"
            }
        ]

It gets much more compact with

data TreeNode = Node { lSubtree, rSubtree :: Tree }
 deriving (Generic, FromJSON, ToJSON)

type Tree = Maybe TreeNode

where the equivalent Node (Just (Node Nothing Nothing)) Nothing is now saved as

        {
            "rSubtree": null,
            "lSubtree": {
                "rSubtree": null,
                "lSubtree": null
            }
        }


问:
Get the full path of file name which is numbers only `highest number` , on main Folder or Subfolders?
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

```<code>Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub
</code>```

答:
Please try the next function. It will return independent of the number name pattern. I mean, being "0002345" or "02346", It processes all files from folder and subfolders:

```<code>Function getLastFileName(strFold As String, Optional strext As String = "*.*") As String
    Dim arrD, i As Long, lastName As String, lngNb As Long, arrN, El
    'return all files name in an array
    arrD = Filter(Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b /s").StdOut.ReadAll, vbCrLf), "\")
    For Each El In arrD   'iterate between the array elements
            arrN = Split(El, "\") 'make an array splitting the name by "\"
            'check if the name is numeric:
            If IsNumeric(Split(arrN(UBound(arrN)), ".")(0)) Then
                'compare the lngNb variable (initially 0) with the numeric value:
                If lngNb < CLng(Split(arrN(UBound(arrN)), ".")(0)) Then
                     'addapt lngNb like the bigger number
                     lngNb = CLng(Split(arrN(UBound(arrN)), ".")(0)): lastName = El
                End If
            End If
    Next
    getLastFileName = lastName 'build the necessary path
End Function
</code>```

It can be tested in the next way:

```<code>Sub testGetLastFileName()
    Debug.Print getLastFileName("D:\Users\Waleed\Desktop\", "*.xls*")
End Sub
</code>```

It excludes workbooks name not being a number...

Edited:

The next version returns (and process) only the files in the main folder (excluding files in subfolders):

```<code>Function getLastNumberFile(strFold As String, Optional strext As String = "*.*") As String
    Dim arrD, i As Long, lastName As String, lngNb As Long, El
    'return all files name in an array
    arrD = Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b").StdOut.ReadAll, vbCrLf)
    If UBound(arrD) = -1 Then MsgBox "Nothing could be found in the path you supplied...": Exit Function
    arrD(UBound(arrD)) = "@@##": arrD = Filter(arrD, "@@##", False) 'remove the last (empty) element

    For Each El In arrD   'iterate between the array elements
            If IsNumeric(Split(El, ".")(0)) Then
                'compare the lngNb variable (initially 0) with the numeric value:
                If lngNb < CLng(Split(El, ".")(0)) Then
                     'addapt lngNb like the bigger number
                     lngNb = CLng(Split(El, ".")(0)): lastName = El
                End If
            End If
    Next
    getLastNumberFile = strFold & lastName 'build the necessary path
End Function
</code>```

It can be used simple setting the necessary workbook as:

```<code>  Set wb1 = Workbooks.Open(getLastNumberFile("D:\Users\Waleed\Desktop\", "*.xls*"))
</code>```

And the next version, able to return for both cases. It uses a trick, splitting a joined array using the separator obtained by concatenation between the folder path and "|". Then removing the last array element (in case of returning without subfolders files):

```<code>Function getLastFileN(strFold As String, Optional strext As String = "*.*", Optional boolSubfolders = False) As String
    Dim arrD, i As Long, lastName As String, lngNb As Long, arrN, El
    'return all files name in an array
    If boolSubfolders Then 'subfolders included
        arrD = Filter(Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b/s").StdOut.ReadAll, vbCrLf), "\")
    Else                   'without subfolders
        arrD = Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b").StdOut.ReadAll, vbCrLf)
        arrD = Split(strFold & Join(arrD, "|" & strFold), "|")  'add the folder path to the file names
        arrD(UBound(arrD)) = "@@##": arrD = Filter(arrD, "@@##", False) 'remove the last (empty) array element
    End If

    For Each El In arrD           'iterate between the array elements
            arrN = Split(El, "\") 'make an array splitting the name by "\"
            'check if the name is numeric:
            If IsNumeric(Split(arrN(UBound(arrN)), ".")(0)) Then
                'compare the lngNb variable (initially 0) with the numeric value:
                If lngNb < CLng(Split(arrN(UBound(arrN)), ".")(0)) Then
                     'addapt lngNb like the bigger number
                     lngNb = CLng(Split(arrN(UBound(arrN)), ".")(0)): lastName = El
                End If
            End If
    Next
    getLastFileN = lastName
End Function
</code>```

Body:
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub

Body:
Please try the next function. It will return independent of the number name pattern. I mean, being "0002345" or "02346", It processes all files from folder and subfolders:

Function getLastFileName(strFold As String, Optional strext As String = "*.*") As String
    Dim arrD, i As Long, lastName As String, lngNb As Long, arrN, El
    'return all files name in an array
    arrD = Filter(Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b /s").StdOut.ReadAll, vbCrLf), "\")
    For Each El In arrD   'iterate between the array elements
            arrN = Split(El, "\") 'make an array splitting the name by "\"
            'check if the name is numeric:
            If IsNumeric(Split(arrN(UBound(arrN)), ".")(0)) Then
                'compare the lngNb variable (initially 0) with the numeric value:
                If lngNb < CLng(Split(arrN(UBound(arrN)), ".")(0)) Then
                     'addapt lngNb like the bigger number
                     lngNb = CLng(Split(arrN(UBound(arrN)), ".")(0)): lastName = El
                End If
            End If
    Next
    getLastFileName = lastName 'build the necessary path
End Function

It can be tested in the next way:

Sub testGetLastFileName()
    Debug.Print getLastFileName("D:\Users\Waleed\Desktop\", "*.xls*")
End Sub

It excludes workbooks name not being a number...

Edited:

The next version returns (and process) only the files in the main folder (excluding files in subfolders):

Function getLastNumberFile(strFold As String, Optional strext As String = "*.*") As String
    Dim arrD, i As Long, lastName As String, lngNb As Long, El
    'return all files name in an array
    arrD = Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b").StdOut.ReadAll, vbCrLf)
    If UBound(arrD) = -1 Then MsgBox "Nothing could be found in the path you supplied...": Exit Function
    arrD(UBound(arrD)) = "@@##": arrD = Filter(arrD, "@@##", False) 'remove the last (empty) element

    For Each El In arrD   'iterate between the array elements
            If IsNumeric(Split(El, ".")(0)) Then
                'compare the lngNb variable (initially 0) with the numeric value:
                If lngNb < CLng(Split(El, ".")(0)) Then
                     'addapt lngNb like the bigger number
                     lngNb = CLng(Split(El, ".")(0)): lastName = El
                End If
            End If
    Next
    getLastNumberFile = strFold & lastName 'build the necessary path
End Function

It can be used simple setting the necessary workbook as:

  Set wb1 = Workbooks.Open(getLastNumberFile("D:\Users\Waleed\Desktop\", "*.xls*"))

And the next version, able to return for both cases. It uses a trick, splitting a joined array using the separator obtained by concatenation between the folder path and "|". Then removing the last array element (in case of returning without subfolders files):

Function getLastFileN(strFold As String, Optional strext As String = "*.*", Optional boolSubfolders = False) As String
    Dim arrD, i As Long, lastName As String, lngNb As Long, arrN, El
    'return all files name in an array
    If boolSubfolders Then 'subfolders included
        arrD = Filter(Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b/s").StdOut.ReadAll, vbCrLf), "\")
    Else                   'without subfolders
        arrD = Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b").StdOut.ReadAll, vbCrLf)
        arrD = Split(strFold & Join(arrD, "|" & strFold), "|")  'add the folder path to the file names
        arrD(UBound(arrD)) = "@@##": arrD = Filter(arrD, "@@##", False) 'remove the last (empty) array element
    End If

    For Each El In arrD           'iterate between the array elements
            arrN = Split(El, "\") 'make an array splitting the name by "\"
            'check if the name is numeric:
            If IsNumeric(Split(arrN(UBound(arrN)), ".")(0)) Then
                'compare the lngNb variable (initially 0) with the numeric value:
                If lngNb < CLng(Split(arrN(UBound(arrN)), ".")(0)) Then
                     'addapt lngNb like the bigger number
                     lngNb = CLng(Split(arrN(UBound(arrN)), ".")(0)): lastName = El
                End If
            End If
    Next
    getLastFileN = lastName
End Function


问:
What is the difference between Live IP and STATIC IP?
I came across the terms LIVE IP and STATIC IP and did research on them but couldn't find useful info about the differences between them.

Can anyone please explain the difference to me?

答:
A static IP is one that will never change. A dynamic IP is exactly that, dynamic(live ip). It could change frequently, or not change for more than 1 year. It really depends on how the DHCP server that’s assigns the IPs is set up.

Read more: here

here is the another link
http://btbusiness.custhelp.com/app/answers/detail/a_id/134/~/what-is-the-difference-between-a-static-and-a-dynamic-ip-address%3F


问:
R - loop even for variable
How to use this command in R for a range of numbers?

```<code>PR01 <- Pra_Ruz[grep("-01-", Pra_Ruz$Date), ]
</code>```

I mean

```<code>PR01 <- Pra_Ruz[grep("-01-", Pra_Ruz$Date), ]
PR02 <- Pra_Ruz[grep("-02-", Pra_Ruz$Date), ]
PR03 <- Pra_Ruz[grep("-03-", Pra_Ruz$Date), ]
PR04 <- Pra_Ruz[grep("-04-", Pra_Ruz$Date), ]
....
</code>```

答:
It is easier to help if you provide data in a reproducible format with expected output.

Consider this as your data -

```<code>Pra_Ruz <- data.frame(Date = as.Date(c('2012-01-31', '2020-12-28',
        '2015-10-11', '2014-04-16', '2016-03-22')), a = 1:5)

Pra_Ruz
#        Date a
#1 2012-01-31 1
#2 2020-12-28 2
#3 2015-10-11 3
#4 2014-04-16 4
#5 2016-03-22 5
</code>```

You can specify the range in regex using [1-4]

```<code>Pra_Ruz[grep("-0[1-4]-", Pra_Ruz$Date), ]

#        Date a
#1 2012-01-31 1
#4 2014-04-16 4
#5 2016-03-22 5
</code>```

Another option -

If these are date objects you can extract the month value from it and then subset.

```<code>Pra_Ruz[as.integer(format(Pra_Ruz$Date, '%m')) %in% 1:4, ]
</code>```

If you want to split the datasets in multiple individual dataframes

```<code>data <- split(Pra_Ruz, format(Pra_Ruz$Date, '%m'))
names(data) <- paste0('PR', names(data))
list2env(data, .GlobalEnv) #Not recommended, do only if necessary.
</code>```

Title: R - loop even for variable

Body:
How to use this command in R for a range of numbers?

PR01 <- Pra_Ruz[grep("-01-", Pra_Ruz$Date), ]

I mean

PR01 <- Pra_Ruz[grep("-01-", Pra_Ruz$Date), ]
PR02 <- Pra_Ruz[grep("-02-", Pra_Ruz$Date), ]
PR03 <- Pra_Ruz[grep("-03-", Pra_Ruz$Date), ]
PR04 <- Pra_Ruz[grep("-04-", Pra_Ruz$Date), ]
....

Body:
It is easier to help if you provide data in a reproducible format with expected output.

Consider this as your data -

Pra_Ruz <- data.frame(Date = as.Date(c('2012-01-31', '2020-12-28',
        '2015-10-11', '2014-04-16', '2016-03-22')), a = 1:5)

Pra_Ruz
#        Date a
#1 2012-01-31 1
#2 2020-12-28 2
#3 2015-10-11 3
#4 2014-04-16 4
#5 2016-03-22 5

You can specify the range in regex using [1-4]

Pra_Ruz[grep("-0[1-4]-", Pra_Ruz$Date), ]

#        Date a
#1 2012-01-31 1
#4 2014-04-16 4
#5 2016-03-22 5

Another option -

If these are date objects you can extract the month value from it and then subset.

Pra_Ruz[as.integer(format(Pra_Ruz$Date, '%m')) %in% 1:4, ]

If you want to split the datasets in multiple individual dataframes

data <- split(Pra_Ruz, format(Pra_Ruz$Date, '%m'))
names(data) <- paste0('PR', names(data))
list2env(data, .GlobalEnv) #Not recommended, do only if necessary.


问:
Excel formula where certain combinations of cells would return a value
I'm creating a stakeholder map and I have two columns with two possible entries for each

```<code>Power | Interest | Strategy
</code>```

Power and Interest can be either High or Low

So I am trying to get a strategy to return a value based on whether Power or Interest is one of those two combinations as an example:

```<code>Power = High, Interest = High, Strategy = Manage Closely
Power = Low, Interest = High, Strategy = Keep Informed
Power = Low, Interest = Low, Strategy = Monitor
Power = High, Interest = Low, Strategy = Meet Their Needs
</code>```

Can someone help me with this formula?

答:
So, a long way is to use if() with AND() like so:

```<code>IF(AND(B1="high",D1="High"),"Manage closely",IF(AND(B1="Low",D1="High"),"Keep informed",IF(AND(B1="Low",D1="Low"),"Monitor",IF(AND(B1="high",D1="Low"),"Meet their needs"))))
</code>```

But a table with vlookup() is easier to control as per the other answer. However, this does not use a helper column...

Body:
I'm creating a stakeholder map and I have two columns with two possible entries for each

Power | Interest | Strategy

Power and Interest can be either High or Low

So I am trying to get a strategy to return a value based on whether Power or Interest is one of those two combinations as an example:

Power = High, Interest = High, Strategy = Manage Closely
Power = Low, Interest = High, Strategy = Keep Informed
Power = Low, Interest = Low, Strategy = Monitor
Power = High, Interest = Low, Strategy = Meet Their Needs

Can someone help me with this formula?

Body:
So, a long way is to use if() with AND() like so:

IF(AND(B1="high",D1="High"),"Manage closely",IF(AND(B1="Low",D1="High"),"Keep informed",IF(AND(B1="Low",D1="Low"),"Monitor",IF(AND(B1="high",D1="Low"),"Meet their needs"))))

But a table with vlookup() is easier to control as per the other answer. However, this does not use a helper column...


问:
running Powershell in batch file failed because of special character "|"
I recently started to some scripts in batch file to do some works but I failed when I tried to get some results from PowerShell then process it.

```<code>@echo off
setlocal

set "ps= $FindProcess = Get-Process | Where-Object {$_.MainWindowTitle -like 'VNC viewer'};"
set "ps=%ps% $title = $FindProcess.MainWindowTitle ^| Measure-Object -Line;"
set "ps=%ps% $title.Lines"

echo %ps%
for /f "delims=" %%I in ('powershell "%ps%"') do set "title=%%I"
:: For debugging and get the result
:: for /f "delims=" %%I in ('powershell "%ps%"') do echo %%I

echo %title% number of apps have "VNC viewer" title
</code>```

but when run it i throw 'Where-Object' is not recognized as an internal or external command, operable program or batch file. and when put ^ before | it result empty %title% and when uncommenting the debug section I shows this error

```<code> $FindProcess = Get-Process | Where-Object {$_.MainWindowTitle -like 'VNC viewer'}; $title = $FindProcess.MainWindowTitle | Measure-Object -Line; $title.Lines
At line:1 char:124
+ ...  -like 'VNC viewer'}; $title = $FindProcess.MainWindowTitle ^| Measur ...
+                                                                 ~
Unexpected token '^' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
ECHO is off.
 number of apps have "VNC viewer" title
</code>```

答:
I find out removing echo %ps% and do not putting ^ before | makes it work successfully but still don't know why echo it throws error!

Edited:
After reading aschipfl comment I finally understood why. Actually echo %ps% will be parse to echo what-was-in-the-variable-which-in-this-case-has-|-character and this command also won't work without double quotation :) thank you

Body:
I recently started to some scripts in batch file to do some works but I failed when I tried to get some results from PowerShell then process it.

@echo off
setlocal

set "ps= $FindProcess = Get-Process | Where-Object {$_.MainWindowTitle -like 'VNC viewer'};"
set "ps=%ps% $title = $FindProcess.MainWindowTitle ^| Measure-Object -Line;"
set "ps=%ps% $title.Lines"

echo %ps%
for /f "delims=" %%I in ('powershell "%ps%"') do set "title=%%I"
:: For debugging and get the result
:: for /f "delims=" %%I in ('powershell "%ps%"') do echo %%I

echo %title% number of apps have "VNC viewer" title

but when run it i throw 'Where-Object' is not recognized as an internal or external command, operable program or batch file. and when put ^ before | it result empty %title% and when uncommenting the debug section I shows this error

 $FindProcess = Get-Process | Where-Object {$_.MainWindowTitle -like 'VNC viewer'}; $title = $FindProcess.MainWindowTitle | Measure-Object -Line; $title.Lines
At line:1 char:124
+ ...  -like 'VNC viewer'}; $title = $FindProcess.MainWindowTitle ^| Measur ...
+                                                                 ~
Unexpected token '^' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
ECHO is off.
 number of apps have "VNC viewer" title


问:
I want to add many object inside a nested array of object with a specific key in javascript
I want to add one or many objects inside an array of object which a specific key whose structure has been shown below.

Help would be appreciated

structure:

```<code>{
  "nameEn": "string",
  "nameFr": "string",
  "descriptionFr": "string",
  "descriptionEn": "string",
  "code": "string",
  "permissions": [
    {
      "endUI": "string"
    },
    {
      "endUI": "string"
    }
  ]
}
</code>```

here is what I did but it gives me something else:

```<code>let data = {
          nameEn: this.dataForm.nameEn,
          nameFr: this.dataForm.nameFr,
          descriptionFr: this.dataForm.descriptionFr,
          descriptionEn: this.dataForm.descriptionEn,
          code: this.dataForm.code,
          permissions:  [
            {
              "endUI": this.dataForm.endUI
            }
          ]
        }
</code>```

And this is the result:

答:
it seems like this.dataForm.endUI is a list so
you probably want to map it like this:</p>
```<code>permissions:  this.dataForm.endUI.map((elm) => {return {endUI: elm}})
</code>```

Body:
I want to add one or many objects inside an array of object which a specific key whose structure has been shown below.

Help would be appreciated

structure:

{
  "nameEn": "string",
  "nameFr": "string",
  "descriptionFr": "string",
  "descriptionEn": "string",
  "code": "string",
  "permissions": [
    {
      "endUI": "string"
    },
    {
      "endUI": "string"
    }
  ]
}

here is what I did but it gives me something else:

let data = {
          nameEn: this.dataForm.nameEn,
          nameFr: this.dataForm.nameFr,
          descriptionFr: this.dataForm.descriptionFr,
          descriptionEn: this.dataForm.descriptionEn,
          code: this.dataForm.code,
          permissions:  [
            {
              "endUI": this.dataForm.endUI
            }
          ]
        }

And this is the result:

Body:
it seems like this.dataForm.endUI is a list so
you probably want to map it like this:

permissions:  this.dataForm.endUI.map((elm) => {return {endUI: elm}})


问:
Flutter-How to change the Statusbar text color in Dark Mode?
I hope to control the statusbar text color in iOS 13 Dark Mode. I could change the statusbar color by setting the Scaffold's AppBar property "brightness" When not open the Dark Mode.
Codes just like below:

```<code>return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,  //<--Here!!!
        title: Text(widget.title),
      ),
...
</code>```

The effort just like this:

light brightness:

dark brightness:

But when I enable the simulator's Dark Mode, the method is not working.
Open the simulator's "Dark Appearance":

After opening the "Dark Appearance", the statusbar text color couldn't change any more by the method, it's just in white color(lightness mode).

I have tried those method to change statusbar text color:

Method 1:

```<code>void main() {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  runApp(MyApp());
}
</code>```

Method 2:

```<code>return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: Material(
        child: Scaffold(
          appBar: AppBar(
            brightness: Brightness.light,
            title: Text(widget.title),
          ),
          body: Center(
</code>```

But neither of them could work.

Hope your help! Thank you.

答:
In my case I wanted a dark font in my status bar on my light themed app. The problem is that my app bar's background color is transparent so the status bar default font color is white (I tried setting the app bars color to white and voilà - the status bar text font was black).
Since I wanted to keep my transparent status bar, my solution was to add systemOverlayStyle to my theme's appBarTheme like this.:

```<code> AppBarTheme(
        systemOverlayStyle: SystemUiOverlayStyle(
          statusBarBrightness: Brightness.light,
        ),
</code>```

The app_bar_theme.dart file told me this solution in the brightness' deprecation notes:

@Deprecated(
'This property is no longer used, please use systemOverlayStyle instead. '
'This feature was deprecated after v2.4.0-0.0.pre.',
)
this.brightness,

Body:
I hope to control the statusbar text color in iOS 13 Dark Mode. I could change the statusbar color by setting the Scaffold's AppBar property "brightness" When not open the Dark Mode.
Codes just like below:

return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,  //<--Here!!!
        title: Text(widget.title),
      ),
...

The effort just like this:

light brightness:

dark brightness:

But when I enable the simulator's Dark Mode, the method is not working.
Open the simulator's "Dark Appearance":

After opening the "Dark Appearance", the statusbar text color couldn't change any more by the method, it's just in white color(lightness mode).

I have tried those method to change statusbar text color:

Method 1:

void main() {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  runApp(MyApp());
}

Method 2:

return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: Material(
        child: Scaffold(
          appBar: AppBar(
            brightness: Brightness.light,
            title: Text(widget.title),
          ),
          body: Center(

But neither of them could work.

Hope your help! Thank you.

Body:
In my case I wanted a dark font in my status bar on my light themed app. The problem is that my app bar's background color is transparent so the status bar default font color is white (I tried setting the app bars color to white and voilà - the status bar text font was black).
Since I wanted to keep my transparent status bar, my solution was to add systemOverlayStyle to my theme's appBarTheme like this.:

 AppBarTheme(
        systemOverlayStyle: SystemUiOverlayStyle(
          statusBarBrightness: Brightness.light,
        ),

The app_bar_theme.dart file told me this solution in the brightness' deprecation notes:

@Deprecated(
'This property is no longer used, please use systemOverlayStyle instead. '
'This feature was deprecated after v2.4.0-0.0.pre.',
)
this.brightness,


问:
Making a Grid pixel editor in iPad
I need to make a pixel editor in iPad similar like Microsoft Paint when displaying per pixel of the image, would like some advise on approach :

Should I make a series of UIButtons stacked in grid fashion in a UIScrollView? (sounds pretty resourceful and laggy), tapping the uibutton will toggle state to display the pixel.

Should I draw line grids using coregraphic and detect taps using gesturerecognizer (I like this, but need some code samples).

Or should I look into using UITableView and making use of reusable cells for the editor? (This seems like how apple would advise).

Hope to get some interesting responses!

答:
A custom-drawn view (i. e. Core Graphics) is the only reasonable approach. Anything using multiple views will lag with larger images, no matter if it's UIButtons or UITableViewCells.

For a general Core Graphics introduction, try the official one or that one.

To draw your fat pixels with a grid, you could either fill the entire canvas with the grid colour, then fill the fat pixels with the respective colour using UIRectFill() taking into account the proper grid spacing. Or you could draw the grid lines with -[UIBezierPath stroke] and a bezier path that encloses the fat pixel.

Also, for performance reasons you will probably want to respect the dirty rect passed to -[UIView drawRect:] so as to not draw regions that don’t need to be redrawn.

Title: Making a Grid pixel editor in iPad


问:
Django : Invalid block tag on line 121: 'popular_products', expected 'endblock'. Did you forget to register or load this tag?
I have a custom template tag in my project and every thing looks fine but when i want to use this template tag i got this error:

Invalid block tag on line 122: 'popular_products', expected 'endblock'. Did you forget to register or load this tag?

base_tags.py:

```<code>from django import template
from django.db.models import Count, Q
from datetime import datetime, timedelta
from shop.models import Product

register = template.Library()

@register.inclusion_tag('shared/partials/popular_product_slider.html')
def popular_products():
    last_week = datetime.today() - timedelta(days=7)
    return {
        "popular_products": Product.objects.filter(available=True).annotate(
            count=Count('hits', filter=Q(producthit__date__gt=last_week))).order_by(
            '-count', '-created')[:3]
    }
</code>```

home_page.html template:

```<code> {% extends 'shared/_base.html' %}
 {% load base_tags %}
 {% load i18n %}
 {% load render_partial %}
 {% load static %}
 {% load ratings %}
 {% load thumbnail %}

 {% block content %}
    <div class="row">
      <div class="col-lg-12">
         <div class="tab-content">
            <div id="recent" class="tab-pane fade show active">
                <div class="row  product-slider">
                        {% popular_products %}
                </div>
            </div>
       </div>
  </div>
 </div>
{% endblock %}
</code>```

popular_product_slider.html

```<code>{% for product in popular_products %}
    {{product.image}}
    {{product.detail}}
    {{product.title}}
{% endfor %}

</code>```

views.py

```<code>def home_page(request):
    context = {}
    return render(request, 'Home_page.html', context)

</code>```

答:
you need to place your code in home_page.html in block. xxx is the name of block that you placed in _base.html</p>
```<code>{% block xxx %}
   <div class="row">
       <div class="col-lg-12">
           <div class="tab-content">
               <div id="recent" class="tab-pane fade show active">
                   <div class="row  product-slider">
                        {% popular_products %}
                   </div>
               </div>
          </div>
      </div>
   </div>
{% endblock %}
</code>```

Body:
I have a custom template tag in my project and every thing looks fine but when i want to use this template tag i got this error:

Invalid block tag on line 122: 'popular_products', expected 'endblock'. Did you forget to register or load this tag?

base_tags.py:

from django import template
from django.db.models import Count, Q
from datetime import datetime, timedelta
from shop.models import Product

register = template.Library()

@register.inclusion_tag('shared/partials/popular_product_slider.html')
def popular_products():
    last_week = datetime.today() - timedelta(days=7)
    return {
        "popular_products": Product.objects.filter(available=True).annotate(
            count=Count('hits', filter=Q(producthit__date__gt=last_week))).order_by(
            '-count', '-created')[:3]
    }

home_page.html template:

 {% extends 'shared/_base.html' %}
 {% load base_tags %}
 {% load i18n %}
 {% load render_partial %}
 {% load static %}
 {% load ratings %}
 {% load thumbnail %}

 {% block content %}

                        {% popular_products %}

{% endblock %}

popular_product_slider.html

{% for product in popular_products %}
    {{product.image}}
    {{product.detail}}
    {{product.title}}
{% endfor %}

views.py

def home_page(request):
    context = {}
    return render(request, 'Home_page.html', context)

Body:
you need to place your code in home_page.html in block. xxx is the name of block that you placed in _base.html

{% block xxx %}
   <div class="row">
       <div class="col-lg-12">
           <div class="tab-content">
               <div id="recent" class="tab-pane fade show active">
                   <div class="row  product-slider">
                        {% popular_products %}
                   </div>
               </div>
          </div>
      </div>
   </div>
{% endblock %}


问:
perform calculation on column of a dataframe using data from another dataframe
I have two dataframes, one called order_values & the other fx_rates. They look like below.

What I need to do is convert the value_loc value in the order_values dataframe into EUR's using the fx_rates dataframe.

In reality I won't know how many different currency there are & its likely to be more than shown below.

My current solution I believe is far from optimal. I loop through each different currency (i.e. USD, JPY etc) and merge that currency column (EURUSD, EURJPY) to the order_values dataframe & perform the calculation to convert the value_loc into value_eur & then drop the currency column from the order_values dataframe.

```<code>  order_values
  order_num   value_loc  currency   date
  1           2,345      USD        2-12-2021
  2           104        EUR        2-12-2021
  3           20,000     JPY        2-15-2021
  4           550        USD        3-06-2021

  fx_rates
  date       pair    rate
  2-12-2021  EURUSD  1.5
  2-12-2021  EURJPY  5
  2-12-2021  EUREUR  1
  ...
  3-06-2021  EURUSD  1.56
  3-06-2021  EURJPY  5.6
  3-06-2021  EUREUR  1
</code>```

答:
I tried to reproduce the data you presented in the question.

you can find my solution below using 'pandas.Series.str'1

```<code>import pandas as pd
fx_rates = pd.DataFrame({'date':['2-12-2021','2-12-2021','2-12-2021','3-06-2021','3-06-2021','3-06-2021'],
                         'pair':['EURUSD','EURJPY','EUREUR','EURUSD','EURJPY','EUREUR'],'rate':[1.5,5,1,1.56,5.6,1]})
order_values=pd.DataFrame({'order_num':[1,2,3,4],'value_loc':[2345,104,2000,550],  'currency':['USD','EUR','JPY','USD'],
                           'date':['2-12-2021','2-12-2021','2-15-2021','3-06-2021']})

fx_rates['pair_split']=fx_rates['pair'].str.split('EUR',expand=True)[1].replace('','EUR')
df=pd.merge(order_values,fx_rates,right_on=['date','pair_split'],left_on=['date','currency'],how='inner')
</code>```

Body:
I have two dataframes, one called order_values & the other fx_rates. They look like below.

What I need to do is convert the value_loc value in the order_values dataframe into EUR's using the fx_rates dataframe.

In reality I won't know how many different currency there are & its likely to be more than shown below.

My current solution I believe is far from optimal. I loop through each different currency (i.e. USD, JPY etc) and merge that currency column (EURUSD, EURJPY) to the order_values dataframe & perform the calculation to convert the value_loc into value_eur & then drop the currency column from the order_values dataframe.

  order_values
  order_num   value_loc  currency   date
  1           2,345      USD        2-12-2021
  2           104        EUR        2-12-2021
  3           20,000     JPY        2-15-2021
  4           550        USD        3-06-2021

  fx_rates
  date       pair    rate
  2-12-2021  EURUSD  1.5
  2-12-2021  EURJPY  5
  2-12-2021  EUREUR  1
  ...
  3-06-2021  EURUSD  1.56
  3-06-2021  EURJPY  5.6
  3-06-2021  EUREUR  1

Body:
I tried to reproduce the data you presented in the question.

you can find my solution below using 'pandas.Series.str'1

import pandas as pd
fx_rates = pd.DataFrame({'date':['2-12-2021','2-12-2021','2-12-2021','3-06-2021','3-06-2021','3-06-2021'],
                         'pair':['EURUSD','EURJPY','EUREUR','EURUSD','EURJPY','EUREUR'],'rate':[1.5,5,1,1.56,5.6,1]})
order_values=pd.DataFrame({'order_num':[1,2,3,4],'value_loc':[2345,104,2000,550],  'currency':['USD','EUR','JPY','USD'],
                           'date':['2-12-2021','2-12-2021','2-15-2021','3-06-2021']})

fx_rates['pair_split']=fx_rates['pair'].str.split('EUR',expand=True)[1].replace('','EUR')
df=pd.merge(order_values,fx_rates,right_on=['date','pair_split'],left_on=['date','currency'],how='inner')


问:
How to insert list at specific position into list of lists
I want to know if it is possible to insert a list of floats into a list of lists at a specific position and how to index it or if I should consider using a different datatype (like an array or dictionary) instead:

As an example:

```<code>list_to_insert = [0.7, 0.3, 0.85, -0.1, 0.4]

list_of_lists = [[[], []],
                [[], [], [], [], [], []],
                [[], [], [], [], [], []],
                [[], []]]

=> list_of_lists = [[[], []],
                   [[], [], [], [], [], []],
                   [[], [], [], [], [list_to_insert], []],
                   [[], []]]
</code>```

答:
You can simply specify the index and assign the list at that index. For example, in your example, the following line will get the desired output.</p>
```<code>list_of_lists[2][4] = list_to_insert
</code>```

Body:
I want to know if it is possible to insert a list of floats into a list of lists at a specific position and how to index it or if I should consider using a different datatype (like an array or dictionary) instead:

As an example:

list_to_insert = [0.7, 0.3, 0.85, -0.1, 0.4]

list_of_lists = [[[], []],
                [[], [], [], [], [], []],
                [[], [], [], [], [], []],
                [[], []]]

=> list_of_lists = [[[], []],
                   [[], [], [], [], [], []],
                   [[], [], [], [], [list_to_insert], []],
                   [[], []]]

Body:
You can simply specify the index and assign the list at that index. For example, in your example, the following line will get the desired output.

list_of_lists[2][4] = list_to_insert


问:
How to tell MEF to re-create object?
I'm using mef to create WCF web services. This is how service looks:

```<code>[Export]
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MobileService
    {
        [Import]
        public IEmailService EmailService { get; set; }

        [Import]
        public ILoggerService LoggerService { get; set; }

        [Import]
        public IContextManager ContextManager { get; set; }
</code>```

This is how code to retreive service instance looks:

```<code>// Get Service instace via MEF
    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        var lazyInstance = Container.GetExports(ServiceType, null, null).FirstOrDefault();
        var instance = lazyInstance.Value;

        return instance;
    }
</code>```

MEF creates EmailService, LoggerService and this if fine, they live happily while service lives.

Now, ContextManager is different animal. In GetInstance - I really like to "kill" it and re-create. ContextManager studies URL and headers during construction and populates "context". With code like I have - it is created first time and never get's destroyed. How to change this behavior?

Thanks!

答:
On your export of the implementation of IContextManager, you need to mark the export with the non-shared part creation policy. For example:

```<code>[Export(typeof(IContextManager)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ContextManager : IContextManager
{
   ...
}
</code>```

This will inform MEF that it should create a new instance of the export every time it satisfies an import. By default MEF uses CreationPolicy.Shared which will create just a single exported value (a singleton), which is probably what you want for the Email and Logging implementations.

Title: How to tell MEF to re-create object?

Body:
I'm using mef to create WCF web services. This is how service looks:

[Export]
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MobileService
    {
        [Import]
        public IEmailService EmailService { get; set; }

        [Import]
        public ILoggerService LoggerService { get; set; }

        [Import]
        public IContextManager ContextManager { get; set; }

This is how code to retreive service instance looks:

// Get Service instace via MEF
    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        var lazyInstance = Container.GetExports(ServiceType, null, null).FirstOrDefault();
        var instance = lazyInstance.Value;

        return instance;
    }

MEF creates EmailService, LoggerService and this if fine, they live happily while service lives.

Now, ContextManager is different animal. In GetInstance - I really like to "kill" it and re-create. ContextManager studies URL and headers during construction and populates "context". With code like I have - it is created first time and never get's destroyed. How to change this behavior?

Thanks!

Body:
On your export of the implementation of IContextManager, you need to mark the export with the non-shared part creation policy. For example:

[Export(typeof(IContextManager)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ContextManager : IContextManager
{
   ...
}

This will inform MEF that it should create a new instance of the export every time it satisfies an import. By default MEF uses CreationPolicy.Shared which will create just a single exported value (a singleton), which is probably what you want for the Email and Logging implementations.


问:
Windows 10 -> 'npx create-react-app myapp' command does not work because of whitespace username in file path
I ran into some issues when trying to install a react app on my Windows 10 via npx create-react-app appname, receiving the following error message:

```<code>Error: EPERM: operation not permitted, mkdir 'C:\Users\Daniel'
TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js:77:20
    at cb (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:225:22)
    at C:\Program Files\nodejs\node_modules\npm\lib\npm.js:263:24
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:83:7
    at Array.forEach (<anonymous>)
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:82:13
    at f (C:\Program Files\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:173:20)
C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98
  var doExit = npm.config.loaded ? npm.config.get('_exit') : true
                          ^

TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at process.errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at process.emit (events.js:198:13)
    at process._fatalException (internal/bootstrap/node.js:496:27)
Install for create-react-app@latest failed with code 7
</code>```

Solution:

I started some research and finally found out, that this issue emerges if your Windows Username has a whitespace included e.g. "C:\Users\Firstname Lastname\AppData\Roaming\npm-cache"

After some tedious hours of running in circles and re-reading multiple GitHub-threads on this issue, I finally found a patch, that worked for me:
run npm config set cache "C:\Users\Firstname~1\AppData\Roaming\npm-cache" --global from your terminal, it will replace the whitespace and everything after it with ~1, which seems to solve the issue

The source, where I found this solution is https://github.com/zkat/npx/issues/146#issuecomment-384019497

I am posting this comment here in order to save anyone the chore of working through the gazillions of circularly linked github threads.

答: I did update the node version to 16.13.2 which solved the problem.</p>

Body:
I ran into some issues when trying to install a react app on my Windows 10 via npx create-react-app appname, receiving the following error message:

Error: EPERM: operation not permitted, mkdir 'C:\Users\Daniel'
TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js:77:20
    at cb (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:225:22)
    at C:\Program Files\nodejs\node_modules\npm\lib\npm.js:263:24
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:83:7
    at Array.forEach (<anonymous>)
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:82:13
    at f (C:\Program Files\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:173:20)
C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98
  var doExit = npm.config.loaded ? npm.config.get('_exit') : true
                          ^

TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at process.errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at process.emit (events.js:198:13)
    at process._fatalException (internal/bootstrap/node.js:496:27)
Install for create-react-app@latest failed with code 7

Solution:

I started some research and finally found out, that this issue emerges if your Windows Username has a whitespace included e.g. "C:\Users\Firstname Lastname\AppData\Roaming\npm-cache"

After some tedious hours of running in circles and re-reading multiple GitHub-threads on this issue, I finally found a patch, that worked for me:
run npm config set cache "C:\Users\Firstname~1\AppData\Roaming\npm-cache" --global from your terminal, it will replace the whitespace and everything after it with ~1, which seems to solve the issue

The source, where I found this solution is https://github.com/zkat/npx/issues/146#issuecomment-384019497

I am posting this comment here in order to save anyone the chore of working through the gazillions of circularly linked github threads.


问:
Is there a way to clear all data within a CSV file in order to fill it up again with new data?
I am trying to create an IOT weather station where in a Python file it would receive data from a temperature sensor and save it in a CSV along with the second(s) it was received.

Since this is going to be plotted in a graph in real time, I can't have it save new data without clearing the CSV file out first since if I did, the line in the graph will overlap, because of the eventual repetition of seconds in the CSV file.

This is a sample of what is saved in the CSV file:

Celcius,Time
56,20.50
57,20.50
58,20.50
59,20.50
00,20.50
```
<p>I want the code to clear the CSV file once the seconds reach 60 (or 00), so it can be repopulated with new data.</p>
<p>This is what I have come up with so far:</p>
```with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if (secondsNow[2] == "00"):
        print("CLEAR CLEAR CLEAR")
        csv_file.close()
    else:
        csv_writer.writerow(info)
```

答:
You can clear the file by passing the shell command via python os module:

```<code>import os

...
print(CLEAR CLEAR CLEAR)
exit_code = os.system(": > $FILEPATH")
...
</code>```

Body:
I am trying to create an IOT weather station where in a Python file it would receive data from a temperature sensor and save it in a CSV along with the second(s) it was received.

Since this is going to be plotted in a graph in real time, I can't have it save new data without clearing the CSV file out first since if I did, the line in the graph will overlap, because of the eventual repetition of seconds in the CSV file.

This is a sample of what is saved in the CSV file:

Celcius,Time
56,20.50
57,20.50
58,20.50
59,20.50
00,20.50

I want the code to clear the CSV file once the seconds reach 60 (or 00), so it can be repopulated with new data.

This is what I have come up with so far:

with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if (secondsNow[2] == "00"):
        print("CLEAR CLEAR CLEAR")
        csv_file.close()
    else:
        csv_writer.writerow(info)

Body:
You can clear the file by passing the shell command via python os module:

import os

...
print(CLEAR CLEAR CLEAR)
exit_code = os.system(": > $FILEPATH")
...


答:
I tried this formula and it worked for me:

```<code>=IF(AND(A2="High";B2="High");"Manage Closely"; IF(AND(A2="Low";B3="High");"Keep Informed"; IF(AND(A2="Low";B2="Low");"Monitor"; IF(AND(A2="High";B2="Low");"Meet Their Needs";0))))
</code>```

Drag down/Copy and paste the formula under the Strategy Column and it should turn out like this:

Title: Excel formula where certain combinations of cells would return a value

Body:
I'm creating a stakeholder map and I have two columns with two possible entries for each

Power | Interest | Strategy

Power and Interest can be either High or Low

So I am trying to get a strategy to return a value based on whether Power or Interest is one of those two combinations as an example:

Power = High, Interest = High, Strategy = Manage Closely
Power = Low, Interest = High, Strategy = Keep Informed
Power = Low, Interest = Low, Strategy = Monitor
Power = High, Interest = Low, Strategy = Meet Their Needs

Can someone help me with this formula?

Body:
I tried this formula and it worked for me:

=IF(AND(A2="High";B2="High");"Manage Closely"; IF(AND(A2="Low";B3="High");"Keep Informed"; IF(AND(A2="Low";B2="Low");"Monitor"; IF(AND(A2="High";B2="Low");"Meet Their Needs";0))))

Drag down/Copy and paste the formula under the Strategy Column and it should turn out like this:


问:
ASP.NET Core - Get tuple with two values
I just want to get the user's role and ID from the user table. But I do not know why the following code gives an error!!!

public Tuple<Guid,Guid> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}
```

I searched a lot but did not find an answer?

Error:

答:
Meanwhile, your existing code will return IEnumerable<Tuple<Guid,Guid>> or IQueryable<Tuple<Guid,Guid>>, which un-match with the method return type, Tuple<Guid,Guid>.

Assume that you are trying to filter with mobile.

You need either of these methods:

.First()

.Single()

.FirstOrDefault()

.SingleOrDefault()

to return (single) result Tuple<Guid,Guid>.

public Tuple<Guid,Guid> GetUserId(string mobile)
{
    return _context.Users
        .Where(u => u.Mobile == mobile)
        .Select(u => new Tuple<Guid,Guid>(u.UserId,u.RoleId))
        .First();
}
```

Body:
I just want to get the user's role and ID from the user table. But I do not know why the following code gives an error!!!

public Tuple<Guid,Guid> GetUserId(string mobile)
{
    return _context.Users.Select(u => new Tuple<Guid,Guid,Boolean>(u.UserId,u.RoleId,u.Mobile == mobile));
}

I searched a lot but did not find an answer?

Error:


问:
How can I extract the table from the given URL
I am trying to scrape the data from the table ETH ZERO SEK of the given URL, however I can't make it work. Does anyone have some advise how I can get it to work?</p>
```<code>from selenium import webdriver
from selenium.webdriver.common.by import By

url = 'https://www.ngm.se/marknaden/vardepapper?symbol=ETH%20ZERO%20SEK'
driver = webdriver.Chrome()
driver.get(url)

element = driver.find_element(By.Xpath, './/*[@id="detailviewDiv"]/table/tbody/tr[1]/td/div')
</code>```

答:
What happens?

Content you are looking for is provided via iframe, so you xpath won't work.

How to fix?

Option#1

Change your url to https://mdweb.ngm.se/detailview.html?locale=sv_SE&symbol=ETH%20ZERO%20SEK and call content directly

Option#2

Grab the source of iframe from your original url:

```<code>driver.get('https://www.ngm.se/marknaden/vardepapper?symbol=ETH%20ZERO%20SEK')
</code>```

get the src of iframe that holds your table

```<code>iframe = driver.find_element(By.XPATH, '//iframe').get_attribute("src")
</code>```

get the iframe

```<code>driver.get(iframe)
</code>```

wait until your tbody of table is located and store it in element

```<code>element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@id="detailviewDiv"]//thead[.//span[contains(text(),"Volym")]]/following-sibling::tbody')))
</code>```

Assign values from cells to variables, by split of elements text:

```<code>volym = element.text.split('\n')[-3]
vwap = element.text.split('\n')[-2]
</code>```

Note waits requires - from selenium.webdriver.support.ui import WebDriverWait

Body:
I am trying to scrape the data from the table ETH ZERO SEK of the given URL, however I can't make it work. Does anyone have some advise how I can get it to work?

from selenium import webdriver
from selenium.webdriver.common.by import By

url = 'https://www.ngm.se/marknaden/vardepapper?symbol=ETH%20ZERO%20SEK'
driver = webdriver.Chrome()
driver.get(url)

element = driver.find_element(By.Xpath, './/*[@id="detailviewDiv"]/table/tbody/tr[1]/td/div')

Body:
What happens?

Content you are looking for is provided via iframe, so you xpath won't work.

How to fix?

Option#1

Change your url to https://mdweb.ngm.se/detailview.html?locale=sv_SE&symbol=ETH%20ZERO%20SEK and call content directly

Option#2

Grab the source of iframe from your original url:

driver.get('https://www.ngm.se/marknaden/vardepapper?symbol=ETH%20ZERO%20SEK')

get the src of iframe that holds your table

iframe = driver.find_element(By.XPATH, '//iframe').get_attribute("src")

get the iframe

driver.get(iframe)

wait until your tbody of table is located and store it in element

element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@id="detailviewDiv"]//thead[.//span[contains(text(),"Volym")]]/following-sibling::tbody')))

Assign values from cells to variables, by split of elements text:

volym = element.text.split('\n')[-3]
vwap = element.text.split('\n')[-2]

Note waits requires - from selenium.webdriver.support.ui import WebDriverWait


问:
Play multiple tracks <audio>
I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But in the end, the very first track plays in a circle. How can this be fixed?

```<code><audio id="audio" preload="" autoplay="" loop="">
  <source type="audio/mp3" src="music/mus1.mp3">
  <source type="audio/mp3" src="music/mus.mp3">
</audio>
</code>```
```<code><script type="text/javascript">
var audio = document.getElementById("audio");

function pVid() {
    audio.paused ? audio.play() : audio.pause();
}
</script>
</code>```

答:
Add a skip button

when clicked, call a skip function that will

pause if there is something playing then

clear the playing/paused class clist

increment the current to the next track

then play

let sounds = new Array(new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
  new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
  new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"), new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
  new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
  new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"));

let current = random(0);
let paused = true;

// set event handlers on all audio objects
for (let s of sounds) {
  s.addEventListener('ended', ended);
  s.addEventListener('play', play);
  s.addEventListener('pause', pause);
}

updateVolume()

// handle button click
function playPause() {
  if (paused) {
    sounds[current].play();
    btn.innerText = 'pause';
    paused = false;

  } else {
    sounds[current].pause();
    btn.innerText = 'play';
    paused = true;
  }
}

// handle button skip
function skip() {
  if(!paused) playPause();
  document.getElementById(current + '').classList.remove('playing');
  document.getElementById(current + '').classList.remove('paused');
  current = (current + 1) % sounds.length;
  playPause();
}

function ended(e) {
  document.getElementById(current + '').classList.remove('playing');
  document.getElementById(current + '').classList.remove('paused');
  /*i++;
  if (i >= sounds.length) //loop
    i = 0;
  */
  current = random(current); // shuffle

  paused = true;
  playPause();
}

function play() {
  document.getElementById(current + '').classList.add('playing');
  document.getElementById(current + '').classList.remove('paused');
}

function pause() {
  document.getElementById(current + '').classList.add('paused');
  document.getElementById(current + '').classList.remove('playing');
}

function random(i) {
  let next = i;
  while (next == i)
    next = Math.floor(Math.random() * sounds.length);
  return next;
}

function updateVolume() {
  for (let s of sounds) {
    s.volume = volume.value;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#list {
  margin-top: 1rem;
  border: 1px solid gray;
  width: 100px;
}

#controls {
  position: fixed;
  right: 2rem;
  top: 1rem;
  width: 50px;
}

#volume {
  width: 150px;
  height: 20px;
  transform-origin: 75px 75px;
  transform: rotate(-90deg) translateY(50%);
}

.playing {
  background-color: lightblue;
}

.paused {
  background-color: wheat;
}</code>```

<Button id=btn onClick='playPause()'>play</Button>
<Button id=btnSkip onClick='skip()'>skip</Button>

Guitar

Drum

Violin

Guitar

Drum

Violin

  Volume

  <input id=volume type="range" id="volume" name="volume" min="0" max="1" step='.1' value='.5' onInput='updateVolume()'>

```

Title: Play multiple tracks <audio>

Body:
I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But in the end, the very first track plays in a circle. How can this be fixed?

<audio id="audio" preload="" autoplay="" loop="">
  <source type="audio/mp3" src="music/mus1.mp3">
  <source type="audio/mp3" src="music/mus.mp3">
</audio>

Body:
Add a skip button

when clicked, call a skip function that will

pause if there is something playing then

clear the playing/paused class clist

increment the current to the next track

then play

let sounds = new Array(new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
  new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
  new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"), new Audio("https://freesound.org/data/previews/46/46992_514283-lq.mp3"),
  new Audio("https://freesound.org/data/previews/610/610823_13156161-lq.mp3"),
  new Audio("https://freesound.org/data/previews/92/92005_1499847-lq.mp3"));

let current = random(0);
let paused = true;

// set event handlers on all audio objects
for (let s of sounds) {
  s.addEventListener('ended', ended);
  s.addEventListener('play', play);
  s.addEventListener('pause', pause);
}

updateVolume()

// handle button click
function playPause() {
  if (paused) {
    sounds[current].play();
    btn.innerText = 'pause';
    paused = false;

  } else {
    sounds[current].pause();
    btn.innerText = 'play';
    paused = true;
  }
}

// handle button skip
function skip() {
  if(!paused) playPause();
  document.getElementById(current + '').classList.remove('playing');
  document.getElementById(current + '').classList.remove('paused');
  current = (current + 1) % sounds.length;
  playPause();
}

function ended(e) {
  document.getElementById(current + '').classList.remove('playing');
  document.getElementById(current + '').classList.remove('paused');
  /*i++;
  if (i >= sounds.length) //loop
    i = 0;
  */
  current = random(current); // shuffle

  paused = true;
  playPause();
}

function play() {
  document.getElementById(current + '').classList.add('playing');
  document.getElementById(current + '').classList.remove('paused');
}

function pause() {
  document.getElementById(current + '').classList.add('paused');
  document.getElementById(current + '').classList.remove('playing');
}

function random(i) {
  let next = i;
  while (next == i)
    next = Math.floor(Math.random() * sounds.length);
  return next;
}

function updateVolume() {
  for (let s of sounds) {
    s.volume = volume.value;
  }
}

#list {
  margin-top: 1rem;
  border: 1px solid gray;
  width: 100px;
}

#controls {
  position: fixed;
  right: 2rem;
  top: 1rem;
  width: 50px;
}

#volume {
  width: 150px;
  height: 20px;
  transform-origin: 75px 75px;
  transform: rotate(-90deg) translateY(50%);
}

.playing {
  background-color: lightblue;
}

.paused {
  background-color: wheat;
}

<Button id=btn onClick='playPause()'>play</Button>
<Button id=btnSkip onClick='skip()'>skip</Button>
<div id=list>
  <div id='0'>Guitar</div>
  <div id='1'>Drum</div>
  <div id='2'>Violin</div>
  <div id='3'>Guitar</div>
  <div id='4'>Drum</div>
  <div id='5'>Violin</div>
</div>
<div id=controls>
  <label for="volume">Volume</label><br>
  <input id=volume type="range" id="volume" name="volume" min="0" max="1" step='.1' value='.5' onInput='updateVolume()'>

</div>


问:
Unable to create superuser in django due to not working in TTY
I go through first django tutorial from djangoproject.com and at the very beginning of part 2, which is creating superuser when I run "python manage.py createsuperuser" I get the following message back:

```<code>Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually.
</code>```

I get the same message when I go on to create superuser after running syncdb.

I am working on Eclipse for Windows 7, and Django 1.7.1 together with Python 2.7.8.

答:
If you are Windows user using GitBash terminal and trying to create super for admin it won't work instead of that use command prompt in administrative privilege it works

Gitbash terminal error

```<code>$ python manage.py createsuperuser
Superuser creation skipped due to not running in a TTY. You can run "manage.py createsuperuser" in your project to create one manually.
</code>```

Error Resolved Using Command Prompt

```<code>python manage.py createsuperuser
Username (leave blank to use 'user'): admin
Email address:
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
</code>```

This might be helpful for others. Do Upvote for this if it works for you

Body:
I go through first django tutorial from djangoproject.com and at the very beginning of part 2, which is creating superuser when I run "python manage.py createsuperuser" I get the following message back:

Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually.

I get the same message when I go on to create superuser after running syncdb.

I am working on Eclipse for Windows 7, and Django 1.7.1 together with Python 2.7.8.

Body:
If you are Windows user using GitBash terminal and trying to create super for admin it won't work instead of that use command prompt in administrative privilege it works

Gitbash terminal error

$ python manage.py createsuperuser
Superuser creation skipped due to not running in a TTY. You can run "manage.py createsuperuser" in your project to create one manually.

Error Resolved Using Command Prompt

python manage.py createsuperuser
Username (leave blank to use 'user'): admin
Email address:
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

This might be helpful for others. Do Upvote for this if it works for you


问:
can we register entity to global store in ngrx? is that possible?
It would be nice if we entity in our global store?

I have some crud operations, which are very easily done using @ngrx/entity and I want to have it in root-store.

I have tried creating an entity, but schematics did it for forFeature().

答:
NgRx Entity is basically a Dictionary with matching NgRx operators to update/read.

You can always hold an Entity Object in any store that can store a string for example. You can do so by extending the Store if you just need one Entity Object

export interface State extends EntityState<User> {
    ...
}
```
<p>or you can create Entity Objects in the Store like</p>
<pre class="lang-js prettyprint-override"><code>export interface State {
  users: EntityState<User>;
  books: EntityState<Book>;
}
</code>```

Both ways you can work with adapters. For the extend version pass the whole State to the adapter. For the second approach pass the users property to the adapter method and set the result as new value for that property in the state.

Edit

To update the Entity object a adapter is used. Create an adapter and use it in the reducers. A lot more infos about it and code examples can be found at https://ngrx.io/guide/entity/adapter

// adapter definition
export const userAdapter: EntityAdapter<User> = createEntityAdapter<User>();

// reducer call for extended state / first version
on(UserActions.setUsers, (state, { users }): State => userAdapter.setAll(users, state)),
```

Body:
NgRx Entity is basically a Dictionary with matching NgRx operators to update/read.

You can always hold an Entity Object in any store that can store a string for example. You can do so by extending the Store if you just need one Entity Object

export interface State extends EntityState<User> {
    ...
}

or you can create Entity Objects in the Store like

export interface State {
  users: EntityState<User>;
  books: EntityState<Book>;
}

Both ways you can work with adapters. For the extend version pass the whole State to the adapter. For the second approach pass the users property to the adapter method and set the result as new value for that property in the state.

Edit

To update the Entity object a adapter is used. Create an adapter and use it in the reducers. A lot more infos about it and code examples can be found at https://ngrx.io/guide/entity/adapter

// adapter definition
export const userAdapter: EntityAdapter<User> = createEntityAdapter<User>();

// reducer call for extended state / first version
on(UserActions.setUsers, (state, { users }): State => userAdapter.setAll(users, state)),


问:
Creating a simple bar chart in D3
I am really new to D3 and wanting to create a simple bar chart to get the gist of how D3 functions. I am using this website:

https://observablehq.com/@uwdata/introduction-to-d3-part-1

It has an online built-in repl which is how I have access to the data that is being used.

I am stuck on the second exercise where it wants use to recreate this bar chart

Currently, this is the code I have

{
  const container = d3.create('div');

  const data = barData;

  const barChart = container.selectAll('div')
  /* TODO: Add code here to generate the bar chart within the container. */
  data.forEach(function(d) {
    var dataValue = 0
    dataValue = d.value

  })
  barChart
      .data(data)
      .style('background', 'steelblue')   // Set the background color of the div to 'steelblue'
      .style('border', '1px solid white') // Set the border of the div as 'white'
      .style('font-size', 'small')        // Set the text font size in the div to 'small'
      .style('color', 'white')            // Set the text font color to 'white'
      .style('text-align', 'right')       // Set the text alignment in the div to 'right'
      .style('padding', '3px')            // HINT: CSS styles require units, not just numbers
      .style('height', '500px')
      .style('width', '960px')
  /* TODO: Add code here to finish updating the visual properties of the bars */

  return container.node();
}
```

What I assume that has to be done is looping through the dataset provided and then grabbing the values which are what I am doing but after the chart should show up with the styling that is provided. I am confused as to why nothing is displaying at all. Any help would be greatly appricated.

答:
Use the methods:

merge

enter

update

exit
to map your data 1-to-1 to a DOM element.

This article is rather old, but has very good animations how enter, update and exit work. merge is a new addition to combine enter and update.
https://bost.ocks.org/mike/selection/

Title: Creating a simple bar chart in D3

Body:
I am really new to D3 and wanting to create a simple bar chart to get the gist of how D3 functions. I am using this website:

https://observablehq.com/@uwdata/introduction-to-d3-part-1

It has an online built-in repl which is how I have access to the data that is being used.

I am stuck on the second exercise where it wants use to recreate this bar chart

Currently, this is the code I have

{
  const container = d3.create('div');

  const data = barData;

  const barChart = container.selectAll('div')
  /* TODO: Add code here to generate the bar chart within the container. */
  data.forEach(function(d) {
    var dataValue = 0
    dataValue = d.value

  })
  barChart
      .data(data)
      .style('background', 'steelblue')   // Set the background color of the div to 'steelblue'
      .style('border', '1px solid white') // Set the border of the div as 'white'
      .style('font-size', 'small')        // Set the text font size in the div to 'small'
      .style('color', 'white')            // Set the text font color to 'white'
      .style('text-align', 'right')       // Set the text alignment in the div to 'right'
      .style('padding', '3px')            // HINT: CSS styles require units, not just numbers
      .style('height', '500px')
      .style('width', '960px')
  /* TODO: Add code here to finish updating the visual properties of the bars */

  return container.node();
}

What I assume that has to be done is looping through the dataset provided and then grabbing the values which are what I am doing but after the chart should show up with the styling that is provided. I am confused as to why nothing is displaying at all. Any help would be greatly appricated.


问:
TypeScript: Typing a value based on an object key
I need some help on my TypeScript adventure.

Here's my example type:

type Target = {
  names: string[]
  addresses: {
      location: string
    }[]
};
```
<p>Here's my example object:</p>
<pre class="lang-js prettyprint-override"><code>const myTarget: Target = {
  names: ["Alex", "Nico"],
  addresses: [
    {
      location: "Miami",
    },
    {
      location: "New York",
    },
  ],
};
</code>```

And here's my function example:

const changeValue = (
    key: keyof Target,
    value: string | Record<string, unknown>
) => {
 myTarget[key] = [...myTarget[key], value]
}

changeValue('names', 'Elvis')
changeValue('addresses', { location: "Atlanta" })
```

I've an error on the myTarget[key] saying this:

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[] & { location: string; }[]'.

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[]'.

Cannot assign type 'string | Record<string, unknown>' of type 'string'.

Cannot assign type 'Record<string, unknown>' to type 'string'
.ts(2322)

From what I understand is that, for example, TypeScript is testing all combinations, including adding an object  to the names array, which is invalid, or adding a string inside addresses array.

Can someone please help me to understand what's the problem and how can I handle it. ( the real project is so much more complicated, but maybe with this example I'll understand a bit..)

Thanks a lot.

答:
Why do you have an error ?

Answer on this question you can find here , here , here and in my article here.

Using this type string | Record<string, unknown> for value argument is not safe. It is better to infer the type of key argument:

const changeValue = <Key extends keyof Target>(
    key: Key,
    value: Target[Key][number]
) => {
    // error
    myTarget[key] = [...myTarget[key], value]
}
```
<p>You have an error here, because there is no correlation (inside) function body between <code>key</code> and <code>value</code>. Such correlation exists only outisde of function, I mean, when you call this function.</p>
<p>Please keep in mind that <code>key</code> is still a union type.
I think it worth using immutable approach:</p>
<pre class="lang-js prettyprint-override"><code>type Target = {
    names: string[]
    addresses: {
        location: string
    }[]
};

const myTarget: Target = {
    names: ["Alex", "Nico"],
    addresses: [
        {
            location: "Miami",
        },
        {
            location: "New York",
        },
    ],
};

const withTarget = <
    Obj extends Record<string, unknown[]>
>(target: Obj) => <
    Key extends keyof Obj
>(
    key: Key,
    value: Obj[Key][number]
): Obj => ({
    ...target,
    [key]: target[key].concat(value)
})

const changeValue = withTarget(myTarget);
const result = changeValue('names', 'Elvis')
</code>```

Body:
I need some help on my TypeScript adventure.

Here's my example type:

type Target = {
  names: string[]
  addresses: {
      location: string
    }[]
};

Here's my example object:

const myTarget: Target = {
  names: ["Alex", "Nico"],
  addresses: [
    {
      location: "Miami",
    },
    {
      location: "New York",
    },
  ],
};

And here's my function example:

const changeValue = (
    key: keyof Target,
    value: string | Record<string, unknown>
) => {
 myTarget[key] = [...myTarget[key], value]
}

changeValue('names', 'Elvis')
changeValue('addresses', { location: "Atlanta" })

I've an error on the myTarget[key] saying this:

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[] & { location: string; }[]'.

Cannot assign type '(string | Record<string, unknown>)[]' to type 'string[]'.

Cannot assign type 'string | Record<string, unknown>' of type 'string'.

Cannot assign type 'Record<string, unknown>' to type 'string'
.ts(2322)

From what I understand is that, for example, TypeScript is testing all combinations, including adding an object  to the names array, which is invalid, or adding a string inside addresses array.

Can someone please help me to understand what's the problem and how can I handle it. ( the real project is so much more complicated, but maybe with this example I'll understand a bit..)

Thanks a lot.

Body:
Why do you have an error ?

Answer on this question you can find here , here , here and in my article here.

Using this type string | Record<string, unknown> for value argument is not safe. It is better to infer the type of key argument:

const changeValue = <Key extends keyof Target>(
    key: Key,
    value: Target[Key][number]
) => {
    // error
    myTarget[key] = [...myTarget[key], value]
}

You have an error here, because there is no correlation (inside) function body between key and value. Such correlation exists only outisde of function, I mean, when you call this function.

Please keep in mind that key is still a union type.
I think it worth using immutable approach:

type Target = {
    names: string[]
    addresses: {
        location: string
    }[]
};

const myTarget: Target = {
    names: ["Alex", "Nico"],
    addresses: [
        {
            location: "Miami",
        },
        {
            location: "New York",
        },
    ],
};

const withTarget = <
    Obj extends Record<string, unknown[]>
>(target: Obj) => <
    Key extends keyof Obj
>(
    key: Key,
    value: Obj[Key][number]
): Obj => ({
    ...target,
    [key]: target[key].concat(value)
})

const changeValue = withTarget(myTarget);
const result = changeValue('names', 'Elvis')


问:
Transform java object to JSONObject return null on live server
I have a web application (Maven project, JSP/SERVLET, TomCat 8.5.20). The application run perfectly in localhost (same TomCat version), but when i deploy to a live server, the following code doesn't work, the 'x01Json' (JSONObject) variable value be 'null' after i cal the transfromGameToJson() method.

Game init servlet, where i set JSON in request

```<code>        X01Game x01Game = gameController.initX01Game(type, legsNumber, setsNumber, users, doubleIn, doubleOut, x01,
                randomOrder, startingPoint);

        JSONObject x01Json = gameController.transfromGameToJson(x01Game);

        session.setAttribute("x01Game", x01Game);

        request.setAttribute("x01Json", x01Json);
        request.getRequestDispatcher("/darts/x01game.jsp").forward(request, response);
</code>```

the method

```<code>public JSONObject transfromGameToJson(X01Game x01Game) {

    ObjectMapper mapper = new ObjectMapper();

    try {
        mapper.writeValue(new File("x01Game.json"), x01Game);
        JSONObject object = new JSONObject(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(x01Game));
        return object;
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
</code>```

答:
If i delete this line from my method, it's working:</p>
```<code>      mapper.writeValue(new File("x01Game.json"), x01Game);
</code>```

Body:
I have a web application (Maven project, JSP/SERVLET, TomCat 8.5.20). The application run perfectly in localhost (same TomCat version), but when i deploy to a live server, the following code doesn't work, the 'x01Json' (JSONObject) variable value be 'null' after i cal the transfromGameToJson() method.

Game init servlet, where i set JSON in request

        X01Game x01Game = gameController.initX01Game(type, legsNumber, setsNumber, users, doubleIn, doubleOut, x01,
                randomOrder, startingPoint);

        JSONObject x01Json = gameController.transfromGameToJson(x01Game);

        session.setAttribute("x01Game", x01Game);

        request.setAttribute("x01Json", x01Json);
        request.getRequestDispatcher("/darts/x01game.jsp").forward(request, response);

the method

public JSONObject transfromGameToJson(X01Game x01Game) {

    ObjectMapper mapper = new ObjectMapper();

    try {
        mapper.writeValue(new File("x01Game.json"), x01Game);
        JSONObject object = new JSONObject(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(x01Game));
        return object;
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

Body:
If i delete this line from my method, it's working:

      mapper.writeValue(new File("x01Game.json"), x01Game);