问:
SVG mask used in SVG embedded in HTML document not working
I am making an HTML document version of a griefer list for Dredark.io because the ship I made that had the list was ruined. An idiot I thought was my friend went promoting everyone who joined to captain rank and they all messed EVERYTHING up. However, I am having issues with the portion that shows the last seen appearance of each griefer: the SVG mask="url(#face/body/legs/hand)" attribute is not working.

<!DOCTYPE html>

        <title>Dredark.io Griefers</title>

            Because the previous one was ruined

by La Danse Macabre, someone I trusted.

                Note to La Danse Macabre:

Do not promote random people to Captain on MY ships!

The warning level of a griefer depends on how many ships they griefed and how much hard work is lost to them per ship. Griefers with a level below 20 are not really that bad and can still be trusted. Griefers with a level of less than 5 mean that they are possible but not proven.

            <svg id='skin' xmlns='http://www.w3.org/2000/svg' width='50px' height='80px' viewbox='0 0 50 80'>
                <defs>
                    <mask maskContentUnits="userSpaceOnUse" id="face" width="50" height="80" viewbox="0 0 50 80"><image href="https://test.drednot.io/img/player_head.png" x="0" y="0"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="body"><image href="https://test.drednot.io/img/player.png" x="17" y="7"/>
                    <image href="https://test.drednot.io/img/player_arm.png" x="20" y="-5"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="legs"><image href="https://test.drednot.io/img/player_leg.png" x="17" y="8"/>
                    <image href="https://test.drednot.io/img/player_leg.png" x="20" y="8"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="hand"><image href="https://test.drednot.io/img/player_hand.png" x="19" y="-5"/></mask>
                </defs>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#face)"/>
                <rect x="0" y="0" width="100" height="100" fill="!_---" mask="url(#body)"/>
                <rect x="0" y="0" width="100" height="100" fill="!-_--" mask="url(#legs)"/>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#hand)"/>
                <image href="https://test.drednot.io/img/player_face.png" x="0" y="0"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="17" y="8"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="20" y="8"/>
            </svg>

                #
                Name
                Warning level
                Proof
                Last seen appearance

```

As its own file, the SVG image DOES support it, but for some reason when I embed it within the HTML document it just stops working. The best I can do is make the whole thing disappear. I have tried everything and I have been searching the whole web for a fix but I have lost all hope other than you kind people. What am I doing wrong and how do I fix this?

答:
Svg <mask> won't be applied, if your svg containing it is hidden via display: none.

But you can hide it like so

```<code>#prototypes {
  position: absolute;
  width.0;
  height: 0;
  overflow: hidden;
}
</code>```

This also applies to other svg elements like <clipPath> or filters.

So It's actually a better practice to hide your svg containing all assets and definitions this way.

Workin example

var list = {
  "clown": {
    warning: 15,
    hair: "none",
    skin: "#ff8800",
    shirt: "#111111",
    pants: "#000000",
    proof: "Many people know him as a griefer"
  },
  "SMARTLABRAT": {
    warning: 1,
    hair: "none",
    skin: "#ffeeaa",
    shirt: "#11aa11",
    pants: "#1122aa",
    proof: "none"
  }
};

function load() {
  var max = 0;
  var sorted = [];
  for (var prop in list) {
    if (list[prop].warning >= max) {
      max = list[prop].warning;
    }
  }
  var cur = max;
  for (var i = max; i > 0; i--) {
    for (var prop in list) {
      if (list[prop].warning == i) {
        sorted.push(prop);
      }
    }
  }
  var html = "";
  var warningColors = ["#00ff00", "#44ff00", "#88ff00", "#aaff00", "#ffff00", "#ffaa00", "#ff8800", "#ff4400", "#ff0000"];
  for (var i = 0; i < sorted.length; i++) {
    var color = "";
    for (var j = 0; j < warningColors.length; j++) {
      if (list[sorted[i]].warning >= (j * 10)) {
        color = warningColors[j];
      }
    }
    html = "
" + (i + 1) + "	" + sorted[i] + "	" + list[sorted[i]].warning + "	" + list[sorted[i]].proof + "	" + document.getElementById("skin").outerHTML.replace(/!----/g, "#00ff00").replace("!_---", "#222222").replace("!-_--", "#111111") + "
";
    document.getElementById("list").innerHTML += html;
  }
}
window.onload = function() {
  load();
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#list {
  border: 1px solid #004400;
}

#prototypes {
  position: absolute;
  width.0;
  height: 0;
  overflow: hidden;
}</code>```

  Because the previous one was ruined

by La Danse Macabre, someone I trusted.

    Note to La Danse Macabre:

Do not promote random people to Captain on MY ships!

The warning level of a griefer depends on how many ships they griefed and how much hard work is lost to them per ship. Griefers with a level below 20 are not really that bad and can still be trusted. Griefers with a level of less than 5  mean that they are possible but not proven.

  <svg aria-hidden="true" id='skin' xmlns='http://www.w3.org/2000/svg' width='50px' height='80px' viewbox='0 0 50 80'>
                <defs>
                    <mask maskContentUnits="userSpaceOnUse" id="face" width="50" height="80" viewbox="0 0 50 80"><image href="https://test.drednot.io/img/player_head.png" x="0" y="0"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="body"><image href="https://test.drednot.io/img/player.png" x="17" y="7"/>
                    <image href="https://test.drednot.io/img/player_arm.png" x="20" y="-5"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="legs"><image href="https://test.drednot.io/img/player_leg.png" x="17" y="8"/>
                    <image href="https://test.drednot.io/img/player_leg.png" x="20" y="8"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="hand"><image href="https://test.drednot.io/img/player_hand.png" x="19" y="-5"/></mask>
                </defs>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#face)"/>
                <rect x="0" y="0" width="100" height="100" fill="!_---" mask="url(#body)"/>
                <rect x="0" y="0" width="100" height="100" fill="!-_--" mask="url(#legs)"/>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#hand)"/>
                <image href="https://test.drednot.io/img/player_face.png" x="0" y="0"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="17" y="8"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="20" y="8"/>
            </svg>

    #
    Name
    Warning level
    Proof
    Last seen appearance

```

Body:
I am making an HTML document version of a griefer list for Dredark.io because the ship I made that had the list was ruined. An idiot I thought was my friend went promoting everyone who joined to captain rank and they all messed EVERYTHING up. However, I am having issues with the portion that shows the last seen appearance of each griefer: the SVG mask="url(#face/body/legs/hand)" attribute is not working.

<!DOCTYPE html>

        <title>Dredark.io Griefers</title>

            Because the previous one was ruined

by La Danse Macabre, someone I trusted.

                Note to La Danse Macabre:

Do not promote random people to Captain on MY ships!

The warning level of a griefer depends on how many ships they griefed and how much hard work is lost to them per ship. Griefers with a level below 20 are not really that bad and can still be trusted. Griefers with a level of less than 5 mean that they are possible but not proven.

            <svg id='skin' xmlns='http://www.w3.org/2000/svg' width='50px' height='80px' viewbox='0 0 50 80'>
                <defs>
                    <mask maskContentUnits="userSpaceOnUse" id="face" width="50" height="80" viewbox="0 0 50 80"><image href="https://test.drednot.io/img/player_head.png" x="0" y="0"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="body"><image href="https://test.drednot.io/img/player.png" x="17" y="7"/>
                    <image href="https://test.drednot.io/img/player_arm.png" x="20" y="-5"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="legs"><image href="https://test.drednot.io/img/player_leg.png" x="17" y="8"/>
                    <image href="https://test.drednot.io/img/player_leg.png" x="20" y="8"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="hand"><image href="https://test.drednot.io/img/player_hand.png" x="19" y="-5"/></mask>
                </defs>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#face)"/>
                <rect x="0" y="0" width="100" height="100" fill="!_---" mask="url(#body)"/>
                <rect x="0" y="0" width="100" height="100" fill="!-_--" mask="url(#legs)"/>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#hand)"/>
                <image href="https://test.drednot.io/img/player_face.png" x="0" y="0"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="17" y="8"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="20" y="8"/>
            </svg>

                #
                Name
                Warning level
                Proof
                Last seen appearance

As its own file, the SVG image DOES support it, but for some reason when I embed it within the HTML document it just stops working. The best I can do is make the whole thing disappear. I have tried everything and I have been searching the whole web for a fix but I have lost all hope other than you kind people. What am I doing wrong and how do I fix this?

Body:
Svg <mask> won't be applied, if your svg containing it is hidden via display: none.

But you can hide it like so

#prototypes {
  position: absolute;
  width.0;
  height: 0;
  overflow: hidden;
}

This also applies to other svg elements like <clipPath> or filters.

So It's actually a better practice to hide your svg containing all assets and definitions this way.

Workin example

var list = {
  "clown": {
    warning: 15,
    hair: "none",
    skin: "#ff8800",
    shirt: "#111111",
    pants: "#000000",
    proof: "Many people know him as a griefer"
  },
  "SMARTLABRAT": {
    warning: 1,
    hair: "none",
    skin: "#ffeeaa",
    shirt: "#11aa11",
    pants: "#1122aa",
    proof: "none"
  }
};

function load() {
  var max = 0;
  var sorted = [];
  for (var prop in list) {
    if (list[prop].warning >= max) {
      max = list[prop].warning;
    }
  }
  var cur = max;
  for (var i = max; i > 0; i--) {
    for (var prop in list) {
      if (list[prop].warning == i) {
        sorted.push(prop);
      }
    }
  }
  var html = "";
  var warningColors = ["#00ff00", "#44ff00", "#88ff00", "#aaff00", "#ffff00", "#ffaa00", "#ff8800", "#ff4400", "#ff0000"];
  for (var i = 0; i < sorted.length; i++) {
    var color = "";
    for (var j = 0; j < warningColors.length; j++) {
      if (list[sorted[i]].warning >= (j * 10)) {
        color = warningColors[j];
      }
    }
    html = "<tr><td>" + (i + 1) + "</td><td>" + sorted[i] + "</td><td style='background: " + color + ";'>" + list[sorted[i]].warning + "</td><td>" + list[sorted[i]].proof + "</td><td>" + document.getElementById("skin").outerHTML.replace(/!----/g, "#00ff00").replace("!_---", "#222222").replace("!-_--", "#111111") + "</td></tr>";
    document.getElementById("list").innerHTML += html;
  }
}
window.onload = function() {
  load();
};

#list {
  border: 1px solid #004400;
}

#prototypes {
  position: absolute;
  width.0;
  height: 0;
  overflow: hidden;
}

<details>
  <summary>Because the previous one was ruined</summary>
  <p>by <b>La Danse Macabre</b>, someone I trusted.</p>
  <details>
    <summary>Note to <b>La Danse Macabre</b>:</summary>
    <p>Do not promote random people to <u>Captain</u> on <b>MY</b> ships!</p>
  </details>
</details>
<p>The warning level of a griefer depends on how many ships they griefed and how much hard work is lost to them per ship. Griefers with a level below <code>20</code> are not really that bad and can still be trusted. Griefers with a level of less than <code>5</code>  mean that they are possible but not proven.</p>
<div id="prototypes">
  <svg aria-hidden="true" id='skin' xmlns='http://www.w3.org/2000/svg' width='50px' height='80px' viewbox='0 0 50 80'>
                <defs>
                    <mask maskContentUnits="userSpaceOnUse" id="face" width="50" height="80" viewbox="0 0 50 80"><image href="https://test.drednot.io/img/player_head.png" x="0" y="0"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="body"><image href="https://test.drednot.io/img/player.png" x="17" y="7"/>
                    <image href="https://test.drednot.io/img/player_arm.png" x="20" y="-5"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="legs"><image href="https://test.drednot.io/img/player_leg.png" x="17" y="8"/>
                    <image href="https://test.drednot.io/img/player_leg.png" x="20" y="8"/></mask>
                    <mask maskContentUnits="userSpaceOnUse" id="hand"><image href="https://test.drednot.io/img/player_hand.png" x="19" y="-5"/></mask>
                </defs>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#face)"/>
                <rect x="0" y="0" width="100" height="100" fill="!_---" mask="url(#body)"/>
                <rect x="0" y="0" width="100" height="100" fill="!-_--" mask="url(#legs)"/>
                <rect x="0" y="0" width="100" height="100" fill="!----" mask="url(#hand)"/>
                <image href="https://test.drednot.io/img/player_face.png" x="0" y="0"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="17" y="8"/>
                <image href="https://test.drednot.io/img/player_foot.png" x="20" y="8"/>
            </svg>
</div>
<table id="list" border="1" cellSpacing="0px">
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Warning level</th>
    <th>Proof</th>
    <th>Last seen appearance</th>
  </tr>
</table>


来源: stackexchange

问:
Creating a constraint validator for an external, 3rd party annotation
I have an annotation from a third-party library to which I'd like to add a custom validator implementation. Let's call it @Requirement, and define it as follows:

```<code>@Target({PACKAGE, TYPE, METHOD, FIELD})
@Retention(RUNTIME)
@interface Requirement {}
</code>```

Now I would like to add a constraint validator without adding my own annotation into the mix. I cannot do this with the XML-based (META-INF/validation.xml) configuration, the service loader configuration (a javax.validation.ConstraintValidator file with my validator in it), nor can I with adding custom mappings to the HibernateValidatorConfiguration using LocalValidatorFactoryBean: all of these aforementioned possibilities end up checking for @Constraint sooner or later as well.

Is there any way whatsoever to add a @Constraint-less annotation with a validator implementation?

In my specific case, I am using Java 8 and Spring Boot 2.6.1 (which itself uses Hibernate Validator 6.2.0 and javax.validation:validation-api 2.0.1), but I am (of course) welcoming of information using any Java version and Spring version.

答:
i think rewrite the validator implement may be achieve your goal. Below is the draft code:

```<code>@Log4j2
public class CustomHibernateValidator extends HibernateValidator {

    @Override
    public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
        ValidatorFactoryImpl validatorFactory = new ValidatorFactoryImpl(configurationState);
        CustomConstraintHelper customConstraintHelper = new CustomConstraintHelper();
        try {
            Field field = validatorFactory.getClass().getDeclaredField("constraintHelper");
            field.setAccessible(true);
            field.set(validatorFactory,customConstraintHelper);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            log.error("{}",e);
        }
        customConstraintHelper.modify();

        return validatorFactory;
    }
}

class CustomConstraintHelper extends ConstraintHelper {

    public CustomConstraintHelper() {
        super();
    }

    void modify() {
        Field field = null;
        try {
            field = this.getClass().getSuperclass().getDeclaredField("builtinConstraints");
            field.setAccessible(true);

            Object o = field.get(this);

            Map<Class<? extends Annotation>, List<ConstraintValidatorDescriptor<?>>> tmpConstraints = new HashMap<>();
            tmpConstraints.putAll((Map<Class<? extends Annotation>, List<ConstraintValidatorDescriptor<?>>>) o);
            //inject your validator
            putConstraint(tmpConstraints, Requirement.class, RequirementValidator.class);
            field.set(this, tmpConstraints);
        } catch (NoSuchFieldException | IllegalAccessException e) {

        }

    }

    private static <A extends Annotation> void putConstraint(Map<Class<? extends Annotation>, List<ConstraintValidatorDescriptor<?>>> validators,
                                                             Class<A> constraintType, Class<? extends ConstraintValidator<A, ?>> validatorType) {
        validators.put(constraintType, Collections.singletonList(ConstraintValidatorDescriptor.forClass(validatorType, constraintType)));
    }

}
</code>```

and use this implement to replace default hv via write xx.xx.CustomHibernateValidator to META-INF/services/javax.validation.spi.ValidationProvider

ContentLicense: CC BY-SA 4.0

Body:
I have an annotation from a third-party library to which I'd like to add a custom validator implementation. Let's call it @Requirement, and define it as follows:

@Target({PACKAGE, TYPE, METHOD, FIELD})
@Retention(RUNTIME)
@interface Requirement {}

Now I would like to add a constraint validator without adding my own annotation into the mix. I cannot do this with the XML-based (META-INF/validation.xml) configuration, the service loader configuration (a javax.validation.ConstraintValidator file with my validator in it), nor can I with adding custom mappings to the HibernateValidatorConfiguration using LocalValidatorFactoryBean: all of these aforementioned possibilities end up checking for @Constraint sooner or later as well.

Is there any way whatsoever to add a @Constraint-less annotation with a validator implementation?

In my specific case, I am using Java 8 and Spring Boot 2.6.1 (which itself uses Hibernate Validator 6.2.0 and javax.validation:validation-api 2.0.1), but I am (of course) welcoming of information using any Java version and Spring version.

Body:
i think rewrite the validator implement may be achieve your goal. Below is the draft code:

@Log4j2
public class CustomHibernateValidator extends HibernateValidator {

    @Override
    public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
        ValidatorFactoryImpl validatorFactory = new ValidatorFactoryImpl(configurationState);
        CustomConstraintHelper customConstraintHelper = new CustomConstraintHelper();
        try {
            Field field = validatorFactory.getClass().getDeclaredField("constraintHelper");
            field.setAccessible(true);
            field.set(validatorFactory,customConstraintHelper);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            log.error("{}",e);
        }
        customConstraintHelper.modify();

        return validatorFactory;
    }
}

class CustomConstraintHelper extends ConstraintHelper {

    public CustomConstraintHelper() {
        super();
    }

    void modify() {
        Field field = null;
        try {
            field = this.getClass().getSuperclass().getDeclaredField("builtinConstraints");
            field.setAccessible(true);

            Object o = field.get(this);

            Map<Class<? extends Annotation>, List<ConstraintValidatorDescriptor<?>>> tmpConstraints = new HashMap<>();
            tmpConstraints.putAll((Map<Class<? extends Annotation>, List<ConstraintValidatorDescriptor<?>>>) o);
            //inject your validator
            putConstraint(tmpConstraints, Requirement.class, RequirementValidator.class);
            field.set(this, tmpConstraints);
        } catch (NoSuchFieldException | IllegalAccessException e) {

        }

    }

    private static <A extends Annotation> void putConstraint(Map<Class<? extends Annotation>, List<ConstraintValidatorDescriptor<?>>> validators,
                                                             Class<A> constraintType, Class<? extends ConstraintValidator<A, ?>> validatorType) {
        validators.put(constraintType, Collections.singletonList(ConstraintValidatorDescriptor.forClass(validatorType, constraintType)));
    }

}

and use this implement to replace default hv via write xx.xx.CustomHibernateValidator to META-INF/services/javax.validation.spi.ValidationProvider


问:
how to refresh this api so it's get updated every 5 seconds
```<code>eth_api = "https://api.coinbase.com/v2/exchange-rates?currency=ETH"
headers = {"Accept": "application/json"}

r = requests.request("GET", eth_api, headers=headers)
data2 = r.json()
eth_price = data2['data']['rates']['USD']
print (eth_price)
</code>```

I am still new to this, tried other ways but they are not effective, i want to reuse this in commands

答:
You can use while loop and time. Here's an example for you

```<code>import time
import requests

eth_api = "https://api.coinbase.com/v2/exchange-rates?currency=ETH"
headers = {"Accept": "application/json"}

# initialize variable before the loop.
data2 = None

while True:
    r = requests.request("GET", eth_api, headers=headers)
    data2 = r.json()
    eth_price = data2['data']['rates']['USD']
    print (eth_price)

    # Wait 5 seconds before continuing.
    time.sleep(5)
</code>```

Body:
eth_api = "https://api.coinbase.com/v2/exchange-rates?currency=ETH"
headers = {"Accept": "application/json"}

r = requests.request("GET", eth_api, headers=headers)
data2 = r.json()
eth_price = data2['data']['rates']['USD']
print (eth_price)

I am still new to this, tried other ways but they are not effective, i want to reuse this in commands

Body:
You can use while loop and time. Here's an example for you

import time
import requests

eth_api = "https://api.coinbase.com/v2/exchange-rates?currency=ETH"
headers = {"Accept": "application/json"}

# initialize variable before the loop.
data2 = None

while True:
    r = requests.request("GET", eth_api, headers=headers)
    data2 = r.json()
    eth_price = data2['data']['rates']['USD']
    print (eth_price)

    # Wait 5 seconds before continuing.
    time.sleep(5)


问:
How to Restrict Access to Certain Folders under Project on TFS Server
I have folder (Solution) on TFS/DevOps, under that solution I have 5 sub projects. I want to restrict access to 3 projects so developers will not be able to download or sync those projects folders in their local Visual Studio.
But they will be able to download and work on 2 projects and then check-in the code.
Is there any way I can restrict the access to those 3 projects (folders) on TFS.</p>

答:
If you use GIT you can not restrict access to a folder. Consider using submodules and restricting access to referenced repositories (Git Tools - Submodules).

If you use TFVC you can restrict access to folders: Control access to Team Foundation Version Control


问:
Property length does not exist on type Observable <[]> in angular
I have this service in angular which returns transcript

```<code>public transcript_arr =new ReplaySubject<[]>(1);
public confidence_arr=new ReplaySubject<[]>(1);
getTranscriptValue()
  {
    return this.transcript_arr.pipe(data => {return data;})
  }

getConfidenceValue()
  {
    return this.confidence_arr;
  }
</code>```

.ts file

```<code>service_transcript$: Observable<[]>;

this.service_transcript$=this.service.getTranscriptValue();

 for (var i = 0; i < this.service_transcript$.length; i++) {

 }

 this.http.post(this.baseUrl+'api/auth/post-data', formData).subscribe(response  => {

}
</code>```

In .ts file i'm using service data for computational purpose then sending it to server but getting
this error :

Property length does not exist on type Observable <[]> in angular
Updated Code:

```<code> const transcript_arr = [];
 const confidence_arr = [];

      this.service.getTranscriptValue().subscribe(el=>{
        for (var i = 0; i < el.length; i++) {
            if(this.hasWhiteSpace(el[i]))
            {
              const arr_transcript = el[i].trim().split(" ");
              for (var j = 0; j < arr_transcript.length; j++) {
                transcript_arr.push(arr_transcript[j].toLowerCase());
                confidence_arr.push(service_confidence[i]);
              }
            }
            else
            {
              transcript_arr.push(el[i].toLowerCase());
              confidence_arr.push(service_confidence[i]);
            }
        }
      }) ;
</code>```

Any solution to resolve this issue Thanks

答:
The pipe in your getTranscriptValue doesn't do anything, you can safely remove it altogether:

```<code>getTranscriptValue() {
  return this.transcript_arr;
}
</code>```

As for the for loop, you need to get access to the actual data by subscribing to your Observable and then loop through that. Something like this:

```<code>this.service_transcript$.subscribe(transcripts => {
  for (var i = 0; i < transcripts.length; i++) {

  }
});
</code>```

Body:
I have this service in angular which returns transcript

public transcript_arr =new ReplaySubject<[]>(1);
public confidence_arr=new ReplaySubject<[]>(1);
getTranscriptValue()
  {
    return this.transcript_arr.pipe(data => {return data;})
  }

getConfidenceValue()
  {
    return this.confidence_arr;
  }

.ts file

service_transcript$: Observable<[]>;

this.service_transcript$=this.service.getTranscriptValue();

 for (var i = 0; i < this.service_transcript$.length; i++) {

 }

 this.http.post(this.baseUrl+'api/auth/post-data', formData).subscribe(response  => {

}

In .ts file i'm using service data for computational purpose then sending it to server but getting
this error :

Property length does not exist on type Observable <[]> in angular
Updated Code:

 const transcript_arr = [];
 const confidence_arr = [];

      this.service.getTranscriptValue().subscribe(el=>{
        for (var i = 0; i < el.length; i++) {
            if(this.hasWhiteSpace(el[i]))
            {
              const arr_transcript = el[i].trim().split(" ");
              for (var j = 0; j < arr_transcript.length; j++) {
                transcript_arr.push(arr_transcript[j].toLowerCase());
                confidence_arr.push(service_confidence[i]);
              }
            }
            else
            {
              transcript_arr.push(el[i].toLowerCase());
              confidence_arr.push(service_confidence[i]);
            }
        }
      }) ;

Any solution to resolve this issue Thanks

Body:
The pipe in your getTranscriptValue doesn't do anything, you can safely remove it altogether:

getTranscriptValue() {
  return this.transcript_arr;
}

As for the for loop, you need to get access to the actual data by subscribing to your Observable and then loop through that. Something like this:

this.service_transcript$.subscribe(transcripts => {
  for (var i = 0; i < transcripts.length; i++) {

  }
});


问:
Gitlab CI variables and script section give different results
I've searched a lot of examples but they did not work for me.

I'm trying to run linters for changed files when MR is opened.

My .gitlab-ci.yml

```<code>run_linters:
  image: python:3
  variables:
    FILES: git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
  before_script:
    - python3 -m pip install black==21.5b1
    - python3 -m pip install flake8==3.9.2
  script:
    - echo $FILES
    - git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
    - black --check $FILES
    - flake8 $FILES
  only:
    - merge_requests
</code>```

And I'm getting strange output.

echo $FILES says git diff --name-only main | grep incoming_file.py

incoming_file.py is the only file in that MR. Why is it around grep?

And git diff at script section says fatal: ambiguous argument 'main': unknown revision or path not in the working tree.

Why is filename present around grep?

Why are same git diff commands give different result?

答:
Why is filename present around grep?

In bash when you refer to * this will expand and try to match the files/directories present in your current path, in your case since only the incoming_file.py is present, so it expands to this.

Why are same git diff commands give different result?

```<code>variables:
  FILES: git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
</code>```

When you define a variable in variables section, Gitlab doesnt execute the command, it simple populates the variable FILES with the string git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py

Then in the script section, the runner expands *.py to incoming_file.py and $CI_MERGE_REQUEST_TARGET_BRANCH_NAME to main

that's why in echo you see git diff --name-only main | grep incoming_file.py

Here

```<code> - git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
</code>```

You actually execute the command and you get the mentioned message

Body:
I've searched a lot of examples but they did not work for me.

I'm trying to run linters for changed files when MR is opened.

My .gitlab-ci.yml

run_linters:
  image: python:3
  variables:
    FILES: git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
  before_script:
    - python3 -m pip install black==21.5b1
    - python3 -m pip install flake8==3.9.2
  script:
    - echo $FILES
    - git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
    - black --check $FILES
    - flake8 $FILES
  only:
    - merge_requests

And I'm getting strange output.

echo $FILES says git diff --name-only main | grep incoming_file.py

incoming_file.py is the only file in that MR. Why is it around grep?

And git diff at script section says fatal: ambiguous argument 'main': unknown revision or path not in the working tree.

Why is filename present around grep?

Why are same git diff commands give different result?

Body:
Why is filename present around grep?

In bash when you refer to * this will expand and try to match the files/directories present in your current path, in your case since only the incoming_file.py is present, so it expands to this.

Why are same git diff commands give different result?

variables:
  FILES: git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py

When you define a variable in variables section, Gitlab doesnt execute the command, it simple populates the variable FILES with the string git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py

Then in the script section, the runner expands *.py to incoming_file.py and $CI_MERGE_REQUEST_TARGET_BRANCH_NAME to main

that's why in echo you see git diff --name-only main | grep incoming_file.py

Here

 - git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py

You actually execute the command and you get the mentioned message


问:
HttpClient configuration
I was refactoring some old code the other day and came across a WebClient creation. (The code is written in Kotlin)

fun String.createClient(responseFilter: ExchangeFilterFunction = ExchangeFilterFunction.ofResponseProcessor { Mono.just(it) }): WebClient =
    WebClient
        .builder()
        .codecs {
            it.defaultCodecs().maxInMemorySize(52428800) // 50 Mb
            it.defaultCodecs().jackson2JsonEncoder(jackson2JsonEncoder())
            it.defaultCodecs().jackson2JsonDecoder(jackson2JsonDecoder())
        }
        .baseUrl(this)
        .filter(responseFilter)
        .clientConnector(
            ReactorClientHttpConnector(
                HttpClient.create()
                    .tcpConfiguration {
                        it.bootstrap { b ->

                            b.setCustomRequestLogging {
                                b
                                    .group(onClient(DEFAULT_NATIVE))
                                    .channel(EpollSocketChannel::class.java)
                            }

                            updateLogSupport(b, CustomLoggingHandler(HttpClient::class.java))
                        }
                    }
                    .apply {
                        if (this@createClient.startsWith("https://", true))
                            secure { it.sslContext(SslContextBuilder.forClient().trustManager(INSTANCE).build()) }
                    }
            )
        )
        .build()

fun <B : AbstractBootstrap, C : Channel> AbstractBootstrap.setCustomRequestLogging(init: HttpResources.() -> Unit) {

    if (System.getProperty("os.name").toLowerCase() == "linux" && config().group() == null)
        HttpResources.get().init()
}
```
<p>Since <code>tcpConfiguration</code> and <code>bootstrap</code> are both marked deprecated I figured out I can replace it with</p>
<pre class="lang-kotlin prettyprint-override"><code>
HttpClient.create().doOnRequest { _, connection -> connection.addHandlerFirst(CustomLoggingHandler(HttpClient::class.java)) }
</code>```

but I'm not quite sure what's going on in this part

b.setCustomRequestLogging {
                                b
                                    .group(onClient(DEFAULT_NATIVE))
                                    .channel(EpollSocketChannel::class.java)
                            }
```

and how can I replace it using not deprecated api?

答:
By default when you are running on Linux OS, Reactor Netty will configure for you Epoll transport. There is no need to configure by yourself neither the channel type nor the EventLoopGroup.
For the deprecated tcpConfiguration check the javadoc for HttpClient.html#tcpConfiguration where you can find a complete documentation for the replacements.

Title: HttpClient configuration

Body:
I was refactoring some old code the other day and came across a WebClient creation. (The code is written in Kotlin)

fun String.createClient(responseFilter: ExchangeFilterFunction = ExchangeFilterFunction.ofResponseProcessor { Mono.just(it) }): WebClient =
    WebClient
        .builder()
        .codecs {
            it.defaultCodecs().maxInMemorySize(52428800) // 50 Mb
            it.defaultCodecs().jackson2JsonEncoder(jackson2JsonEncoder())
            it.defaultCodecs().jackson2JsonDecoder(jackson2JsonDecoder())
        }
        .baseUrl(this)
        .filter(responseFilter)
        .clientConnector(
            ReactorClientHttpConnector(
                HttpClient.create()
                    .tcpConfiguration {
                        it.bootstrap { b ->

                            b.setCustomRequestLogging {
                                b
                                    .group(onClient(DEFAULT_NATIVE))
                                    .channel(EpollSocketChannel::class.java)
                            }

                            updateLogSupport(b, CustomLoggingHandler(HttpClient::class.java))
                        }
                    }
                    .apply {
                        if (this@createClient.startsWith("https://", true))
                            secure { it.sslContext(SslContextBuilder.forClient().trustManager(INSTANCE).build()) }
                    }
            )
        )
        .build()

fun <B : AbstractBootstrap, C : Channel> AbstractBootstrap.setCustomRequestLogging(init: HttpResources.() -> Unit) {

    if (System.getProperty("os.name").toLowerCase() == "linux" && config().group() == null)
        HttpResources.get().init()
}

Since tcpConfiguration and bootstrap are both marked deprecated I figured out I can replace it with

HttpClient.create().doOnRequest { _, connection -> connection.addHandlerFirst(CustomLoggingHandler(HttpClient::class.java)) }

but I'm not quite sure what's going on in this part

b.setCustomRequestLogging {
                                b
                                    .group(onClient(DEFAULT_NATIVE))
                                    .channel(EpollSocketChannel::class.java)
                            }

and how can I replace it using not deprecated api?


问:
Error registering Gitlab Runner in Mac. forbidden
I have been trying to register a gitlab runner in my Mac but I keep getting errors saying it is forbidden. I was able to register on windows but for some reason it doesn't work on my Mac.
These are the steps I take:

```<code>gitlab-runner register \
>   --non-interactive \
>   --url "https://gitlab.com/" \
>   --registration-token "token" \
>   --description "MyApp runner with shell" \
>   --tag-list ios \
>   --executor "shell"
Runtime platform                                    arch=amd64 os=darwin pid=3868    revision=98daeee0 version=14.7.0
WARNING: Running in user-mode.
WARNING: Use sudo for system-mode:
WARNING: $ sudo gitlab-runner...

ERROR: Registering runner... forbidden (check registration token)  runner=WswE4
PANIC: Failed to register the runner. You may be having network problems.
</code>```

I am using the right token. I tried registering with docker and manually in Mac and both failed. Any help?

答:
Unless you are registering a GitLab runner to a secondary node (issue 350755) or you have a problem with a reset token (issue 351114), that seems to be a bug which should be reported.

An issues search does not show many other cases where "Registering runner... forbidden".

Check also the logs in case of any recorded error message linked to your command there.

Body:
I have been trying to register a gitlab runner in my Mac but I keep getting errors saying it is forbidden. I was able to register on windows but for some reason it doesn't work on my Mac.
These are the steps I take:

gitlab-runner register \
>   --non-interactive \
>   --url "https://gitlab.com/" \
>   --registration-token "token" \
>   --description "MyApp runner with shell" \
>   --tag-list ios \
>   --executor "shell"
Runtime platform                                    arch=amd64 os=darwin pid=3868    revision=98daeee0 version=14.7.0
WARNING: Running in user-mode.
WARNING: Use sudo for system-mode:
WARNING: $ sudo gitlab-runner...

ERROR: Registering runner... forbidden (check registration token)  runner=WswE4
PANIC: Failed to register the runner. You may be having network problems.

I am using the right token. I tried registering with docker and manually in Mac and both failed. Any help?


问:
How to Tesseract OCR for php without Composer
Hi can anyone help me to install Tesseract OCR for php without Composer. How can I use it on xampp server so that the code can be used to develop a web application. Thanks in advance</p>

答:
I know this is old, but still would have helped me out...  This is the code that I created to use the latest Tesseract without composer.  To those that are asking why, instead of creating a solution, why waste people's reading time when you don't understand?

<?php
require_once "./tesseract-ocr/src/TesseractOCR.php";
require_once "./tesseract-ocr/src/Command.php";
require_once "./tesseract-ocr/src/FriendlyErrors.php";
require_once "./tesseract-ocr/src/Process.php";
require_once "./tesseract-ocr/src/TesseractOcrException.php";
require_once "./tesseract-ocr/src/TesseractNotFoundException.php";
require_once "./tesseract-ocr/src/ImageNotFoundException.php";
require_once "./tesseract-ocr/src/UnsuccessfulCommandException.php";

$filepath = "./images/processing";
$dir = new DirectoryIterator("$filepath");

use thiagoalessio\TesseractOCR\TesseractOCR;

foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
    $filename = $fileinfo->getFilename();

$fullfilepath = $filepath . "/" . $filename;
$ocr = new TesseractOCR("$filename");
try {
$content = $ocr->run();
}
catch (exception $e) {
 echo "$filename - No text, good image\n";
continue;
}

echo "$filename - There's Text!\n";
die();

}
}

?>```

In this case, I'm using Tesseract just to detect if there's any text in an image at all (which for me is bad).

ContentLicense: CC BY-SA 3.0

Body:
I know this is old, but still would have helped me out...  This is the code that I created to use the latest Tesseract without composer.  To those that are asking why, instead of creating a solution, why waste people's reading time when you don't understand?

<?php
require_once "./tesseract-ocr/src/TesseractOCR.php";
require_once "./tesseract-ocr/src/Command.php";
require_once "./tesseract-ocr/src/FriendlyErrors.php";
require_once "./tesseract-ocr/src/Process.php";
require_once "./tesseract-ocr/src/TesseractOcrException.php";
require_once "./tesseract-ocr/src/TesseractNotFoundException.php";
require_once "./tesseract-ocr/src/ImageNotFoundException.php";
require_once "./tesseract-ocr/src/UnsuccessfulCommandException.php";

$filepath = "./images/processing";
$dir = new DirectoryIterator("$filepath");

use thiagoalessio\TesseractOCR\TesseractOCR;

foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
    $filename = $fileinfo->getFilename();

$fullfilepath = $filepath . "/" . $filename;
$ocr = new TesseractOCR("$filename");
try {
$content = $ocr->run();
}
catch (exception $e) {
 echo "$filename - No text, good image\n";
continue;
}

echo "$filename - There's Text!\n";
die();

}
}

?>

In this case, I'm using Tesseract just to detect if there's any text in an image at all (which for me is bad).


问:
compiling 10000 of java project simultaneously
Any one know how to compiling and run huge no of java project in simultaneously(assume request comming every time) can i use for sun jdk for this situation. is there way to distributed compilation? </p>

答:
Maven is starting to support it... but why? In the time it takes to do a parallel build of Firefox (a typical, large C++ app) on say... a Core 2 Duo, you probably could build at least 5,000 independent Java apps so long as your build process was properly glued together.

(In the time it takes to build about a half dozen or so large C++ objects for Firefox on my MacBook Pro, I could probably build the entire CAS webapp which has a few hundred Java classes and about 12-18 Maven submodules)


问:
The body of view to be destroyed gets called (but it shouldn't)
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

```<code> list view -> detail view
</code>```

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

```<code>list view -> detail view -> another detail view (containing the same item)
</code>```

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

```<code>import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}
</code>```

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

答:
You need to use your data model rather than performing procedural code in your views.  Also, don't pass items by id; Just pass the item.

Because you use the id of the Foo instead of the Foo itself, and you have a force unwrap in your get function, you get a crash.

If you refactor to use your model and not use ids it works as you want.

You don't really need your array extension. Specialised code as an extension to a generic object doesn't look right to me.

The delete code is so simple you can just handle it in your model, and do so safely with conditional unwrapping.

```<code>class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]

    func delete(foo: Foo) {
       if let index = firstIndex(where: { $0.id == id }) {
           self.foos.remove(at: index)
       }
    }
}

struct ListView: View {
    @ObservedObject var model: DataModel

    var body: some View {
        NavigationView {
            List {
                ForEach(model.foos) { foo in
                    NavigationLink {
                        DetailView(model: model, foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @ObservedObject var model: DataModel
    var foo: Foo
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(foo.id)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foo.value)")
            NavigationLink {
                DetailView(model: model, foo: foo, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                model.delete(foo:foo)
            }
        }
    }
}
</code>```

Body:
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

 list view -> detail view

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

list view -> detail view -> another detail view (containing the same item)

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

Body:
You need to use your data model rather than performing procedural code in your views.  Also, don't pass items by id; Just pass the item.

Because you use the id of the Foo instead of the Foo itself, and you have a force unwrap in your get function, you get a crash.

If you refactor to use your model and not use ids it works as you want.

You don't really need your array extension. Specialised code as an extension to a generic object doesn't look right to me.

The delete code is so simple you can just handle it in your model, and do so safely with conditional unwrapping.

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]

    func delete(foo: Foo) {
       if let index = firstIndex(where: { $0.id == id }) {
           self.foos.remove(at: index)
       }
    }
}

struct ListView: View {
    @ObservedObject var model: DataModel

    var body: some View {
        NavigationView {
            List {
                ForEach(model.foos) { foo in
                    NavigationLink {
                        DetailView(model: model, foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @ObservedObject var model: DataModel
    var foo: Foo
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(foo.id)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foo.value)")
            NavigationLink {
                DetailView(model: model, foo: foo, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                model.delete(foo:foo)
            }
        }
    }
}


问:
Concatenating distinct column values in SQL Server
I am trying to concatenate many columns and separating it with a comma as below:

```<code>Column
------
abc
bcd
bgd
abc
</code>```

Expected output: abc,bcd,bgd

I am using this code:

```<code>CREATE FUNCTION concatinate(@PK uniqueidentifier)
RETURNS varchar(max)
AS
BEGIN
    DECLARE @result varchar(max)

    SELECT @result = ISNULL(@result + ', ', '') + Column
    FROM table
</code>```

The result I am getting is

```<code>abc,bcd,bgd,abc
</code>```

I am not able to only select the distinct values. Please guide.

答:
A few amendments to your original code:

```<code>DECLARE @result varchar(max)

SELECT @result = ISNULL(@result + ', ', '') + dist.Column
FROM (SELECT DISTINCT Column FROM table) dist

PRINT(@result)
</code>```

This will concatenate a distinct list. Unlike the initial answer above, you will not get an extra comma ',' at the end.

Body:
I am trying to concatenate many columns and separating it with a comma as below:

Column
------
abc
bcd
bgd
abc

Expected output: abc,bcd,bgd

I am using this code:

CREATE FUNCTION concatinate(@PK uniqueidentifier)
RETURNS varchar(max)
AS
BEGIN
    DECLARE @result varchar(max)

    SELECT @result = ISNULL(@result + ', ', '') + Column
    FROM table

The result I am getting is

abc,bcd,bgd,abc

I am not able to only select the distinct values. Please guide.

Body:
A few amendments to your original code:

DECLARE @result varchar(max)

SELECT @result = ISNULL(@result + ', ', '') + dist.Column
FROM (SELECT DISTINCT Column FROM table) dist

PRINT(@result)

This will concatenate a distinct list. Unlike the initial answer above, you will not get an extra comma ',' at the end.


问:
How do I automatically redirect when the session cookie expires?
When a user is idle for ten minutes, I would like to have an automatic redirect. Below is the test code, which is not working.

The LoginPath, LogoutPath, and AccessDeniedPath do not exist. Therefore, I would expect an error after the timeout period. Instead, I can continue to successfully click "Home" and "About" without an error and without being redirected. My expectation is that I will be redirected back to the home page.

Sample code:

services.AddMemoryCache();
services.AddSession(options =>
    {
        options.Cookie.Name = "MyAppCookie";
        options.Cookie.IsEssential = true;
        options.Cookie.HttpOnly = true;
        options.IdleTimeout = TimeSpan.FromMinutes(1);
    });

services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Login";
        options.AccessDeniedPath = "/Account/AccessDenied";
        options.SlidingExpiration = true;
    });
```

答:
You can use Axios interceptors for them, in the first request after token expiration you can redirect it.
Also, you can decode your token at [https://jwt.io/][1] and take the expiration date, you can check by it.</p>


问:
remove toggle gear icon controlbar
I'm trying to customize how my R shiny app looks like and playing around with various elements on the page.

Just wondering how do I remove this toggle icon from the header? I've tried something like this but it doesn't work:

```<code>shinyjs::runjs("document.getElementsByClassName('skin-blue sidebar-mini')[0].style.visibility = 'hidden';")
</code>```

reproducible example:

```<code>library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyjs)
library(DT)

ui <- shinydashboardPlus::dashboardPage(
  options = list(sidebarExpandOnHover = TRUE),
   header = dashboardHeader(
    tags$li(
      id = 'right-sidebar-toggle-list-item',
      class = "dropdown",
      actionLink("rightSidebarToggle", "Select Population"))

  ),
  shinydashboardPlus::dashboardSidebar( disable = TRUE ,
                                        sidebarMenu(
                                          selectInput(
                                            "countries", label = "Select Countries",
                                            choices = c("B", "C", "A"), selected = "A",
                                            multiple = TRUE
                                          ))
  ),# minified = TRUE, collapsed = F),
  controlbar = shinydashboardPlus::dashboardControlbar(id = "controlbar", collapsed = F,
                                                       skin = "dark",
                                                       controlbarMenu(
                                                         id = "menu",
                                                         controlbarItem(
                                                           "Tab 1",
                                                           "Welcome to tab 1"
                                                         ),
                                                         controlbarItem(
                                                           "Tab 2",
                                                           "Welcome to tab 2"
                                                         )
                                                       )
  ),

  shinydashboard::dashboardBody(
    useShinyjs(),
    tabsetPanel( id="tabset",
                 tabPanel("Resource Allocation", value="tab1", plotOutput("plot")),
    )
  ),
  # controlbar = dashboardControlbar(collapsed = F),
  title = "DashboardPage"
)
server <- function(input, output) {
  output$plot <- renderPlot(plot(cars))

}

shinyApp(ui, server)
</code>```

答:
We can use some JS via tags$script to hide the icon:

```<code>library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyjs)
library(DT)

ui <- shinydashboardPlus::dashboardPage(
  options = list(sidebarExpandOnHover = TRUE),
  shinydashboardPlus::dashboardHeader(
    tags$li(
      id = 'right-sidebar-toggle-list-item',
      class = "dropdown",
      actionLink("rightSidebarToggle", "Select Population"))

  ),
  shinydashboardPlus::dashboardSidebar(disable = TRUE ,
                                       sidebarMenu(
                                         selectInput(
                                           "countries",
                                           label = "Select Countries",
                                           choices = c("B", "C", "A"),
                                           selected = "A",
                                           multiple = TRUE
                                         )
                                       )),
  # minified = TRUE, collapsed = F),
  controlbar = shinydashboardPlus::dashboardControlbar(
    id = "controlbar",
    collapsed = F,
    skin = "dark",
    controlbarMenu(
      id = "menu",
      controlbarItem("Tab 1",
                     "Welcome to tab 1"),
      controlbarItem("Tab 2",
                     "Welcome to tab 2")
    )
  ),
  shinydashboard::dashboardBody(
    useShinyjs(),
    # hide icon
    # tags$script(
    #   HTML(
    #     'var e = document.querySelector("body > div.wrapper > header > nav > div:nth-child(4) > ul > li > a > i");
    #        e.setAttribute("style", "display: none;");'
    #   )
    # ),
    # hide hyperlink
    tags$script(HTML('var e = document.querySelector("body > div.wrapper > header > nav > div:nth-child(4) > ul > li:last-child > a");
                      e.setAttribute("style", "display: none;");')),
    tabsetPanel(
      id = "tabset",
      tabPanel("Resource Allocation", value = "tab1", plotOutput("plot")),
    )
  ),
  # controlbar = dashboardControlbar(collapsed = F),
  title = "DashboardPage"
)

server <- function(input, output) {
  output$plot <- renderPlot(plot(cars))
}

shinyApp(ui, server)
</code>```

Title: remove toggle gear icon controlbar

Body:
I'm trying to customize how my R shiny app looks like and playing around with various elements on the page.

Just wondering how do I remove this toggle icon from the header? I've tried something like this but it doesn't work:

shinyjs::runjs("document.getElementsByClassName('skin-blue sidebar-mini')[0].style.visibility = 'hidden';")

reproducible example:

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyjs)
library(DT)

ui <- shinydashboardPlus::dashboardPage(
  options = list(sidebarExpandOnHover = TRUE),
   header = dashboardHeader(
    tags$li(
      id = 'right-sidebar-toggle-list-item',
      class = "dropdown",
      actionLink("rightSidebarToggle", "Select Population"))

  ),
  shinydashboardPlus::dashboardSidebar( disable = TRUE ,
                                        sidebarMenu(
                                          selectInput(
                                            "countries", label = "Select Countries",
                                            choices = c("B", "C", "A"), selected = "A",
                                            multiple = TRUE
                                          ))
  ),# minified = TRUE, collapsed = F),
  controlbar = shinydashboardPlus::dashboardControlbar(id = "controlbar", collapsed = F,
                                                       skin = "dark",
                                                       controlbarMenu(
                                                         id = "menu",
                                                         controlbarItem(
                                                           "Tab 1",
                                                           "Welcome to tab 1"
                                                         ),
                                                         controlbarItem(
                                                           "Tab 2",
                                                           "Welcome to tab 2"
                                                         )
                                                       )
  ),

  shinydashboard::dashboardBody(
    useShinyjs(),
    tabsetPanel( id="tabset",
                 tabPanel("Resource Allocation", value="tab1", plotOutput("plot")),
    )
  ),
  # controlbar = dashboardControlbar(collapsed = F),
  title = "DashboardPage"
)
server <- function(input, output) {
  output$plot <- renderPlot(plot(cars))

}

shinyApp(ui, server)

Body:
We can use some JS via tags$script to hide the icon:

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyjs)
library(DT)

ui <- shinydashboardPlus::dashboardPage(
  options = list(sidebarExpandOnHover = TRUE),
  shinydashboardPlus::dashboardHeader(
    tags$li(
      id = 'right-sidebar-toggle-list-item',
      class = "dropdown",
      actionLink("rightSidebarToggle", "Select Population"))

  ),
  shinydashboardPlus::dashboardSidebar(disable = TRUE ,
                                       sidebarMenu(
                                         selectInput(
                                           "countries",
                                           label = "Select Countries",
                                           choices = c("B", "C", "A"),
                                           selected = "A",
                                           multiple = TRUE
                                         )
                                       )),
  # minified = TRUE, collapsed = F),
  controlbar = shinydashboardPlus::dashboardControlbar(
    id = "controlbar",
    collapsed = F,
    skin = "dark",
    controlbarMenu(
      id = "menu",
      controlbarItem("Tab 1",
                     "Welcome to tab 1"),
      controlbarItem("Tab 2",
                     "Welcome to tab 2")
    )
  ),
  shinydashboard::dashboardBody(
    useShinyjs(),
    # hide icon
    # tags$script(
    #   HTML(
    #     'var e = document.querySelector("body > div.wrapper > header > nav > div:nth-child(4) > ul > li > a > i");
    #        e.setAttribute("style", "display: none;");'
    #   )
    # ),
    # hide hyperlink
    tags$script(HTML('var e = document.querySelector("body > div.wrapper > header > nav > div:nth-child(4) > ul > li:last-child > a");
                      e.setAttribute("style", "display: none;");')),
    tabsetPanel(
      id = "tabset",
      tabPanel("Resource Allocation", value = "tab1", plotOutput("plot")),
    )
  ),
  # controlbar = dashboardControlbar(collapsed = F),
  title = "DashboardPage"
)

server <- function(input, output) {
  output$plot <- renderPlot(plot(cars))
}

shinyApp(ui, server)


问:
ERR_SSL_VERSION_OR_CIPHER_MISMATCH error on Chrome only
While opening my private website, I am getting the following error in CHROME only.  in internet explorer its working without any issue.

I tried resetting chrome, delete all cache but no luck. nothing changed from backend site and error was started as of sudden.

weird thing is, if I open Fiddler 4 at the same time then its working. don't know what Fiddler is doing to fix that prob but when I close it again, then its again giving the same error.

答: The warning occurs because the website does not support TLS 1.2. Contact the site administrator. Problem encountered after updating Chrome to 98x. The warning appears with Firefox but the site works by enabling tls 1.0 and 1.1.</p>


问:
No such module 'IQKeyboardManagerSwift'
New to Xcode (dabble a little). I paid a developer to build an iOS app for me. He sent me the source code and I have opened it in Xcode 13.2.1. I needed to edit the info.plist to include a description why location was required (got this done). When I try to run the build, I get the error 'no such module 'IQKeyboardManagerSwift'. In AppDelegate, I see 'import IQKeyboardManagerSwift --- No such module 'IQKeyboardManagerSwift'. I went to the Podfile directory and ran 'pod install'. Output says:

Analyzing dependencies

Downloading dependencies

Generating Pods project

Integrating client project

Pod installation complete! There are 7 dependencies from the Podfile and 8 total pods installed.

I'm still getting the error when trying to run the build. I tried cleaning the build folder and running the build again but still, same error. What am I missing?

答:
Is the codebase completely in Swift?, else you will have to include import in the Bridging header file
If in swift you can try:
Select project name -> Select Build Settings(tab) and search Framework Search Paths double click and set the desired path($(SRCROOT)) to recursive

Title: No such module 'IQKeyboardManagerSwift'


答:
By updating do you mean to run this block of code every 5 seconds.
If you are trying to do that then you have to put the block of code in a while loop and put time.sleep(5) to run the loop every 5 seconds.
NOTE ~ You can't close the running process or the loop will stop so as your script.</p>

Title: how to refresh this api so it's get updated every 5 seconds


问:
Calculate Time difference using powershell
I would like to calculate Time difference between two time stamps in seconds

```<code>$starttime = (Get-Date).ToString("yyyy-MM-ddThh:mm:ss")
$endtime = (Get-Date).ToString("yyyy-MM-ddThh:mm:ss")

$tdiff = $starttime-$endtime

Write-Output $tdiff.seconds
</code>```

The above code throws the below error:

```<code>Cannot convert value "2022-02-10T11:40:07" to type "System.Int32". Error: "Input string was not in a correct format."
</code>```

Appreciate, if any one can help

答:
It is actually much simpler than that.

```<code>$StartDate=(GET-DATE)

$EndDate=[datetime]”01/01/2014 00:00”

NEW-TIMESPAN –Start $StartDate –End $EndDate
</code>```

This is an example from Microsoft Devblogs
https://devblogs.microsoft.com/scripting/powertip-get-time-difference-between-dates-with-powershell/

Body:
I would like to calculate Time difference between two time stamps in seconds

$starttime = (Get-Date).ToString("yyyy-MM-ddThh:mm:ss")
$endtime = (Get-Date).ToString("yyyy-MM-ddThh:mm:ss")

$tdiff = $starttime-$endtime

Write-Output $tdiff.seconds

The above code throws the below error:

Cannot convert value "2022-02-10T11:40:07" to type "System.Int32". Error: "Input string was not in a correct format."

Appreciate, if any one can help

Body:
It is actually much simpler than that.

$StartDate=(GET-DATE)

$EndDate=[datetime]”01/01/2014 00:00”

NEW-TIMESPAN –Start $StartDate –End $EndDate

This is an example from Microsoft Devblogs
https://devblogs.microsoft.com/scripting/powertip-get-time-difference-between-dates-with-powershell/


问:
Spring Tool Suite(STS) desktop entry for ubuntu
How to create desktop entry for Spring Tool Suite in Ubuntu?.Want to open the IDE from desktop.</p>

答:
This worked for me on Ubuntu 20.04 LTS, the important bit is the StartupVMClass=SpringToolSuite4 had to match the executable in the line Exec=/home/johan/bin/sts-4.13.1.RELEASE/SpringToolSuite4 %u:

```<code>[Desktop Entry]
Version=1.1
Name=Spring Tool Suite 4
Comment=Spring Tool Sutie 4.13.1
Exec=/home/johan/bin/sts-4.13.1.RELEASE/SpringToolSuite4 %u
Type=Application
MimeType=x-scheme-handler/eclipse+command;x-scheme-handler/eclipse+mpc;
Icon=/home/johan/bin/sts-4.13.1.RELEASE/icon.xpm
Terminal=false
Categories=Utility;Development;IDE;
StartupWMClass=SpringToolSuite4
</code>```

Otherwise another icon opened up.

Body:
This worked for me on Ubuntu 20.04 LTS, the important bit is the StartupVMClass=SpringToolSuite4 had to match the executable in the line Exec=/home/johan/bin/sts-4.13.1.RELEASE/SpringToolSuite4 %u:

[Desktop Entry]
Version=1.1
Name=Spring Tool Suite 4
Comment=Spring Tool Sutie 4.13.1
Exec=/home/johan/bin/sts-4.13.1.RELEASE/SpringToolSuite4 %u
Type=Application
MimeType=x-scheme-handler/eclipse+command;x-scheme-handler/eclipse+mpc;
Icon=/home/johan/bin/sts-4.13.1.RELEASE/icon.xpm
Terminal=false
Categories=Utility;Development;IDE;
StartupWMClass=SpringToolSuite4

Otherwise another icon opened up.


问:
MySQL Compare TIME data with Current Time
I have MySQL Column time_start with data type TIME , 00:00:00 Format

I tried to get row in the next 60 Minutes

```<code>SELECT * FROM time_table
        WHERE time_status = 'OK' AND (time_start > TIME(NOW()) AND time_start < TIME(NOW()) + '60 MINUTE')
</code>```

But apparently it doesnt work

Then i tried using CURTIME

```<code>SELECT * FROM time_table
    WHERE time_status = 'Waiting' AND (time_start > CURTIME() AND time_start < (CURTIME() + '60 MINUTE'))
</code>```

it still doesn't work

Is there anything wrong with my query?

答:
Trying to increase a datetime value by using a string won't work. You have to use the INTERVAL keyword:

```<code>SELECT * FROM time_table
        WHERE time_status = 'OK' AND
       (time_start > TIME(NOW()) AND time_start < TIME(NOW()) + INTERVAL 60 MINUTE)
</code>```

Body:
I have MySQL Column time_start with data type TIME , 00:00:00 Format

I tried to get row in the next 60 Minutes

SELECT * FROM time_table
        WHERE time_status = 'OK' AND (time_start > TIME(NOW()) AND time_start < TIME(NOW()) + '60 MINUTE')

But apparently it doesnt work

Then i tried using CURTIME

SELECT * FROM time_table
    WHERE time_status = 'Waiting' AND (time_start > CURTIME() AND time_start < (CURTIME() + '60 MINUTE'))

it still doesn't work

Is there anything wrong with my query?

Body:
Trying to increase a datetime value by using a string won't work. You have to use the INTERVAL keyword:

SELECT * FROM time_table
        WHERE time_status = 'OK' AND
       (time_start > TIME(NOW()) AND time_start < TIME(NOW()) + INTERVAL 60 MINUTE)


问:
Issue with displaying Error message in a page having two forms
I am developing one JSF page, in that i am having two forms.  And I am using rich:messages in both the forms.

Suppose, in the first form, if I don't enter any required fields and I click Save, then error messages are displaying twice in the page(as i am using rich:messages in two forms).

Is there any way so that error messages display with respect to the form?

Thanks in advance.

答:
If you are using RichFaces 3.3.3.Final you can do it like so:

```<code><a4j:form id="tmpfrm1">
    <rich:messages />
    <h:inputText value="#{mybean.intmp1}" required="true"/>
    <a4j:commandButton value="save" action="#{mybean.test1}" reRender="tmpfrm1" limitToList="true" />
</a4j:form>

<a4j:form id="tmpfrm2">
    <rich:messages />
    <h:inputText value="#{mybean.intmp2}" required="true"/>
    <a4j:commandButton value="save" action="#{mybean.test2}" reRender="tmpfrm2" limitToList="true" />
</a4j:form>
</code>```

If you are uisng RichFaces 4 you need to replace the limitToList with limitRender and the reRender with render

Body:
If you are using RichFaces 3.3.3.Final you can do it like so:

<a4j:form id="tmpfrm1">
    <rich:messages />
    <h:inputText value="#{mybean.intmp1}" required="true"/>
    <a4j:commandButton value="save" action="#{mybean.test1}" reRender="tmpfrm1" limitToList="true" />
</a4j:form>

<a4j:form id="tmpfrm2">
    <rich:messages />
    <h:inputText value="#{mybean.intmp2}" required="true"/>
    <a4j:commandButton value="save" action="#{mybean.test2}" reRender="tmpfrm2" limitToList="true" />
</a4j:form>

If you are uisng RichFaces 4 you need to replace the limitToList with limitRender and the reRender with render


问:
openapi-generator-maven-plugin creates JsonNullable<Object> for properties with ref: #
I've created my .yml (reduced):

```<code>openapi: 3.0.1
...
components:
  messages:
  ...
  schemas:
    device:
      type: object
      properties:
        identifier:
          type: string
        manufacturer:
          type: string
        model:
          type: string
    controllerId:
      type: number
    controller:
      type: object
      properties:
        controllerId:
          ref: '#/components/schemas/controllerId'
        device:
          ref: '#/components/schemas/device'
</code>```

I let generate java classes for Vertx by

```<code><groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>5.3.0</version>
</code>```

Properties with type: are generated as expected but all properties with ref: are generated as JsonNullable<Object>.
Because of that the jackson-ObjectMapper reads the values as LinkedHashMap instead of e. g. Device in Controller's field.

I copied the generated classes and fixed the generics so the mapper reads the values to the expected classes.
Do you have any idea how to write the .yml that the generator creates JsonNullable<Device> instead of JsonNullable<Object>?
Or is there any configuration of the generator I didn't found yet to solve this problem?

答:
Reading the specs...
I had to change ref: to $ref and the correct member type is generated.

Body:
I've created my .yml (reduced):

openapi: 3.0.1
...
components:
  messages:
  ...
  schemas:
    device:
      type: object
      properties:
        identifier:
          type: string
        manufacturer:
          type: string
        model:
          type: string
    controllerId:
      type: number
    controller:
      type: object
      properties:
        controllerId:
          ref: '#/components/schemas/controllerId'
        device:
          ref: '#/components/schemas/device'

I let generate java classes for Vertx by

<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>5.3.0</version>

Properties with type: are generated as expected but all properties with ref: are generated as JsonNullable<Object>.
Because of that the jackson-ObjectMapper reads the values as LinkedHashMap instead of e. g. Device in Controller's field.

I copied the generated classes and fixed the generics so the mapper reads the values to the expected classes.
Do you have any idea how to write the .yml that the generator creates JsonNullable<Device> instead of JsonNullable<Object>?
Or is there any configuration of the generator I didn't found yet to solve this problem?


问:
How to restrict access to subdocument based on parent collection in firebase
I have a firestore db with 2 top-level collections (Reports, Users). My rules are set up like this:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /reports/{report} {
        allow read: if request.auth != null && request.auth.uid == resource.data.userID;
      allow create: if request.auth != null && request.resource.data.userID == request.auth.uid;
      allow delete, update: if request.auth != null &&
      request.auth.uid == resource.data.userID;
    }
    match /users/{user}{
        allow read: if request.auth != null && request.auth.uid == resource.id;
      allow create: if request.auth != null;
      allow delete: if request.auth != null && request.auth.uid == resource.id;
      allow update: if request.auth != null && request.auth.uid == resource.id;
    }
  }
}
</code>```

I want to create a sub-collection under the users collection. This would contain that user's default settings. In my head the rules would look like this:

```<code>match /users/{user}/defaultSettings/{document} {
   allow read, write: if request.auth != null && user.id == request.auth.uid
}
</code>```

However, I don't think I can use 2 placeholders (users and document) in my rules. Firestore is complaining about my use of user.id

In other words, I want to have a users collection that anyone who is authenticated to can read and write to because upon signing up I create a User document with that user's info. I also want to create a sub-collection under each user with only one document that holds that user's settings and I want to restrict access to that document to only the user that is represented by the parent (User) document.

How can I do this?

答:
Just change your rule to:

```<code>match /users/{user}/defaultSettings/{document} {
   allow read, write: if request.auth != null && user == request.auth.uid
}
</code>```

And to make your rule on the user collection a bit simpler your can use:

```<code>match /users/{user}{
    allow read: if request.auth != null && request.auth.uid == user;
  allow create: if request.auth != null;
  allow delete: if request.auth != null && request.auth.uid == user;
  allow update: if request.auth != null && request.auth.uid == user;
}
</code>```

Body:
I have a firestore db with 2 top-level collections (Reports, Users). My rules are set up like this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /reports/{report} {
        allow read: if request.auth != null && request.auth.uid == resource.data.userID;
      allow create: if request.auth != null && request.resource.data.userID == request.auth.uid;
      allow delete, update: if request.auth != null &&
      request.auth.uid == resource.data.userID;
    }
    match /users/{user}{
        allow read: if request.auth != null && request.auth.uid == resource.id;
      allow create: if request.auth != null;
      allow delete: if request.auth != null && request.auth.uid == resource.id;
      allow update: if request.auth != null && request.auth.uid == resource.id;
    }
  }
}

I want to create a sub-collection under the users collection. This would contain that user's default settings. In my head the rules would look like this:

match /users/{user}/defaultSettings/{document} {
   allow read, write: if request.auth != null && user.id == request.auth.uid
}

However, I don't think I can use 2 placeholders (users and document) in my rules. Firestore is complaining about my use of user.id

In other words, I want to have a users collection that anyone who is authenticated to can read and write to because upon signing up I create a User document with that user's info. I also want to create a sub-collection under each user with only one document that holds that user's settings and I want to restrict access to that document to only the user that is represented by the parent (User) document.

How can I do this?

Body:
Just change your rule to:

match /users/{user}/defaultSettings/{document} {
   allow read, write: if request.auth != null && user == request.auth.uid
}

And to make your rule on the user collection a bit simpler your can use:

match /users/{user}{
    allow read: if request.auth != null && request.auth.uid == user;
  allow create: if request.auth != null;
  allow delete: if request.auth != null && request.auth.uid == user;
  allow update: if request.auth != null && request.auth.uid == user;
}


问:
Property length does not exist on type Observable <[]> in angular
I have this service in angular which returns transcript

```<code>public transcript_arr =new ReplaySubject<[]>(1);
public confidence_arr=new ReplaySubject<[]>(1);
getTranscriptValue()
  {
    return this.transcript_arr.pipe(data => {return data;})
  }

getConfidenceValue()
  {
    return this.confidence_arr;
  }
</code>```

.ts file

```<code>service_transcript$: Observable<[]>;

this.service_transcript$=this.service.getTranscriptValue();

 for (var i = 0; i < this.service_transcript$.length; i++) {

 }

 this.http.post(this.baseUrl+'api/auth/post-data', formData).subscribe(response  => {

}
</code>```

In .ts file i'm using service data for computational purpose then sending it to server but getting
this error :

Property length does not exist on type Observable <[]> in angular
Updated Code:

```<code> const transcript_arr = [];
 const confidence_arr = [];

      this.service.getTranscriptValue().subscribe(el=>{
        for (var i = 0; i < el.length; i++) {
            if(this.hasWhiteSpace(el[i]))
            {
              const arr_transcript = el[i].trim().split(" ");
              for (var j = 0; j < arr_transcript.length; j++) {
                transcript_arr.push(arr_transcript[j].toLowerCase());
                confidence_arr.push(service_confidence[i]);
              }
            }
            else
            {
              transcript_arr.push(el[i].toLowerCase());
              confidence_arr.push(service_confidence[i]);
            }
        }
      }) ;
</code>```

Any solution to resolve this issue Thanks

答:
You are trying to get the length of observable, not the content of that observable you should try below code,
Because this.service_transcript$ is observable and observable contains data which you need. so you can try this code.</p>
```<code>
this.service_transcript$.subscribe(res =>{

   for (var i = 0; i < response.length; i++) {
      // Your computation
   }
   this.http.post(this.baseUrl+'api/auth/post-data',formData).subscribe(response  => { });

 })
</code>```

Body:
I have this service in angular which returns transcript

public transcript_arr =new ReplaySubject<[]>(1);
public confidence_arr=new ReplaySubject<[]>(1);
getTranscriptValue()
  {
    return this.transcript_arr.pipe(data => {return data;})
  }

getConfidenceValue()
  {
    return this.confidence_arr;
  }

.ts file

service_transcript$: Observable<[]>;

this.service_transcript$=this.service.getTranscriptValue();

 for (var i = 0; i < this.service_transcript$.length; i++) {

 }

 this.http.post(this.baseUrl+'api/auth/post-data', formData).subscribe(response  => {

}

In .ts file i'm using service data for computational purpose then sending it to server but getting
this error :

Property length does not exist on type Observable <[]> in angular
Updated Code:

 const transcript_arr = [];
 const confidence_arr = [];

      this.service.getTranscriptValue().subscribe(el=>{
        for (var i = 0; i < el.length; i++) {
            if(this.hasWhiteSpace(el[i]))
            {
              const arr_transcript = el[i].trim().split(" ");
              for (var j = 0; j < arr_transcript.length; j++) {
                transcript_arr.push(arr_transcript[j].toLowerCase());
                confidence_arr.push(service_confidence[i]);
              }
            }
            else
            {
              transcript_arr.push(el[i].toLowerCase());
              confidence_arr.push(service_confidence[i]);
            }
        }
      }) ;

Any solution to resolve this issue Thanks

Body:
You are trying to get the length of observable, not the content of that observable you should try below code,
Because this.service_transcript$ is observable and observable contains data which you need. so you can try this code.

this.service_transcript$.subscribe(res =>{

   for (var i = 0; i < response.length; i++) {
      // Your computation
   }
   this.http.post(this.baseUrl+'api/auth/post-data',formData).subscribe(response  => { });

 })


问:
How to "map" a variadic macro with boost preprocessor?
Say I have a macro F:

```<code>#define F(x) /*...*/
</code>```

and a macro G that takes one or more arguments:

```<code>#define G(...) /*...*/
</code>```

and I want to write a macro H that takes one or more arguments that expands to G with F applied to each argument:

```<code>#define H(...) /* G(F(arg1),F(arg2),...,F(argn)) */
</code>```

How can H be implemented with boost.preprocessor ?

For example:

```<code>#include <boost/preprocessor.hpp>

#define F(x) A x

#define G(...) B __VA_ARGS__ C

#define H(...) ???

H(X, Y, Z)
</code>```

The final line should preprocess to:

```<code>B A X, A Y, A Z C
</code>```

What code should replace the ??? ?

Update: This similar question C Macros: How to map another macro to variadic arguments? describes how to do it without boost preprocessor, but mentions EVAL and MAP from boost preprocessor but I can't seem to find either of those in the documentation: https://www.boost.org/doc/libs/1_78_0/libs/preprocessor/doc/index.html  Am I blind?

Update 2: I've got it working thanks to @Artyer. For posterity, here is the code of the final solution of the enclosing use case mentioned in the comments (generating comparison operators for a struct):

```<code>#pragma once

#include <boost/preprocessor.hpp>
#define COMPARISON_H_STRUCT_MEMBER_LOOKUP(member) (_struct.member)

#define COMPARISON_H_COMMA_SEPARATED_MAP(r, macro, i, elem) \
  BOOST_PP_COMMA_IF(i) macro(elem)

#define COMPARISON_H_DECL_TIE_FOR(ClassName, seq)                              \
  inline auto comparison_h_tie_struct(const ClassName& _struct) {              \
    return std::tie(BOOST_PP_SEQ_FOR_EACH_I(COMPARISON_H_COMMA_SEPARATED_MAP,  \
                            COMPARISON_H_STRUCT_MEMBER_LOOKUP, \
                                    seq));                             \
  }

#define DECL_STRUCT_EQ_OPS(ClassName, ...)                                    \
  COMPARISON_H_DECL_TIE_FOR(ClassName, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \
  COMPARISON_H_DECL_OP(ClassName, ==)                                         \
  COMPARISON_H_DECL_OP(ClassName, !=)

#define DECL_STRUCT_CMP_OPS(ClassName, ...)                                   \
  COMPARISON_H_DECL_TIE_FOR(ClassName, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \
  COMPARISON_H_DECL_OP(ClassName, ==)                                         \
  COMPARISON_H_DECL_OP(ClassName, !=)                                         \
  COMPARISON_H_DECL_OP(ClassName, <)                                          \
  COMPARISON_H_DECL_OP(ClassName, >)                                          \
  COMPARISON_H_DECL_OP(ClassName, <=)                                         \
  COMPARISON_H_DECL_OP(ClassName, >=)
</code>```

Example usage:

```<code>struct TestStruct {
  int member1, member2, member3;
};

DECL_STRUCT_CMP_OPS(TestStruct, member1, member2, member3)

int main() {
  TestStruct a, b;
  for (int i = 0; i < 27; i++)
    for (int j = 0; j < 27; j++) {
      a.member1 = (i / 9) % 3;
      b.member1 = (j / 9) % 3;
      a.member2 = (i / 3) % 3;
      b.member2 = (j / 3) % 3;
      a.member3 = (i / 1) % 3;
      b.member3 = (j / 1) % 3;

      assert((i == j) == (a == b));
      assert((i != j) == (a != b));
      assert((i < j) == (a < b));
      assert((i > j) == (a > b));
      assert((i <= j) == (a <= b));
      assert((i >= j) == (a >= b));
    }
}
</code>```

Update 3:  Added FOR_EACH_I fix.

答:
You can use BOOST_PP_SEQ_FOR_EACH_I to do this "mapping" operation:

#define VARIADIC_MAP(r, macro, i, elem) BOOST_PP_COMMA_IF(i) macro(elem)
#define H(...) G(BOOST_PP_SEQ_FOR_EACH_I(VARIADIC_MAP, F, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)))
```

The BOOST_PP_COMMA_IF(i) prepends a , before every value except the first so this expands to what you want.

Body:
Say I have a macro F:

#define F(x) /*...*/

and a macro G that takes one or more arguments:

#define G(...) /*...*/

and I want to write a macro H that takes one or more arguments that expands to G with F applied to each argument:

#define H(...) /* G(F(arg1),F(arg2),...,F(argn)) */

How can H be implemented with boost.preprocessor ?

For example:

#include <boost/preprocessor.hpp>

#define F(x) A x

#define G(...) B __VA_ARGS__ C

#define H(...) ???

H(X, Y, Z)

The final line should preprocess to:

B A X, A Y, A Z C

What code should replace the ??? ?

Update: This similar question C Macros: How to map another macro to variadic arguments? describes how to do it without boost preprocessor, but mentions EVAL and MAP from boost preprocessor but I can't seem to find either of those in the documentation: https://www.boost.org/doc/libs/1_78_0/libs/preprocessor/doc/index.html  Am I blind?

Update 2: I've got it working thanks to @Artyer. For posterity, here is the code of the final solution of the enclosing use case mentioned in the comments (generating comparison operators for a struct):

#pragma once

#include <boost/preprocessor.hpp>
#define COMPARISON_H_STRUCT_MEMBER_LOOKUP(member) (_struct.member)

#define COMPARISON_H_COMMA_SEPARATED_MAP(r, macro, i, elem) \
  BOOST_PP_COMMA_IF(i) macro(elem)

#define COMPARISON_H_DECL_TIE_FOR(ClassName, seq)                              \
  inline auto comparison_h_tie_struct(const ClassName& _struct) {              \
    return std::tie(BOOST_PP_SEQ_FOR_EACH_I(COMPARISON_H_COMMA_SEPARATED_MAP,  \
                            COMPARISON_H_STRUCT_MEMBER_LOOKUP, \
                                    seq));                             \
  }

#define DECL_STRUCT_EQ_OPS(ClassName, ...)                                    \
  COMPARISON_H_DECL_TIE_FOR(ClassName, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \
  COMPARISON_H_DECL_OP(ClassName, ==)                                         \
  COMPARISON_H_DECL_OP(ClassName, !=)

#define DECL_STRUCT_CMP_OPS(ClassName, ...)                                   \
  COMPARISON_H_DECL_TIE_FOR(ClassName, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \
  COMPARISON_H_DECL_OP(ClassName, ==)                                         \
  COMPARISON_H_DECL_OP(ClassName, !=)                                         \
  COMPARISON_H_DECL_OP(ClassName, <)                                          \
  COMPARISON_H_DECL_OP(ClassName, >)                                          \
  COMPARISON_H_DECL_OP(ClassName, <=)                                         \
  COMPARISON_H_DECL_OP(ClassName, >=)

Example usage:

struct TestStruct {
  int member1, member2, member3;
};

DECL_STRUCT_CMP_OPS(TestStruct, member1, member2, member3)

int main() {
  TestStruct a, b;
  for (int i = 0; i < 27; i++)
    for (int j = 0; j < 27; j++) {
      a.member1 = (i / 9) % 3;
      b.member1 = (j / 9) % 3;
      a.member2 = (i / 3) % 3;
      b.member2 = (j / 3) % 3;
      a.member3 = (i / 1) % 3;
      b.member3 = (j / 1) % 3;

      assert((i == j) == (a == b));
      assert((i != j) == (a != b));
      assert((i < j) == (a  j) == (a > b));
      assert((i <= j) == (a <= b));
      assert((i >= j) == (a >= b));
    }
}

Update 3:  Added FOR_EACH_I fix.

Body:
You can use BOOST_PP_SEQ_FOR_EACH_I to do this "mapping" operation:

#define VARIADIC_MAP(r, macro, i, elem) BOOST_PP_COMMA_IF(i) macro(elem)
#define H(...) G(BOOST_PP_SEQ_FOR_EACH_I(VARIADIC_MAP, F, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)))

The BOOST_PP_COMMA_IF(i) prepends a , before every value except the first so this expands to what you want.


问:
Removed DC2 from replication but still able query date from DC2 nodes
I am trying to remove a DC2 from my Cassandra Cluster. For this I start with altering replication factor from 2 to 0 in DC2. I try to insert a row in DC1 node1 and I am still receiving this row while queried from DC2 nodes.
Why is this happening?</p>

答:
I'm assuming that you're querying the data with cqlsh. By default, it uses a consistency of ONE so it will query any replica. In your case, they all happen to be in DC1.

If you try to query with a local consistency then you will probably get the result (or lack of) which I think you're expecting.

As a side note, although setting replication to 0 is technically valid, it is more customary to simply remove a DC completely from replication so you end up with:

```<code>ALTER KEYSPACE some_ks WITH REPLICATION = { \
   'class' : 'NetworkTopologyStrategy', \
   'DC1' : 3
}
</code>```

Body:
I'm assuming that you're querying the data with cqlsh. By default, it uses a consistency of ONE so it will query any replica. In your case, they all happen to be in DC1.

If you try to query with a local consistency then you will probably get the result (or lack of) which I think you're expecting.

As a side note, although setting replication to 0 is technically valid, it is more customary to simply remove a DC completely from replication so you end up with:

ALTER KEYSPACE some_ks WITH REPLICATION = { \
   'class' : 'NetworkTopologyStrategy', \
   'DC1' : 3
}