问:
How can I run a function (to get side effects) when a python Mock is called?
I am mocking (using python Mock) a function where I want to return a list of values, but in some of the items in the list I want a side effect to also occur (at the point where the mocked function is called).  How is this most easily done?  I'm trying something like this:

```<code>import mock
import socket

def oddConnect():
  result = mock.MagicMock()  # this is where the return value would go
  raise socket.error  # I want it assigned but also this raised

socket.create_connection = mock(spec=socket.create_connection,
  side_effect=[oddConnect, oddConnect, mock.MagicMock(),])
# what I want: call my function twice, and on the third time return normally
# what I get: two function objects returned and then the normal return

for _ in xrange(3):
  result = None
  try:
    # this is the context in which I want the oddConnect function call
    # to be called (not above when creating the list)
    result = socket.create_connection()
  except socket.error:
    if result is not None:
      # I should get here twice
      result.close()
      result = None
  if result is not None:
    # happy days we have a connection
    # I should get here the third time
    pass
</code>```

The except clause (and it's internal if) I copied from the internals of socket and want to verify that I "test" that path through my copy of the code.  (I don't understand how socket can get to that code (setting the target while still raising an exception, but that isn't my concern, only the I verify that I can replicate that code path.)  That's why I want the side effect to happen when the mock is called and not when I build the list.

答:
I also encountered the problem of wanting a side effect to occur for only some items in a list of values.

In my case, I wanted to call a method from freezegun the third time my mocked method was called. These answers were really helpful for me; I ended up writing up a fairly general wrapper class, which I thought I'd share here:

class DelayedSideEffect:
    """
    If DelayedSideEffect.side_effect is assigned to a mock.side_effect, allows you to
    delay the first call of callback until after a certain number of iterations.
    """
    def __init__(self, callback, delay_until_call_num: int, return_value=DEFAULT):
        self.times_called = 0
        self.delay_until_call_num = delay_until_call_num
        self.callback = callback
        self.return_value = return_value

    def side_effect(self, *args, **kwargs):
        self.times_called += 1
        if self.times_called >= self.delay_until_call_num:
            self.callback()
        return self.return_value
```

<p>To then return "my_default_return_value" without calling the lambda function on the first three calls:</p>

<pre class="lang-py prettyprint-override"><code>with freeze_time(datetime.now()) as freezer:
    se = DelayedSideEffect(callback=lambda: freezer.move_to(the_future), 3)
    my_mock = MagicMock(return_value="my_default_return_value", side_effect=se)
</code>```

Body:
I am mocking (using python Mock) a function where I want to return a list of values, but in some of the items in the list I want a side effect to also occur (at the point where the mocked function is called).  How is this most easily done?  I'm trying something like this:

import mock
import socket

def oddConnect():
  result = mock.MagicMock()  # this is where the return value would go
  raise socket.error  # I want it assigned but also this raised

socket.create_connection = mock(spec=socket.create_connection,
  side_effect=[oddConnect, oddConnect, mock.MagicMock(),])
# what I want: call my function twice, and on the third time return normally
# what I get: two function objects returned and then the normal return

for _ in xrange(3):
  result = None
  try:
    # this is the context in which I want the oddConnect function call
    # to be called (not above when creating the list)
    result = socket.create_connection()
  except socket.error:
    if result is not None:
      # I should get here twice
      result.close()
      result = None
  if result is not None:
    # happy days we have a connection
    # I should get here the third time
    pass

The except clause (and it's internal if) I copied from the internals of socket and want to verify that I "test" that path through my copy of the code.  (I don't understand how socket can get to that code (setting the target while still raising an exception, but that isn't my concern, only the I verify that I can replicate that code path.)  That's why I want the side effect to happen when the mock is called and not when I build the list.

Body:
I also encountered the problem of wanting a side effect to occur for only some items in a list of values.

In my case, I wanted to call a method from freezegun the third time my mocked method was called. These answers were really helpful for me; I ended up writing up a fairly general wrapper class, which I thought I'd share here:

class DelayedSideEffect:
    """
    If DelayedSideEffect.side_effect is assigned to a mock.side_effect, allows you to
    delay the first call of callback until after a certain number of iterations.
    """
    def __init__(self, callback, delay_until_call_num: int, return_value=DEFAULT):
        self.times_called = 0
        self.delay_until_call_num = delay_until_call_num
        self.callback = callback
        self.return_value = return_value

    def side_effect(self, *args, **kwargs):
        self.times_called += 1
        if self.times_called >= self.delay_until_call_num:
            self.callback()
        return self.return_value

To then return "my_default_return_value" without calling the lambda function on the first three calls:

with freeze_time(datetime.now()) as freezer:
    se = DelayedSideEffect(callback=lambda: freezer.move_to(the_future), 3)
    my_mock = MagicMock(return_value="my_default_return_value", side_effect=se)


来源: stackexchange

问:
Cannot turn off short_open_tag with ini_set
I'm embedding a javascript syntax highlighter to a PHP script that reads source file and echos it back. The js highlighter has this string on one line:

... [z,/^[^<?]+/], ...

The short_open_tag is on on this server and the <? in the string confuses the script and causes errors. I cannot turn off in php.ini or elsewhere.

I have used ini_set('short_open_tag', '0'); in the same script, but it does not take effect. What could be the problem?

Edit

In the end, I used what Col Shrapnel suggested in a comment:

I changed [z,/^[^<?]+/], to [z,/^[^<?php echo '<' .'?'; ?>]+/],

答:
'short_open_tag' is marked as PHP_INI_PERDIR in PHP <5.3.0, which means you can't
change it with ini_set().</p>

ContentLicense: CC BY-SA 3.0


问:
How can I stop input with newline character
I am reading a list of numbers separated by spaces. Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\n') character. </p>

```<code>    int numArrayCount = 0;
    int num, count = 0;
    int binaryArray[CAPACITY];
    int numArray[CAPACITY];

    //takes in positive numbers higher than zero and less than 64.
    //End output with Ctrl+Z

    while (scanf_s( "%d", &num ) == 1) {
        if (num < 64 && num > 0) {
            binaryArray[ count++ ] = base10ToBinary(num);
            numArray[ numArrayCount++ ] = num;
        }
    }
</code>```

答:
How can I stop input with newline character (?)

Look for the '\n' with getchar() before scanf( "%d", &num ) as "%d" quietly consumes leading white-space including '\n'.

```<code>// concept code
int ch;
while (isspace(c = getchar())) {
  if (c == '\n') return "We are done, \\n"
}
if (c == EOF) return "We are done, EOF"
// put back
ungetc(c, stdin);
if (scanf( "%d", &num ) != 1) return "Non-numeric input";
return "Success";
</code>```

Full solution here for float.

An alternative approach uses fgets() and then pares the string.  This good approach does has trouble with long line management and fails should the line of input include an uncommon null character.

ContentLicense: CC BY-SA 4.0

Body:
I am reading a list of numbers separated by spaces. Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\n') character.

    int numArrayCount = 0;
    int num, count = 0;
    int binaryArray[CAPACITY];
    int numArray[CAPACITY];

    //takes in positive numbers higher than zero and less than 64.
    //End output with Ctrl+Z

    while (scanf_s( "%d", &num ) == 1) {
        if (num < 64 && num > 0) {
            binaryArray[ count++ ] = base10ToBinary(num);
            numArray[ numArrayCount++ ] = num;
        }
    }

Body:
How can I stop input with newline character (?)

Look for the '\n' with getchar() before scanf( "%d", &num ) as "%d" quietly consumes leading white-space including '\n'.

// concept code
int ch;
while (isspace(c = getchar())) {
  if (c == '\n') return "We are done, \\n"
}
if (c == EOF) return "We are done, EOF"
// put back
ungetc(c, stdin);
if (scanf( "%d", &num ) != 1) return "Non-numeric input";
return "Success";

Full solution here for float.

An alternative approach uses fgets() and then pares the string.  This good approach does has trouble with long line management and fails should the line of input include an uncommon null character.


问:
X-Frame-Options is not working in meta tag?
I want to restrict my site content to be used in other domains through iframe control. The recommented meta tag i.e <meta http-equiv="X-Frame-Options" content="deny"> is not working. What can i do?

答:
It will not work. Browser error: X-Frame-Options may only be set via an HTTP header sent along with a document. It may not be set inside .

Note: Setting the meta tag is useless! For instance,  has no effect. Do not use it! Only by setting through the HTTP header like the examples below, X-Frame-Options will work.

Source Link

Configuring Apache:

```<code>Header set X-Frame-Options "deny"
Header always set X-Frame-Options "sameorigin"
</code>```

Configuring nginx:

```<code>add_header X-Frame-Options sameorigin always;
</code>```

Configuring IIS:

```<code><system.webServer>
  ...
  <httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="sameorigin" />
    </customHeaders>
  </httpProtocol>
  ...
</system.webServer>
</code>```

X-Frame-Options is a mitigation technique for clickjacking attacks. It is an HTTP response header sent by the server to indicate under what circumstances page contents should be displayed in a frame context. A browser that understands the header will not display the contents of a page if the header directive is violated (for instance, if evil-example.com puts good-site.com in an iframe but good-site.com sends a header that says X-Frame-Options: DENY. Thus, no clickjacking can occur because no UI elements can be displayed to a victim.
It provides no protection against CSRF. Read more: clickjacking and .. , Security through HTTP response

Body:
It will not work. Browser error: X-Frame-Options may only be set via an HTTP header sent along with a document. It may not be set inside .

Note: Setting the meta tag is useless! For instance,  has no effect. Do not use it! Only by setting through the HTTP header like the examples below, X-Frame-Options will work.

Source Link

Configuring Apache:

Header set X-Frame-Options "deny"
Header always set X-Frame-Options "sameorigin"

Configuring nginx:

add_header X-Frame-Options sameorigin always;

Configuring IIS:

<system.webServer>
  ...
  <httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="sameorigin" />
    </customHeaders>
  </httpProtocol>
  ...
</system.webServer>

X-Frame-Options is a mitigation technique for clickjacking attacks. It is an HTTP response header sent by the server to indicate under what circumstances page contents should be displayed in a frame context. A browser that understands the header will not display the contents of a page if the header directive is violated (for instance, if evil-example.com puts good-site.com in an iframe but good-site.com sends a header that says X-Frame-Options: DENY. Thus, no clickjacking can occur because no UI elements can be displayed to a victim.
It provides no protection against CSRF. Read more: clickjacking and .. , Security through HTTP response


问:
Can the vanilla JS date object be used normally in React.js?
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

```<code>componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}
</code>```

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

```<code>{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}
</code>```

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

```<code>import React from "react";
import Calendar from "./Calendar"

function App() {
    return (
        <div>
            <Calendar />
        </div>

    )
}

export default App;
</code>```

File Calendar.js

```<code>import React from "react";
import Date from "./Date";

class Calendar extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;
</code>```

File Date.js

```<code>import React from "react";

function Date() {
    return (
        <div className="grid date">
            <p>1</p>
        </div>
    )
}

export default Date;
</code>```

答: Wow, I figured out the problem and the simplicity of it almost makes me wanna bash my head. Though I'm not sure about the specifics, it seems the naming of the Date component was interfering with the date object which is being instantiated. So I am assuming that somehow, although I was trying to output the Date object, I was actually outputting the Date component, hence the unknown object being the Date component with its corresponding classes grid date. If anyone can clarify what's going on in the nitty gritty, I'd love to hear it! Also, thank you for all your replies!</p>

Body:
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

import React from "react";
import Calendar from "./Calendar"

function App() {
    return (

            <Calendar />

    )
}

export default App;

File Calendar.js

import React from "react";
import Date from "./Date";

class Calendar extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;

File Date.js

import React from "react";

function Date() {
    return (

1

    )
}

export default Date;


问:
How to detect orientation change in IEMobile 7 with Javascript?
is there a way I can detect an orientation change in Internet Explorer Mobile 7? Since no orientationchange event is firred I guess the only way is to look wether the screen width has changed?

Perhaps someone has a better idea :)

答: Assuming that you mean from a web page, not from an application, then no there's no way to detect the orientation change directly, but as you suggest, you could detect the screen width change instead.</p>


问:
Error in calling crypto prices in Google Sheets
This command:

```<code>=VALUE(REGEXEXTRACT(IMPORTDATA("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD"), "{.+:(.+)}"))
</code>```

used to work just fine for ETH and BTC, but it is giving me this error now:

Error

  Function REGEXEXTRACT parameter 2 value "{.+:(.+)}" does not match text of
Function REGEXEXTRACT parameter 1 value "{"Response":"Error"".

What's the reason?

答: try it perhaps tomorrow (you probably reached the max limit of free API calls for the day)

Body:
This command:

=VALUE(REGEXEXTRACT(IMPORTDATA("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD"), "{.+:(.+)}"))

used to work just fine for ETH and BTC, but it is giving me this error now:

Error

  Function REGEXEXTRACT parameter 2 value "{.+:(.+)}" does not match text of
Function REGEXEXTRACT parameter 1 value "{"Response":"Error"".

What's the reason?


问:
How to retrieve HTTP Code and Content from IActionResult?
I've 7 actions in my controllers. I've refactored them an was able to isolate the common portion.

```<code>public IActionResult Get()
{
    var response = CommonCode();
}

public IActionResult Get(guid id)
{
    var response = CommonCode();
}

public IActionResult Post(ViewModel vm)
{
    var response = CommonCode();
}
</code>```

This is where I refactored the common code.

```<code>provate IActionResult CommonCode()
{
   if(userHasNoPermission())
     return Forbid();

   if(IdProvidedDoesntExist())
     return BadRequest();

   //...
}
</code>```

When I look inside the response, I see only one method: ExecuteResultAsync().

Is there a way to retrieve the HTTP code that I sent inside the helper method?

I'd like for instance to stop the processing if it's 500, retrieve the message to add to the ModelState* if it's 400, but proceed if it's OK.

答:
There are a few "filthy" ways you can do it without a case statement. The status code is actually in the result but IActionResult and ActionResult hate being cast to a common type.

This example takes a IActionResult from any common result and rips the status code out using reflection. If you don't mind doing it that way it saves requiring the case statement to pattern match. The same can be done for the content.

```<code>    public static HttpStatusCode GetHttpStatusCode(IActionResult functionResult)
    {
        try
        {
            return (HttpStatusCode)functionResult
                .GetType()
                .GetProperty("StatusCode")
                .GetValue(functionResult, null);
        }
        catch
        {
            return HttpStatusCode.InternalServerError;
        }
    }
</code>```

Body:
I've 7 actions in my controllers. I've refactored them an was able to isolate the common portion.

public IActionResult Get()
{
    var response = CommonCode();
}

public IActionResult Get(guid id)
{
    var response = CommonCode();
}

public IActionResult Post(ViewModel vm)
{
    var response = CommonCode();
}

This is where I refactored the common code.

provate IActionResult CommonCode()
{
   if(userHasNoPermission())
     return Forbid();

   if(IdProvidedDoesntExist())
     return BadRequest();

   //...
}

When I look inside the response, I see only one method: ExecuteResultAsync().

Is there a way to retrieve the HTTP code that I sent inside the helper method?

I'd like for instance to stop the processing if it's 500, retrieve the message to add to the ModelState* if it's 400, but proceed if it's OK.

Body:
There are a few "filthy" ways you can do it without a case statement. The status code is actually in the result but IActionResult and ActionResult hate being cast to a common type.

This example takes a IActionResult from any common result and rips the status code out using reflection. If you don't mind doing it that way it saves requiring the case statement to pattern match. The same can be done for the content.

    public static HttpStatusCode GetHttpStatusCode(IActionResult functionResult)
    {
        try
        {
            return (HttpStatusCode)functionResult
                .GetType()
                .GetProperty("StatusCode")
                .GetValue(functionResult, null);
        }
        catch
        {
            return HttpStatusCode.InternalServerError;
        }
    }


问:
android material button icon center vertically
I am trying to use the material components button with an icon, but the icon does not appear vertically centered. I want the phone icon centered vertically with the text.

```<code><com.google.android.material.button.MaterialButton
                android:id="@+id/callButton"
                style="@style/PrimaryButtonRoundedCorner"
                android:layout_width="match_parent"
                android:layout_gravity="center"
                android:layout_marginStart="@dimen/default_margin_medium"
                android:layout_marginTop="@dimen/default_margin_large"
                android:layout_marginEnd="@dimen/default_margin_medium"
                android:gravity="center"
                android:text="@string/call_kris_bodnar"
                app:icon="@drawable/ic_phone"
                app:iconGravity="start"
                app:iconTint="@color/wireframe_dark_gray"/>

<style name="PrimaryButtonRoundedCorner" parent="Widget.MaterialComponents.Button.Icon">
        <item name="textAllCaps">true</item>
        <item name="backgroundTint">@color/white</item>
        <item name="android:layout_height">@dimen/button_height</item>
        <item name="android:textColor">@color/colorPrimaryDark</item>
        <item name="android:textSize">@dimen/text_size_small</item>
        <item name="android:textStyle">bold</item>
        <item name="cornerRadius">@dimen/button_corner_radius</item>s
    </style>
</code>```

Vector drawable xml.

```<code><vector android:height="24dp" android:viewportHeight="24"
    android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#4A4A4A" android:fillType="evenOdd"
        android:pathData="M3.2178,8.2228C4.4978,11.21 6.56,13.6483 9.0756,15.1789L11.0311,12.8567C11.2711,12.5717 11.6267,12.4767 11.9378,12.6033C12.9333,12.9939 14.0089,13.205 15.1111,13.205C15.6,13.205 16,13.68 16,14.2606L16,17.9444C16,18.525 15.6,19 15.1111,19C6.7644,19 0,10.9672 0,1.0556C0,0.475 0.4,0 0.8889,0L4,0C4.4889,0 4.8889,0.475 4.8889,1.0556C4.8889,2.375 5.0667,3.6417 5.3956,4.8239C5.4933,5.1933 5.4222,5.605 5.1733,5.9006L3.2178,8.2228L3.2178,8.2228Z"
        android:strokeColor="#00000000" android:strokeWidth="1"/>
</vector>
</code>```

I am using version implementation "com.google.android.material:material:1.1.0-alpha06"

Any idea?
Many thanks

答:
i don't know much about the MaterialButton , i have never used it before but assuming it is still a button, add drawable padding </p>

```<code>       android:drawablePadding="8dp"
</code>```

Body:
I am trying to use the material components button with an icon, but the icon does not appear vertically centered. I want the phone icon centered vertically with the text.

<com.google.android.material.button.MaterialButton
                android:id="@+id/callButton"
                style="@style/PrimaryButtonRoundedCorner"
                android:layout_width="match_parent"
                android:layout_gravity="center"
                android:layout_marginStart="@dimen/default_margin_medium"
                android:layout_marginTop="@dimen/default_margin_large"
                android:layout_marginEnd="@dimen/default_margin_medium"
                android:gravity="center"
                android:text="@string/call_kris_bodnar"
                app:icon="@drawable/ic_phone"
                app:iconGravity="start"
                app:iconTint="@color/wireframe_dark_gray"/>

Vector drawable xml.

<vector android:height="24dp" android:viewportHeight="24"
    android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#4A4A4A" android:fillType="evenOdd"
        android:pathData="M3.2178,8.2228C4.4978,11.21 6.56,13.6483 9.0756,15.1789L11.0311,12.8567C11.2711,12.5717 11.6267,12.4767 11.9378,12.6033C12.9333,12.9939 14.0089,13.205 15.1111,13.205C15.6,13.205 16,13.68 16,14.2606L16,17.9444C16,18.525 15.6,19 15.1111,19C6.7644,19 0,10.9672 0,1.0556C0,0.475 0.4,0 0.8889,0L4,0C4.4889,0 4.8889,0.475 4.8889,1.0556C4.8889,2.375 5.0667,3.6417 5.3956,4.8239C5.4933,5.1933 5.4222,5.605 5.1733,5.9006L3.2178,8.2228L3.2178,8.2228Z"
        android:strokeColor="#00000000" android:strokeWidth="1"/>
</vector>

I am using version implementation "com.google.android.material:material:1.1.0-alpha06"

Any idea?
Many thanks

Body:
i don't know much about the MaterialButton , i have never used it before but assuming it is still a button, add drawable padding

       android:drawablePadding="8dp"


问:
Don't Abort build job which was triggered by another build job that was triggered manually
Exclude to Abort/Stop a running build job (example: Job-B) which was triggered by job (example: Job A) where Job A was manually triggered.

I am able to get the details of the job whether started manually or not by using the below code.

```<code>def was_previous_build_triggered_manually() {
    for (cause in currentBuild?.rawBuild?.getPreviousBuild()?.getCauses()) {
        if (cause.getShortDescription() =~ 'Started by user') {
            return true
        }
    }
    return false
}
</code>```

So I just need to add some condition here - to check whether the job is triggered by another job which was triggered manually (since I already have the above  code to check whether it is manually triggered or not)

答:
We use a shared library to evaluate causes for a few different conditions. Same as yours, checking if its an automated build vs user invoked (two different causes could mean user invoked).

One function to retrieve the causes into a nice list.

One function to evaluate true/false if relevant causes are present.

Simple if condition to gate.

Our shared library under /vars jobCauses.groovy

```<code>    /**
     * Checks if job causes contain automated causes
     * Return true if automated cause found
     *
     * @return boolean
     */
    boolean hasAutomatedCauses() {

        List automatedCauses = ['UpstreamCause', 'TimerTriggerCause']

        List intersection = []
        intersection = automatedCauses.intersect(getCauses())

        // if no automated causes are found means intersection is empty and then return false
        return !intersection.isEmpty()
    }

    /**
     * Checks if job causes contain Non-automated causes
     * Either
     *** Run by a User
    *** Rebuilt by a User
    *** Replayed by a User
    * Return true if  non automated cause found
    *
    * @return boolean
    */
    boolean hasNonAutomatedCauses() {

        List nonAutomatedCauses = ['UserIdCause', 'ReplayCause']

        List intersection = []
        intersection = nonAutomatedCauses.intersect(getCauses())
        // if no user triggered causes are found means intersection is empty and then return false
        return !intersection.isEmpty()
    }

    /**
     * Retrieves list of causes that generated job execution
     *
     * @return list
     */
    List getCauses() {

        return currentBuild.rawBuild.getCauses().collect { it.getClass().getCanonicalName().tokenize('.').last() }

    }
</code>```

In our Jenkinsfile:

```<code>Boolean isHumanTriggered = jobCauses.hasNonAutomatedCauses()
if ( isHumanTriggered ) {
    //do the thing
}
</code>```

Body:
Exclude to Abort/Stop a running build job (example: Job-B) which was triggered by job (example: Job A) where Job A was manually triggered.

I am able to get the details of the job whether started manually or not by using the below code.

def was_previous_build_triggered_manually() {
    for (cause in currentBuild?.rawBuild?.getPreviousBuild()?.getCauses()) {
        if (cause.getShortDescription() =~ 'Started by user') {
            return true
        }
    }
    return false
}

So I just need to add some condition here - to check whether the job is triggered by another job which was triggered manually (since I already have the above  code to check whether it is manually triggered or not)

Body:
We use a shared library to evaluate causes for a few different conditions. Same as yours, checking if its an automated build vs user invoked (two different causes could mean user invoked).

One function to retrieve the causes into a nice list.

One function to evaluate true/false if relevant causes are present.

Simple if condition to gate.

Our shared library under /vars jobCauses.groovy

    /**
     * Checks if job causes contain automated causes
     * Return true if automated cause found
     *
     * @return boolean
     */
    boolean hasAutomatedCauses() {

        List automatedCauses = ['UpstreamCause', 'TimerTriggerCause']

        List intersection = []
        intersection = automatedCauses.intersect(getCauses())

        // if no automated causes are found means intersection is empty and then return false
        return !intersection.isEmpty()
    }

    /**
     * Checks if job causes contain Non-automated causes
     * Either
     *** Run by a User
    *** Rebuilt by a User
    *** Replayed by a User
    * Return true if  non automated cause found
    *
    * @return boolean
    */
    boolean hasNonAutomatedCauses() {

        List nonAutomatedCauses = ['UserIdCause', 'ReplayCause']

        List intersection = []
        intersection = nonAutomatedCauses.intersect(getCauses())
        // if no user triggered causes are found means intersection is empty and then return false
        return !intersection.isEmpty()
    }

    /**
     * Retrieves list of causes that generated job execution
     *
     * @return list
     */
    List getCauses() {

        return currentBuild.rawBuild.getCauses().collect { it.getClass().getCanonicalName().tokenize('.').last() }

    }

In our Jenkinsfile:

Boolean isHumanTriggered = jobCauses.hasNonAutomatedCauses()
if ( isHumanTriggered ) {
    //do the thing
}


问:
Optimization of CodeWars Python 3.6 code: Factorial decomposition
I need help about optimizing my codewars code that named factorial decomposing. The aim of the kata is to decompose n! (factorial n) into its prime factors. The result has to return string like that;

n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"

My code is working properly and passing tests but when i try to attempt my code, i take time out error. Here is my try;

def decomp(n):

    number_count = {2 : 1}
    return_str = ""

    def add_list(num):
        if num not in number_count:
            number_count[num] = 1
        else:
            number_count[num] += 1

    for x in range(n, 1, -1):
        add = False
        for y in range(1, x):
            if x == 1 or y == 1: continue
            a = True
            while a:
                if x % y == 0 and y != 1:
                    x = int(x / y)
                    add_list(y)
                else:
                    a = False
                    add = True

        if add and x != 1:
            add_list(x)

    number_count3 = {k: number_count[k] for k in sorted(number_count.keys())}

    for x, y in number_count3.items():
        if y == 1:
            return_str += str(x) + " * "
        else:
            return_str += str(x) + "^" + str(y) + " * "

    return return_str[:-3]
```

答:
You can improve this be taking advantage of some number theory. For a factorial like 12!, there will be

```<code>12//2 + 6//2 + 3//2
</code>```

factors of two. Similar patterns will hold for all the other primes. So you can make a list of primes smaller than n and quickly decompose the exponent with something like:

```<code>def primes(n):
    n += 1
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

def mults(n):
    res = []
    for p in primes(n):
        rest = n
        s = 0
        while rest >0:
            j = rest // p
            s += j
            rest = j
        if s > 1:
            res.append(f'{p}^{s}')
        else:
            res.append(str(p))
    return ' * '.join(res)

mults(16)
</code>```

Result

```<code>'2^15 * 3^6 * 5^3 * 7^2 * 11 * 13'
</code>```

Timing it compared to the original gives:

```<code>%timeit decomp(22)
54 µs ± 201 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit mults(22)
8.23 µs ± 30.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Which seems to be a decent improvement. The difference is more pronounced with larger n:

```<code>%timeit decomp(130)
823 µs ± 965 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit mults(130)
25.4 µs ± 73 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Body:
You can improve this be taking advantage of some number theory. For a factorial like 12!, there will be

12//2 + 6//2 + 3//2

factors of two. Similar patterns will hold for all the other primes. So you can make a list of primes smaller than n and quickly decompose the exponent with something like:

def primes(n):
    n += 1
    sieve = [True] * n
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i]:
            sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
    return [2] + [i for i in range(3,n,2) if sieve[i]]

def mults(n):
    res = []
    for p in primes(n):
        rest = n
        s = 0
        while rest >0:
            j = rest // p
            s += j
            rest = j
        if s > 1:
            res.append(f'{p}^{s}')
        else:
            res.append(str(p))
    return ' * '.join(res)

mults(16)

Result

'2^15 * 3^6 * 5^3 * 7^2 * 11 * 13'

Timing it compared to the original gives:

%timeit decomp(22)
54 µs ± 201 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit mults(22)
8.23 µs ± 30.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Which seems to be a decent improvement. The difference is more pronounced with larger n:

%timeit decomp(130)
823 µs ± 965 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit mults(130)
25.4 µs ± 73 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)


问:
What does this Python code do? Explanation of brackets
Can you explain these lines?
I can't understand what's happening in brackets (j,pbase).

```<code>mults = {}
if c in mults:
    (j,pbase) = mults.pop(c)
</code>```

答:
Unpacking a tuple:

```<code>(j,pbase) = mults.pop(c)
</code>```

Is the same as:

```<code>x = mults.pop(c)
j = x[0]
pbase = x[1]
</code>```

Body:
Can you explain these lines?
I can't understand what's happening in brackets (j,pbase).

mults = {}
if c in mults:
    (j,pbase) = mults.pop(c)

Body:
Unpacking a tuple:

(j,pbase) = mults.pop(c)

Is the same as:

x = mults.pop(c)
j = x[0]
pbase = x[1]


问:
ORA-24247: Access denied by ACL from within PL/SQL function but NOT from SQL
I've successfully set up the ACL for my user and URL.
I confirm this by running:

```<code>select utl_http.request(*my URL*)
from   dual;
</code>```

which returns the corresponding HTML code.

However, when I place this code inside a PL/SQL function, as follows:

```<code>create or replace function temp_func (p_url varchar2)
return varchar2 is
    v_output varchar2(1000);
begin
    select  utl_http.request(p_url)
    into    v_output
    from    dual;

    return v_output;
end;
</code>```

and run this code from an anonymous PL/SQL block:

```<code>declare
    v_result varchar2(1000);
begin
    v_result := temp_func(*my URL*);
    dbms_output.put_line(v_result);
end;
</code>```

I get the following error stack:

```<code>Error report -
ORA-29273: HTTP request failed
ORA-06512: at "SYS.UTL_HTTP", line 1722
ORA-24247: network access denied by access control list (ACL)
ORA-06512: at line 1
ORA-06512: at "SIEF.TEMP_FUNC", line 7
ORA-06512: at line 4
29273. 00000 -  "HTTP request failed"
*Cause:    The UTL_HTTP package failed to execute the HTTP request.
*Action:   Use get_detailed_sqlerrm to check the detailed error message.
           Fix the error and retry the HTTP request.
</code>```

Is there any way to fix this?

I was reading https://support.oracle.com/knowledge/Oracle%20Database%20Products/1074843_1.html
and the closest thing I find is:
'4. Granting the ACL via roles does not work when the service is requested through from a PLSQL procedure',
however, I did not use roles while setting up the ACL.

Thank you!

My database version:

```<code>Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
PL/SQL Release 11.2.0.3.0 - Production
"CORE   11.2.0.3.0  Production"
TNS for Linux: Version 11.2.0.3.0 - Production
NLSRTL Version 11.2.0.3.0 - Production
</code>```

My ACL setup:

```<code>-- Creating ACL
begin
    dbms_network_acl_admin.create_acl(
        acl         => 'WS_test_acl.xml',
        description => 'ACL file for testing purposes.',
        principal   => *my user*,
        is_grant    => TRUE,
        privilege   => 'connect');
end;
-- Adding URL to ACL
begin
    dbms_network_acl_admin.assign_acl(
        acl         => 'WS_test_acl.xml',
        host        => *my URL*);
end;
</code>```

答:
When things work in anonymous blocks but not in stored procedures it's usually because of definer's rights versus invoker's rights.  Anonymous blocks and invoker's rights procedures can use privileges granted through roles, but definer's rights procedures cannot.

Try changing return varchar2 is to return varchar2 authid current_user is.

Body:
I've successfully set up the ACL for my user and URL.
I confirm this by running:

select utl_http.request(*my URL*)
from   dual;

which returns the corresponding HTML code.

However, when I place this code inside a PL/SQL function, as follows:

create or replace function temp_func (p_url varchar2)
return varchar2 is
    v_output varchar2(1000);
begin
    select  utl_http.request(p_url)
    into    v_output
    from    dual;

    return v_output;
end;

and run this code from an anonymous PL/SQL block:

declare
    v_result varchar2(1000);
begin
    v_result := temp_func(*my URL*);
    dbms_output.put_line(v_result);
end;

I get the following error stack:

Error report -
ORA-29273: HTTP request failed
ORA-06512: at "SYS.UTL_HTTP", line 1722
ORA-24247: network access denied by access control list (ACL)
ORA-06512: at line 1
ORA-06512: at "SIEF.TEMP_FUNC", line 7
ORA-06512: at line 4
29273. 00000 -  "HTTP request failed"
*Cause:    The UTL_HTTP package failed to execute the HTTP request.
*Action:   Use get_detailed_sqlerrm to check the detailed error message.
           Fix the error and retry the HTTP request.

Is there any way to fix this?

I was reading https://support.oracle.com/knowledge/Oracle%20Database%20Products/1074843_1.html
and the closest thing I find is:
'4. Granting the ACL via roles does not work when the service is requested through from a PLSQL procedure',
however, I did not use roles while setting up the ACL.

Thank you!

My database version:

Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
PL/SQL Release 11.2.0.3.0 - Production
"CORE   11.2.0.3.0  Production"
TNS for Linux: Version 11.2.0.3.0 - Production
NLSRTL Version 11.2.0.3.0 - Production

My ACL setup:

-- Creating ACL
begin
    dbms_network_acl_admin.create_acl(
        acl         => 'WS_test_acl.xml',
        description => 'ACL file for testing purposes.',
        principal   => *my user*,
        is_grant    => TRUE,
        privilege   => 'connect');
end;
-- Adding URL to ACL
begin
    dbms_network_acl_admin.assign_acl(
        acl         => 'WS_test_acl.xml',
        host        => *my URL*);
end;


问:
How to check specific elements of a list for a string value?
So im coding Tic Tac Toe

Ive created the environment as a list of 9 elements as shown below -

```<code>board=[' ']*9
</code>```

I then place the X or O in the board

```<code>board[move-1] = 'X'
</code>```

which works fine

The issue I'm having is after placing the X or O, im not able to check for the win condition. The output always returns as false check the output here

```<code>if (board[0] and board[1] and board[2] == 'X') or (board[0] and board[1] and board[2] == 'O') :
    return winner==1
</code>```

in the above code even when index 0,1 and 2 are X, it returns winner as false.

I think this is a simple string handling issue but I'm not really sure. Any help would be appreciated.

答:
Try using the following for the if statements: all will be True if all the 3 elements of board are either X. The same applies to O

```<code>if all(board[i]=='X' for i in range(3)) or all(board[i]=='O' for i in range(3)):
    return winner==1
</code>```

Body:
So im coding Tic Tac Toe

Ive created the environment as a list of 9 elements as shown below -

board=[' ']*9

I then place the X or O in the board

board[move-1] = 'X'

which works fine

The issue I'm having is after placing the X or O, im not able to check for the win condition. The output always returns as false check the output here

if (board[0] and board[1] and board[2] == 'X') or (board[0] and board[1] and board[2] == 'O') :
    return winner==1

in the above code even when index 0,1 and 2 are X, it returns winner as false.

I think this is a simple string handling issue but I'm not really sure. Any help would be appreciated.

Body:
Try using the following for the if statements: all will be True if all the 3 elements of board are either X. The same applies to O

if all(board[i]=='X' for i in range(3)) or all(board[i]=='O' for i in range(3)):
    return winner==1


问:
Html Table Button Taking too much space
I want make two buttons sit next to each other within the same cell. How can I go about that without having alot space in the cell. Only Enough space to have the buttons sit in comfortable space between each other.

I have used display: inline-block; as well as display:block and style='white-space: nowrap'. Have looked at similar questions and their answers don't work with my project.

    Employee Name
    Email Address
    Action

    Johnny Depp
    hotdog69@gmail.com

      <button type="button">Add</button>
      <button type="button">Edit</button>

```

When one or two buttons are present within a cell, they create this super long horizontal cell. The buttons are also far apart from each other.

答:
Maybe you need to use the command  "colspan". For example...</p>

```<code><tr>
    <th>Name</th>
    <th colspan="2">Address</th>
</tr>
</code>```

Title: Html Table Button Taking too much space

Body:
I want make two buttons sit next to each other within the same cell. How can I go about that without having alot space in the cell. Only Enough space to have the buttons sit in comfortable space between each other.

I have used display: inline-block; as well as display:block and style='white-space: nowrap'. Have looked at similar questions and their answers don't work with my project.

    Employee Name
    Email Address
    Action

    Johnny Depp
    hotdog69@gmail.com

      <button type="button">Add</button>
      <button type="button">Edit</button>

When one or two buttons are present within a cell, they create this super long horizontal cell. The buttons are also far apart from each other.

Body:
Maybe you need to use the command  "colspan". For example...

<tr>
    <th>Name</th>
    <th colspan="2">Address</th>
</tr>


问:
Output using 2 conditions, second condition will use one of 2 different formulas
Currently trying to make this formula using IF/IFS , AND
currently looks like this: =IF((D7=Yes)AND(C7>2500),C7*E5)
so I am trying to check for 2 conditions

I have a cell that has a "yes, no" pull down. So it is checking for a yes

if it is yes then it should check if another cell is less than 2500.

If it is >2500, then a specific formula should be used (C7*E5)

If it was <2500, then it would use a different formula (basically the same, just E5 would be F%, fulling from a different number.

I am not sure if I am on the right track at all.

I have tried using AND, IF, IFS. I am sure I am close but not doing the right combo.

答:
this is how you do it:

```<code>=IF(AND(D7="Yes"; C7>2500); C7*E5; C7*F5)
</code>```

unless you want it like this:

```<code>=IF(D7="Yes"; IF(C7>2500; C7*E5; C7*F5); )
</code>```

Body:
this is how you do it:

=IF(AND(D7="Yes"; C7>2500); C7*E5; C7*F5)

unless you want it like this:

=IF(D7="Yes"; IF(C7>2500; C7*E5; C7*F5); )


问:
Why does std::array not have an operator T*?
With C arrays, it's been the case that simply naming an array has the same effect as writing &foo[0] for something approaching 50 years.

When converting from C style arrays to std::array<> in a project I'm working on, the vast majority of "error"s that appeared were due to the above property of C arrays.

In all cases, the solution was trivial, just append .data().  However it occurred to me that a carefully crafted operator T* ought to directly solve this issue.

Is there any technical reason this operator could not be created?

答:
Is there any good reason this operator doesn't exist?

If you mean why there is no operator T*() to automatically provide the cast, one (of multiple) potential reasons is exactly that -- the idea of automatic casting.

Maybe it would be convenient to have the code using std::array to just compile correctly by utilizing operator T*(), and away you go with a program that has been built with no errors.  However there are some implications to this:

1) The call to operator T*() is a potential runtime cost that the programmer may not have desired, but just comes along for the ride.  In C++, the goal is to only pay for what is desired, and having casting operators just impose themselves goes against this idea.

2) operator T*() and casting operators in general can potentially hide bugs or
    bottlenecks in running code, due to usage that the programmer is not aware of.

In my experience, ask a programmer that has a code base littered with casting operators what functions are actually being called, and more times than not, they are not sure what path their code is taking, or they are just plain wrong (and don't realize it until they partake in a debugging session and see all the twists and turns being done by the seemingly innocent casting operators being invoked).

Thus it is deemed far safer for the programmer to explicitly want to "convert" the data by calling a function such as data(), and not by utilizing a operator T*() they may not have been aware of.


问:
How to exactly match the previous group including case insensitivity?
I think this is something that simply does not exist. But I know that some of the functionality exists in other regex engines, I'm hoping they maybe something similar to this.

```<code>pattern = r"""
    ([a-zA-Z])    # Match a single letter and capture it as group1
    .*?           # random matches in between
    \1            # Match whatever capture group1 matched
"""
</code>```

Now this matches AA, bb and so on. So far so good in python.
Now some language (idk if python regex engine does) allows

```<code>pattern = r"""
    ([a-zA-Z])    # Match a single letter and capture it as group1
    .*?           # random matches in between
    \U1           # Match group1 in upper case
"""
</code>```

There are couple of "function" like this that allows you to somewhat manipulate the prev capture groups but they are very limited from what I read at some regex website

Now my question is that, is it possible to write our own "functions" for regex to use somewhat like

```<code>@re.register_function('X')
def between_x(group):
    return f'X{group}X'
</code>```

and then

```<code>pattern = r"""
    ([a-zA-Z]{2})    # Match a single letter and capture it as group1
    .*?              # random matches in between
    (\X1)            # Match if the previous group is inbetween Xes.
"""
# For example, AArandomletterXAAX would match and group1 would be AA
# and second group would be XAAX
</code>```

Doesn't need to be the re module, I'm open to any other regex engines.

As an example the pattern should match

```<code>string: "hello...HELLO"
</code>```

and not match

```<code>string: "hello...hello"
</code>```

given that our function is

```<code>def f(group):
    return group.upper()
</code>```

答:
This question is quite interesting, and I'm sure it has a great solution, if I understand it correctly.

We can maybe start with an expression with three sub-expressions:

```<code>([a-z]+)(.+?)((?=.+[A-Z].+)(?i:\1))
</code>```

Here we are having a starting lowercase word:

```<code>([a-z]+)
</code>```

followed by anything in between:

```<code> (.+?)
</code>```

and here is the group we should be working on, if we really wish to solve this problem:

```<code>((?=.+[A-Z].+)(?i:\1))
</code>```

We are backrefereing with an i flag, which is working fine.

Now, it would most likely pass all case insensitive letters from the first capturing group and fails the entirely lowercase third group, which I'm hoping that's what might be desired here.

If not, this group ((?=.+[A-Z].+) is actually what we might want to focus on
to pass our desired third group and fail the undesireds.

DEMO

Body:
I think this is something that simply does not exist. But I know that some of the functionality exists in other regex engines, I'm hoping they maybe something similar to this.

pattern = r"""
    ([a-zA-Z])    # Match a single letter and capture it as group1
    .*?           # random matches in between
    \1            # Match whatever capture group1 matched
"""

Now this matches AA, bb and so on. So far so good in python.
Now some language (idk if python regex engine does) allows

pattern = r"""
    ([a-zA-Z])    # Match a single letter and capture it as group1
    .*?           # random matches in between
    \U1           # Match group1 in upper case
"""

There are couple of "function" like this that allows you to somewhat manipulate the prev capture groups but they are very limited from what I read at some regex website

Now my question is that, is it possible to write our own "functions" for regex to use somewhat like

@re.register_function('X')
def between_x(group):
    return f'X{group}X'

and then

pattern = r"""
    ([a-zA-Z]{2})    # Match a single letter and capture it as group1
    .*?              # random matches in between
    (\X1)            # Match if the previous group is inbetween Xes.
"""
# For example, AArandomletterXAAX would match and group1 would be AA
# and second group would be XAAX

Doesn't need to be the re module, I'm open to any other regex engines.

As an example the pattern should match

string: "hello...HELLO"

and not match

string: "hello...hello"

given that our function is

def f(group):
    return group.upper()

Body:
This question is quite interesting, and I'm sure it has a great solution, if I understand it correctly.

We can maybe start with an expression with three sub-expressions:

([a-z]+)(.+?)((?=.+[A-Z].+)(?i:\1))

Here we are having a starting lowercase word:

([a-z]+)

followed by anything in between:

 (.+?)

and here is the group we should be working on, if we really wish to solve this problem:

((?=.+[A-Z].+)(?i:\1))

We are backrefereing with an i flag, which is working fine.

Now, it would most likely pass all case insensitive letters from the first capturing group and fails the entirely lowercase third group, which I'm hoping that's what might be desired here.

If not, this group ((?=.+[A-Z].+) is actually what we might want to focus on
to pass our desired third group and fail the undesireds.

DEMO


问:
PHP Doctrine 2 ORM: Non-Entity object as attribute in entity
I'm using Doctrine ORM 2.
I got the following entity class.

```<code>/**
 * @Entity
 * @Table(name="objects")
 */
class MyObject
{
  /**
   * @Id
   * @GeneratedValue
   * @Column(type="integer")
   */
  private $id;

  /**
   * @var Coordinate
   */
  private $coordinate;
}

class Coordinate
{
   private $x;
   private $y;
   private $z;
}
</code>```

I want to implement the 3 coordinate values in a separate class for better handling within php. But within the database I want the 3 values to be included in the database table "objects".

Does anyone know how to achieve this?

Best regards

Edit:
I found a workaround but it's not the nicest.

```<code>    /**
     *
 * @var integer
 * @Column(type="integer")
 */
private $x;
/**
 *
 * @var integer
 * @Column(type="integer")
 */
private $y;
/**
 *
 * @var integer
 * @Column(type="integer")
 */
private $z;

public function getCoordinate()
{
    return new Coordinate($this->x, $this->y, $this->z);
}

public function setCoordinate(Coordinate $coord)
{
    $this->x = $coord->getX();
    $this->y = $coord->getY();
    $this->z = $coord->getZ();
}
</code>```

答:
The easiest way would be to set that field to use the "object" mapping type.

```<code>/**
 * @Column(type="object")
 */
private $coordinate;
</code>```

Then whatever class of object you put in that field, Doctrine will automatically serialise and unserialise when it is inserted and pulled out of the database.

The other way is to make a custom mapping type - http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/custom-mapping-types.html. This uses the same method as the object type, but allows you to specify exactly how the object will be converted between PHP and SQL.

If you used this method had a mapping type named coordinate, you would then just declare this for the field:

```<code>/**
 * @Column(type="coordinate")
 */
private $coordinate;
</code>```

One drawback and as far as I can see there is no way around it, is that you can only use one database column for the field. So you wouldn't be able to order by x, y or z separately using DQL.

Body:
I'm using Doctrine ORM 2.
I got the following entity class.

/**
 * @Entity
 * @Table(name="objects")
 */
class MyObject
{
  /**
   * @Id
   * @GeneratedValue
   * @Column(type="integer")
   */
  private $id;

  /**
   * @var Coordinate
   */
  private $coordinate;
}

class Coordinate
{
   private $x;
   private $y;
   private $z;
}

I want to implement the 3 coordinate values in a separate class for better handling within php. But within the database I want the 3 values to be included in the database table "objects".

Does anyone know how to achieve this?

Best regards

Edit:
I found a workaround but it's not the nicest.

    /**
     *
 * @var integer
 * @Column(type="integer")
 */
private $x;
/**
 *
 * @var integer
 * @Column(type="integer")
 */
private $y;
/**
 *
 * @var integer
 * @Column(type="integer")
 */
private $z;

public function getCoordinate()
{
    return new Coordinate($this->x, $this->y, $this->z);
}

public function setCoordinate(Coordinate $coord)
{
    $this->x = $coord->getX();
    $this->y = $coord->getY();
    $this->z = $coord->getZ();
}

Body:
The easiest way would be to set that field to use the "object" mapping type.

/**
 * @Column(type="object")
 */
private $coordinate;

Then whatever class of object you put in that field, Doctrine will automatically serialise and unserialise when it is inserted and pulled out of the database.

The other way is to make a custom mapping type - http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/custom-mapping-types.html. This uses the same method as the object type, but allows you to specify exactly how the object will be converted between PHP and SQL.

If you used this method had a mapping type named coordinate, you would then just declare this for the field:

/**
 * @Column(type="coordinate")
 */
private $coordinate;

One drawback and as far as I can see there is no way around it, is that you can only use one database column for the field. So you wouldn't be able to order by x, y or z separately using DQL.


问:
How to generate a simple popup box with simple html,css and javascript?
I want to make a "contact form" popup in home page and I want that contact form should be in a light box.I am successfully displaying contact form in home page.But I am not getting light box background.I want to get a grey colour background behind the popup.Can any body help me?

window.addEventListener("load", popupContact, true);

function popupContact() {
  setTimeout(popup, 3000);
}

function popup() {
  document.getElementById("popupBackground").style.display = "block";
  document.getElementById("popupBackground").style.width = 500 px;
  document.getElementById("popupBackground").style.height = 500 px;
  document.getElementById("contactPopup").style.display = "block";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#popupBackground {
  display: block;
  background-color: blue;
  z-index: 1000;
}

contactPopup {
  display: none;
  position: absolute;
  top: 250px;
}</code>```

this is 3987

Contact Us

  <form action="https://www.SnapHost.com/captcha/send.aspx" id="ContactUsCaptchaWebForm" method="post" onsubmit="return ValidateForm(this);" target="_top">

        Name*:
        <input name="Name" type="text" maxlength="60" style="width:350px;" />

        Phone number:
        <input name="PhoneNumber" type="text" maxlength="43" style="width:350px;" />

        Email address*:
        <input name="FromEmailAddress" type="text" maxlength="60" style="width:350px;" />

        Comments and questions*:
        <textarea name="Comments" rows="7" cols="40" style="width:350px;"></textarea>

  </form>

```

答:
Your original code had a couple of issues:

1)  It crashed because of a syntax error. Both times where you wrote 500 px it should have been "500px".

2) Your CSS rule for "contactPopup" was missing the # at the start to denote an element ID.

3) I'm not sure what the purpose of the separate "popupBackground" area was. It neither covered the area behind the popup, nor set it to a grey (or grey-ish) colour. And you don't need a separate background element anyway, you can just style the contactPopup element directly.

Here's a demo:

window.addEventListener("load", popupContact, true);

function popupContact() {
  setTimeout(popup, 3000);
}

function popup() {
  document.getElementById("contactPopup").style.display = "block";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#contactPopup {
  display: none;
  background-color: #dddddd;
  padding: 5px 10px;
  border-radius: 5px;
  font-family: sans-serif;
  color: #121212;
  font-size: 0.9em;
}

input[type="text"],
textarea {
  border: 1px solid #cccccc;
  border-radius: 3px;
  width: 350px;
}

table {
  width: 600px;
  border-collapse: collapse;
  border: none;
}

th {
  text-align: left;
  vertical-align: top;
}

th,
td {
  padding: 5px;
}</code>```

Contact Us

  <form action="https://www.SnapHost.com/captcha/send.aspx" id="ContactUsCaptchaWebForm" method="post" onsubmit="return ValidateForm(this);" target="_top">

        Name*
        <input name="Name" type="text" maxlength="60" />

        Phone number
        <input name="PhoneNumber" type="text" maxlength="43" />

        Email address*
        <input name="FromEmailAddress" type="text" maxlength="60" />

        Comments and questions
        <textarea name="Comments" rows="7" cols="40"></textarea>

  </form>

```

You also had some deprecated element properties (e.g. on your table) which should be replaced by CSS, and some inline styles on your elements which should be replaced by entries in your main CSS block. I've also made the popup look a bit nicer in general with some rounded corners and softer font and colours.

Body:
I want to make a "contact form" popup in home page and I want that contact form should be in a light box.I am successfully displaying contact form in home page.But I am not getting light box background.I want to get a grey colour background behind the popup.Can any body help me?

window.addEventListener("load", popupContact, true);

function popupContact() {
  setTimeout(popup, 3000);
}

function popup() {
  document.getElementById("popupBackground").style.display = "block";
  document.getElementById("popupBackground").style.width = 500 px;
  document.getElementById("popupBackground").style.height = 500 px;
  document.getElementById("contactPopup").style.display = "block";
}

#popupBackground {
  display: block;
  background-color: blue;
  z-index: 1000;
}

contactPopup {
  display: none;
  position: absolute;
  top: 250px;
}

this is 3987

Contact Us

  <form action="https://www.SnapHost.com/captcha/send.aspx" id="ContactUsCaptchaWebForm" method="post" onsubmit="return ValidateForm(this);" target="_top">

        Name*:
        <input name="Name" type="text" maxlength="60" style="width:350px;" />

        Phone number:
        <input name="PhoneNumber" type="text" maxlength="43" style="width:350px;" />

        Email address*:
        <input name="FromEmailAddress" type="text" maxlength="60" style="width:350px;" />

        Comments and questions*:
        <textarea name="Comments" rows="7" cols="40" style="width:350px;"></textarea>

  </form>

Body:
Your original code had a couple of issues:

1)  It crashed because of a syntax error. Both times where you wrote 500 px it should have been "500px".

2) Your CSS rule for "contactPopup" was missing the # at the start to denote an element ID.

3) I'm not sure what the purpose of the separate "popupBackground" area was. It neither covered the area behind the popup, nor set it to a grey (or grey-ish) colour. And you don't need a separate background element anyway, you can just style the contactPopup element directly.

Here's a demo:

window.addEventListener("load", popupContact, true);

function popupContact() {
  setTimeout(popup, 3000);
}

function popup() {
  document.getElementById("contactPopup").style.display = "block";
}

#contactPopup {
  display: none;
  background-color: #dddddd;
  padding: 5px 10px;
  border-radius: 5px;
  font-family: sans-serif;
  color: #121212;
  font-size: 0.9em;
}

input[type="text"],
textarea {
  border: 1px solid #cccccc;
  border-radius: 3px;
  width: 350px;
}

table {
  width: 600px;
  border-collapse: collapse;
  border: none;
}

th {
  text-align: left;
  vertical-align: top;
}

th,
td {
  padding: 5px;
}

<div id="contactPopup">
  <h2>Contact Us</h2>
  <form action="https://www.SnapHost.com/captcha/send.aspx" id="ContactUsCaptchaWebForm" method="post" onsubmit="return ValidateForm(this);" target="_top">
    <table>
      <tr>
        <th>Name*</th>
        <td><input name="Name" type="text" maxlength="60" /></td>
      </tr>
      <tr>
        <th>Phone number</th>
        <td><input name="PhoneNumber" type="text" maxlength="43" /></td>
      </tr>
      <tr>
        <th>Email address*</th>
        <td><input name="FromEmailAddress" type="text" maxlength="60" /></td>
      </tr>
      <tr>
        <th>Comments and questions</th>
        <td><textarea name="Comments" rows="7" cols="40"></textarea></td>
      </tr>
      <table>
  </form>
</div>

You also had some deprecated element properties (e.g. on your table) which should be replaced by CSS, and some inline styles on your elements which should be replaced by entries in your main CSS block. I've also made the popup look a bit nicer in general with some rounded corners and softer font and colours.


问:
How to select columns based on the max value of each column?
I have a data frame with many columns and rows, for example

```<code>id  column1 column2 column3
1   2   3   5
2   3   2   6
3   4   1   3
4   1   1   2
5   3   3   2
6   5   2   1
</code>```

How can I select the column (except id) whose max value is more than certain value, like 5 in the example data?

So the select data should be:

```<code>id  column1 column3
1   2   5
2   3   6
3   4   3
4   1   2
5   3   2
6   5   1
</code>```

I would appreciate any help on my question. Thank you very much!

答:
That requires first finding those maximal values and then accordingly subsetting the data frame, as in

```<code>df[c(TRUE, apply(df[-1], 2, max) >= 5)]
#   id column1 column3
# 1  1       2       5
# 2  2       3       6
# 3  3       4       3
# 4  4       1       2
# 5  5       3       2
# 6  6       5       1
</code>```

where

```<code>apply(df[-1], 2, max)
# column1 column2 column3
#       5       3       6
</code>```

and adding TRUE also preserves the id column.

Body:
I have a data frame with many columns and rows, for example

id  column1 column2 column3
1   2   3   5
2   3   2   6
3   4   1   3
4   1   1   2
5   3   3   2
6   5   2   1

How can I select the column (except id) whose max value is more than certain value, like 5 in the example data?

So the select data should be:

id  column1 column3
1   2   5
2   3   6
3   4   3
4   1   2
5   3   2
6   5   1

I would appreciate any help on my question. Thank you very much!

Body:
That requires first finding those maximal values and then accordingly subsetting the data frame, as in

df[c(TRUE, apply(df[-1], 2, max) >= 5)]
#   id column1 column3
# 1  1       2       5
# 2  2       3       6
# 3  3       4       3
# 4  4       1       2
# 5  5       3       2
# 6  6       5       1

where

apply(df[-1], 2, max)
# column1 column2 column3
#       5       3       6

and adding TRUE also preserves the id column.


问:
How to exclude the first 10 sheets from a spreadsheet?
This script here loops through the sheet names and changes the names to match the value in A1. How can I exclude the first 10 sheet names from the execution instead of providing the specific sheet names to be excluded?</p>

```<code>function onEdit() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array holding the names of the sheets to exclude from the execution
  var exclude =["Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var s in allsheets){
var sheet = allsheets[s];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is meet.
if(exclude.indexOf(sheet.getName())==-1) continue;
  }

} // end of loop

} // end of function
</code>```

答:
Solution

As getSheets() method returns an Array of Sheet instances, you have access to every method designed for iterating over arrays and thus do not need for...in (if want to be able to break out of the loop or use continue statement, use for...of instead).

Use slice()

The simplest would be using slice method - it returns a partial copy of the array without modifying the original. The method call accepts two arguments, both optional:

0-based start index

0-based end index (end is exclusive)

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];
var relevantSheets = arr.slice(10); //simply slice everything after sheet 10
console.log(relevantSheets); //should log [Sh11, Sh12]```
</div>
</div>
</p>

<p><strong>Use splice()</strong></p>

<p><code>splice()</code> method is very similar to the first one, but allows to "permanently" exclude elements from the array. Just configure it to remove first N elements and do not replace them:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];
arr.splice(0, 10); //0-based start and end indices (end is exclusive);
console.log(arr); //should log [Sh11, Sh12]</code>```

Refer to documentation for an in-depth explanation. In short, this method accepts an indefinite amount of arguments:

Required: 0-based index to start from

Optional: 0-based index to end before (if not provided or greater than length of the Array the method is called on, removes every element starting from start index)

Optional: Comma separated list of elements to replace removed items

Note that the method mutates (changes) the original array.

Use forEach()

A more modern approach if you need some side-effects to happen for each element, is using forEach method and checking if index is greater than 10 (array indices are 0-based, hence 9 in sample):

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];

var res = [];

arr.forEach(function(element, index) {
  if (index > 9) {
    res.push(element); //push to test Array;
    //iterable code goes here;
  }
});

console.log(res); //should log ['Sh11','Sh12']```

Note that forEach method callback function accepts three arguments:

Required: Array element to iterate over;

Optional: 0-based index of element currently looped over;

Optional: Array over which the loop iterates;

Please refer to documentation to better understand how this Array method works. Also, refrain from using a for...in loop in contexts where order of iteration is relevant.

Notes

You do not need to stop iteration after there are no more
Sheet instances in an Array - the loop will terminate upon finishing iterating over the last element.

References

slice() method

forEach() method

splice() method

getSheets() method

for...of loop

Body:
This script here loops through the sheet names and changes the names to match the value in A1. How can I exclude the first 10 sheet names from the execution instead of providing the specific sheet names to be excluded?

function onEdit() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array holding the names of the sheets to exclude from the execution
  var exclude =["Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var s in allsheets){
var sheet = allsheets[s];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is meet.
if(exclude.indexOf(sheet.getName())==-1) continue;
  }

} // end of loop

} // end of function

Body:
Solution

As getSheets() method returns an Array of Sheet instances, you have access to every method designed for iterating over arrays and thus do not need for...in (if want to be able to break out of the loop or use continue statement, use for...of instead).

Use slice()

The simplest would be using slice method - it returns a partial copy of the array without modifying the original. The method call accepts two arguments, both optional:

0-based start index

0-based end index (end is exclusive)

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];
var relevantSheets = arr.slice(10); //simply slice everything after sheet 10
console.log(relevantSheets); //should log [Sh11, Sh12]

Use splice()

splice() method is very similar to the first one, but allows to "permanently" exclude elements from the array. Just configure it to remove first N elements and do not replace them:

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];
arr.splice(0, 10); //0-based start and end indices (end is exclusive);
console.log(arr); //should log [Sh11, Sh12]

Refer to documentation for an in-depth explanation. In short, this method accepts an indefinite amount of arguments:

Required: 0-based index to start from

Optional: 0-based index to end before (if not provided or greater than length of the Array the method is called on, removes every element starting from start index)

Optional: Comma separated list of elements to replace removed items

Note that the method mutates (changes) the original array.

Use forEach()

A more modern approach if you need some side-effects to happen for each element, is using forEach method and checking if index is greater than 10 (array indices are 0-based, hence 9 in sample):

var arr = ['Sh1', 'Sh2', 'Sh3', 'Sh4', 'Sh5', 'Sh6', 'Sh7', 'Sh8', 'Sh9', 'Sh10', 'Sh11', 'Sh12'];

var res = [];

arr.forEach(function(element, index) {
  if (index > 9) {
    res.push(element); //push to test Array;
    //iterable code goes here;
  }
});

console.log(res); //should log ['Sh11','Sh12']

Note that forEach method callback function accepts three arguments:

Required: Array element to iterate over;

Optional: 0-based index of element currently looped over;

Optional: Array over which the loop iterates;

Please refer to documentation to better understand how this Array method works. Also, refrain from using a for...in loop in contexts where order of iteration is relevant.

Notes

You do not need to stop iteration after there are no more
Sheet instances in an Array - the loop will terminate upon finishing iterating over the last element.

References

slice() method

forEach() method

splice() method

getSheets() method

for...of loop


答:
```<code>a,b = something
</code>```

This means something is a sequence of two values.  a is assigned to the first value, and b is assigned to the second.

This is called tuple unpacking.

Title: What does this Python code do? Explanation of brackets

Body:
Can you explain these lines?
I can't understand what's happening in brackets (j,pbase).

mults = {}
if c in mults:
    (j,pbase) = mults.pop(c)

Body:
a,b = something

This means something is a sequence of two values.  a is assigned to the first value, and b is assigned to the second.

This is called tuple unpacking.


问:
Why replace is not saved?
Trying to translate for image addresses, found the replace function for sql
doing

```<code>SELECT product_id, REPLACE(image, 'к', 'k') as text FROM oc_product;
</code>```

It gives the result supposedly everything is replaced - I update the page - everything is as before ...

https://www.dropbox.com/s/kz3x55lwprauti9/Ub97uw5x42.mp4?dl=0

答:
I think what you are trying to achieve it's an UPDATE:

```<code>UPDATE oc_product SET image = REPLACE(image, 'к', 'k');
</code>```

Be careful since you don't have a WHERE clause in this query.

Title: Why replace is not saved?

Body:
Trying to translate for image addresses, found the replace function for sql
doing

SELECT product_id, REPLACE(image, 'к', 'k') as text FROM oc_product;

It gives the result supposedly everything is replaced - I update the page - everything is as before ...

https://www.dropbox.com/s/kz3x55lwprauti9/Ub97uw5x42.mp4?dl=0

Body:
I think what you are trying to achieve it's an UPDATE:

UPDATE oc_product SET image = REPLACE(image, 'к', 'k');

Be careful since you don't have a WHERE clause in this query.


答:
Multiple ways to do this.

Using base R

```<code>cbind(df[1], df[-1][sapply(df[-1], function(x) any(x >=5))])

#  id column1 column3
#1  1       2       5
#2  2       3       6
#3  3       4       3
#4  4       1       2
#5  5       3       2
#6  6       5       1
</code>```

We could also use colSums on logical matrix after comparing it with >= 5

```<code>cbind(df[1], df[-1][colSums(df[-1] >= 5)  > 0])
</code>```

Or with Filter

```<code>cbind(df[1], Filter(function(x) any(x >= 5), df[-1]))
</code>```

Or using dplyr

```<code>library(dplyr)

bind_cols(df[1], df %>%
                 select(-1) %>%
                 select_if(~any(. >=5)))
</code>```

Title: How to select columns based on the max value of each column?

Body:
Multiple ways to do this.

Using base R

cbind(df[1], df[-1][sapply(df[-1], function(x) any(x >=5))])

#  id column1 column3
#1  1       2       5
#2  2       3       6
#3  3       4       3
#4  4       1       2
#5  5       3       2
#6  6       5       1

We could also use colSums on logical matrix after comparing it with >= 5

cbind(df[1], df[-1][colSums(df[-1] >= 5)  > 0])

Or with Filter

cbind(df[1], Filter(function(x) any(x >= 5), df[-1]))

Or using dplyr

library(dplyr)

bind_cols(df[1], df %>%
                 select(-1) %>%
                 select_if(~any(. >=5)))


问:
How to change image according to language choice (i18n gem in Rails)?
I am willing to change a picture based on the choice of the language. It is because my image contains some text and I made three different versions of the image according to language choice (Dutch, French and English). How do I need to do that?

I tried to add my
<%= image_tag("lansink_en.png", class: "center-image") %> in my different en.yml, fr.ymland nl.yml files but it didn't work out.

Thanks for your help!

答:
I am of the opinion that translation files should not contain code or any more specific markup than is strictly semantic.

If they get shipped to translators (or auto-translated with something like Google Translate), then English code could get translated, leaving you with something broken in one or more languages, and something working in the others.

If you change your class-names, it shouldn't require a round of translation or a bypass for this special case.

I'd prefer a good-old helper method:

```<code>module SomeHelper
  def lansink_image_tag
    image_tag("lansink_#{I18n.locale}.png", class: "center-image")
  end
end
</code>```

Or, if you don't know that all languages will necessarily have a file, but you want a fallback:

```<code>module SomeHelper
  def lansink_image_tag
    has_image = [:de, :fr, :en]
    suffix = has_image.include?(I18n.locale) ? I18n.locale : :en
    image_tag("lansink_#{suffix}.png", class: "center-image")
  end
end
</code>```

Body:
I am of the opinion that translation files should not contain code or any more specific markup than is strictly semantic.

If they get shipped to translators (or auto-translated with something like Google Translate), then English code could get translated, leaving you with something broken in one or more languages, and something working in the others.

If you change your class-names, it shouldn't require a round of translation or a bypass for this special case.

I'd prefer a good-old helper method:

module SomeHelper
  def lansink_image_tag
    image_tag("lansink_#{I18n.locale}.png", class: "center-image")
  end
end

Or, if you don't know that all languages will necessarily have a file, but you want a fallback:

module SomeHelper
  def lansink_image_tag
    has_image = [:de, :fr, :en]
    suffix = has_image.include?(I18n.locale) ? I18n.locale : :en
    image_tag("lansink_#{suffix}.png", class: "center-image")
  end
end


问:
Configure Nginx to serve Angular front end, Django Rest Framework backend on same server?
My site's frontend is built with Angular 7, and the back end is built with Django Rest Framework. It's all running via docker-compose, and I'm trying to serve the entire site through NGINX.

The basic premise of my configuration is this:

If the request includes a url with /api/ or /admin/ in it, allow gunicorn to handle the request.

If the url is anything else, send it to the root index.html so that Angular can handle the routing.

The root url / should serve my pre-compiled javascript via the index.html.

With the following Nginx config, I can visit all of the Angular routes. I can visit the admin page and my browsable API. However, when I go to /admin or the browsable API, all of the static files return a 404 error.

Do you see the issue? Thanks!

```<code># urls.py

urlpatterns = [
    re_path(r'^favicon\.ico$', favicon_view),

    path('api/v1/', include('api.urls'), name='api'),
    path('admin/', admin.site.urls),
]

# nginx.conf

upstream my_app {
    server django:8000;
}

server {

    listen 80;

    location /staticfiles/ {
        alias /usr/src/app/staticfiles/;
    }

    location ~ (api|admin) {
        proxy_pass http://my_app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location / {
        root /usr/src/app/staticfiles/;
        try_files $uri $uri/ /index.html;
    }

}
</code>```

答:
Your configs are saying that everything available from /api/ or /admin/ are provided by the proxy to my_app. So, you may either ensure that the static files used by those endpoints are available through Django Rest Framework, OR tell NGINX to always try the static files first, then fall back to the my_app proxy.

The first option will involve setting STATIC_ROOT, STATIC_URL, STATICFILES_STORAGE, etc per the Django documentation on static files (link goes to current dev version).

The other option involves collecting the assets used by /api/ and /admin/ in the same location as your Angular assets, and altering your NGINX configuration to look something like this:

```<code># nginx.conf

upstream my_app {
    server django:8000;
}

server {

    listen 80;

    location /staticfiles/ {
        alias /usr/src/app/staticfiles/;
    }

    location / {
        root /usr/src/app/staticfiles/;
        try_files $uri $uri/ index.html;
        location /drf {
            proxy_pass http://my_app;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_redirect off;

        }
    }

}
</code>```

This basically says try to look up everything in your Angular staticfiles directory, if it's not found, try looking it up in your DRF application.

Body:
My site's frontend is built with Angular 7, and the back end is built with Django Rest Framework. It's all running via docker-compose, and I'm trying to serve the entire site through NGINX.

The basic premise of my configuration is this:

If the request includes a url with /api/ or /admin/ in it, allow gunicorn to handle the request.

If the url is anything else, send it to the root index.html so that Angular can handle the routing.

The root url / should serve my pre-compiled javascript via the index.html.

With the following Nginx config, I can visit all of the Angular routes. I can visit the admin page and my browsable API. However, when I go to /admin or the browsable API, all of the static files return a 404 error.

Do you see the issue? Thanks!

# urls.py

urlpatterns = [
    re_path(r'^favicon\.ico$', favicon_view),

    path('api/v1/', include('api.urls'), name='api'),
    path('admin/', admin.site.urls),
]

# nginx.conf

upstream my_app {
    server django:8000;
}

server {

    listen 80;

    location /staticfiles/ {
        alias /usr/src/app/staticfiles/;
    }

    location ~ (api|admin) {
        proxy_pass http://my_app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location / {
        root /usr/src/app/staticfiles/;
        try_files $uri $uri/ /index.html;
    }

}

Body:
Your configs are saying that everything available from /api/ or /admin/ are provided by the proxy to my_app. So, you may either ensure that the static files used by those endpoints are available through Django Rest Framework, OR tell NGINX to always try the static files first, then fall back to the my_app proxy.

The first option will involve setting STATIC_ROOT, STATIC_URL, STATICFILES_STORAGE, etc per the Django documentation on static files (link goes to current dev version).

The other option involves collecting the assets used by /api/ and /admin/ in the same location as your Angular assets, and altering your NGINX configuration to look something like this:

# nginx.conf

upstream my_app {
    server django:8000;
}

server {

    listen 80;

    location /staticfiles/ {
        alias /usr/src/app/staticfiles/;
    }

    location / {
        root /usr/src/app/staticfiles/;
        try_files $uri $uri/ index.html;
        location /drf {
            proxy_pass http://my_app;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_redirect off;

        }
    }

}

This basically says try to look up everything in your Angular staticfiles directory, if it's not found, try looking it up in your DRF application.


问:
Why are multiple sql queries run in sequece and not concurrently?
I am running  mysql “select” queries in seperate go routines at the same time. However the mysql service seems to collect these queries, run them in sequence (not concurrently) and then returns all the resultsets at the same time and only after all the queries have been run.

My questions are:

1. Why are theses queries run in sequence and not concurrently?

2. Why does mysql wait until all queries have been run before returning the resultset for each query  at the same time (even though each single resultset belongs to a different go routine and supposedly also uses a seperate connection)?

Another thing: when I set “SetMaxOpenConns(2)” then it returns two resultsets at the same time. If set to 3,  3 resultsets are returned at the same time. However they are still always run in sequence.

Anybody know what is going on here?

```<code>package main

import (
    "database/sql"
    "fmt"
    "sync"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

var database *sql.DB

func init() {
    var err error
    databaseURI := "root:toor@tcp(192.168.200.10:3306)/ahc"
    database, err = sql.Open("mysql", databaseURI)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("DB Connection Established")
        //database.SetMaxIdleConns(0)
        //database.SetMaxOpenConns(2)
    }
}

func test(device string, wg *sync.WaitGroup) {
    fmt.Println("Thread: " + device + " started")
    start := time.Now()

    var count string

    //using go-sql-driver
    sqlStatement, err := database.Prepare("select count(cpeName) from report where errMessage <> \"ok\" and cpeName = ? and jobID = ?")
    if err != nil {
        fmt.Println(err)
    }
    defer sqlStatement.Close()
    err = sqlStatement.QueryRow(device, "11534").Scan(&count)
    sqlStatement.Close()

    duration := time.Since(start)
    fmt.Println("Thread: " + device + " Duration: " + duration.String() + "\n")
    wg.Done()
}

func main() {
    var wg sync.WaitGroup
    var deviceList = []string{"xx-swrk-ca-gen-s-002", "xx-leus-ca-ust-ap-068", "xx-sgvn-ca-lug-ap-004", "xx-swrk-ca-vez-s-005", "xx-swrk-ca-vez-ap-006",    "xx-leus-ca-ust-ap-065", "xx-leus-ca-ust-ap-073", "xx-leus-ca-ust-ap-076", "xx-leus-ca-ust-ap-077", "xx-swrk-ca-gen-s-001"}
    total := time.Now()
    for _, device := range deviceList {
        wg.Add(1)
        go test(device, &wg)
    }
    wg.Wait()
    duration := time.Since(total)
    fmt.Println("\n\nTotal: Duration: " + duration.String() + "\n")
}
</code>```

THis is the output

```<code>DB Connection Established
Thread: xx-leus-ca-ust-ap-068 started
Thread: xx-sgvn-ca-lug-ap-004 started
Thread: xx-leus-ca-ust-ap-065 started
Thread: xx-leus-ca-ust-ap-073 started
Thread: xx-swrk-ca-vez-ap-006 started
Thread: xx-swrk-ca-vez-s-005 started
Thread: xx-leus-ca-ust-ap-076 started
Thread: xx-leus-ca-ust-ap-077 started
Thread: xx-swrk-ca-gen-s-002 started
Thread: xx-swrk-ca-gen-s-001 started
Thread: xx-leus-ca-ust-ap-076 Duration: 7.291656143s

Thread: xx-swrk-ca-gen-s-002 Duration: 7.304134404s

Thread: xx-leus-ca-ust-ap-065 Duration: 7.307958641s

Thread: xx-swrk-ca-vez-s-005 Duration: 7.313591747s

Thread: xx-leus-ca-ust-ap-077 Duration: 7.313992638s

Thread: xx-swrk-ca-vez-ap-006 Duration: 7.314905664s

Thread: xx-swrk-ca-gen-s-001 Duration: 7.320466323s

Thread: xx-leus-ca-ust-ap-073 Duration: 7.322158337s

Thread: xx-leus-ca-ust-ap-068 Duration: 7.324745097s

Thread: xx-sgvn-ca-lug-ap-004 Duration: 7.326001783s

Total: Duration: 7.326096238s
</code>```

When using database.SetMaxOpenConns(1), this is the output:

```<code>DB Connection Established
Thread: xx-leus-ca-ust-ap-068 started
Thread: xx-swrk-ca-gen-s-001 started
Thread: xx-swrk-ca-vez-ap-006 started
Thread: xx-leus-ca-ust-ap-065 started
Thread: xx-leus-ca-ust-ap-073 started
Thread: xx-swrk-ca-gen-s-002 started
Thread: xx-leus-ca-ust-ap-077 started
Thread: xx-sgvn-ca-lug-ap-004 started
Thread: xx-leus-ca-ust-ap-076 started
Thread: xx-swrk-ca-vez-s-005 started
Thread: xx-leus-ca-ust-ap-068 Duration: 1.131790286s

Thread: xx-leus-ca-ust-ap-077 Duration: 2.128919333s

Thread: xx-swrk-ca-gen-s-001 Duration: 3.073559464s

Thread: xx-leus-ca-ust-ap-073 Duration: 4.002964333s

Thread: xx-swrk-ca-vez-s-005 Duration: 4.932256684s

Thread: xx-sgvn-ca-lug-ap-004 Duration: 5.853361245s

Thread: xx-swrk-ca-gen-s-002 Duration: 6.785042625s

Thread: xx-leus-ca-ust-ap-065 Duration: 7.705957815s

Thread: xx-swrk-ca-vez-ap-006 Duration: 8.633000734s

Thread: xx-leus-ca-ust-ap-076 Duration: 9.550948572s

Total: Duration: 9.551103129s
</code>```

答:
A simple technique to see whether they are run in parallel or serially:  Have each connection do

```<code>SELECT SLEEP(1);
</code>```

If parallel, the set won't take much more than 1 second.  If serially, then N seconds.

If they are run sequentially, but no output until all are finished, that would be a GO problem.

If your 7.3s is really parallel and 9.5 is serial, then that points out why it is not worth it to run things in parallel -- They will step on each other and not finish much faster.  The conflict could be CPU or I/O or mutexes or network or something else; it depends on the query.  (My sleep test is very non-invasive, yet takes a predictable amount of time.)

Body:
I am running  mysql “select” queries in seperate go routines at the same time. However the mysql service seems to collect these queries, run them in sequence (not concurrently) and then returns all the resultsets at the same time and only after all the queries have been run.

My questions are:

1. Why are theses queries run in sequence and not concurrently?

2. Why does mysql wait until all queries have been run before returning the resultset for each query  at the same time (even though each single resultset belongs to a different go routine and supposedly also uses a seperate connection)?

Another thing: when I set “SetMaxOpenConns(2)” then it returns two resultsets at the same time. If set to 3,  3 resultsets are returned at the same time. However they are still always run in sequence.

Anybody know what is going on here?

package main

import (
    "database/sql"
    "fmt"
    "sync"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

var database *sql.DB

func init() {
    var err error
    databaseURI := "root:toor@tcp(192.168.200.10:3306)/ahc"
    database, err = sql.Open("mysql", databaseURI)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("DB Connection Established")
        //database.SetMaxIdleConns(0)
        //database.SetMaxOpenConns(2)
    }
}

func test(device string, wg *sync.WaitGroup) {
    fmt.Println("Thread: " + device + " started")
    start := time.Now()

    var count string

    //using go-sql-driver
    sqlStatement, err := database.Prepare("select count(cpeName) from report where errMessage <> \"ok\" and cpeName = ? and jobID = ?")
    if err != nil {
        fmt.Println(err)
    }
    defer sqlStatement.Close()
    err = sqlStatement.QueryRow(device, "11534").Scan(&count)
    sqlStatement.Close()

    duration := time.Since(start)
    fmt.Println("Thread: " + device + " Duration: " + duration.String() + "\n")
    wg.Done()
}

func main() {
    var wg sync.WaitGroup
    var deviceList = []string{"xx-swrk-ca-gen-s-002", "xx-leus-ca-ust-ap-068", "xx-sgvn-ca-lug-ap-004", "xx-swrk-ca-vez-s-005", "xx-swrk-ca-vez-ap-006",    "xx-leus-ca-ust-ap-065", "xx-leus-ca-ust-ap-073", "xx-leus-ca-ust-ap-076", "xx-leus-ca-ust-ap-077", "xx-swrk-ca-gen-s-001"}
    total := time.Now()
    for _, device := range deviceList {
        wg.Add(1)
        go test(device, &wg)
    }
    wg.Wait()
    duration := time.Since(total)
    fmt.Println("\n\nTotal: Duration: " + duration.String() + "\n")
}

THis is the output

DB Connection Established
Thread: xx-leus-ca-ust-ap-068 started
Thread: xx-sgvn-ca-lug-ap-004 started
Thread: xx-leus-ca-ust-ap-065 started
Thread: xx-leus-ca-ust-ap-073 started
Thread: xx-swrk-ca-vez-ap-006 started
Thread: xx-swrk-ca-vez-s-005 started
Thread: xx-leus-ca-ust-ap-076 started
Thread: xx-leus-ca-ust-ap-077 started
Thread: xx-swrk-ca-gen-s-002 started
Thread: xx-swrk-ca-gen-s-001 started
Thread: xx-leus-ca-ust-ap-076 Duration: 7.291656143s

Thread: xx-swrk-ca-gen-s-002 Duration: 7.304134404s

Thread: xx-leus-ca-ust-ap-065 Duration: 7.307958641s

Thread: xx-swrk-ca-vez-s-005 Duration: 7.313591747s

Thread: xx-leus-ca-ust-ap-077 Duration: 7.313992638s

Thread: xx-swrk-ca-vez-ap-006 Duration: 7.314905664s

Thread: xx-swrk-ca-gen-s-001 Duration: 7.320466323s

Thread: xx-leus-ca-ust-ap-073 Duration: 7.322158337s

Thread: xx-leus-ca-ust-ap-068 Duration: 7.324745097s

Thread: xx-sgvn-ca-lug-ap-004 Duration: 7.326001783s

Total: Duration: 7.326096238s

When using database.SetMaxOpenConns(1), this is the output:

DB Connection Established
Thread: xx-leus-ca-ust-ap-068 started
Thread: xx-swrk-ca-gen-s-001 started
Thread: xx-swrk-ca-vez-ap-006 started
Thread: xx-leus-ca-ust-ap-065 started
Thread: xx-leus-ca-ust-ap-073 started
Thread: xx-swrk-ca-gen-s-002 started
Thread: xx-leus-ca-ust-ap-077 started
Thread: xx-sgvn-ca-lug-ap-004 started
Thread: xx-leus-ca-ust-ap-076 started
Thread: xx-swrk-ca-vez-s-005 started
Thread: xx-leus-ca-ust-ap-068 Duration: 1.131790286s

Thread: xx-leus-ca-ust-ap-077 Duration: 2.128919333s

Thread: xx-swrk-ca-gen-s-001 Duration: 3.073559464s

Thread: xx-leus-ca-ust-ap-073 Duration: 4.002964333s

Thread: xx-swrk-ca-vez-s-005 Duration: 4.932256684s

Thread: xx-sgvn-ca-lug-ap-004 Duration: 5.853361245s

Thread: xx-swrk-ca-gen-s-002 Duration: 6.785042625s

Thread: xx-leus-ca-ust-ap-065 Duration: 7.705957815s

Thread: xx-swrk-ca-vez-ap-006 Duration: 8.633000734s

Thread: xx-leus-ca-ust-ap-076 Duration: 9.550948572s

Total: Duration: 9.551103129s

Body:
A simple technique to see whether they are run in parallel or serially:  Have each connection do

SELECT SLEEP(1);

If parallel, the set won't take much more than 1 second.  If serially, then N seconds.

If they are run sequentially, but no output until all are finished, that would be a GO problem.

If your 7.3s is really parallel and 9.5 is serial, then that points out why it is not worth it to run things in parallel -- They will step on each other and not finish much faster.  The conflict could be CPU or I/O or mutexes or network or something else; it depends on the query.  (My sleep test is very non-invasive, yet takes a predictable amount of time.)


问:
Extracting TOP directory from from file path in R
I need guidance on how to extract the first (or) top directory from a given path. This includes the first slash and the last slash.  For example, in the path: "/chemicalemergencies/category/test-page1.html", I need to extract "/chemicalemergencies/"  I've used str_extract and regex to identify the pattern, but the problem is that it is returning ANY match.  This is problematic if the URL has duplicate folders.  So for example, if the path is "/chemicalemergencies/category/chemicalemergencies/test-page1.html", it will return BOTH the results, when I only need the first one.  How do make pattern detect stop after the first match in the string?</p>

```<code>Sys.time()
#i=4
for (i in 1:nrow(wwwdevurls)) {
  pathextract_wwwdev <- str_extract(wwwdevurls[i,3],"\\/([A-z0-9]+)\\/")
  pathextract_wwwdev.df[i,1] <- pathextract_wwwdev #Load pathextract into pathextract.df
  pathextract_wwwdev.df[i,2] <- wwwdevurls[i,1] #Load CIO into pathextract.df
}
Sys.time()
</code>```

答:
Use ^[^/]*(/[^/]*/)

where the first directory encased in slashes is in group 1.

Body:
I need guidance on how to extract the first (or) top directory from a given path. This includes the first slash and the last slash.  For example, in the path: "/chemicalemergencies/category/test-page1.html", I need to extract "/chemicalemergencies/"  I've used str_extract and regex to identify the pattern, but the problem is that it is returning ANY match.  This is problematic if the URL has duplicate folders.  So for example, if the path is "/chemicalemergencies/category/chemicalemergencies/test-page1.html", it will return BOTH the results, when I only need the first one.  How do make pattern detect stop after the first match in the string?

Sys.time()
#i=4
for (i in 1:nrow(wwwdevurls)) {
  pathextract_wwwdev <- str_extract(wwwdevurls[i,3],"\\/([A-z0-9]+)\\/")
  pathextract_wwwdev.df[i,1] <- pathextract_wwwdev #Load pathextract into pathextract.df
  pathextract_wwwdev.df[i,2] <- wwwdevurls[i,1] #Load CIO into pathextract.df
}
Sys.time()


答:
If your paths always start with a slash, you can use:

```<code>sub("(/.*?/).*", "\\1", path)
"/chemicalemergencies/"
</code>```

Title: Extracting TOP directory from from file path in R

Body:
If your paths always start with a slash, you can use:

sub("(/.*?/).*", "\\1", path)
"/chemicalemergencies/"


问:
Strange visual studio 2008 behavior when pressing keys
Every once in a while I'll do something that causes strang behavior when pressing certain keys.

1)The single quote key (') will not type a character unless I press it twice, in which case it will print two backwards single quote characters (``).

2)The ` (backwards single quote?) key types a # character.

3)The angle bracket keys (< and >) type a single quote (') and a period (.).

4)Shift + any A-Z character types the character and brings the code completion window up.

I'm sure there's other symptomps, and they only want I've found to stop it is to restart Visual studio.  This behavior does not appear in any other apps.  Anybody experience this?

答: Like others have said, you can press ctrl-shift to "loop" through the settings. </p>

OwnerDisplayName: Jeremy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: John Sheehan

OwnerDisplayName: masfenix