问:
IdentityServer4 and external oauth privider: The oauth state was missing or invalid
I'm trying to implement external oauth authentication within IdentityServer4.
All auth requests goes successfully. I have a message AuthenticationScheme: Identity.External signed in. in app log.
But when authentication process tries to go back to ExternalLoginCallback action it falls with Error 500 (The oauth state was missing or invalid) after HTTP 302.
Screenshot is here

Result 302. Request https://localhost:5999/Account/ExternalLoginCallback?state=xxx&code=xxx&session_state=xxx

Then request goes to https://localhost:5999/Account/ExternalLoginCallback (without any parametres)

My IS4 Startup

```<code>IdentityServerConfiguration.AddIdentityServer(services, _configuration);

        services
            .AddAuthentication()
            .AddTinkoff(_configuration)
            .AddSber(_configuration)
            .AddEsia(_configuration);
</code>```

AddTinkoff extension method:

```<code>public static AuthenticationBuilder AddTinkoff(this AuthenticationBuilder builder, IConfiguration config)
    {
        return builder.AddOAuth("TinkoffId", "Tinkoff ID", options =>
        {
            options.AuthorizationEndpoint = "https://id.tinkoff.ru/auth/authorize?response_type=code";
            options.TokenEndpoint = "https://id.tinkoff.ru/auth/token?grant_type=authorization_code";
            options.UserInformationEndpoint = "https://id.tinkoff.ru/userinfo/userinfo";
            options.CallbackPath = "/Account/ExternalLoginCallback";
            options.ClientId = "xxx";
            options.ClientSecret = "xxxx";
            options.SaveTokens = true;
            options.SignInScheme = IdentityConstants.ExternalScheme;
            options.BackchannelHttpHandler = new TinkoffAuthorizingHandler(new HttpClientHandler(), options);
            options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "name");
            options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email", ClaimValueTypes.Email);
            options.ClaimActions.MapAll();

            options.Events = new OAuthEvents
            {

                OnCreatingTicket = async context =>
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, context.Options.UserInformationEndpoint);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                    request.Headers.Add(
                       HttpRequestHeader.ContentType.ToString(),
                       "application/x-www-form-urlencoded"
                    );

                    request.Content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>() {
                            new KeyValuePair<string, string>("client_id",options.ClientId),
                            new KeyValuePair<string, string>("client_secret",options.ClientSecret)
                        });

                    var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                    response.EnsureSuccessStatusCode();

                    var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync());

                    context.RunClaimActions(user.RootElement);
                },
                //OnTicketReceived = async context =>
                //{
                //    context.HttpContext.User = context.Principal;
                //    //context.SkipHandler();
                //}
            };
            //options.Scope.Add("profile");
            //options.Scope.Add("email");
            //options.Scope.Add("phone");
        });
    }
</code>```

My ExternalLogin action:

```<code>[HttpPost]
    [HttpGet]
    [AllowAnonymous]
    public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {
        _logger.LogInformation($"External login fired. ReturnUrl='{returnUrl}'. Provider='{provider}'");
        var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return Challenge(properties, provider);
    }
</code>```

ExternalLoginCallback action not fired while debug.

What I'm doing wrong. Why request redirects to itself without params?

Thank you.

答:
I solved an issue for me.
I added

```<code>OnTicketReceived = async context =>
                {
                    context.HttpContext.User = context.Principal;
                    //context.SkipHandler();
                    context.ReturnUri += $"/{context.Request.QueryString}";
                }
</code>```

Now it works as expected

Body:
I'm trying to implement external oauth authentication within IdentityServer4.
All auth requests goes successfully. I have a message AuthenticationScheme: Identity.External signed in. in app log.
But when authentication process tries to go back to ExternalLoginCallback action it falls with Error 500 (The oauth state was missing or invalid) after HTTP 302.
Screenshot is here

Result 302. Request https://localhost:5999/Account/ExternalLoginCallback?state=xxx&code=xxx&session_state=xxx

Then request goes to https://localhost:5999/Account/ExternalLoginCallback (without any parametres)

My IS4 Startup

IdentityServerConfiguration.AddIdentityServer(services, _configuration);

        services
            .AddAuthentication()
            .AddTinkoff(_configuration)
            .AddSber(_configuration)
            .AddEsia(_configuration);

AddTinkoff extension method:

public static AuthenticationBuilder AddTinkoff(this AuthenticationBuilder builder, IConfiguration config)
    {
        return builder.AddOAuth("TinkoffId", "Tinkoff ID", options =>
        {
            options.AuthorizationEndpoint = "https://id.tinkoff.ru/auth/authorize?response_type=code";
            options.TokenEndpoint = "https://id.tinkoff.ru/auth/token?grant_type=authorization_code";
            options.UserInformationEndpoint = "https://id.tinkoff.ru/userinfo/userinfo";
            options.CallbackPath = "/Account/ExternalLoginCallback";
            options.ClientId = "xxx";
            options.ClientSecret = "xxxx";
            options.SaveTokens = true;
            options.SignInScheme = IdentityConstants.ExternalScheme;
            options.BackchannelHttpHandler = new TinkoffAuthorizingHandler(new HttpClientHandler(), options);
            options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "name");
            options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email", ClaimValueTypes.Email);
            options.ClaimActions.MapAll();

            options.Events = new OAuthEvents
            {

                OnCreatingTicket = async context =>
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, context.Options.UserInformationEndpoint);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                    request.Headers.Add(
                       HttpRequestHeader.ContentType.ToString(),
                       "application/x-www-form-urlencoded"
                    );

                    request.Content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>() {
                            new KeyValuePair<string, string>("client_id",options.ClientId),
                            new KeyValuePair<string, string>("client_secret",options.ClientSecret)
                        });

                    var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                    response.EnsureSuccessStatusCode();

                    var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync());

                    context.RunClaimActions(user.RootElement);
                },
                //OnTicketReceived = async context =>
                //{
                //    context.HttpContext.User = context.Principal;
                //    //context.SkipHandler();
                //}
            };
            //options.Scope.Add("profile");
            //options.Scope.Add("email");
            //options.Scope.Add("phone");
        });
    }

My ExternalLogin action:

[HttpPost]
    [HttpGet]
    [AllowAnonymous]
    public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {
        _logger.LogInformation($"External login fired. ReturnUrl='{returnUrl}'. Provider='{provider}'");
        var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return Challenge(properties, provider);
    }

ExternalLoginCallback action not fired while debug.

What I'm doing wrong. Why request redirects to itself without params?

Thank you.

Body:
I solved an issue for me.
I added

OnTicketReceived = async context =>
                {
                    context.HttpContext.User = context.Principal;
                    //context.SkipHandler();
                    context.ReturnUri += $"/{context.Request.QueryString}";
                }

Now it works as expected


来源: stackexchange

问:
Extract specific list elements from a nested list in R?
I have a nested list that looks like this:

```<code>x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1]  1 10

[[1]]$b
[1]  2 10

[[2]]
[[2]]$c
[1]  3 10

[[2]]$d
[1]  6 10

[[3]]
[[3]]$e
[1]  3 10
</code>```

I'm trying to extract just the first value from each list element. However, if the length of a list is greater than 1, then I want to add the extracted values together.

For example, in my list x above, we can see that the first list (i.e., x[[1]]) contains a and b... so I want to extract the 1st values from this list (in this case, 1 and 2) and since they belong to the same list, they get added together.

At the end, Im just trying to return a vector of the extracted (and where necessary, added) values. So in my example, I would expect a vector like: [1] 3 9 3.

ContentLicense: CC BY-SA 4.0

Body:
I have a nested list that looks like this:

x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1]  1 10

[[1]]$b
[1]  2 10

[[2]]
[[2]]$c
[1]  3 10

[[2]]$d
[1]  6 10

[[3]]
[[3]]$e
[1]  3 10

I'm trying to extract just the first value from each list element. However, if the length of a list is greater than 1, then I want to add the extracted values together.

For example, in my list x above, we can see that the first list (i.e., x[[1]]) contains a and b... so I want to extract the 1st values from this list (in this case, 1 and 2) and since they belong to the same list, they get added together.

At the end, Im just trying to return a vector of the extracted (and where necessary, added) values. So in my example, I would expect a vector like: [1] 3 9 3.

Body:
A fast rapply - vapply approach.

vapply(rapply(x, \(x) unlist(`[`(x, 1)), how='list'), \(x) sum(unlist(x)), 0)
# [1] 3 9 3

## microbenchmark ##
# Unit: microseconds
#   expr     min       lq      mean   median       uq      max neval cld
# sapply 124.166 128.4550 150.57375 131.5865 133.5845 2010.623   100  ab
# vapply  45.655  47.8645  84.40778  48.9600  49.7950 3583.235   100  a
#  purrr 185.724 189.9295 194.47557 192.8915 195.6345  281.938   100   b


问:
How to map parts of text to an alias word using machine learning or nlp
I'm trying to figure out a machine learning/NLP/programatic approach for the following:

I have a tools description:  1 1/2" 10 1,000# pw pipes me-999h_

I'm breaking this into tokens:  1 1/2" | 10 | 1,000# | pw | pipes | me-999h_

What I'd like to do is replace the tokens with their alias/synonym word if available:

1.5 | 10 | 1m | sbe | pipe | me999h

Result is the alias tool description:

1.5 10 1m sbe pipe me999h

In the above example the token:

1 1/2" is changed to its alias 1.5

1,000# is changed to its alias 1m

pw is changed to its alias pe

pipes is changed to its alias pipe

me-999h_ is changed to its alias me999h

There are multiple tokens that map to a single alias.
For example, for the alias pe, any of these would be changed to alias pe:

pw, pe x pw, pw x pw, pe x pe, st x pe    -------> are all changed to pe

I have a excel file with the following columns:

tool description, alias tool description, each token (with each variation as a separate row in the same column), each corresponding alias of token.

Right now, these tokens are being changed manually with find and replace.

What I'm trying to figure out is how I could change any of the tokens to it's corresponding alias in a machine learning/NLP model model by predicting the alias. (so given any of the tokens pw, pe x pw, pw x pw, pe x pe, st x pe, the model should predict the alias as pe).

I was thinking and tried using a column as a 'x' variable and the target 'y variable' as the corresponding alias column, however I couldn't get that to work.

Any help/ideas would be greatly appreciated. Thanks

答:
I believe the data has similar pattern widely. Also, as I have understood you want change the data into its alias form. So, instead of using machine learning you could just try to solve this via regex.
Here is a reference you can use.


问:
wrap spans around individual letters of a div using JQuery
I'm trying to insert span elements around every letter of a div's text, belonging to a given class, using JQuery.
But my code only returns words, not letters. What is wrong?</p>
```<code>$(function() {
    var title = $(".js-split-text").text();
    var titleText = title.split(" ");
    var newTitle = [];
    var letterCount = 0;
    titleText.forEach(function(el) {
            var titleElement = "<span>" + el + "</span>";
            newTitle.push(titleElement);
            letterCount++;
            if (titleText.length === letterCount) {
                var newTitleText = newTitle.join(" ");
                $(".js-split-text")
                    .html(newTitleText)
                    .css({ opacity: 1 });

                var aniTime = 0;
                var offset = 500;
                $(".js-split-text span").each(function() {
                    var currentSpan = $(this);
                    aniTime += offset;
                    setTimeout(function() {
                        currentSpan.addClass("animate");
                    }, aniTime);
                });
            }
        });
    });
</code>```

答:
You're are wrapping the spans around the words in the text with this code

var titleElement = "" + el + "";

If you want to wrap the spans around the letters, you should further split the words into letters like so

var titleElement = "" + el.split('').join("")  + "";

Body:
I'm trying to insert span elements around every letter of a div's text, belonging to a given class, using JQuery.
But my code only returns words, not letters. What is wrong?

$(function() {
    var title = $(".js-split-text").text();
    var titleText = title.split(" ");
    var newTitle = [];
    var letterCount = 0;
    titleText.forEach(function(el) {
            var titleElement = "" + el + "";
            newTitle.push(titleElement);
            letterCount++;
            if (titleText.length === letterCount) {
                var newTitleText = newTitle.join(" ");
                $(".js-split-text")
                    .html(newTitleText)
                    .css({ opacity: 1 });

                var aniTime = 0;
                var offset = 500;
                $(".js-split-text span").each(function() {
                    var currentSpan = $(this);
                    aniTime += offset;
                    setTimeout(function() {
                        currentSpan.addClass("animate");
                    }, aniTime);
                });
            }
        });
    });

Body:
You're are wrapping the spans around the words in the text with this code

var titleElement = "<span>" + el + "</span>";

If you want to wrap the spans around the letters, you should further split the words into letters like so

var titleElement = "<span>" + el.split('').join("</span><span>")  + "</span>";


问:
passing command line arguments to selenium python test case
I have a selenium python automation test where i want to pass url of website as a parameter to function. I will be calling the function via command line.

my_python_code.py

```<code>class my_automation_class(unittest.TestCase)

    def setUp(self):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--disable-gpu")
        self.driver = webdriver.Chrome(ChromeDriverManager().install())
        parser = argparse.ArgumentParser()
        parser.add_argument("url_link", help="display url")
        self.args = parser.parse_args()

    def test_my_automation(self):

        driver = self.driver
        driver.maximize_window()

        driver.get(self.args.url_link)
        //performs some operation after this

if __name__ == "__main__":
unittest.main(testRunner=HTMLTestRunner(output='Reports'),exit=False)
</code>```

When I ran this via command line

python my_python_code.py "https://www.netflix.com/in/ "

I am getting

ERROR [0.000000s]: unittest.loader._FailedTest.https://www

AttributeError: module 'main' has no attribute 'https://www'

I am not sure why it's not working. Is there any other way i can pass arguments to selenium python  test case ?

答:
```<code>class my_automation_class(unittest.TestCase)
      def setUp(self):
          chrome_options = webdriver.ChromeOptions()
          chrome_options.add_argument("--headless")
          chrome_options.add_argument("--disable-gpu")
          self.driver = webdriver.Chrome(ChromeDriverManager().install())
          self.url_link = args.url_link

      def test_my_automation(self):
          driver = self.driver
          driver.maximize_window()
          driver.get(self.url_link)
          //performs some operation after this

if __name__ == "__main__":
     parser = argparse.ArgumentParser()
     parser.add_argument("url_link", help="display url")
     args = parser.parse_args()
     sys.argv.pop()
     unittest.main(testRunner=HTMLTestRunner(output='Reports'),exit=False)
</code>```

Run code:

```<code>    python my_python_code  --url_link="https://www.netflix.com/in/"
</code>```

Body:
I have a selenium python automation test where i want to pass url of website as a parameter to function. I will be calling the function via command line.

my_python_code.py

class my_automation_class(unittest.TestCase)

    def setUp(self):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--disable-gpu")
        self.driver = webdriver.Chrome(ChromeDriverManager().install())
        parser = argparse.ArgumentParser()
        parser.add_argument("url_link", help="display url")
        self.args = parser.parse_args()

    def test_my_automation(self):

        driver = self.driver
        driver.maximize_window()

        driver.get(self.args.url_link)
        //performs some operation after this

if __name__ == "__main__":
unittest.main(testRunner=HTMLTestRunner(output='Reports'),exit=False)

When I ran this via command line

python my_python_code.py "https://www.netflix.com/in/ "

I am getting

ERROR [0.000000s]: unittest.loader._FailedTest.https://www

AttributeError: module 'main' has no attribute 'https://www'

I am not sure why it's not working. Is there any other way i can pass arguments to selenium python  test case ?

Body:
class my_automation_class(unittest.TestCase)
      def setUp(self):
          chrome_options = webdriver.ChromeOptions()
          chrome_options.add_argument("--headless")
          chrome_options.add_argument("--disable-gpu")
          self.driver = webdriver.Chrome(ChromeDriverManager().install())
          self.url_link = args.url_link

      def test_my_automation(self):
          driver = self.driver
          driver.maximize_window()
          driver.get(self.url_link)
          //performs some operation after this

if __name__ == "__main__":
     parser = argparse.ArgumentParser()
     parser.add_argument("url_link", help="display url")
     args = parser.parse_args()
     sys.argv.pop()
     unittest.main(testRunner=HTMLTestRunner(output='Reports'),exit=False)

Run code:

    python my_python_code  --url_link="https://www.netflix.com/in/"


问:
The designer could not be shown for this file because none of the classes within it can be designed
We have the following shared component:

```<code>public class OurServiceBase : System.ServiceProcess.ServiceBase
</code>```

This class has functionality we want in all our downstream services, such as standardized execution scheduling and logging functionality.

In a new project, I add the following:

```<code>public class MyService : System.ServiceProcess.ServiceBase
</code>```

In the Windows Designer, the class shows properly.

When I change the service to derive from OurServiceBase

```<code>public class MyService : OurSharedLibrary.OurServiceBase
</code>```

The designer stops working:

The full error is:
The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file: EmailProcessor --- The base class 'OurSharedLibrary.CienaServiceBase' could not be loaded. Ensure the assembly has been referenced and that all projects have been built.

The proper assemblies are referenced, the project builds.  I don't understand why the designer is flipping out over this since my service ultimately does derive from a designable class.

Any suggestions would be most welcome.

Bit more information - the call stack from the designer when it renders the error about not being able to design the derived service:

```<code>at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.EnsureDocument(IDesignerSerializationManager manager)
at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
at System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad(IDesignerLoaderHost host)
</code>```

7/19/2011 2:34PM EDT New discovery.

Class "OurServiceBase" exists in a separate project (usually referenced as a DLL only).  On a whim, I copied the base class file into my project, built, and opened the designer.  It worked!  When I removed the base class file again and returned to the external DLL reference, the designer broke again.

答: I had this issue with a WinForms .NET framework project from 2016 that I developed with VS 2015. I opened it with VS 2022 and the error appeared. After downgrading the project from .NET 4.7.1 to 3.5, then back to 4.7.1, everything worked fine.

ContentLicense: CC BY-SA 3.0

Body:
We have the following shared component:

public class OurServiceBase : System.ServiceProcess.ServiceBase

This class has functionality we want in all our downstream services, such as standardized execution scheduling and logging functionality.

In a new project, I add the following:

public class MyService : System.ServiceProcess.ServiceBase

In the Windows Designer, the class shows properly.

When I change the service to derive from OurServiceBase

public class MyService : OurSharedLibrary.OurServiceBase

The designer stops working:

The full error is:
The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file: EmailProcessor --- The base class 'OurSharedLibrary.CienaServiceBase' could not be loaded. Ensure the assembly has been referenced and that all projects have been built.

The proper assemblies are referenced, the project builds.  I don't understand why the designer is flipping out over this since my service ultimately does derive from a designable class.

Any suggestions would be most welcome.

Bit more information - the call stack from the designer when it renders the error about not being able to design the derived service:

at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.EnsureDocument(IDesignerSerializationManager manager)
at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
at System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad(IDesignerLoaderHost host)

7/19/2011 2:34PM EDT New discovery.

Class "OurServiceBase" exists in a separate project (usually referenced as a DLL only).  On a whim, I copied the base class file into my project, built, and opened the designer.  It worked!  When I removed the base class file again and returned to the external DLL reference, the designer broke again.


问:
Rounded Semicircle with CSS

I'm struggling to make the semicircle edges round, where can i fix my code?

.circle {
  position: absolute;
  width: 80px;
  height: 50px;
  background-color: transparent;
  top: 70;
  left: 20;
  border-bottom-right-radius: 70px;
  border-bottom-left-radius: 70px;
  border: 20px solid #fff58f;
  border-top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle"></div></code>```

答:
Only possible way to do this in pure CSS is by faking it with pseudo-elements:

.wrapper {
  background: darkorange;
  border-radius: 50%;
  width: 200px;
  height: 200px;
  display: grid;
  justify-content: center;
  align-content: center;
}

.box {
  background: orange;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  position: relative;
}

.circle {
  position: absolute;
  width: 100px;
  height: 50px;
  background-color: transparent;
  bottom: 0;
  left: -10px;
  border-bottom-right-radius: 70px;
  border-bottom-left-radius: 70px;
  border: 20px solid #FFF58F;
  border-top: 0
}

.circle::before, .circle::after {
  content: '';
  width: 20px;
  height: 20px;
  border-radius: 50%;
  position: absolute;
  background: #FFF58F;
}

.circle::before {
  left: -20px;
  top: -8px;
}

.circle::after {
  right: -20px;
  top: -8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="box">
    <div class="circle"></div>
  </div>
</div></code>```

Title: Rounded Semicircle with CSS

Body:
Only possible way to do this in pure CSS is by faking it with pseudo-elements:

.wrapper {
  background: darkorange;
  border-radius: 50%;
  width: 200px;
  height: 200px;
  display: grid;
  justify-content: center;
  align-content: center;
}

.box {
  background: orange;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  position: relative;
}

.circle {
  position: absolute;
  width: 100px;
  height: 50px;
  background-color: transparent;
  bottom: 0;
  left: -10px;
  border-bottom-right-radius: 70px;
  border-bottom-left-radius: 70px;
  border: 20px solid #FFF58F;
  border-top: 0
}

.circle::before, .circle::after {
  content: '';
  width: 20px;
  height: 20px;
  border-radius: 50%;
  position: absolute;
  background: #FFF58F;
}

.circle::before {
  left: -20px;
  top: -8px;
}

.circle::after {
  right: -20px;
  top: -8px;
}

<div class="wrapper">
  <div class="box">
    <div class="circle"></div>
  </div>
</div>


问:
How can i make anchor link # when url visited directly it focus on browser
For instance i have this

```<code><a style="text-decoration:none;" href="#section2">Hello World</a>
</code>```

and when i provided the url to another person such as for instance example.com/test.html#section2
and they visited it i want the browser to somewhat show or focus on
Hello World which is the a content what a href is linking

答:
Specify the "id" of the element you want to be in view when you visit that link:

Go to Section 2

Section 2

```

Body:
For instance i have this

Hello World

and when i provided the url to another person such as for instance example.com/test.html#section2
and they visited it i want the browser to somewhat show or focus on
Hello World which is the a content what a href is linking

Body:
Specify the "id" of the element you want to be in view when you visit that link:

<a href="#section2">Go to Section 2</a>
<div>
  <h1 id="section2">Section 2</h1>
</div>


问:
Subdomain to point to subdirectory of main site?
I have my website running at:

www.example.com

I also have this other domain:

www.example.net

Is it possible to point "www.example.net" to a subdirectory of "www.example.com"? For example:

www.example.net-> www.example.com/other

?

It's not just a redirect, I need to serve the pages and see "www.example.net" in the user's browser.

What do you think?

We use IIS7 and everything is ASP.NET (aspx pages, ascx controls, etc).

答:
Using ISAPI Rewrite</p>

```<code>[ISAPI_Rewrite]

RewriteCond  Host:  (?:www\.)?other\.com
RewriteRule  (.*)   http://www.domain.com/other$1 [I,L]
</code>```

OwnerDisplayName: AnonUser

ContentLicense: CC BY-SA 2.5

Body:
Using ISAPI Rewrite

[ISAPI_Rewrite]

RewriteCond  Host:  (?:www\.)?other\.com
RewriteRule  (.*)   http://www.domain.com/other$1 [I,L]

OwnerDisplayName: vartec


问:
wxpython textctrl doesn't write when bound
I have been working on a simple textctrl project to get more acquainted with wxpython and I have hit a small road block. I am making a simple code editor, and I am currently working on the syntax highlighting. Everything works fine except because I have my textctrl bound to an event:

```<code>self.status_area.Bind(wx.EVT_CHAR, self.onKeyPress)
</code>```

and I have code in that definition:

```<code>def onKeyPress (self, event):
    Line = self.status_area.GetValue()
</code>```

It will no longer allow the user to type in any letters. I am able to delete and create a new line without any problem, but if I type "hello" nothing will show up. When debugging my code I know its running through onKeyPress() and the code inside and if I change the code to:

```<code>def onKeyPress (self, event):
    event.Skip()
</code>```

it will work fine. I tried to recode the normal text editor workings into the onKeyPress() but it began to get too bulky. Any help on the matter would be greatly appreciated.

答: Try EVT_TEXT rather than EVT_CHAR.  In my solution, I added it AFTER event.Skip()

Body:
I have been working on a simple textctrl project to get more acquainted with wxpython and I have hit a small road block. I am making a simple code editor, and I am currently working on the syntax highlighting. Everything works fine except because I have my textctrl bound to an event:

self.status_area.Bind(wx.EVT_CHAR, self.onKeyPress)

and I have code in that definition:

def onKeyPress (self, event):
    Line = self.status_area.GetValue()

It will no longer allow the user to type in any letters. I am able to delete and create a new line without any problem, but if I type "hello" nothing will show up. When debugging my code I know its running through onKeyPress() and the code inside and if I change the code to:

def onKeyPress (self, event):
    event.Skip()

it will work fine. I tried to recode the normal text editor workings into the onKeyPress() but it began to get too bulky. Any help on the matter would be greatly appreciated.


问:
How stop overwrite but adds a number beside the name
How to stop overwriting but add a new number beside the name.

I tried to make this code, but it didn't work.

```<code>set overwrite=0
set newoverwrite=0
:loop
if (%textfile.txt%==EXIST) goto fix
:fix
set /a newoverwrite=%overwrite%+1
if (%textfile%newoverwrite%.txt%==EXIST) goto fix
echo hello > textfile%newoverwrite%.txt
echo skipped!
pause > nul
</code>```

It is a bit sloppy because I have tested it many times.

Does anyone know how? Or fix my code?

答:
I am assuming you want to create files by just incrementing numbers to it.

```<code>@echo off & set cnt=0
:loop
type "textfile%cnt%.txt">nul 2>&1 && echo skipped textfile%cnt%.txt || (echo hello)>"textfile%cnt%.txt"
set /a cnt+=1
pause
goto :loop
</code>```

I am not sure though if you are aware that this will create files in a permanent loop until you interrupt the process. so Do Not remove the pause from the script.

To explain what it does. We test the file for existance by attemtping to type the file. If the file does exist, type is successful and generates errorlevel of 0. This is where the && conditional operators come into play. If the errorlevel is 0 then it will execute the command after && which is to echo Skipped... However, should the file not exist will it will generate errorlevel of 1 and skip the && operator where the code after || will be executed.

Body:
How to stop overwriting but add a new number beside the name.

I tried to make this code, but it didn't work.

set overwrite=0
set newoverwrite=0
:loop
if (%textfile.txt%==EXIST) goto fix
:fix
set /a newoverwrite=%overwrite%+1
if (%textfile%newoverwrite%.txt%==EXIST) goto fix
echo hello > textfile%newoverwrite%.txt
echo skipped!
pause > nul

It is a bit sloppy because I have tested it many times.

Does anyone know how? Or fix my code?

Body:
I am assuming you want to create files by just incrementing numbers to it.

@echo off & set cnt=0
:loop
type "textfile%cnt%.txt">nul 2>&1 && echo skipped textfile%cnt%.txt || (echo hello)>"textfile%cnt%.txt"
set /a cnt+=1
pause
goto :loop

I am not sure though if you are aware that this will create files in a permanent loop until you interrupt the process. so Do Not remove the pause from the script.

To explain what it does. We test the file for existance by attemtping to type the file. If the file does exist, type is successful and generates errorlevel of 0. This is where the && conditional operators come into play. If the errorlevel is 0 then it will execute the command after && which is to echo Skipped... However, should the file not exist will it will generate errorlevel of 1 and skip the && operator where the code after || will be executed.


问:
Getting error while run flutter app in iOS
```<code>Launching lib/main.dart on iPhone 12 Pro Max in debug mode...
</code>```

Running pod install...
CocoaPods' output:
↳
CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only performed in repo update

Error output from CocoaPods:
↳
WARNING: CocoaPods requires your terminal to be using UTF-8 encoding.
Consider adding the following to ~/.profile:

```<code>    export LANG=en_US.UTF-8

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization not appropriate for ASCII-8BIT (Encoding::CompatibilityError)
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `unicode_normalize'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `installation_root'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:226:in `podfile_path'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/user_interface/error_report.rb:105:in `markdown_podfile'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/user_interface/error_report.rb:30:in `report'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:66:in `report_error'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:396:in `handle_exception'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:337:in `rescue in run'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:324:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:52:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/bin/pod:55:in `<top (required)>'
    from /usr/local/bin/pod:23:in `load'
    from /usr/local/bin/pod:23:in `<main>'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization not appropriate for ASCII-8BIT (Encoding::CompatibilityError)
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `unicode_normalize'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `installation_root'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:226:in `podfile_path'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:205:in `podfile'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:160:in `verify_podfile_exists!'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command/install.rb:46:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:52:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/bin/pod:55:in `<top (required)>'
    from /usr/local/bin/pod:23:in `load'
    from /usr/local/bin/pod:23:in `<main>'
</code>```

Error running pod install
Error launching application on iPhone 12 Pro Max.

答: Upgrade Ruby is another way to resolve this issue.</p>

Body:
Launching lib/main.dart on iPhone 12 Pro Max in debug mode...

Running pod install...
CocoaPods' output:
↳
CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only performed in repo update

Error output from CocoaPods:
↳
WARNING: CocoaPods requires your terminal to be using UTF-8 encoding.
Consider adding the following to ~/.profile:

    export LANG=en_US.UTF-8

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization not appropriate for ASCII-8BIT (Encoding::CompatibilityError)
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `unicode_normalize'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `installation_root'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:226:in `podfile_path'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/user_interface/error_report.rb:105:in `markdown_podfile'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/user_interface/error_report.rb:30:in `report'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:66:in `report_error'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:396:in `handle_exception'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:337:in `rescue in run'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:324:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:52:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/bin/pod:55:in `<top (required)>'
    from /usr/local/bin/pod:23:in `load'
    from /usr/local/bin/pod:23:in `'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization not appropriate for ASCII-8BIT (Encoding::CompatibilityError)
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `unicode_normalize'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:166:in `installation_root'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:226:in `podfile_path'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/config.rb:205:in `podfile'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:160:in `verify_podfile_exists!'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command/install.rb:46:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/lib/cocoapods/command.rb:52:in `run'
    from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.0/bin/pod:55:in `<top (required)>'
    from /usr/local/bin/pod:23:in `load'
    from /usr/local/bin/pod:23:in `'

Error running pod install
Error launching application on iPhone 12 Pro Max.


问:
props does not exist on type PropType
I have a prop ("author") which is passed from a parent component. I have typed the propType("AuthorProps") but it say Property 'author' does not exist on type 'AuthorProps' even though the structure look same.

AuthorProps:

```<code>export type AuthorProps = {
  _id: string;
  name: string;
  slug: string;
  authorId:string;
  img: string;
  createdAt?: string;
  updatedAt?: string;
  __v?: number;
}
</code>```

author props logged:

```<code>{
    _id: "61ffff139d0ad2a68738843a",
    name: "Chetan Bagat",
    slug: "chetan-bagat",
    authorId: "0",
    img: "https://img.etimg.com/thumb/msid-66099431,width-650,imgsize-149367,,resizemode-4,quality-100/chetan-bhagats-advice-for-students-its-all-about-knowing-how-to-market-yourself.jpg",
    createdAt: "2022-02-06T17:02:11.490Z",
    updatedAt: "2022-02-06T17:02:11.490Z",
    __v: 0
}
</code>```

Component:

```<code>function AuthorContainer({ author }: AuthorProps) { // }
</code>```

答:
If you don't want to modify the type, this is recommended.</p>
```<code>function AuthorContainer(author: AuthorProps) { // }
</code>```

Title: props does not exist on type PropType

Body:
I have a prop ("author") which is passed from a parent component. I have typed the propType("AuthorProps") but it say Property 'author' does not exist on type 'AuthorProps' even though the structure look same.

AuthorProps:

export type AuthorProps = {
  _id: string;
  name: string;
  slug: string;
  authorId:string;
  img: string;
  createdAt?: string;
  updatedAt?: string;
  __v?: number;
}

author props logged:

{
    _id: "61ffff139d0ad2a68738843a",
    name: "Chetan Bagat",
    slug: "chetan-bagat",
    authorId: "0",
    img: "https://img.etimg.com/thumb/msid-66099431,width-650,imgsize-149367,,resizemode-4,quality-100/chetan-bhagats-advice-for-students-its-all-about-knowing-how-to-market-yourself.jpg",
    createdAt: "2022-02-06T17:02:11.490Z",
    updatedAt: "2022-02-06T17:02:11.490Z",
    __v: 0
}

Component:

function AuthorContainer({ author }: AuthorProps) { // }

Body:
If you don't want to modify the type, this is recommended.

function AuthorContainer(author: AuthorProps) { // }


问:
How to properly store variable in a Loop in Bash?
May I ask how to loop in a while? he's my attempt on creating a file that will generate the data in a specific way. My aim is to append the rule into one single line, regardless of application number.

My Code is:

```<code>#!/bin/bash
file="temp3"
while IFS= read -r line
do
        # display $line or do somthing with $line
                #printf '%s\n' "$line"
                echo
                printf '%s\n' "$line" | grep "MySource" | awk '{printf " " $5}'
                printf '%s\n' "$line" | grep "MySource-" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyDestination" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyAppName" | awk '{printf " " $8}' #| awk '{printf " " $7 " " $8}'

                VARIABLE=$(printf '%s\n' "$line" | grep "source" | awk '{printf " " $5}')
                VARIABLE=$(printf '%s\n' "$line" | grep "source-" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "destination" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "application" | awk '{printf " " $8}')

                done <"$file"

echo $VARIABLE
printf $VARIABLE
</code>```

here's the contents of my file

```<code>zone lab zone trust  new-rule-162 match source-address MySourceName1
zone lab zone trust  new-rule-162 match source-address MySourceName2
zone lab zone trust  new-rule-162 match destination-address MyDestinationName1
zone lab zone trust  new-rule-162 match destination-address MyDestinationName2
zone lab zone trust  new-rule-162 match application MyApplicationName1
zone lab zone trust  new-rule-162 match application MyApplicationName2
zone lab zone trust  new-rule-162 match application MyApplicationName3
zone lab zone trust  new-rule-162 then permit
</code>```

Hopefully, ill be able to expand this in a way that I will be able to sort them out in the following manner.

```<code>new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 application MyAppName1 MyAppName2 MyAppName3
</code>```

The ultimate goal. In this case since, there are 2 sources and 2 destinations, the equivalent output should be 4 rows with all rows indicating the total X number of apps (4) and the permission "permit"

```<code>new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName1 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3
</code>```

答:
This code can help you to do it better

```<code>#!/bin/bash
while IFS=" " read -ra line; do
    # Set last Element equal to last element in array line avoid use awk
    lastElement=${line[-1]:-"Default value here"}

    echo "${line[4]} $lastElement ${line[-2]} where is the rest of the data ???"
# # For use a var here
# done <<<"$myVar"
done <log.txt
</code>```

The output is.

```
new-rule-162 MySourceName source-address where is the rest of the data ???
new-rule-162 MyDestinationName destination-address where is the rest of the data ???
new-rule-162 MyApplicationName application where is the rest of the data ???
```

Note:
You don't need to print in order to grep, just do:
grep -q "Some string" <<<"$line"

```<code>if (grep -q "Some string" <<<"$line"); then
   Do some stuff
fi
</code>```

Or

```<code>(grep -q "Some text" <<<"$lone") && echo "Found" || echo "Not found"
</code>```

Body:
May I ask how to loop in a while? he's my attempt on creating a file that will generate the data in a specific way. My aim is to append the rule into one single line, regardless of application number.

My Code is:

#!/bin/bash
file="temp3"
while IFS= read -r line
do
        # display $line or do somthing with $line
                #printf '%s\n' "$line"
                echo
                printf '%s\n' "$line" | grep "MySource" | awk '{printf " " $5}'
                printf '%s\n' "$line" | grep "MySource-" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyDestination" | awk '{printf " " $7 " " $8}'
                printf '%s\n' "$line" | grep "MyAppName" | awk '{printf " " $8}' #| awk '{printf " " $7 " " $8}'

                VARIABLE=$(printf '%s\n' "$line" | grep "source" | awk '{printf " " $5}')
                VARIABLE=$(printf '%s\n' "$line" | grep "source-" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "destination" | awk '{printf " " $7 " " $8}')
                VARIABLE=$(printf '%s\n' "$line" | grep "application" | awk '{printf " " $8}')

                done <"$file"

echo $VARIABLE
printf $VARIABLE

here's the contents of my file

zone lab zone trust  new-rule-162 match source-address MySourceName1
zone lab zone trust  new-rule-162 match source-address MySourceName2
zone lab zone trust  new-rule-162 match destination-address MyDestinationName1
zone lab zone trust  new-rule-162 match destination-address MyDestinationName2
zone lab zone trust  new-rule-162 match application MyApplicationName1
zone lab zone trust  new-rule-162 match application MyApplicationName2
zone lab zone trust  new-rule-162 match application MyApplicationName3
zone lab zone trust  new-rule-162 then permit

Hopefully, ill be able to expand this in a way that I will be able to sort them out in the following manner.

new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 application MyAppName1 MyAppName2 MyAppName3

The ultimate goal. In this case since, there are 2 sources and 2 destinations, the equivalent output should be 4 rows with all rows indicating the total X number of apps (4) and the permission "permit"

new-rule-162 source-address MySourceName1 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName1 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName1 permit application MyAppName1 MyAppName2 MyAppName3
new-rule-162 source-address MySourceName2 destination-address MyDestinationName2 permit application MyAppName1 MyAppName2 MyAppName3

Body:
This code can help you to do it better

#!/bin/bash
while IFS=" " read -ra line; do
    # Set last Element equal to last element in array line avoid use awk
    lastElement=${line[-1]:-"Default value here"}

    echo "${line[4]} $lastElement ${line[-2]} where is the rest of the data ???"
# # For use a var here
# done <<<"$myVar"
done <log.txt

The output is.

new-rule-162 MySourceName source-address where is the rest of the data ???
new-rule-162 MyDestinationName destination-address where is the rest of the data ???
new-rule-162 MyApplicationName application where is the rest of the data ???

Note:
You don't need to print in order to grep, just do:
grep -q "Some string" <<<"$line"

if (grep -q "Some string" <<<"$line"); then
   Do some stuff
fi

Or

(grep -q "Some text" <<<"$lone") && echo "Found" || echo "Not found"


问:
Will I get a Promise once use context.done()?
I've followed all guidelines from MS writing Azure Function. Somehow have to use .done() else client (Postman) won't see any returns:

```<code>module.exports = async function(context)
{
  ...
  const result = await aPromise().catch((bad)=>
    {
    context.res = {status: 401, body: "bad"};
    context.done();  // needed so client can get the above res
    });
}
</code>```

Does it mean the return is not a Promise?

答:
If your function is synchronous it doesn't return a Promise, so you must pass the context object, as calling context.done  is required for correct use.

// You should include context, other arguments are optional

```<code>module.exports = function(context, yourTrigger, yourInput) {
    // your function code
    context.done();
};
</code>```

If your function is async function. You don’t need to call the context.text. While your async function declaration of the Functions runtime, you do not need to explicitly call the context.done callback to signal that your function has been completed.

It is applicable from function version 2.x. If you are using function version 1.x you need to call the context.done callback.

```<code>module.exports = async function (context) {
    context.log(‘your log');
};
</code>```

Note:

Explicitly calling done is unnecessary when writing an async function the done callback is called implicitly.

Refer here  for more information

Body:
I've followed all guidelines from MS writing Azure Function. Somehow have to use .done() else client (Postman) won't see any returns:

module.exports = async function(context)
{
  ...
  const result = await aPromise().catch((bad)=>
    {
    context.res = {status: 401, body: "bad"};
    context.done();  // needed so client can get the above res
    });
}

Does it mean the return is not a Promise?

Body:
If your function is synchronous it doesn't return a Promise, so you must pass the context object, as calling context.done  is required for correct use.

// You should include context, other arguments are optional

module.exports = function(context, yourTrigger, yourInput) {
    // your function code
    context.done();
};

If your function is async function. You don’t need to call the context.text. While your async function declaration of the Functions runtime, you do not need to explicitly call the context.done callback to signal that your function has been completed.

It is applicable from function version 2.x. If you are using function version 1.x you need to call the context.done callback.

module.exports = async function (context) {
    context.log(‘your log');
};

Note:

Explicitly calling done is unnecessary when writing an async function the done callback is called implicitly.

Refer here  for more information


问:
Heightmap on custom cube sphere Unity
How do I distort my custom cube sphere mesh with a heightmap texture? I would prefer to do this by script if possible.

I am trying to make a 3D model of the world but cannot figure out how to make a heightmap texture apply to my sphere. I have tried using getPixel.grayscale to change the y position of verts but I just get a 3D pizza slice. I have also tried to use the same method to change the radius at that point but still just a pizza slice.

My current sphere generation code is below I am using the cube sphere from Sebastian Lagues planet vidios.

Sphere.cs

```<code>public class Sphere : MonoBehaviour
{
private World world;
private ShapeSettings shapeSettings;

[HideInInspector]
public Material material;

[SerializeField, HideInInspector]
MeshFilter[] meshFilters;
SphereSide[] sphereSides;

public void GenerateSphere()
{
    Initialize();
    GenerateMesh();
}

void Initialize()
{
    world = gameObject.GetComponentInParent<World>();
    shapeSettings = world.shapeSettings;

    if (meshFilters == null || meshFilters.Length == 0)
    {
        meshFilters = new MeshFilter[6];
    }
    sphereSides = new SphereSide[6];

    Vector3[] directions = { Vector3.up, Vector3.down, Vector3.left, Vector3.right, Vector3.forward, Vector3.back };

    for (int i = 0; i < 6; i++)
    {
        if (meshFilters[i] == null)
        {
            GameObject meshObj = new GameObject("mesh");
            meshObj.transform.parent = transform;

            meshObj.AddComponent<MeshRenderer>();
            meshFilters[i] = meshObj.AddComponent<MeshFilter>();
            meshFilters[i].sharedMesh = new Mesh();
        }
        meshFilters[i].GetComponent<MeshRenderer>().sharedMaterial = material;

        sphereSides[i] = new SphereSide(world, meshFilters[i].sharedMesh, shapeSettings.resolution, directions[i]);
    }

    SphereCollider sc = gameObject.GetComponent<SphereCollider>();
    if (sc == null)
    {
        sc = gameObject.AddComponent<SphereCollider>() as SphereCollider;
        sc.radius = shapeSettings.worldRadius;
    }
    else if (sc.radius != shapeSettings.worldRadius)
        sc.radius = shapeSettings.worldRadius;
}

public void OnSettingsUpdated(Material Material)
{
    material = Material;
    GenerateSphere();
}

void GenerateMesh()
{
    foreach (SphereSide face in sphereSides)
    {
        face.ConstructMesh();
    }
}
}
</code>```

SphereSide.cs

```<code>public SphereSide(World world, Mesh mesh, int resolution, Vector3 localUp)
{
    this.world = world;
    this.mesh = mesh;
    this.resolution = resolution;
    this.localUp = localUp;

    axisA = new Vector3(localUp.y, localUp.z, localUp.x);
    axisB = Vector3.Cross(localUp, axisA);
}

private static Vector3 PointOnCubeToPointOnSphere(Vector3 p)
{
    float x2 = p.x * p.x;
    float y2 = p.y * p.y;
    float z2 = p.z * p.z;
    float x = p.x * Mathf.Sqrt(1 - (y2 + z2) / 2 + (y2 * z2) / 3);
    float y = p.y * Mathf.Sqrt(1 - (z2 + x2) / 2 + (z2 * x2) / 3);
    float z = p.z * Mathf.Sqrt(1 - (x2 + y2) / 2 + (x2 * y2) / 3);
    return new Vector3(x, y, z);
}

public void ConstructMesh()
{
    Vector3[] vertices = new Vector3[resolution * resolution];
    Vector2[] uvs = new Vector2[vertices.Length];
    int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6];
    int triIndex = 0;

    for (int y = 0; y < resolution; y++)
    {
        for (int x = 0; x < resolution; x++)
        {
            int i = x + y * resolution;
            Vector2 percent = new Vector2(x, y) / (resolution - 1);
            Vector3 pointOnUnitCube = localUp + (percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB;
            Vector3 pointOnUnitSphere = PointOnCubeToPointOnSphere(pointOnUnitCube);
            vertices[i] = pointOnUnitSphere * world.shapeSettings.worldRadius;

            if (x != resolution - 1 && y != resolution - 1)
            {
                triangles[triIndex] = i;
                triangles[triIndex + 1] = i + resolution + 1;
                triangles[triIndex + 2] = i + resolution;

                triangles[triIndex + 3] = i;
                triangles[triIndex + 4] = i + 1;
                triangles[triIndex + 5] = i + resolution + 1;
                triIndex += 6;
            }
        }
    }

    for (int i = 0; i < uvs.Length; i++)
        uvs[i] = new Vector2(vertices[i].x, vertices[i].z);

    mesh.Clear();
    mesh.vertices = vertices;
    mesh.uv = uvs;
    mesh.triangles = triangles;
    mesh.RecalculateNormals();
}
</code>```

Any help is much apreatiated.

答:
I have tried using getPixel.grayscale to change the y position of verts but I just get a 3D pizza slice.

You should apply height as offset aligned to its vertex normal.

I think  you are applying height as offset aligned to y-axis.

Title: Heightmap on custom cube sphere Unity

Body:
How do I distort my custom cube sphere mesh with a heightmap texture? I would prefer to do this by script if possible.

I am trying to make a 3D model of the world but cannot figure out how to make a heightmap texture apply to my sphere. I have tried using getPixel.grayscale to change the y position of verts but I just get a 3D pizza slice. I have also tried to use the same method to change the radius at that point but still just a pizza slice.

My current sphere generation code is below I am using the cube sphere from Sebastian Lagues planet vidios.

Sphere.cs

public class Sphere : MonoBehaviour
{
private World world;
private ShapeSettings shapeSettings;

[HideInInspector]
public Material material;

[SerializeField, HideInInspector]
MeshFilter[] meshFilters;
SphereSide[] sphereSides;

public void GenerateSphere()
{
    Initialize();
    GenerateMesh();
}

void Initialize()
{
    world = gameObject.GetComponentInParent<World>();
    shapeSettings = world.shapeSettings;

    if (meshFilters == null || meshFilters.Length == 0)
    {
        meshFilters = new MeshFilter[6];
    }
    sphereSides = new SphereSide[6];

    Vector3[] directions = { Vector3.up, Vector3.down, Vector3.left, Vector3.right, Vector3.forward, Vector3.back };

    for (int i = 0; i < 6; i++)
    {
        if (meshFilters[i] == null)
        {
            GameObject meshObj = new GameObject("mesh");
            meshObj.transform.parent = transform;

            meshObj.AddComponent<MeshRenderer>();
            meshFilters[i] = meshObj.AddComponent<MeshFilter>();
            meshFilters[i].sharedMesh = new Mesh();
        }
        meshFilters[i].GetComponent<MeshRenderer>().sharedMaterial = material;

        sphereSides[i] = new SphereSide(world, meshFilters[i].sharedMesh, shapeSettings.resolution, directions[i]);
    }

    SphereCollider sc = gameObject.GetComponent<SphereCollider>();
    if (sc == null)
    {
        sc = gameObject.AddComponent<SphereCollider>() as SphereCollider;
        sc.radius = shapeSettings.worldRadius;
    }
    else if (sc.radius != shapeSettings.worldRadius)
        sc.radius = shapeSettings.worldRadius;
}

public void OnSettingsUpdated(Material Material)
{
    material = Material;
    GenerateSphere();
}

void GenerateMesh()
{
    foreach (SphereSide face in sphereSides)
    {
        face.ConstructMesh();
    }
}
}

SphereSide.cs

public SphereSide(World world, Mesh mesh, int resolution, Vector3 localUp)
{
    this.world = world;
    this.mesh = mesh;
    this.resolution = resolution;
    this.localUp = localUp;

    axisA = new Vector3(localUp.y, localUp.z, localUp.x);
    axisB = Vector3.Cross(localUp, axisA);
}

private static Vector3 PointOnCubeToPointOnSphere(Vector3 p)
{
    float x2 = p.x * p.x;
    float y2 = p.y * p.y;
    float z2 = p.z * p.z;
    float x = p.x * Mathf.Sqrt(1 - (y2 + z2) / 2 + (y2 * z2) / 3);
    float y = p.y * Mathf.Sqrt(1 - (z2 + x2) / 2 + (z2 * x2) / 3);
    float z = p.z * Mathf.Sqrt(1 - (x2 + y2) / 2 + (x2 * y2) / 3);
    return new Vector3(x, y, z);
}

public void ConstructMesh()
{
    Vector3[] vertices = new Vector3[resolution * resolution];
    Vector2[] uvs = new Vector2[vertices.Length];
    int[] triangles = new int[(resolution - 1) * (resolution - 1) * 6];
    int triIndex = 0;

    for (int y = 0; y < resolution; y++)
    {
        for (int x = 0; x < resolution; x++)
        {
            int i = x + y * resolution;
            Vector2 percent = new Vector2(x, y) / (resolution - 1);
            Vector3 pointOnUnitCube = localUp + (percent.x - .5f) * 2 * axisA + (percent.y - .5f) * 2 * axisB;
            Vector3 pointOnUnitSphere = PointOnCubeToPointOnSphere(pointOnUnitCube);
            vertices[i] = pointOnUnitSphere * world.shapeSettings.worldRadius;

            if (x != resolution - 1 && y != resolution - 1)
            {
                triangles[triIndex] = i;
                triangles[triIndex + 1] = i + resolution + 1;
                triangles[triIndex + 2] = i + resolution;

                triangles[triIndex + 3] = i;
                triangles[triIndex + 4] = i + 1;
                triangles[triIndex + 5] = i + resolution + 1;
                triIndex += 6;
            }
        }
    }

    for (int i = 0; i < uvs.Length; i++)
        uvs[i] = new Vector2(vertices[i].x, vertices[i].z);

    mesh.Clear();
    mesh.vertices = vertices;
    mesh.uv = uvs;
    mesh.triangles = triangles;
    mesh.RecalculateNormals();
}

Any help is much apreatiated.


问:
extracting a list within a list in a tuple which happens to be in a pd.series
```<code>x=
[[(some text,[a]), (some text,[b]), (some text,[c]).........]]
   [[(some text,[d]), (some text,[e]), (some text,[f]).........]]
    [[(some text,[g]), (some text,[h]), (some text,[k]).........]]
    [[(some text,[i]), (some text,[x]), (some text,[y]).........]]
    [[(some text,[z]), (some text,[t]), (some text,[w]).........]]
    [[(some text,[t]), (some text,[g]), (some text,[u]).........]]

type(x)

pandas.core.series.Series
</code>```

I want to create a series that only contains the values of the list within the tuple such as those[a] or [u] or [w].

How can I extract? Thank you.

UPDATE: I realized the way I phrase the question was confusing. I changed it now. It represents my problem better. Basically, I need to extract all [a] or [u] or [w]row by row. This is tokenized text data, they are words in sentences. Sorry for the confusion.

答:
Given Series s,

```<code>s = pd.Series(x)
</code>```

we can first get take the first elements out (since each row is a nested list), explode it and use the str accessor to get the second elements in each tuple; then take the elements out from singleton lists to get the raw data. Then groupby the index, and join the tokens.

```<code>out = s.str[0].explode().str[1].str[0].groupby(level=0).apply(','.join)
</code>```

Output:

```<code>0    a,b,c
1    d,e,f
2    g,h,k
3    i,x,y
4    z,t,w
5    t,g,u
</code>```

Body:
x=
[[(some text,[a]), (some text,[b]), (some text,[c]).........]]
   [[(some text,[d]), (some text,[e]), (some text,[f]).........]]
    [[(some text,[g]), (some text,[h]), (some text,[k]).........]]
    [[(some text,[i]), (some text,[x]), (some text,[y]).........]]
    [[(some text,[z]), (some text,[t]), (some text,[w]).........]]
    [[(some text,[t]), (some text,[g]), (some text,[u]).........]]

type(x)

pandas.core.series.Series

I want to create a series that only contains the values of the list within the tuple such as those[a] or [u] or [w].

How can I extract? Thank you.

UPDATE: I realized the way I phrase the question was confusing. I changed it now. It represents my problem better. Basically, I need to extract all [a] or [u] or [w]row by row. This is tokenized text data, they are words in sentences. Sorry for the confusion.

Body:
Given Series s,

s = pd.Series(x)

we can first get take the first elements out (since each row is a nested list), explode it and use the str accessor to get the second elements in each tuple; then take the elements out from singleton lists to get the raw data. Then groupby the index, and join the tokens.

out = s.str[0].explode().str[1].str[0].groupby(level=0).apply(','.join)

Output:

0    a,b,c
1    d,e,f
2    g,h,k
3    i,x,y
4    z,t,w
5    t,g,u


问:
How can I import xhr-mock module right?
I have a problem with xhr-mock import (I'm using Jest framework). I have an exercise in which I must test a simple function that use XMLHttprequest. In order to do this I use the xhr-mock module and use 'setup' method in order to replace the global XMLHttpRequest object with the MockXMLHttpRequest. When I call 'setup' method from test I get the error: mockXHR.setup is not a function. Below there is my code.

const mockXHR = require('xhr-mock');
const { exampleFunction } = require('../function/exampleXHR');

describe('exampleXHR', () => {
    beforeEach(() => mockXHR.setup());

    test('xhr test', () => {
        exampleFunction();
    });

});
```

答:
For commonJS, use it like this:

var xhrMock = require("xhr-mock").default;

console.log(xhrMock.setup)
```

See: https://runkit.com/embed/gyrys612q3a2

Title: How can I import xhr-mock module right?

Body:
For commonJS, use it like this:

var xhrMock = require("xhr-mock").default;

console.log(xhrMock.setup)

See: https://runkit.com/embed/gyrys612q3a2


问:
How to find Min and Max in Python without using lists
I am completely lost on how to solve this problem. We are to write a program that asks a user for an amount of integers and then calculates the minimum and maximum from the integers the user enters. Below is the assignment:

Write a program that asks the user how many integers they would like to enter. You can assume they will enter an integer >= 1. The program will then prompt the user to enter that many integers. After all the numbers have been entered, the program should display the largest and smallest of those numbers (no, you cannot use lists, or any other material we haven't covered). When you run your program it should match the following format:

How many integers would you like to enter?
4
Please enter 4 integers.
-4
105
2
-7
min: -7
max: 105

Any help would be extremely appreciated

```<code>num_1 = int(input("How many integers would you like to enter?")) #enter an
integer greater than or equal to 1
print("Please enter", num_1, "integers.")
min = 0
max = 0
for i in range(0,num_1):
numbers = int(input()) #reads the integers one at a time
     if numbers > 0 a
       numbers = min
</code>```

答:
```<code>N = int(input())
smallest = 0
largest = 0
for i in range(N):
   entered_number = int(input())
   if (i == 0): #consider the first number is minimum first
       smallest = entered_number
   if(entered_number < smallest ):
       smallest = entered_number
   if(entered_number > largest):
       largest = entered_number
print (smallest)
print (largest)
</code>```

Body:
I am completely lost on how to solve this problem. We are to write a program that asks a user for an amount of integers and then calculates the minimum and maximum from the integers the user enters. Below is the assignment:

Write a program that asks the user how many integers they would like to enter. You can assume they will enter an integer >= 1. The program will then prompt the user to enter that many integers. After all the numbers have been entered, the program should display the largest and smallest of those numbers (no, you cannot use lists, or any other material we haven't covered). When you run your program it should match the following format:

How many integers would you like to enter?
4
Please enter 4 integers.
-4
105
2
-7
min: -7
max: 105

Any help would be extremely appreciated

num_1 = int(input("How many integers would you like to enter?")) #enter an
integer greater than or equal to 1
print("Please enter", num_1, "integers.")
min = 0
max = 0
for i in range(0,num_1):
numbers = int(input()) #reads the integers one at a time
     if numbers > 0 a
       numbers = min


问:
How do i display the username who posted the comment?
So far I am only able to display the username who is logged in at the moment, therefore, all the comments will be posted by the username who is logged in at the moment :(</p>
```<code>if (isset($_SESSION['username'])) {
  echo '<div class="media my-3">
    <img src="img/userprofile.png" width="54px" class="mr-3" alt="...">
    <div class="media-body">
      <p class="font-weight-bold my-0">'.$_SESSION['username'].' at '. $thread_time.'</p>
      <h5 class="mt-0">
        <a class="text-dark" href="thread.php?threadid=' . $id . '">'. $title .'</a>
      </h5>
      '. $desc .'
    </div>
  </div>';
}
</code>```

答: i think your using a username session value who is logged in....you need to to save the userId in the table while submitting the comments form and use the userId to show the username.</p>

Body:
So far I am only able to display the username who is logged in at the moment, therefore, all the comments will be posted by the username who is logged in at the moment :(

if (isset($_SESSION['username'])) {
  echo '

'.$_SESSION['username'].' at '. $thread_time.'

        '. $title .'

      '. $desc .'

';
}


问:
Join Dense_Rank query result to view on calculated field
I have a SQL view where I am adding transformations/calculated columns etc.

One of the columns needs to be true or false, based on the dense rank of a calculated ID over a category being < 12.

I have the results I need over the category in a seperate query

```<code>SELECT [cat], CASE WHEN DENSE_RANK () OVER (ORDER BY COUNT([id]) desc) < 12 THEN 'TRUE' ELSE 'FALSE' END As 'Top'
FROM [i].[dbo].[view]
GROUP BY [cat]
</code>```

This is giving me a table with two columns, the category name and a true/false based on the calculation (which is correct).

My problem stands in trying to join the result of this query back into the view that was used to create it.

I want to add the true/false value as a new column, joining on [id]. I have tried to use join functions, but as the [id] column was calculated as part of the view, it's throwing me errors that it's an invalid column name.

How do I go about joining the results to the view?

Thank you.

Edited to include sample data/results.

Right now my view contains lots of columns.

ID - is calculated by COALESCE, so it isn't in the original datatable, just a view column.

A very rough example of my table could be

```<code>A | B | C | D | Cat | ID
- | - | - | - | Red | 1
- | - | - | - | Red | 2
- | - | - | - | Blu | 1
- | - | - | - | Yel | 1
</code>```

In reality, there are about 30 categories and about 5000 distinct id's.

My query results returns a two column table

```<code>Cat | Top
Red | True
Blu | False
Yel | True
--- | ---
--- | ---
</code>```

What I need, is to either join the query results with the view, or to somehow include the query itself in the view select statement so my view reads

```<code>A | B | C | D | Cat | ID | top
- | - | - | - | Red | 1  | TRUE
- | - | - | - | Red | 2  | TRUE
- | - | - | - | Blu | 1  | FALSE
- | - | - | - | Yel | 1  | TRUE
</code>```

I hope this clears it up for everyone. Thank you.

答:
Your table

```<code>declare @R TABLE (
   A   VARCHAR(2) NOT NULL
  ,B   VARCHAR(3) NOT NULL
  ,C   VARCHAR(3) NOT NULL
  ,D   VARCHAR(3) NOT NULL
  ,Cat VARCHAR(5) NOT NULL
  ,ID  INT  NOT NULL
);
INSERT INTO @R(A,B,C,D,Cat,ID) VALUES
('-','-','-','-','Red',1),
('-','-','-','-','Red',2),
('-','-','-','-','Blu',1),
('-','-','-','-','Yel',1);
</code>```

result of query

```<code>DECLARE @T TABLE (
   Cat VARCHAR(4) NOT NULL PRIMARY KEY
  ,Top1 VARCHAR(6) NOT NULL
);
INSERT INTO @T(Cat ,Top1) VALUES
('Red','True'),
('Blu','False'),
('Yel','True');
</code>```

you should use your result query in cte, subquery , Table Variable and temp table in order to join it with your table

```<code>SELECT A,B,C,D,R.Cat,ID,Top1 FROM @R R
JOIN (SELECT Cat ,Top1 FROM @T) T
ON R.Cat=T.Cat
</code>```

Body:
I have a SQL view where I am adding transformations/calculated columns etc.

One of the columns needs to be true or false, based on the dense rank of a calculated ID over a category being < 12.

I have the results I need over the category in a seperate query

SELECT [cat], CASE WHEN DENSE_RANK () OVER (ORDER BY COUNT([id]) desc) < 12 THEN 'TRUE' ELSE 'FALSE' END As 'Top'
FROM [i].[dbo].[view]
GROUP BY [cat]

This is giving me a table with two columns, the category name and a true/false based on the calculation (which is correct).

My problem stands in trying to join the result of this query back into the view that was used to create it.

I want to add the true/false value as a new column, joining on [id]. I have tried to use join functions, but as the [id] column was calculated as part of the view, it's throwing me errors that it's an invalid column name.

How do I go about joining the results to the view?

Thank you.

Edited to include sample data/results.

Right now my view contains lots of columns.

ID - is calculated by COALESCE, so it isn't in the original datatable, just a view column.

A very rough example of my table could be

A | B | C | D | Cat | ID
- | - | - | - | Red | 1
- | - | - | - | Red | 2
- | - | - | - | Blu | 1
- | - | - | - | Yel | 1

In reality, there are about 30 categories and about 5000 distinct id's.

My query results returns a two column table

Cat | Top
Red | True
Blu | False
Yel | True
--- | ---
--- | ---

What I need, is to either join the query results with the view, or to somehow include the query itself in the view select statement so my view reads

A | B | C | D | Cat | ID | top
- | - | - | - | Red | 1  | TRUE
- | - | - | - | Red | 2  | TRUE
- | - | - | - | Blu | 1  | FALSE
- | - | - | - | Yel | 1  | TRUE

I hope this clears it up for everyone. Thank you.

Body:
Your table

declare @R TABLE (
   A   VARCHAR(2) NOT NULL
  ,B   VARCHAR(3) NOT NULL
  ,C   VARCHAR(3) NOT NULL
  ,D   VARCHAR(3) NOT NULL
  ,Cat VARCHAR(5) NOT NULL
  ,ID  INT  NOT NULL
);
INSERT INTO @R(A,B,C,D,Cat,ID) VALUES
('-','-','-','-','Red',1),
('-','-','-','-','Red',2),
('-','-','-','-','Blu',1),
('-','-','-','-','Yel',1);

result of query

DECLARE @T TABLE (
   Cat VARCHAR(4) NOT NULL PRIMARY KEY
  ,Top1 VARCHAR(6) NOT NULL
);
INSERT INTO @T(Cat ,Top1) VALUES
('Red','True'),
('Blu','False'),
('Yel','True');

you should use your result query in cte, subquery , Table Variable and temp table in order to join it with your table

SELECT A,B,C,D,R.Cat,ID,Top1 FROM @R R
JOIN (SELECT Cat ,Top1 FROM @T) T
ON R.Cat=T.Cat


问:
How to number rows with multiple condition using arrayformula on spreadsheet
Column Number is the numbers of column Integer starts on 1 and so on, and if there is multiple number on the column Integer so will the Number make multiple number too.

I succed using formula
=IF(B2="","",IF(ROW(B2)=2,1,IF(B2=B1,A1,A1+1)))

which is i should copy for each rows.
But i want a single formula that can apply for not blank colB such as using arrayformula but i haven't solved it yet.
Thanks for your time :).

Number
Integer

1
1

2
3

3
5

3
5

4
6

4
6

4
6

5
7

6
8

6
8

答:
use:

```<code>=ARRAYFORMULA(IFNA(VLOOKUP(B2:B, {UNIQUE(B2:B), SEQUENCE(COUNTUNIQUE(B2:B)+1)}, 2, 0)))
</code>```

Body:
use:

=ARRAYFORMULA(IFNA(VLOOKUP(B2:B, {UNIQUE(B2:B), SEQUENCE(COUNTUNIQUE(B2:B)+1)}, 2, 0)))


问:
How to tell if a user has updated a profile field in Drupal 7
I am trying to determine how in drupal 7 I can programmatically tell if a user has updated a custom field in their profile within the past 24 hours however looking through the tables I can't seem to find any field with that information does anyone have any ideas?? Essentially I need to pull this information out during a batch job that run onces a night and updates other systems based upon the information in drupal. If someone can think of a better way todo this it would be appreciated. thanks for any help you can provide</p>

答:
ok i dont know if its working or not try the following steps

1- first you should tell drupal....when user edit the profile page do something...(whatever the something is ..insert something to database..retrieve something..etc)

```<code>/**
* Implementation of hook_form_alter
*/
function newcontent_form_alter(&$form, &$form_state, $form_id){
if($form_id == 'user_profile_form'){
    $form['#submit'][]  = '_do_something_when_user_save_profile';
}
}

/**
* do something when user save profile
*/
function _do_something_when_user_save_profile($form,$form_state){
// do something
}
</code>```

now i think we need to do some queries ... first we need to create 2 tables
http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_schema/7
(this url will help you to create your schema)

the first table will contain the current value of the field u want track so i think this table should have the following fields
(primary key , user id, field name, field value)

the second table will contain the date of the last upated operation the user made
i think the fields will be like the following (primary key,user id , field name, date)

now lets return to the form submit function

```<code>/**
* do something when user save profile
*/
function _do_something_when_user_save_profile($form,$form_state){
   // now i can check in the first table to see
       // is the current submitted value for this field = the value in the table
       // if its = the table value then the user didn't change any thing now i dont
       // need to update the second table
       // if the current submitted value != the value in the table then its mean
       // that the user have updated this field ...
       // now i should insert new value to the second
       // table with the current date time and the current field value
}
</code>```

i hope u under stand me and sorry for my bad english

Body:
ok i dont know if its working or not try the following steps

1- first you should tell drupal....when user edit the profile page do something...(whatever the something is ..insert something to database..retrieve something..etc)

/**
* Implementation of hook_form_alter
*/
function newcontent_form_alter(&$form, &$form_state, $form_id){
if($form_id == 'user_profile_form'){
    $form['#submit'][]  = '_do_something_when_user_save_profile';
}
}

/**
* do something when user save profile
*/
function _do_something_when_user_save_profile($form,$form_state){
// do something
}

now i think we need to do some queries ... first we need to create 2 tables
http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_schema/7
(this url will help you to create your schema)

the first table will contain the current value of the field u want track so i think this table should have the following fields
(primary key , user id, field name, field value)

the second table will contain the date of the last upated operation the user made
i think the fields will be like the following (primary key,user id , field name, date)

now lets return to the form submit function

/**
* do something when user save profile
*/
function _do_something_when_user_save_profile($form,$form_state){
   // now i can check in the first table to see
       // is the current submitted value for this field = the value in the table
       // if its = the table value then the user didn't change any thing now i dont
       // need to update the second table
       // if the current submitted value != the value in the table then its mean
       // that the user have updated this field ...
       // now i should insert new value to the second
       // table with the current date time and the current field value
}

i hope u under stand me and sorry for my bad english


问:
We noticed that the different durations of your auto-renewable subscriptions were still created as separate in-app purchase products
i have create 3 different auto renew subscription of different duration in same subscription group.

Weekly,Monthly,Yearly within 1 subscription group.

App reject for below reason

Guideline 3.1.2 - Business - Payments - Subscriptions

We noticed that the different durations of your auto-renewable subscriptions were still created as separate in-app purchase products, rather than as different durations within the same subscription group.

答:
Firstly i have Created 3 in app purchase products in 3 subscription group. So From apple store, They rejected my app with the reason "We noticed that the different durations of your auto-renewable subscriptions in saperate Group."

After that i have created 3 new In app purchase products in and used them in my app. But i haven't remove it from apple developer Console and submit my app for review.so again they reject app with the same reason "We noticed that the different durations of your auto-renewable subscriptions in saperate Group."

After that i remove old In app purchase products from apple developer console and submit old binary for review and App Approved.

so just create new in app purchase product with same subscription group rather than different group and Remove OLD in app purchase IDS from apple developer console.


问:
Webpack, html-webpack-plugin, Error: Child compilation failed
I 've got a problem with my webpack configuration. After implementing html-webpack-plugin I got an Error, there's whole error stack from generated index.html.

Error Stack:
Html Webpack Plugin:```
  Error: Child compilation failed:
  Conflict: Multiple assets emit to the same filename index.html:
  Error: Conflict: Multiple assets emit to the same filename index.html</p>

<ul>
<li><p>compiler.js:76
[Pre-build]/[html-webpack-plugin]/lib/compiler.js:76:16</p></li>
<li><p>Compiler.js:291 Compiler.
[Pre-build]/[webpack]/lib/Compiler.js:291:10</p></li>
<li><p>Compiler.js:494
[Pre-build]/[webpack]/lib/Compiler.js:494:13</p></li>
<li><p>Tapable.js:138 next
[Pre-build]/[tapable]/lib/Tapable.js:138:11</p></li>
<li><p>CachePlugin.js:62 Compiler.
[Pre-build]/[webpack]/lib/CachePlugin.js:62:5</p></li>
<li><p>Tapable.js:142 Compiler.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:142:13</p></li>
<li><p>Compiler.js:491
[Pre-build]/[webpack]/lib/Compiler.js:491:10</p></li>
<li><p>Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46</p></li>
<li><p>Compilation.js:645 self.applyPluginsAsync.err
[Pre-build]/[webpack]/lib/Compilation.js:645:19</p></li>
<li><p>Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46</p></li>
<li><p>Compilation.js:636 self.applyPluginsAsync.err
[Pre-build]/[webpack]/lib/Compilation.js:636:11</p></li>
<li><p>Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46</p></li>
<li><p>Compilation.js:631 self.applyPluginsAsync.err
[Pre-build]/[webpack]/lib/Compilation.js:631:10</p></li>
<li><p>Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46</p></li>
<li><p>Compilation.js:627 sealPart2
[Pre-build]/[webpack]/lib/Compilation.js:627:9</p></li>
<li><p>Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46</p></li>
<li><p>Compilation.js:575 Compilation.seal
[Pre-build]/[webpack]/lib/Compilation.js:575:8</p></li>
<li><p>Compiler.js:488
[Pre-build]/[webpack]/lib/Compiler.js:488:16</p></li>
<li><p>Tapable.js:225
[Pre-build]/[tapable]/lib/Tapable.js:225:11</p></li>
<li><p>Compilation.js:477 _addModuleChain
[Pre-build]/[webpack]/lib/Compilation.js:477:11</p></li>
<li><p>Compilation.js:448 processModuleDependencies.err
[Pre-build]/[webpack]/lib/Compilation.js:448:13</p></li>
<li><p>next_tick.js:73 _combinedTickCallback
internal/process/next_tick.js:73:7</p></li>
<li><p>next_tick.js:104 process._tickCallback
internal/process/next_tick.js:104:9
```

My webpack configuration code:

```<code>var webpack = require('webpack'),
    path = require('path');

var CopyWebpackPlugin = require('copy-webpack-plugin'),
    ExtractTextWebpackPlugin = require('extract-text-webpack-plugin'),
    HtmlWebpackPlugin = require('html-webpack-plugin'),

const sourcePath = path.resolve(__dirname, './src');
const staticPath = path.resolve(__dirname, './static');

module.exports = function (env) {

    const nodeEnv = env && env.prod ? 'production' : 'development';
    const isProd = nodeEnv === 'production';

    const postcssLoader = {
        loader: 'postcss-loader',
        options: {
            plugins: function () {
                return [
                    require('autoprefixer')
                ];
            }
        }
    }

    const plugins = [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: Infinity,
            filename: 'vendor.bundle.js'
        }),
        new webpack.EnvironmentPlugin({
            NODE_ENV: nodeEnv,
        }),
        new HtmlWebpackPlugin({
            template: 'index.html',
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
            },
            chunksSortMode: 'dependency'
        })
    ];

    if(isProd) {
        plugins.push(
            new webpack.LoaderOptionsPlugin({
                minimize: true,
                debug: false
            }),
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false,
                    screw_ie8: true,
                    conditionals: true,
                    unused: true,
                    comparisons: true,
                    sequences: true,
                    dead_code: true,
                    evaluate: true,
                    if_return: true,
                    join_vars: true,
                },
                output: {
                    comments: false,
                },
            })
        );
    } else {
        plugins.push(
            new webpack.HotModuleReplacementPlugin()
        );
    }

    return {
        devtool: isProd? 'source-map' : 'eval',
        context: sourcePath,

        entry: {
            app: './app/entry.ts',
            vendor: './app/vendor.ts'
        },

        output: {
            path: staticPath,
            filename: '[name].bundle.js',
        },

        module: {
            rules: [
                {
                    test: /\.html$/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'file-loader',
                        query: {
                            name: '[name].[ext]'
                        },
                    },
                },
                {
                    test: /\.css$/,
                    exclude: /node_modules/,
                    use: [
                        'style-loader',
                        'css-loader',
                        'postcss-loader'
                    ]
                },
                {
                    test: /\.scss$/,
                    exclude: /node_modules/,
                    use: [
                        'style-loader',
                        'css-loader',
                        'postcss-loader',
                        'sass-loader'
                    ]
                },
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    use: [
                        'ts-loader'
                    ],
                },
            ],
        },

        resolve: {
            alias: {
                Public: path.resolve(__dirname,'src/public'),
                Style: path.resolve(__dirname,'src/styles')
            },
            extensions: ['.ts','.js', '.html'],
            modules: [
                path.resolve(__dirname, 'node_modules'),
                sourcePath
            ]
        },

        plugins,

        performance: isProd && {
            maxAssetSize: 100,
            maxEntrypointSize: 300,
            hints: 'warning'
        },

        stats: {
            colors: {
                green: '\u001b[32m'
            }
        },

        devServer: {
            contentBase: './src',
            historyApiFallback: true,
            port: 3000,
            compress: isProd,
            inline: !isProd,
            hot: !isProd,
            stats: {
                assets: true,
                children: false,
                chunks: false,
                hash: false,
                modules: false,
                publicPath: false,
                timings: true,
                version: false,
                warnings: true,
                color: {
                    green: '\u001b[32m'
                }
            },
        }
    };
};
</code>```

I couldn't find any source of that Error, maybe I am little bit tired, but I would like to finish it up, so I hope for your help guys.

Maybe should I use some raw-loader to load .html(?), which does not make me happy.

答:
I had to upgrade my node version. then the issue is fixed.

upgrade to latest node version(ubuntu)

```<code>sudo npm cache clean -f
sudo npm install -g n
sudo n stable
sudo n latest
</code>```

to check the version

```<code>node -v
</code>```

you might need to restart your terminal to see the latest version.

Body:
I 've got a problem with my webpack configuration. After implementing html-webpack-plugin I got an Error, there's whole error stack from generated index.html.

Error Stack:
Html Webpack Plugin:

  Error: Child compilation failed:
  Conflict: Multiple assets emit to the same filename index.html:
  Error: Conflict: Multiple assets emit to the same filename index.html

compiler.js:76
[Pre-build]/[html-webpack-plugin]/lib/compiler.js:76:16

Compiler.js:291 Compiler.
[Pre-build]/[webpack]/lib/Compiler.js:291:10

Compiler.js:494
[Pre-build]/[webpack]/lib/Compiler.js:494:13

Tapable.js:138 next
[Pre-build]/[tapable]/lib/Tapable.js:138:11

CachePlugin.js:62 Compiler.
[Pre-build]/[webpack]/lib/CachePlugin.js:62:5

Tapable.js:142 Compiler.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:142:13

Compiler.js:491
[Pre-build]/[webpack]/lib/Compiler.js:491:10

Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46

Compilation.js:645 self.applyPluginsAsync.err
[Pre-build]/[webpack]/lib/Compilation.js:645:19

Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46

Compilation.js:636 self.applyPluginsAsync.err
[Pre-build]/[webpack]/lib/Compilation.js:636:11

Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46

Compilation.js:631 self.applyPluginsAsync.err
[Pre-build]/[webpack]/lib/Compilation.js:631:10

Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46

Compilation.js:627 sealPart2
[Pre-build]/[webpack]/lib/Compilation.js:627:9

Tapable.js:131 Compilation.applyPluginsAsyncSeries
[Pre-build]/[tapable]/lib/Tapable.js:131:46

Compilation.js:575 Compilation.seal
[Pre-build]/[webpack]/lib/Compilation.js:575:8

Compiler.js:488
[Pre-build]/[webpack]/lib/Compiler.js:488:16

Tapable.js:225
[Pre-build]/[tapable]/lib/Tapable.js:225:11

Compilation.js:477 _addModuleChain
[Pre-build]/[webpack]/lib/Compilation.js:477:11

Compilation.js:448 processModuleDependencies.err
[Pre-build]/[webpack]/lib/Compilation.js:448:13

next_tick.js:73 _combinedTickCallback
internal/process/next_tick.js:73:7

next_tick.js:104 process._tickCallback
internal/process/next_tick.js:104:9

My webpack configuration code:

var webpack = require('webpack'),
    path = require('path');

var CopyWebpackPlugin = require('copy-webpack-plugin'),
    ExtractTextWebpackPlugin = require('extract-text-webpack-plugin'),
    HtmlWebpackPlugin = require('html-webpack-plugin'),

const sourcePath = path.resolve(__dirname, './src');
const staticPath = path.resolve(__dirname, './static');

module.exports = function (env) {

    const nodeEnv = env && env.prod ? 'production' : 'development';
    const isProd = nodeEnv === 'production';

    const postcssLoader = {
        loader: 'postcss-loader',
        options: {
            plugins: function () {
                return [
                    require('autoprefixer')
                ];
            }
        }
    }

    const plugins = [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: Infinity,
            filename: 'vendor.bundle.js'
        }),
        new webpack.EnvironmentPlugin({
            NODE_ENV: nodeEnv,
        }),
        new HtmlWebpackPlugin({
            template: 'index.html',
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
            },
            chunksSortMode: 'dependency'
        })
    ];

    if(isProd) {
        plugins.push(
            new webpack.LoaderOptionsPlugin({
                minimize: true,
                debug: false
            }),
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false,
                    screw_ie8: true,
                    conditionals: true,
                    unused: true,
                    comparisons: true,
                    sequences: true,
                    dead_code: true,
                    evaluate: true,
                    if_return: true,
                    join_vars: true,
                },
                output: {
                    comments: false,
                },
            })
        );
    } else {
        plugins.push(
            new webpack.HotModuleReplacementPlugin()
        );
    }

    return {
        devtool: isProd? 'source-map' : 'eval',
        context: sourcePath,

        entry: {
            app: './app/entry.ts',
            vendor: './app/vendor.ts'
        },

        output: {
            path: staticPath,
            filename: '[name].bundle.js',
        },

        module: {
            rules: [
                {
                    test: /\.html$/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'file-loader',
                        query: {
                            name: '[name].[ext]'
                        },
                    },
                },
                {
                    test: /\.css$/,
                    exclude: /node_modules/,
                    use: [
                        'style-loader',
                        'css-loader',
                        'postcss-loader'
                    ]
                },
                {
                    test: /\.scss$/,
                    exclude: /node_modules/,
                    use: [
                        'style-loader',
                        'css-loader',
                        'postcss-loader',
                        'sass-loader'
                    ]
                },
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    use: [
                        'ts-loader'
                    ],
                },
            ],
        },

        resolve: {
            alias: {
                Public: path.resolve(__dirname,'src/public'),
                Style: path.resolve(__dirname,'src/styles')
            },
            extensions: ['.ts','.js', '.html'],
            modules: [
                path.resolve(__dirname, 'node_modules'),
                sourcePath
            ]
        },

        plugins,

        performance: isProd && {
            maxAssetSize: 100,
            maxEntrypointSize: 300,
            hints: 'warning'
        },

        stats: {
            colors: {
                green: '\u001b[32m'
            }
        },

        devServer: {
            contentBase: './src',
            historyApiFallback: true,
            port: 3000,
            compress: isProd,
            inline: !isProd,
            hot: !isProd,
            stats: {
                assets: true,
                children: false,
                chunks: false,
                hash: false,
                modules: false,
                publicPath: false,
                timings: true,
                version: false,
                warnings: true,
                color: {
                    green: '\u001b[32m'
                }
            },
        }
    };
};

I couldn't find any source of that Error, maybe I am little bit tired, but I would like to finish it up, so I hope for your help guys.

Maybe should I use some raw-loader to load .html(?), which does not make me happy.

Body:
I had to upgrade my node version. then the issue is fixed.

upgrade to latest node version(ubuntu)

sudo npm cache clean -f
sudo npm install -g n
sudo n stable
sudo n latest

to check the version

node -v

you might need to restart your terminal to see the latest version.