问:
How to share dynamic text content of DIV or SPAN on whatsapp using jquery?
I have been trying to share text content of DIV on whatsapp. But, no success yet. I do not want to share the whole document. I just want to share a part of it (I want to share contents of showques only).

Here is my code:

SHARE IN WHATSAPP
```

<p>Value of <code>showques</code> gets updated from the following code:</p>

<pre class="lang-js prettyprint-override"><code><script>
function nxtRiddle() {
        var chooserdl = [];
        for (i = 0; i < 164; i++) {
            chooserdl.push(i);
        }
        console.log(chooserdl);
        var riddleno = chooserdl[Math.floor(Math.random() * chooserdl.length)];
        console.log(riddleno);
        $('#showques').append(riddleques[riddleno]);
        $('#showans').append(riddleans[riddleno]);
        return;
    }
    nxtRiddle(0);
</script>
</code>```

答:
Here is a code I got from webflow. It works!

Paste this in Inside  tag of the page:

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</code>```

Paste this in  tag:

```<code> <div class='divblock'>
This is the first line.
This is the second line.
</div>
    <button id='button'> WHATSAPP </button>
</code>```

Paste this in Before  tag:

```<code><script type="text/javascript">
(function clickMe() {
  const button = document.getElementById("button");
  var divblock = $('.divblock').text();
  button.addEventListener("click", event => {
    // Whatsapp Message on Button Click
    window.open("https://api.whatsapp.com/send?text=Show div text: " + divblock)
  });
})();
</script>
</code>```

Output:

show div text: This is the first line. This is the second line.

Body:
I have been trying to share text content of DIV on whatsapp. But, no success yet. I do not want to share the whole document. I just want to share a part of it (I want to share contents of showques only).

Here is my code:

SHARE IN WHATSAPP

Value of showques gets updated from the following code:

Body:
Here is a code I got from webflow. It works!

Paste this in Inside < head > tag of the page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Paste this in < body > tag:

 <div class='divblock'>
This is the first line.
This is the second line.
</div>
    <button id='button'> WHATSAPP </button>

Paste this in Before < /body > tag:

<script type="text/javascript">
(function clickMe() {
  const button = document.getElementById("button");
  var divblock = $('.divblock').text();
  button.addEventListener("click", event => {
    // Whatsapp Message on Button Click
    window.open("https://api.whatsapp.com/send?text=Show div text: " + divblock)
  });
})();
</script>

Output:

show div text: This is the first line. This is the second line.


来源: stackexchange

问:
mvc 3 nested objects binding
I am very new to MVC 3 so this could be an easy one. I have a viewmodel with a nested object like this:

```<code> public class EventViewModel
 {
    public Event Event { get; set; }
 }

 public class Event
 {
    [Required]
    public int Id { get; set; }

    public string Title { get; set; }
 }
</code>```

In my 'create' view I do something like this:

```<code>@model EventViewModel
@Html.EditorFor(model => model.Event.Title)
</code>```

Here's the code form my event controller:

```<code>public class EventController : Controller
{

  [HttpPost]
  public ActionResult Create(EventViewModel @event)
  {
    ...
  }
}
</code>```

This editor is inside of form tag. When i postback to my controller the title of the event is null instead of what i entered in the form. Do I need some kind of custom binder? Am I doing something unconventional when I use nested objects in my viewmodel?

答:
Oh right. When you request the page for the first time, i.e. your default action, you need to instantiate the ViewModel and pass that to the view.

```<code>public ActionResult DefaultActionForEventView()
{
    var eventViewModel = new EventViewModel();
    eventViewModel.Event = new Event() // I can't remember if you need this line
    return View(eventViewModel)
}
</code>```

Let me know about the line above.

ContentLicense: CC BY-SA 3.0

Title: mvc 3 nested objects binding

Body:
I am very new to MVC 3 so this could be an easy one. I have a viewmodel with a nested object like this:

 public class EventViewModel
 {
    public Event Event { get; set; }
 }

 public class Event
 {
    [Required]
    public int Id { get; set; }

    public string Title { get; set; }
 }

In my 'create' view I do something like this:

@model EventViewModel
@Html.EditorFor(model => model.Event.Title)

Here's the code form my event controller:

public class EventController : Controller
{

  [HttpPost]
  public ActionResult Create(EventViewModel @event)
  {
    ...
  }
}

This editor is inside of form tag. When i postback to my controller the title of the event is null instead of what i entered in the form. Do I need some kind of custom binder? Am I doing something unconventional when I use nested objects in my viewmodel?

Body:
Oh right. When you request the page for the first time, i.e. your default action, you need to instantiate the ViewModel and pass that to the view.

public ActionResult DefaultActionForEventView()
{
    var eventViewModel = new EventViewModel();
    eventViewModel.Event = new Event() // I can't remember if you need this line
    return View(eventViewModel)
}

Let me know about the line above.


问:
How do you determine your permissions in AWS S3 through the Java SDK?
I know you can try to read the ACLs or Bucket Policies through the Java SDK, but is there any easy way to just check if you have read and/or write permissions to a bucket and/or its contents?  I don't see any "haveReadPermissions()" method or anything in the AmazonS3 class, but maybe I'm missing something?  I find it hard to believe there's no easy way to check permissions.</p>

答:
Here how you can do this:

```<code>// get list of bucket permission
List<String> bucketPermissions = s3Client
    .getBucketAcl(bucketName)
    .getGrantsAsList().stream().distinct()
    .map(t -> t.getPermission().toString())
    .collect(Collectors.toList());

// check read/write or full control permission
if (
    !((bucketPermissions.contains("READ")
    && bucketPermissions.contains("WRITE"))
    || (bucketPermissions.contains("FULL_CONTROL")))) {
throw new InsufficentBucketPermissionException();
}
</code>```

Please feel free to improve this solution.

Body:
Here how you can do this:

// get list of bucket permission
List<String> bucketPermissions = s3Client
    .getBucketAcl(bucketName)
    .getGrantsAsList().stream().distinct()
    .map(t -> t.getPermission().toString())
    .collect(Collectors.toList());

// check read/write or full control permission
if (
    !((bucketPermissions.contains("READ")
    && bucketPermissions.contains("WRITE"))
    || (bucketPermissions.contains("FULL_CONTROL")))) {
throw new InsufficentBucketPermissionException();
}

Please feel free to improve this solution.

ContentLicense: CC BY-SA 4.0


问:
Task.Run vs Task.Factory.StartNew - Expected Deadlock is not happening
I read about the differences of Task.Run and Task.Factory.StartNew.

```<code>Task.Run(() => {});
</code>```

should be equivalent to

```<code>Task.Factory.StartNew(() => {}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
</code>```

But in my code I expect a deadlock which is not happening because of Task.Factory.StartNew:

```<code>private Task backgroundTask;

private async Task DoSomethingAsync()
{
   // this should deadlock
   await this.backgroundTask.ConfigureAwait(false);
   throw new Exception();
}

private async Task Test()
{
   this.backgroundTask = Task.Factory.StartNew(async () =>
      {
         await this.DoSomethingAsync().ConfigureAwait(false);
      }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

   // just wait here for testing/debugging
   await Task.Delay(10000).ConfigureAwait(false);
   // if no deadlock, this should throw
   await this.backgroundTask.ConfigureAwait(false);
}
</code>```

But it is not deadlocking. The exception in DoSomethingAsync is thrown but never catched.
Awaiting the Task after the Task.Delay is not throwing either, because it is RanToCompletion.

When using Task.Run it is deadlocking as expected:

```<code>private Task backgroundTask;

private async Task DoSomethingAsync()
{
   // this is deadlocking
   await this.backgroundTask.ConfigureAwait(false);
   throw new Exception();
}

private async Task Test()
{
   this.backgroundTask= Task.Run(async () =>
      {
         await this.DoSomethingAsync().ConfigureAwait(false);
      });

   // just wait here for testing/debugging
   await Task.Delay(10000).ConfigureAwait(false);
   // never reached because of deadlock
   await this.backgroundTask.ConfigureAwait(false);
}
</code>```

Can anybody explain this behaviour?

答: The method Task.Factory.StartNew when used with an async delegate returns a nested task: Task<Task>. You are assigning this nested task to a variable of type Task, which is allowed because the class Task<TResult> derives from the class Task. What happens then is that you lose the reference to the inner task, so you have no way of awaiting it. When you await this.backgroundTask you are awaiting the outer Task<Task>, but you can't get the result of the await operation, which is a Task, the inner Task, and await it. The inner task has become a fire-and-forget task.

Body:
I read about the differences of Task.Run and Task.Factory.StartNew.

Task.Run(() => {});

should be equivalent to

Task.Factory.StartNew(() => {}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

But in my code I expect a deadlock which is not happening because of Task.Factory.StartNew:

private Task backgroundTask;

private async Task DoSomethingAsync()
{
   // this should deadlock
   await this.backgroundTask.ConfigureAwait(false);
   throw new Exception();
}

private async Task Test()
{
   this.backgroundTask = Task.Factory.StartNew(async () =>
      {
         await this.DoSomethingAsync().ConfigureAwait(false);
      }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

   // just wait here for testing/debugging
   await Task.Delay(10000).ConfigureAwait(false);
   // if no deadlock, this should throw
   await this.backgroundTask.ConfigureAwait(false);
}

But it is not deadlocking. The exception in DoSomethingAsync is thrown but never catched.
Awaiting the Task after the Task.Delay is not throwing either, because it is RanToCompletion.

When using Task.Run it is deadlocking as expected:

private Task backgroundTask;

private async Task DoSomethingAsync()
{
   // this is deadlocking
   await this.backgroundTask.ConfigureAwait(false);
   throw new Exception();
}

private async Task Test()
{
   this.backgroundTask= Task.Run(async () =>
      {
         await this.DoSomethingAsync().ConfigureAwait(false);
      });

   // just wait here for testing/debugging
   await Task.Delay(10000).ConfigureAwait(false);
   // never reached because of deadlock
   await this.backgroundTask.ConfigureAwait(false);
}

Can anybody explain this behaviour?


问:
closures difference from normal functions?
closures have an access of outerfunction , global and inner function scope. It is an function bundled up together and will be able to return an function. so this is the counter example build with closures

function outerfunction() {
  var y = 10;
  return {
    add() {
      y = y + 1;
      console.log(y)
    },
    sub() {
      console.log(y)
      y = y - 1;

    },
    value() {
      return y;
    }
  }
}
const counter = outerfunction();
console.log(counter.value()); //10
counter.add(); //11
counter.add(); //12
console.log(counter.value()); //12
counter.sub(); //11
counter.sub(); //10
console.log(counter.value()); //10```
</div>
</div>
</p>

<p>And this is the normal function for counter example, even in this functions has access to outside function scope,global scope and inner function scope. So what is the difference. here is the below code.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var counter = 10;

const add = () => {
  console.log(counter);
  counter++;
}

const sub = () => {
  console.log(counter);
  counter--;
}
console.log(counter); //10
add(); //11
add(); //12
console.log(counter); //12
sub(); //11
sub(); //10
console.log(counter); //10</code>```

Please correct if i am wrong. Thanks in advance

答: Well actually every function has a reference to its parent function's environment record (where all the variables reside in). In your second example that environment record is the global scope, in the first example it's the one from the outerFunction call. So there is no difference and there's no such a thing as a closure. That term is just used to describe the resulting behaviour.

Body:
closures have an access of outerfunction , global and inner function scope. It is an function bundled up together and will be able to return an function. so this is the counter example build with closures

function outerfunction() {
  var y = 10;
  return {
    add() {
      y = y + 1;
      console.log(y)
    },
    sub() {
      console.log(y)
      y = y - 1;

    },
    value() {
      return y;
    }
  }
}
const counter = outerfunction();
console.log(counter.value()); //10
counter.add(); //11
counter.add(); //12
console.log(counter.value()); //12
counter.sub(); //11
counter.sub(); //10
console.log(counter.value()); //10

And this is the normal function for counter example, even in this functions has access to outside function scope,global scope and inner function scope. So what is the difference. here is the below code.

var counter = 10;

const add = () => {
  console.log(counter);
  counter++;
}

const sub = () => {
  console.log(counter);
  counter--;
}
console.log(counter); //10
add(); //11
add(); //12
console.log(counter); //12
sub(); //11
sub(); //10
console.log(counter); //10

Please correct if i am wrong. Thanks in advance


问:
Need to update the particular section of the UI
I have a UI where the number of select dropdowns is dynamic. So if its 5, then i will show 5 dropdowns to the user. The options in all dropdowns are the same. But if user selects a particular option i need to fetch the data from a map and show it in the same section as the dropdown.

The object inside Map which is used to render the data is a complex mix of : arrays and maps. Once the section is rendered and the user selects a different drop down , I would only want to render that section again and not the whole page. I believe track-by feature of the ng-template does that.

Is it possible to have a solution where I just have one template which is iterated over depending on the number of drop downs and it knows which drop down it belongs to. So only that section of template refreshes if the drop down value changes.

Is ng-template the best way to achieve this ? would i have to maintain some of index to know which drop down got selected ?

This stackblitz represents what i am trying to achieve

https://stackblitz.com/edit/angular-ivy-f3qp4y

答:
You just need to keep track of your dropdown value. Here is what I suggest:

dropdowns = [];

ngOnInit(){
    for (let i = 0; i < this.numOfTemplates; i++) {
      this.dropdowns.push({
        model: '',
        color: ''
      });
    }
    this.mp.set("Ford",{model : "Ford Mustang", color : "Red"});
    this.mp.set("Volvo",{model : "Volvo XC90", color : "White"});
    this.mp.set("Fiat",{model : "Foat 500", color : "Black"});
  }

refresh(val :any, dropdown){
  const setVal = this.mp.get(val.target.value);
  dropdown.model = setVal.model;
  dropdown.color = setVal.model;
}
```

<p>And then, on the HTML side:</p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let in of dropdowns">
<select (change)="refresh($event, in)">
        <option [value]="car.value" *ngFor="let car of cars">{{car.value}}</option>
</select>
Model : {{in.model}} , Color : {{in.color}}:
</div>
</code>```

Body:
You just need to keep track of your dropdown value. Here is what I suggest:

dropdowns = [];

ngOnInit(){
    for (let i = 0; i < this.numOfTemplates; i++) {
      this.dropdowns.push({
        model: '',
        color: ''
      });
    }
    this.mp.set("Ford",{model : "Ford Mustang", color : "Red"});
    this.mp.set("Volvo",{model : "Volvo XC90", color : "White"});
    this.mp.set("Fiat",{model : "Foat 500", color : "Black"});
  }

refresh(val :any, dropdown){
  const setVal = this.mp.get(val.target.value);
  dropdown.model = setVal.model;
  dropdown.color = setVal.model;
}

And then, on the HTML side:

<div *ngFor="let in of dropdowns">
<select (change)="refresh($event, in)">
        <option [value]="car.value" *ngFor="let car of cars">{{car.value}}</option>
</select>
Model : {{in.model}} , Color : {{in.color}}:
</div>


答:
It could be a bit easier with reactive forms rather than template-driven forms. But as you mentioned, one way would be to track the looped items with an index. One way would be to store the model values in an array and fetch them based on the index. Not sure if it's the best of solutions, but it should work:

https://stackblitz.com/edit/angular-ivy-fxotqc

Title: Need to update the particular section of the UI

Body:
I have a UI where the number of select dropdowns is dynamic. So if its 5, then i will show 5 dropdowns to the user. The options in all dropdowns are the same. But if user selects a particular option i need to fetch the data from a map and show it in the same section as the dropdown.

The object inside Map which is used to render the data is a complex mix of : arrays and maps. Once the section is rendered and the user selects a different drop down , I would only want to render that section again and not the whole page. I believe track-by feature of the ng-template does that.

Is it possible to have a solution where I just have one template which is iterated over depending on the number of drop downs and it knows which drop down it belongs to. So only that section of template refreshes if the drop down value changes.

Is ng-template the best way to achieve this ? would i have to maintain some of index to know which drop down got selected ?

This stackblitz represents what i am trying to achieve

https://stackblitz.com/edit/angular-ivy-f3qp4y


问:
string.split is not working for some reason
I am trying to print the last name of the person "Michael" by splitting the string into an array and calling out the next word available.

When I run this code, I get undefined. I tried using Pythontutor to see what am I doing wrong and it turns out that string.split() is not working.

Can you please take a look and help figure me out what am I doing wrong?

Here is my code:

function getMichaelLastName(inputText) {
  var names = inputText;
  var newN = [names.split(" ")];
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] == "Michael") {
      var Michael = newN[i++];
    }
    return Michael;
  }
}
console.log(
getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")
)```

答:
Regular Expression.  Search for word boundaries and Michael followed by Alphabetic word.

interactive RegEx demo with explanations here: https://regex101.com/r/gC8tsi/2

/\bMichael ([A-Z][a-z]*?)\b/g is a regular expression literal (syntax is enclosed by/ to indicate a regular expression). Regular expressions are a pattern syntax designed for processing text with patterns.

\b looks for word boundaries.  Basically boundaries where it finds non-word elements.

Michael_ just looks for that string.

[A-Z] looks for a uppercase letter

[a-z]*? is a lazy sequence of lowercase letters (matches until the next word boundary \b)

The map and slice at the end is just to slice off the first name from all found names.

||[] just returns an empty array for the case where no matches are found.

function getMichaelLastName(inputText) {
  return (inputText.match(/\bMichael ([A-Z][a-z]*?)\b/g)||[]).map(x=>x.slice('Michael '.length))
}
console.log(
getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?")
)

function getLastNames(inputText, name='Michael') {
  const rex = new RegExp(String.raw`\b${name} ([A-Z][a-z]*?)\b`,'g')
  return (inputText.match(rex)||[]).map(x=>x.slice(name.length+1))
}
console.log(
getLastNames("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?",'John'),
getLastNames("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?",'Michael')
)```


问:
QTP Keyword driven basic example
I have been looking for very basic keyword driven test..i do not understand well how you can separate the test specifically from application so its reusable. In my understanding, the QTP commands like "navigate" are keywords. But how to create my own independent ones? I would be very grateful for example of how to do that. I found either too complex or just theoretical ones.
Thank you very much</p>

答:
In QTP jargon a keyword is a combination of a test object and method (see the available keywords pane).

Keyword driven testing is used to mean creating a test without recording. You can create test objects in one of the following methods and then construct a test from these test objects.

Descriptive programming

Manually create test objects in the object repository (using the create new command)

Using navigate and learn

Record and discard the script

Import from XML

Title: QTP Keyword driven basic example


答:
The difference is that you can make multiple closures, and they each will have their own y variable saved.

function outerfunction() {
  var y = 10;
  return {
    add() {
      y = y + 1;
      console.log(y)
    },
    sub() {
      console.log(y)
      y = y - 1;

    },
    value() {
      return y;
    }
  }
}
const counter = outerfunction();
console.log(counter.value()); //10
counter.add(); //11
counter.add(); //12

const counter2 = outerfunction();
console.log(counter2.value()); //10
counter2.sub(); //9
counter2.sub(); //8
console.log(counter2.value()); //9```

When you use a global variable, there's only one counter.

Title: closures difference from normal functions?

Body:
The difference is that you can make multiple closures, and they each will have their own y variable saved.

function outerfunction() {
  var y = 10;
  return {
    add() {
      y = y + 1;
      console.log(y)
    },
    sub() {
      console.log(y)
      y = y - 1;

    },
    value() {
      return y;
    }
  }
}
const counter = outerfunction();
console.log(counter.value()); //10
counter.add(); //11
counter.add(); //12

const counter2 = outerfunction();
console.log(counter2.value()); //10
counter2.sub(); //9
counter2.sub(); //8
console.log(counter2.value()); //9

When you use a global variable, there's only one counter.


问:
what is the difference between setting rules in tsconfig.json vs tslint.json?
It seems like they both achieve the same result. With TSLint, I had to install a plugin in VSCode? This probably is not preferable should someone in my team use a different editor.</p>

答:
TSConfig : Deals with the compiler. Throws an error on compiling bad code. So in Anguar "ng serve" will give you an error
  Ex Error =>
    error TS6138: Property 'dialog' is declared but its value is never read.

TsLint : Its to ensure best practice is followed. It does not throw an error on compilation. However, it shows a red line on the code to tell you that your style of coding needs some changes.
On VScode , you need to install a plugin to detect tslint.
On webstorm , it is inbuilt


问:
Can't get data from firestore
I am not able to get the data from firestore for my user.
It is giving me blank in my textview.I dont know what this error is but I am also not able to pass data between activities and trust me I am doing everything right.I also added a toast to check the user id and it does show me the user id.The data just doesnt show up no matter what.I have used firestore the same way in my other project and it worked perfect there.I have also tried creating a new project but I am just not able to get the data from outside the activity.

My logcat

```<code>2020-06-02 11:15:52.749 19990-19990/? E/Zygote: v2
2020-06-02 11:15:52.750 19990-19990/? E/Zygote: accessInfo : 0
2020-06-02 11:15:58.778 19990-19990/com.example.feedme2 E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]

</code>```

My java class

```<code>import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class profile extends AppCompatActivity {

    TextView fullname;
    CircleImageView circleImageView;
    BottomNavigationView bottomNavigationView;
    String user_id;
    String url;
    FirebaseFirestore fStore;
    FirebaseAuth fAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        circleImageView = findViewById(R.id.profilepictureuser);
        Picasso.with(this).load(url).resize(400, 400).centerCrop().into(circleImageView);
        fullname = findViewById(R.id.profilename);
        fStore = FirebaseFirestore.getInstance();
        fAuth = FirebaseAuth.getInstance();
        user_id = fAuth.getCurrentUser().getUid();

        Toast.makeText(this, user_id, Toast.LENGTH_SHORT).show();

        DocumentReference documentReference = fStore.collection("User data").document(user_id);
        documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(DocumentSnapshot documentSnapshot,FirebaseFirestoreException e) {
                fullname.setText(documentSnapshot.getString("Full name"));
            }
        });

        bottomNavigationView = findViewById(R.id.bottom_navigation1);
        bottomNavigationView.setSelectedItemId(R.id.profilelogo);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.profilelogo:
                    return true;
                case R.id.home:
                    startActivity(new Intent(getApplicationContext(), homepage.class));
                    return true;

            }
            return false;
        });

    }
}
</code>```

My layout file

```<code>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".homepage">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:orientation="vertical">

        <de.hdodenhof.circleimageview.CircleImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@drawable/profile"
            android:id="@+id/profilepictureuser"
            android:layout_gravity="center"
            android:layout_marginTop="30dp"/>

        <TextView
            android:id="@+id/profilename"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="15dp"
            android:textColor="#000000"
            android:textSize="24sp" />

    </LinearLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bottom_navigation1"
        android:background="#047cfb"
        app:itemIconTint="#ffffff"
        app:itemTextColor="#ffffff"
        app:menu="@menu/menu_navigation"
        android:layout_alignParentBottom="true"
        />

</RelativeLayout>

</code>```

My firestore rules

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

</code>```

My firestore collection

enter image description here

答:
Try running your code to fetch the data on the main thread.</p>

```<code>new Handler(Looper.getMainLooper()).post(new Runnable () {
    @Override
    public void run () {
        // your code here
    }
});
</code>```

Title: Can't get data from firestore

Body:
I am not able to get the data from firestore for my user.
It is giving me blank in my textview.I dont know what this error is but I am also not able to pass data between activities and trust me I am doing everything right.I also added a toast to check the user id and it does show me the user id.The data just doesnt show up no matter what.I have used firestore the same way in my other project and it worked perfect there.I have also tried creating a new project but I am just not able to get the data from outside the activity.

My logcat

2020-06-02 11:15:52.749 19990-19990/? E/Zygote: v2
2020-06-02 11:15:52.750 19990-19990/? E/Zygote: accessInfo : 0
2020-06-02 11:15:58.778 19990-19990/com.example.feedme2 E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]

My java class

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class profile extends AppCompatActivity {

    TextView fullname;
    CircleImageView circleImageView;
    BottomNavigationView bottomNavigationView;
    String user_id;
    String url;
    FirebaseFirestore fStore;
    FirebaseAuth fAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        circleImageView = findViewById(R.id.profilepictureuser);
        Picasso.with(this).load(url).resize(400, 400).centerCrop().into(circleImageView);
        fullname = findViewById(R.id.profilename);
        fStore = FirebaseFirestore.getInstance();
        fAuth = FirebaseAuth.getInstance();
        user_id = fAuth.getCurrentUser().getUid();

        Toast.makeText(this, user_id, Toast.LENGTH_SHORT).show();

        DocumentReference documentReference = fStore.collection("User data").document(user_id);
        documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(DocumentSnapshot documentSnapshot,FirebaseFirestoreException e) {
                fullname.setText(documentSnapshot.getString("Full name"));
            }
        });

        bottomNavigationView = findViewById(R.id.bottom_navigation1);
        bottomNavigationView.setSelectedItemId(R.id.profilelogo);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.profilelogo:
                    return true;
                case R.id.home:
                    startActivity(new Intent(getApplicationContext(), homepage.class));
                    return true;

            }
            return false;
        });

    }
}

My layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".homepage">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:orientation="vertical">

        <de.hdodenhof.circleimageview.CircleImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@drawable/profile"
            android:id="@+id/profilepictureuser"
            android:layout_gravity="center"
            android:layout_marginTop="30dp"/>

        <TextView
            android:id="@+id/profilename"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="15dp"
            android:textColor="#000000"
            android:textSize="24sp" />

    </LinearLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bottom_navigation1"
        android:background="#047cfb"
        app:itemIconTint="#ffffff"
        app:itemTextColor="#ffffff"
        app:menu="@menu/menu_navigation"
        android:layout_alignParentBottom="true"
        />

</RelativeLayout>

My firestore rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

My firestore collection

enter image description here

Body:
Try running your code to fetch the data on the main thread.

new Handler(Looper.getMainLooper()).post(new Runnable () {
    @Override
    public void run () {
        // your code here
    }
});


问:
AWS Lambda not showing cause Exception stacktrace in Python 3.8
I deployed the following code to an AWS Lambda using runtime Python 3.8.

```<code>try:
    raise Exception('my exception')
except Exception as e:
    raise ValueError('my exception 2') from e
</code>```

In CloudWatch, I expect to see exception chaining like this:

```<code>Traceback (most recent call last):
  File "/var/task/handler.py", line 2, in <module>
    raise Exception('my exception')
Exception: my exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/task/handler.py", line 4, in <module>
    raise ValueError('my exception 2') from e
ValueError: my exception 2
</code>```

Instead, I see only the first exception reported in CloudWatch like this:

```<code>[ERROR] ValueError: my exception 2
Traceback (most recent call last):
  File "/var/task/handler.py", line 21, in pevm_import_budget_file
    raise ValueError('my exception 2') from e
</code>```

Why isn't the direct cause exception from the from statement showing in the log?

答:
Another solution that I prefer is printing the stack trace to stderr and raising a generic error so that the program terminates. Example:

```<code>import logging, traceback, sys

class ProgramError(Exception):
    def __init__(self, msg='There should be more of exception traceback above.', **kwargs):
        super(ProgramError, self).__init__(msg, **kwargs)

def log_exception():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    logging.error(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))

try:
    raise Exception('my exception')
except Exception as e:
    log_exception()
    raise ProgramError()
</code>```

This produces CloudWatch output like this:

```<code>2020-06-02T06:08:57.340000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 START RequestId: e609f118-75d9-4cc7-81fe-44036d492814 Version: $LATEST
2020-06-02T06:08:57.341000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 [ERROR]   2020-06-02T06:08:57.341Z    e609f118-75d9-4cc7-81fe-44036d492814    Traceback (most recent call last):
  File "/var/task/handler.py", line 35, in testfile
    raise Exception('my exception')
Exception: my exception
2020-06-02T06:08:57.342000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 [ERROR] ProgramError: There should be more of exception traceback above.
Traceback (most recent call last):
  File "/var/task/handler.py", line 38, in testfile
    raise ProgramError()
2020-06-02T06:08:57.343000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 END RequestId: e609f118-75d9-4cc7-81fe-44036d492814
2020-06-02T06:08:57.343000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 REPORT RequestId: e609f118-75d9-4cc7-81fe-44036d492814    Duration: 2.71 ms   Billed Duration: 100 ms Memory Size: 256 MB Max Memory Used: 95 MB  Init Duration: 1297.82 ms
</code>```

If there is a chain of exceptions leading up to Exception, they will get listed and separated by The above exception was the direct cause of the following exception:.

Thank you @Paradigm for the inspiration for this! Hopefully AWS fixes support for from soon so we don't have to do workarounds like this.

Body:
I deployed the following code to an AWS Lambda using runtime Python 3.8.

try:
    raise Exception('my exception')
except Exception as e:
    raise ValueError('my exception 2') from e

In CloudWatch, I expect to see exception chaining like this:

Traceback (most recent call last):
  File "/var/task/handler.py", line 2, in <module>
    raise Exception('my exception')
Exception: my exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/task/handler.py", line 4, in <module>
    raise ValueError('my exception 2') from e
ValueError: my exception 2

Instead, I see only the first exception reported in CloudWatch like this:

[ERROR] ValueError: my exception 2
Traceback (most recent call last):
  File "/var/task/handler.py", line 21, in pevm_import_budget_file
    raise ValueError('my exception 2') from e

Why isn't the direct cause exception from the from statement showing in the log?

Body:
Another solution that I prefer is printing the stack trace to stderr and raising a generic error so that the program terminates. Example:

import logging, traceback, sys

class ProgramError(Exception):
    def __init__(self, msg='There should be more of exception traceback above.', **kwargs):
        super(ProgramError, self).__init__(msg, **kwargs)

def log_exception():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    logging.error(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))

try:
    raise Exception('my exception')
except Exception as e:
    log_exception()
    raise ProgramError()

This produces CloudWatch output like this:

2020-06-02T06:08:57.340000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 START RequestId: e609f118-75d9-4cc7-81fe-44036d492814 Version: $LATEST
2020-06-02T06:08:57.341000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 [ERROR]   2020-06-02T06:08:57.341Z    e609f118-75d9-4cc7-81fe-44036d492814    Traceback (most recent call last):
  File "/var/task/handler.py", line 35, in testfile
    raise Exception('my exception')
Exception: my exception
2020-06-02T06:08:57.342000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 [ERROR] ProgramError: There should be more of exception traceback above.
Traceback (most recent call last):
  File "/var/task/handler.py", line 38, in testfile
    raise ProgramError()
2020-06-02T06:08:57.343000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 END RequestId: e609f118-75d9-4cc7-81fe-44036d492814
2020-06-02T06:08:57.343000+00:00 2020/06/02/[$LATEST]df0f5bb977b443f9889a809f0d1affa4 REPORT RequestId: e609f118-75d9-4cc7-81fe-44036d492814    Duration: 2.71 ms   Billed Duration: 100 ms Memory Size: 256 MB Max Memory Used: 95 MB  Init Duration: 1297.82 ms

If there is a chain of exceptions leading up to Exception, they will get listed and separated by The above exception was the direct cause of the following exception:.

Thank you @Paradigm for the inspiration for this! Hopefully AWS fixes support for from soon so we don't have to do workarounds like this.


问:
Font size rem doesn't scale on different screen
Fonts and elements don't scale when the screen size is reduced. Following is the code. In the developer tools if I change the root HTML font size, the font's and respective elements scale but when the screen size is reduced it doesn't.

/*
    COLORS:

    Light green: #7ed56f
    Medium green: #55c57a
    Dark green: #28b485
    font-grey: #777777

    */

* *::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

html {
  font-size: 62.5%;
}

body {
  font-family: "Lato", sans-serif;
  font-weight: 400;
  line-height: 1.7;
  color: #777777;
  padding: 3rem;
  box-sizing: border-box;
}

.header {
  height: 95vh;
  /*95% of screen*/
  background-image: linear-gradient( to right bottom, rgba(126, 213, 111, 0.8), rgba(23, 133, 96, 0.8)), url(../img/hero.jpg);
  background-size: cover;
  /*image adapts to the screen*/
  background-position: top;
  /* top of the image stays the same  whatever the screen size*/
  clip-path: polygon(0 0, 100% 0, 100% 70vh, 0 100%);
  position: relative;
}

.logo-box {
  position: absolute;
  top: 4rem;
  left: 4rem;
}

.logo {
  height: 3.5rem;
}

.text-box {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.heading-primary {
  color: #ffffff;
  text-transform: uppercase;
  backface-visibility: hidden;
  /*part behind the element gets hidden*/
  margin-bottom: 4rem;
}

.heading-primary-main {
  display: block;
  font-size: 6rem;
  font-weight: 400;
  letter-spacing: 3.5rem;
  animation-name: left;
  animation-duration: 1s;
  animation-timing-function: ease-out;
  /* animation-iteration-count: 2;
        animation-delay: 2; */
}

.heading-primary-sub {
  display: block;
  font-size: 2rem;
  font-weight: 700;
  letter-spacing: 2.1rem;
  animation: left 1s ease-out;
}

@keyframes right {
  from {
    opacity: 0;
    transform: translateX(10rem);
  }
  80% {
    transform: translateX(-1rem);
  }
  to {
    opacity: 1;
    transform: translate(0);
  }
}

@keyframes left {
  from {
    opacity: 0;
    transform: translateX(-10rem);
  }
  80% {
    transform: translateX(1rem);
  }
  to {
    opacity: 1;
    transform: translate(0);
  }
}

@keyframes button {
  from {
    opacity: 0;
    transform: translateY(2rem);
  }
  to {
    opacity: 1;
    transform: translate(0);
  }
}

.btn-animated {
  animation: button 0.5s ease-out 0.75s;
  animation-fill-mode: backwards;
}

.btn:link,
.btn:visited {
  text-decoration: none;
  text-transform: uppercase;
  padding: 1.5rem 4rem;
  display: inline-block;
  border-radius: 10rem;
  transition: all 0.5s;
  position: relative;
  font-size: 1.6rem;
}

.btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.5);
  /* x-axis y-axis blur color */
}

.btn:active {
  transform: translateY(-1px);
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.8);
}

.btn-white {
  background-color: #fff;
  color: #777777;
}

.btn::after {
  content: "";
  display: inline-block;
  height: 100%;
  width: 100%;
  border-radius: 10rem;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
  transition: all 0.4s;
}

.btn-white::after {
  background-color: #fff;
}

.btn:hover::after {
  transform: scaleX(1.2) scaleY(1.4);
  opacity: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900" rel="stylesheet">
<header class="header">
  <div class="logo-box">
    <img src="img/logo-white.png" alt="Logo Natours" class="logo">
  </div>
  <div class="text-box">
    <h1 class="heading-primary">
      <span class="heading-primary-main">Outdoors</span>
      <span class="heading-primary-sub">Where life happens</span>
    </h1>
    Discover Our Tours
  </div>
</header>
<div>
</div></code>```

答:
CSS doesn't work like that. You need media queries in order to set different font sizes based on screen width.

I.e. you need to tell your browser that when the screen is some width or wider (or smaller), change the font size to Y.

This is for when you want the font size to work for everything above 601px

```<code>@media screen and (min-width: 601px) {
  div.example {
    font-size: 80px;
  }
}
</code>```

This is for when you want the font size to work for everything below 601px

```<code>@media screen and (min-width: 601px) {
  div.example {
    font-size: 80px;
  }
}
</code>```

Body:
Fonts and elements don't scale when the screen size is reduced. Following is the code. In the developer tools if I change the root HTML font size, the font's and respective elements scale but when the screen size is reduced it doesn't.

/*
    COLORS:

    Light green: #7ed56f
    Medium green: #55c57a
    Dark green: #28b485
    font-grey: #777777

    */

* *::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

html {
  font-size: 62.5%;
}

body {
  font-family: "Lato", sans-serif;
  font-weight: 400;
  line-height: 1.7;
  color: #777777;
  padding: 3rem;
  box-sizing: border-box;
}

.header {
  height: 95vh;
  /*95% of screen*/
  background-image: linear-gradient( to right bottom, rgba(126, 213, 111, 0.8), rgba(23, 133, 96, 0.8)), url(../img/hero.jpg);
  background-size: cover;
  /*image adapts to the screen*/
  background-position: top;
  /* top of the image stays the same  whatever the screen size*/
  clip-path: polygon(0 0, 100% 0, 100% 70vh, 0 100%);
  position: relative;
}

.logo-box {
  position: absolute;
  top: 4rem;
  left: 4rem;
}

.logo {
  height: 3.5rem;
}

.text-box {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.heading-primary {
  color: #ffffff;
  text-transform: uppercase;
  backface-visibility: hidden;
  /*part behind the element gets hidden*/
  margin-bottom: 4rem;
}

.heading-primary-main {
  display: block;
  font-size: 6rem;
  font-weight: 400;
  letter-spacing: 3.5rem;
  animation-name: left;
  animation-duration: 1s;
  animation-timing-function: ease-out;
  /* animation-iteration-count: 2;
        animation-delay: 2; */
}

.heading-primary-sub {
  display: block;
  font-size: 2rem;
  font-weight: 700;
  letter-spacing: 2.1rem;
  animation: left 1s ease-out;
}

@keyframes right {
  from {
    opacity: 0;
    transform: translateX(10rem);
  }
  80% {
    transform: translateX(-1rem);
  }
  to {
    opacity: 1;
    transform: translate(0);
  }
}

@keyframes left {
  from {
    opacity: 0;
    transform: translateX(-10rem);
  }
  80% {
    transform: translateX(1rem);
  }
  to {
    opacity: 1;
    transform: translate(0);
  }
}

@keyframes button {
  from {
    opacity: 0;
    transform: translateY(2rem);
  }
  to {
    opacity: 1;
    transform: translate(0);
  }
}

.btn-animated {
  animation: button 0.5s ease-out 0.75s;
  animation-fill-mode: backwards;
}

.btn:link,
.btn:visited {
  text-decoration: none;
  text-transform: uppercase;
  padding: 1.5rem 4rem;
  display: inline-block;
  border-radius: 10rem;
  transition: all 0.5s;
  position: relative;
  font-size: 1.6rem;
}

.btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.5);
  /* x-axis y-axis blur color */
}

.btn:active {
  transform: translateY(-1px);
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.8);
}

.btn-white {
  background-color: #fff;
  color: #777777;
}

.btn::after {
  content: "";
  display: inline-block;
  height: 100%;
  width: 100%;
  border-radius: 10rem;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
  transition: all 0.4s;
}

.btn-white::after {
  background-color: #fff;
}

.btn:hover::after {
  transform: scaleX(1.2) scaleY(1.4);
  opacity: 0;
}

<link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900" rel="stylesheet">

      Outdoors
      Where life happens

    Discover Our Tours

Body:
CSS doesn't work like that. You need media queries in order to set different font sizes based on screen width.

I.e. you need to tell your browser that when the screen is some width or wider (or smaller), change the font size to Y.

This is for when you want the font size to work for everything above 601px

@media screen and (min-width: 601px) {
  div.example {
    font-size: 80px;
  }
}

This is for when you want the font size to work for everything below 601px

@media screen and (min-width: 601px) {
  div.example {
    font-size: 80px;
  }
}


问:
Could a object be moved if this is no `copy constructor` for the class?
Could a object be moved if this is no copy constructor for the class?In another word, is it legal that a class has move constructor whereas its copy constructor is marked as deleted.If it's ok, does it go againt the rule of three, rule of five?

答:
Yes it's perfectly legal.

Think about e.g. std::unique_ptr, which is indeed movable but not copyable.


问:
Cython build path
When I use cython , I use this commandline to compile my pyx file:

```<code>python setup.py build_ext --inplace
</code>```

With the --inplace argument , my C file , builds folders and pyd compiled python module go where my pyx source file is.

There a way to compile all this files in a specific folder?  I searched on google and cython website without findung anything.

答:
You can try:</p>

```<code>python setup.py build_ext -b /../../../../dir/ -t .
</code>```

Title: Cython build path

Body:
When I use cython , I use this commandline to compile my pyx file:

python setup.py build_ext --inplace

With the --inplace argument , my C file , builds folders and pyd compiled python module go where my pyx source file is.

There a way to compile all this files in a specific folder?  I searched on google and cython website without findung anything.

Body:
You can try:

python setup.py build_ext -b /../../../../dir/ -t .


问:
How to split byte array and send it in small packs in Objective-c iOS
How to split byteArray in iOS
Iam getting 160 length of arrayByte data..
I need to split into 4 parts..each part contain 40 arrayByte.that data I need to copy and use for decoding..I tried to converted it but its not working..Can some one help to do this..

Finally i got solution Below is updated working code

```<code>-(NSMutableData*)decodeOpusData:(NSData*)data
{
    NSMutableData *audioData = [[NSMutableData alloc] init];
    for (NSUInteger i = 0; i < 4; i ++)
    {
        int bufferLength = 40;
        if([data length]>= 40){
        NSData *subData = [data subdataWithRange:NSMakeRange(i*bufferLength, bufferLength)];
        Byte *byteData = (Byte*)malloc(sizeof(Byte)*bufferLength);
        memcpy(byteData, [subData bytes], bufferLength);
        //You can do anything here with data..........
        //Below iam decoding audio data using OPUS library
        short decodedBuffer[WB_FRAME_SIZE];
        int nDecodedByte = sizeof(short) * [self decode:byteData length:bufferLength output:decodedBuffer];
        NSData *PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte ];
        [audioData appendData:PCMData];
        //Decoding audio data using OPUS library
        }
    }
    return audioData;
}
</code>```

Below code is android.i want to do like this..

```<code>ArrayByte  length = 160
BUFFER_LENGTH = 40

public fun opusDataDecoder(data:ByteArray){
     for (i in 0..3){
        val byteArray = ByteArray(BUFFER_LENGTH)
        System.arraycopy(data,i * BUFFER_LENGTH,byteArray,0, BUFFER_LENGTH)  //BUFFER_LENGTH = 40
        val decodeBufferArray = ShortArray(byteArray.size * 8)  // decodeBufferArray = 320
        val size = tntOpusUtils.decode(decoderHandler, byteArray, decodeBufferArray)
           if (size > 0) {
                 val decodeArray = ShortArray(size)
                 System.arraycopy(decodeBufferArray, 0, decodeArray, 0, size)
                 opusDecode(decodeArray)
                 } else {
                   Log.e(TAG, "opusDecode error : $size")
                }
         }
 }
</code>```

Iam getting only first 40 bytes..i want like first 0-40 bytes then 40-80 bytes,then 80-120bytes then 120-160bytes..
But here iam getting always 40 bytes...

Can some one help me how to fix this?

答:
Finally i got solution for split byte array and send it in small packs

Below is updated working code..

```<code>-(NSMutableData*)decodeOpusData:(NSData*)data
{
    NSMutableData *audioData = [[NSMutableData alloc] init];
    for (NSUInteger i = 0; i < 4; i ++)
    {
        int bufferLength = 40;
        if([data length]>= 40){
        NSData *subData = [data subdataWithRange:NSMakeRange(i*bufferLength, bufferLength)];
        Byte *byteData = (Byte*)malloc(sizeof(Byte)*bufferLength);
        memcpy(byteData, [subData bytes], bufferLength);
        //You can do anything here with data..........
        //Below iam decoding audio data using OPUS library
        short decodedBuffer[WB_FRAME_SIZE];
        int nDecodedByte = sizeof(short) * [self decode:byteData length:bufferLength output:decodedBuffer];
        NSData *PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte ];
        [audioData appendData:PCMData];
        //Decoding audio data using OPUS library
        }
    }
    return audioData;
}
</code>```

Body:
How to split byteArray in iOS
Iam getting 160 length of arrayByte data..
I need to split into 4 parts..each part contain 40 arrayByte.that data I need to copy and use for decoding..I tried to converted it but its not working..Can some one help to do this..

Finally i got solution Below is updated working code

-(NSMutableData*)decodeOpusData:(NSData*)data
{
    NSMutableData *audioData = [[NSMutableData alloc] init];
    for (NSUInteger i = 0; i < 4; i ++)
    {
        int bufferLength = 40;
        if([data length]>= 40){
        NSData *subData = [data subdataWithRange:NSMakeRange(i*bufferLength, bufferLength)];
        Byte *byteData = (Byte*)malloc(sizeof(Byte)*bufferLength);
        memcpy(byteData, [subData bytes], bufferLength);
        //You can do anything here with data..........
        //Below iam decoding audio data using OPUS library
        short decodedBuffer[WB_FRAME_SIZE];
        int nDecodedByte = sizeof(short) * [self decode:byteData length:bufferLength output:decodedBuffer];
        NSData *PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte ];
        [audioData appendData:PCMData];
        //Decoding audio data using OPUS library
        }
    }
    return audioData;
}

Below code is android.i want to do like this..

ArrayByte  length = 160
BUFFER_LENGTH = 40

public fun opusDataDecoder(data:ByteArray){
     for (i in 0..3){
        val byteArray = ByteArray(BUFFER_LENGTH)
        System.arraycopy(data,i * BUFFER_LENGTH,byteArray,0, BUFFER_LENGTH)  //BUFFER_LENGTH = 40
        val decodeBufferArray = ShortArray(byteArray.size * 8)  // decodeBufferArray = 320
        val size = tntOpusUtils.decode(decoderHandler, byteArray, decodeBufferArray)
           if (size > 0) {
                 val decodeArray = ShortArray(size)
                 System.arraycopy(decodeBufferArray, 0, decodeArray, 0, size)
                 opusDecode(decodeArray)
                 } else {
                   Log.e(TAG, "opusDecode error : $size")
                }
         }
 }

Iam getting only first 40 bytes..i want like first 0-40 bytes then 40-80 bytes,then 80-120bytes then 120-160bytes..
But here iam getting always 40 bytes...

Can some one help me how to fix this?

Body:
Finally i got solution for split byte array and send it in small packs

Below is updated working code..

-(NSMutableData*)decodeOpusData:(NSData*)data
{
    NSMutableData *audioData = [[NSMutableData alloc] init];
    for (NSUInteger i = 0; i < 4; i ++)
    {
        int bufferLength = 40;
        if([data length]>= 40){
        NSData *subData = [data subdataWithRange:NSMakeRange(i*bufferLength, bufferLength)];
        Byte *byteData = (Byte*)malloc(sizeof(Byte)*bufferLength);
        memcpy(byteData, [subData bytes], bufferLength);
        //You can do anything here with data..........
        //Below iam decoding audio data using OPUS library
        short decodedBuffer[WB_FRAME_SIZE];
        int nDecodedByte = sizeof(short) * [self decode:byteData length:bufferLength output:decodedBuffer];
        NSData *PCMData = [NSData dataWithBytes:(Byte *)decodedBuffer length:nDecodedByte ];
        [audioData appendData:PCMData];
        //Decoding audio data using OPUS library
        }
    }
    return audioData;
}


问:
RegEx Ranges with .00 number format
I want to build ranges from numeric values.
Values can be any value: 1.00, 2.00, 3.00 ... 674.00, ... 891.00 ...

Ranges: 1-10, 11-25, 26-50, 51-100, 101-200, 201-350, 351-600 , >601

I am struggling with the format of the numbers. the ".00" is killing me. I already did some research and tried:

```<code>([1-9]\.00|1[0]\.00)
</code>```

to fit to the range "1-10", but this puts every number to this range.

Does anyone have an idea how to solve it?
Thank you for your support.

答:
ok I found the answer to my own question :-D

enter image description here

Title: RegEx Ranges with .00 number format

Body:
I want to build ranges from numeric values.
Values can be any value: 1.00, 2.00, 3.00 ... 674.00, ... 891.00 ...

Ranges: 1-10, 11-25, 26-50, 51-100, 101-200, 201-350, 351-600 , >601

I am struggling with the format of the numbers. the ".00" is killing me. I already did some research and tried:

([1-9]\.00|1[0]\.00)

to fit to the range "1-10", but this puts every number to this range.

Does anyone have an idea how to solve it?
Thank you for your support.


问:
How to get value of a select2 from datatable
I want to get value of a select2 from a datatable and store it into variable.Actually I have appended three rows using for loop and so there are three select2 in three rows.I want get values from that three select2 and store it into variables.
I have tried many ways to get the values from that select2.When I m appending one row then the value is get from that select2 and stored in a variables.
I have used

```<code>var mno_id = $("#mno_idselected :selected").val();
</code>```

The above code is working for getting  the value from one select2 when I m appending one row.
But When I m appending more than one row,I m unable to get the value from a particular select2.

答:
You need to instantiate select2 after dataTables is initialised. You can do that in the drawCallback callback.

Do not use id's to reference the select2's. I guess you will have a lot of select2's on multiple pages, so give them a dummy class like dt-select2 so you can initialise all visible select2's in one call. But by all mean preserve the id's for reference in event handlers.

```<code>$('#example').DataTable({
  ...
  drawCallback: function() {
     $('.dt-select2').select2();
  }
})
</code>```

demo -> http://jsfiddle.net/u91javfy/

See this example include a select option on a header to filter the data: http://jsfiddle.net/73zawd5b/5/#&togetherjs=fgu5BihnA7

```<code>$('#example').DataTable({
  initComplete: function() {
    this.api().columns('.fName').every(function() {
      var column = this;
      var select = $('<select class="f"><option value="">First Name</option></select>')
        .appendTo($(column.header()).empty())
        .on('change', function() {
          var val = $.fn.dataTable.util.escapeRegex(
            $(this).val()
          );

          column
            .search(val ? '^' + val + '$' : '', true, false)
            .draw();
        });

      column.data().unique().sort().each(function(d, j) {
        select.append('<option value="' + d + '">' + d + '</option>')
      });
    });
    this.api().columns('.lName').every(function() {
      var column = this;
      var select = $('<select class="f"><option value="">Last Name</option></select>')
        .appendTo($(column.header()).empty())
        .on('change', function() {
          var val = $.fn.dataTable.util.escapeRegex(
            $(this).val()
          );

          column
            .search(val ? '^' + val + '$' : '', true, false)
            .draw();
        });

      column.data().unique().sort().each(function(d, j) {
        select.append('<option value="' + d + '">' + d + '</option>')
      });
    });
  }

})
$(document).ready(function($) {
  $('.f').select2();
});
</code>```

Body:
I want to get value of a select2 from a datatable and store it into variable.Actually I have appended three rows using for loop and so there are three select2 in three rows.I want get values from that three select2 and store it into variables.
I have tried many ways to get the values from that select2.When I m appending one row then the value is get from that select2 and stored in a variables.
I have used

var mno_id = $("#mno_idselected :selected").val();

The above code is working for getting  the value from one select2 when I m appending one row.
But When I m appending more than one row,I m unable to get the value from a particular select2.

Body:
You need to instantiate select2 after dataTables is initialised. You can do that in the drawCallback callback.

Do not use id's to reference the select2's. I guess you will have a lot of select2's on multiple pages, so give them a dummy class like dt-select2 so you can initialise all visible select2's in one call. But by all mean preserve the id's for reference in event handlers.

$('#example').DataTable({
  ...
  drawCallback: function() {
     $('.dt-select2').select2();
  }
})

demo -> http://jsfiddle.net/u91javfy/

See this example include a select option on a header to filter the data: http://jsfiddle.net/73zawd5b/5/#&togetherjs=fgu5BihnA7

$('#example').DataTable({
  initComplete: function() {
    this.api().columns('.fName').every(function() {
      var column = this;
      var select = $('<select class="f"><option value="">First Name</option></select>')
        .appendTo($(column.header()).empty())
        .on('change', function() {
          var val = $.fn.dataTable.util.escapeRegex(
            $(this).val()
          );

          column
            .search(val ? '^' + val + '$' : '', true, false)
            .draw();
        });

      column.data().unique().sort().each(function(d, j) {
        select.append('<option value="' + d + '">' + d + '</option>')
      });
    });
    this.api().columns('.lName').every(function() {
      var column = this;
      var select = $('<select class="f"><option value="">Last Name</option></select>')
        .appendTo($(column.header()).empty())
        .on('change', function() {
          var val = $.fn.dataTable.util.escapeRegex(
            $(this).val()
          );

          column
            .search(val ? '^' + val + '$' : '', true, false)
            .draw();
        });

      column.data().unique().sort().each(function(d, j) {
        select.append('<option value="' + d + '">' + d + '</option>')
      });
    });
  }

})
$(document).ready(function($) {
  $('.f').select2();
});


问:
Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:
I have windows 10. I have completed installing Tensorflow. It works. It says "Hello Tensorflow!". But it has all of this before it:

```<code>2018-08-18 18:16:01.500579: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2018-08-18 18:16:01.769002: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1405] Found device 0 with properties: name: GeForce GTX 950 major: 5 minor: 2 memoryClockRate(GHz): 1.3545 pciBusID: 0000:01:00.0 totalMemory: 2.00GiB freeMemory: 1.64GiB
2018-08-18 18:16:01.774030: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1484] Adding visible gpu devices: 0
2018-08-18 18:16:02.095489: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:965] Device interconnect StreamExecutor with strength 1 edge matrix:
2018-08-18 18:16:02.099093: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0
2018-08-18 18:16:02.100631: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:984] 0: N
2018-08-18 18:16:02.102156: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1097] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1401 MB memory) -> physical GPU (device: 0, name: GeForce GTX 950, pci bus id: 0000:01:00.0, compute capability: 5.2) Hello Tensorflow!

Process returned 0 (0x0) execution time : 2.327 s Press any key to continue
</code>```

When I type pip3 install --upgrade tensorflow-gpu in cmb, both administrative and normal I get this:

```<code>Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'c:\\users\\dylan\\appdata\\local\\programs\\python\\python35\\Lib\\site-packages\\numpy\\.libs\\libopenblas.BNVRK7633HSX7YVO2TADGR4A5KEKXJAW.gfortran-win_amd64.dll'
Consider using the `--user` option or check the permissions.
</code>```

答:
Step 1 - Open anaconda prompt with administrator privileges.

Step 2 - check pip version
          pip --version

Step 3 - enter this command

```<code>     **python -m pip install --upgrade pip**
</code>```

enter image description here

Body:
I have windows 10. I have completed installing Tensorflow. It works. It says "Hello Tensorflow!". But it has all of this before it:

2018-08-18 18:16:01.500579: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2018-08-18 18:16:01.769002: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1405] Found device 0 with properties: name: GeForce GTX 950 major: 5 minor: 2 memoryClockRate(GHz): 1.3545 pciBusID: 0000:01:00.0 totalMemory: 2.00GiB freeMemory: 1.64GiB
2018-08-18 18:16:01.774030: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1484] Adding visible gpu devices: 0
2018-08-18 18:16:02.095489: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:965] Device interconnect StreamExecutor with strength 1 edge matrix:
2018-08-18 18:16:02.099093: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0
2018-08-18 18:16:02.100631: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:984] 0: N
2018-08-18 18:16:02.102156: I T:\src\github\tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1097] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1401 MB memory) -> physical GPU (device: 0, name: GeForce GTX 950, pci bus id: 0000:01:00.0, compute capability: 5.2) Hello Tensorflow!

Process returned 0 (0x0) execution time : 2.327 s Press any key to continue

When I type pip3 install --upgrade tensorflow-gpu in cmb, both administrative and normal I get this:

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'c:\\users\\dylan\\appdata\\local\\programs\\python\\python35\\Lib\\site-packages\\numpy\\.libs\\libopenblas.BNVRK7633HSX7YVO2TADGR4A5KEKXJAW.gfortran-win_amd64.dll'
Consider using the `--user` option or check the permissions.

Body:
Step 1 - Open anaconda prompt with administrator privileges.

Step 2 - check pip version
          pip --version

Step 3 - enter this command

     **python -m pip install --upgrade pip**

enter image description here


问:
How do I include another file in an httpHandler?
I'm creating a webhandler and want to include classes from another file.  How do I do this?</p>

答:
Include those projects as references in the project that has the HTTPHandler, and then refer to those classes in code; make sure you have the appropriate using namespace definitions defined.

If this doesn't help, please elaborate on the problem.

HTH.


问:
Arrays.asList(array) in java add unwanted spaces between comma separated string?
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

```<code>String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
</code>```

After converting and removing item it prints

```<code>[467, 470, 464]
</code>```

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

```<code>if (idList.toString().contains(userId)) {
      idList.remove(userId);
}
</code>```

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

```<code>List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);
</code>```

or

```<code>String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);
</code>```

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

答:
You can trim spaces using this:</p>

```<code>List<String> newList = new LinkedList<String>();
for(String x: idList)
        newList.add(x.trim());
</code>```

Body:
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));

After converting and removing item it prints

[467, 470, 464]

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

if (idList.toString().contains(userId)) {
      idList.remove(userId);
}

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);

or

String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

Body:
You can trim spaces using this:

List<String> newList = new LinkedList<String>();
for(String x: idList)
        newList.add(x.trim());


问:
Netsuite: How to link Purchase Order to Sales Order
I’m trying to automate linking the NetSuite purchase order to a NetSuite sale order and the following is the code I tried to accomplish this task. But I'm getting error (see at the bottom). Can you please check and let me know what I’m missing here?

Purchase Order Creation code:

```<code>var createPurchaseOrder = new PurchaseOrder();

createPurchaseOrder.entity = new RecordRef()
{
internalId = “653”
//type = RecordType.purchaseOrder,
//typeSpecified = true
};

RecordRef soRecordRef = new RecordRef();
soRecordRef.internalId = “XXXXXXXX”;
soRecordRef.type = RecordType.salesOrder;
soRecordRef.typeSpecified = true;

createPurchaseOrder.createdFrom = soRecordRef;

RecordRef depRecordRef = new RecordRef();
depRecordRef.internalId = “3”;
depRecordRef.name = “eBay : eBay FNC”;
depRecordRef.type = RecordType.department;
depRecordRef.typeSpecified = true;

createPurchaseOrder.department = depRecordRef;

PurchaseOrderItem[] Items = new PurchaseOrderItem[1];

Items[0] = new PurchaseOrderItem();
RecordRef item = new RecordRef();
item.type = RecordType.nonInventoryPurchaseItem;
item.typeSpecified = true;
item.internalId = “XXXXX”;
Items[0].item = item;

Items[0].rate = “5”;
Items[0].quantity = 1;
Items[0].quantitySpecified = true;

PurchaseOrderItemList purchaseOrderItemList = new PurchaseOrderItemList();
purchaseOrderItemList.item = Items;
createPurchaseOrder.itemList = purchaseOrderItemList;

WriteResponse response = Service.add(createPurchaseOrder);
</code>```

Code I'm using to Update Purchase Order Number in Sales Order:

```<code>var updateSalesOrder = new SalesOrder();
updateSalesOrder.internalId = “XXXXXXXX”;

SalesOrderItem[] soItems = new SalesOrderItem[1];

var soItem = new SalesOrderItem();

RecordRef roItem = new RecordRef();
roItem.type = RecordType.inventoryItem;
roItem.typeSpecified = true;
roItem.internalId = “XXXXX”;
soItem.item = roItem;

RecordRef prLevel = new RecordRef();
prLevel.type = RecordType.priceLevel;
prLevel.internalId = “-1”;
prLevel.typeSpecified = true;

soItem.price = prLevel;
soItem.rate = “15”;
soItem.quantity = 1;
soItem.quantitySpecified = true;

RecordRef poItem = new RecordRef();
poItem.type = RecordType.purchaseOrder;
poItem.typeSpecified = true;
poItem.internalId = purchaseOrder.internalId;
soItem.createdPo = poItem;

soItems[0] = soItem;

SalesOrderItemList salesOrderItemList = new SalesOrderItemList();
salesOrderItemList.item = soItems;
updateSalesOrder.itemList = salesOrderItemList;

response = Service.update(updateSalesOrder);
if (response.status.isSuccess != true) throw new Exception(response.status.statusDetail[0].message);
</code>```

But I get the follwoing Error:
You do not have permissions to set a value for element createPOSpecified due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases.

Note: createPOSpecified is not displayed in the sales order screen in NetSuite. When I try to update a field in the sales order which exist in the form, then I am able to update it successfully but the field I am trying to update (createPOSpecified ) is not available in this sales form. In this case how can I update this ? Also is this the better way of linking the purchase order with sales order?

Thanks,
Hemant.

Updated 25-May-2020 (Responding to Anand Rajaram)

We are using the ADMINISTRATOR role for creating purchase order and linking that to sales order. A user with this role has been provided by our client and we don’t have permission to see fields that are displayed in the screen and have been restricted for EDIT. But we are able to edit most of the field displayed in the screen.

createPOSpecified is not a custom field. It’s a property in the SALESORDETITEM class. It will not be displayed in any sales order form.

If this is the proper code for creating purchase order and linking that to sales order, then I have few queries:

3.1 When we create purchase order through NetSuite by clicking the dropship link in the sales order item grid, we are able to see Mark Shipped button.

But when we create purchase order through code, it is displaying the Receive button and there was no changes in the purchase order status.

```<code>3.2 **createdFrom** field is displaying as below when we create purchase order through netsuite.
</code>```

This field is not displaying when we are creating purchase order through code. We have provided information for createdFrom property, but not sure why it is not displaying

We assume this is the field that helps to link with sales order. We have provided this information while creating item fulfillment and vendor bill and these are properly linked with sales order, but we are not sure why purchase order is not getting linked with sales order.

Finally on the below comments which you have provided
Which is basically having a custom transaction body field on Sales Order form, and once PO is created, update the newly created PO in Sales Order field.

We don’t have any custom transaction body field in our sales order form for providing purchase order. But once purchase order is created through NetSuite, purchase order number will be displayed in the sales order item grid.

So all this boils down to: what is that we have missed in the code and what is that we have to fix to display the "Mark Shipped" button, “Created From" label and linking Purchase Order to Sales Order.

Thanks,
Hemant.

答:
With the suggestion and from @Will Charbonneau, we have tested the following script using SuiteScript 1.0 and it helped us to link the purchase order to a sales order.

```<code>var po = nlapiCreateRecord('purchaseorder', {recordmode:"dynamic", soid:soInternalId,poentity:vendorEntity,vendor:vendorEntity,entity:custEntity});
var id = nlapiSubmitRecord(po, true)

nlapiLogExecution("DEBUG", "DropShip PO Created", "PO=" + id);
</code>```

Thanks,
Hemant.

Body:
I’m trying to automate linking the NetSuite purchase order to a NetSuite sale order and the following is the code I tried to accomplish this task. But I'm getting error (see at the bottom). Can you please check and let me know what I’m missing here?

Purchase Order Creation code:

var createPurchaseOrder = new PurchaseOrder();

createPurchaseOrder.entity = new RecordRef()
{
internalId = “653”
//type = RecordType.purchaseOrder,
//typeSpecified = true
};

RecordRef soRecordRef = new RecordRef();
soRecordRef.internalId = “XXXXXXXX”;
soRecordRef.type = RecordType.salesOrder;
soRecordRef.typeSpecified = true;

createPurchaseOrder.createdFrom = soRecordRef;

RecordRef depRecordRef = new RecordRef();
depRecordRef.internalId = “3”;
depRecordRef.name = “eBay : eBay FNC”;
depRecordRef.type = RecordType.department;
depRecordRef.typeSpecified = true;

createPurchaseOrder.department = depRecordRef;

PurchaseOrderItem[] Items = new PurchaseOrderItem[1];

Items[0] = new PurchaseOrderItem();
RecordRef item = new RecordRef();
item.type = RecordType.nonInventoryPurchaseItem;
item.typeSpecified = true;
item.internalId = “XXXXX”;
Items[0].item = item;

Items[0].rate = “5”;
Items[0].quantity = 1;
Items[0].quantitySpecified = true;

PurchaseOrderItemList purchaseOrderItemList = new PurchaseOrderItemList();
purchaseOrderItemList.item = Items;
createPurchaseOrder.itemList = purchaseOrderItemList;

WriteResponse response = Service.add(createPurchaseOrder);

Code I'm using to Update Purchase Order Number in Sales Order:

var updateSalesOrder = new SalesOrder();
updateSalesOrder.internalId = “XXXXXXXX”;

SalesOrderItem[] soItems = new SalesOrderItem[1];

var soItem = new SalesOrderItem();

RecordRef roItem = new RecordRef();
roItem.type = RecordType.inventoryItem;
roItem.typeSpecified = true;
roItem.internalId = “XXXXX”;
soItem.item = roItem;

RecordRef prLevel = new RecordRef();
prLevel.type = RecordType.priceLevel;
prLevel.internalId = “-1”;
prLevel.typeSpecified = true;

soItem.price = prLevel;
soItem.rate = “15”;
soItem.quantity = 1;
soItem.quantitySpecified = true;

RecordRef poItem = new RecordRef();
poItem.type = RecordType.purchaseOrder;
poItem.typeSpecified = true;
poItem.internalId = purchaseOrder.internalId;
soItem.createdPo = poItem;

soItems[0] = soItem;

SalesOrderItemList salesOrderItemList = new SalesOrderItemList();
salesOrderItemList.item = soItems;
updateSalesOrder.itemList = salesOrderItemList;

response = Service.update(updateSalesOrder);
if (response.status.isSuccess != true) throw new Exception(response.status.statusDetail[0].message);

But I get the follwoing Error:
You do not have permissions to set a value for element createPOSpecified due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases.

Note: createPOSpecified is not displayed in the sales order screen in NetSuite. When I try to update a field in the sales order which exist in the form, then I am able to update it successfully but the field I am trying to update (createPOSpecified ) is not available in this sales form. In this case how can I update this ? Also is this the better way of linking the purchase order with sales order?

Thanks,
Hemant.

Updated 25-May-2020 (Responding to Anand Rajaram)

We are using the ADMINISTRATOR role for creating purchase order and linking that to sales order. A user with this role has been provided by our client and we don’t have permission to see fields that are displayed in the screen and have been restricted for EDIT. But we are able to edit most of the field displayed in the screen.

createPOSpecified is not a custom field. It’s a property in the SALESORDETITEM class. It will not be displayed in any sales order form.

If this is the proper code for creating purchase order and linking that to sales order, then I have few queries:

3.1 When we create purchase order through NetSuite by clicking the dropship link in the sales order item grid, we are able to see Mark Shipped button.

But when we create purchase order through code, it is displaying the Receive button and there was no changes in the purchase order status.

3.2 **createdFrom** field is displaying as below when we create purchase order through netsuite.

This field is not displaying when we are creating purchase order through code. We have provided information for createdFrom property, but not sure why it is not displaying

We assume this is the field that helps to link with sales order. We have provided this information while creating item fulfillment and vendor bill and these are properly linked with sales order, but we are not sure why purchase order is not getting linked with sales order.

Finally on the below comments which you have provided
Which is basically having a custom transaction body field on Sales Order form, and once PO is created, update the newly created PO in Sales Order field.

We don’t have any custom transaction body field in our sales order form for providing purchase order. But once purchase order is created through NetSuite, purchase order number will be displayed in the sales order item grid.

So all this boils down to: what is that we have missed in the code and what is that we have to fix to display the "Mark Shipped" button, “Created From" label and linking Purchase Order to Sales Order.

Thanks,
Hemant.

Body:
With the suggestion and from @Will Charbonneau, we have tested the following script using SuiteScript 1.0 and it helped us to link the purchase order to a sales order.

var po = nlapiCreateRecord('purchaseorder', {recordmode:"dynamic", soid:soInternalId,poentity:vendorEntity,vendor:vendorEntity,entity:custEntity});
var id = nlapiSubmitRecord(po, true)

nlapiLogExecution("DEBUG", "DropShip PO Created", "PO=" + id);

Thanks,
Hemant.


问:
Raw Query In Vapor 4

In Vapor 3 I was able to get a newConnection to the database and call a raw sql query using this:

```<code>return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
    return con.raw(sql)...
}
</code>```

Now that I'm migrating my code to Vapor 4 the function raw or withNewConnection is gone, what can I use to make a raw query.

Steps to reproduce

```<code>return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
...
}
</code>```

Error:
Cannot infer contextual base in reference to member 'mysql'
Value of type 'Request' has no member 'withNewConnection'

Expected behavior

Have a function inside request.db that let me get a new connection or run a raw query.

Environment

Vapor Framework version: 4.7.1

Vapor Toolbox version: vapor-beta

OS version: macOS Catalina

答:
Error: Cannot infer contextual base in reference to member 'mysql' Value of type 'Request' has no member 'withNewConnection'

With Fluent 4 database identifier .mysql is not generic anymore unfortunately. So you have to cast it like this request.db as! SQLDatabase all the time to get methods like raw(...) to execute your raw query. Also connections are deep inside under the hood now.

I'd suggest to take a look at SwifQL + Bridges with Vapor 4

import Vapor
import MySQLBridge

struct MyResult: Codable {
    let column1: String
    let column2: Int
}
func someHandler(_ req: Request) throws -> EventLoopFuture<[MyResult]> {
    req.mysql.connection(to: .myDatabase) { conn in
        SwifQL
            .select(\SomeTable.$column1, \SomeTable.$column2)
            .from(SomeTable.table)
            .execute(on: conn)
            .all(decoding: MyResult.self)
    }
}
```

SwifQL is a DSL that gives you an ability to build any raw query safely, and Bridges is a helper for database drivers like mysql-nio and postgres-nio so it gives just convenience methods for them.

Title: Raw Query In Vapor 4

Body:
In Vapor 3 I was able to get a newConnection to the database and call a raw sql query using this:

return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
    return con.raw(sql)...
}

Now that I'm migrating my code to Vapor 4 the function raw or withNewConnection is gone, what can I use to make a raw query.

Steps to reproduce

return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
...
}

Error:
Cannot infer contextual base in reference to member 'mysql'
Value of type 'Request' has no member 'withNewConnection'

Expected behavior

Have a function inside request.db that let me get a new connection or run a raw query.

Environment

Vapor Framework version: 4.7.1

Vapor Toolbox version: vapor-beta

OS version: macOS Catalina

Body:
Error: Cannot infer contextual base in reference to member 'mysql' Value of type 'Request' has no member 'withNewConnection'

With Fluent 4 database identifier .mysql is not generic anymore unfortunately. So you have to cast it like this request.db as! SQLDatabase all the time to get methods like raw(...) to execute your raw query. Also connections are deep inside under the hood now.

I'd suggest to take a look at SwifQL + Bridges with Vapor 4

import Vapor
import MySQLBridge

struct MyResult: Codable {
    let column1: String
    let column2: Int
}
func someHandler(_ req: Request) throws -> EventLoopFuture<[MyResult]> {
    req.mysql.connection(to: .myDatabase) { conn in
        SwifQL
            .select(\SomeTable.$column1, \SomeTable.$column2)
            .from(SomeTable.table)
            .execute(on: conn)
            .all(decoding: MyResult.self)
    }
}

SwifQL is a DSL that gives you an ability to build any raw query safely, and Bridges is a helper for database drivers like mysql-nio and postgres-nio so it gives just convenience methods for them.


答:
For that structure of the data, to get the data between proc {format} and note: procedure {format} you don't have to use the inline modifier (?s) to let the dot match a newline to prevent unnecessary backtracking.

If you want the data in between, you could add a capturing group and instead of using the positive lookbehind at the start, match proc format;

To get the data in between, you could match all lines that do not start with either proc format; or contain   NOTE: PROCEDURE

The data in between in is capture group 2

```<code>^proc (?P<type>\w+);\r?\n\s*((?:(?!proc |.* NOTE: PROCEDURE ).*\r?\n)*.*(?= NOTE: PROCEDURE ))
</code>```

Explanation

^ Start of line

proc  Match literally

(?P<type>\w+); Named group type, match 1+ word chars

\r?\n\s* Match a newline and 0+ whitespace chars

( Capture group 2

(?: Non capture group

(?!proc |.* NOTE: PROCEDURE ) Assert what is directly on the right is not proc  or that the line contains  NOTE: PROCEDURE

.*\r?\n Match any char except a newline 0+ times followed by a newline

)* Close group and repeat 0+ times to match all the lines

.*(?= NOTE: PROCEDURE ) Match any char except a newline asserting what is on the right is  NOTE: PROCEDURE

) Close group 2

Regex demo for the first data | Regex demo for the second data

Title: Negative lookbehind not working with an OR operator in Regex - Python

Body:
I have two scenarios to get some information from a log file which has a structure like this:

proc format;

2018-04-12T07:45:52,430 INFO  [00000009] :t707982 - 26
2018-04-12T07:45:52,430 INFO  [00000009] :t707982 - 27
2018-04-12T07:45:52,433 INFO  [00000009] :t707982 - 35         '0010','0019'="08"
2018-04-12T07:45:52,434 INFO  [00000009] :t707982 - 36         '0005','0007','0011','0013'="09"

NOTE: There were 95219365 observations read from the data set WORK.TESTE1.
2018-04-12T07:55:41,536 INFO  [00000018] :t707982 - NOTE: The data set WORK.TESTE1 has 95219365 observations and 9 variables.
2018-04-12T07:55:41,537 INFO  [00000018] :t707982 - NOTE: Compressing data set WORK.TESTE1 decreased size by 34.04 percent.
2018-04-12T07:55:41,538 INFO  [00000018] :t707982 -       Compressed is 92230 pages; un-compressed would require 139823 pages.
2018-04-12T07:55:42,230 INFO  [00000018] :t707982 - NOTE: PROCEDURE FORMAT used (Total process time):
2018-04-12T07:55:42,231 INFO  [00000018] :t707982 -       real time           2:07.03
2018-04-12T07:55:42,231 INFO  [00000018] :t707982 -       user cpu time       1:56.98
2018-04-12T07:55:42,231 INFO  [00000018] :t707982 -       system cpu time     39.22 seconds
2018-04-12T07:55:42,231 INFO  [00000018] :t707982 -       memory              3159502.32k

proc format;

2018-04-12T08:45:52,430 INFO  [00000009] :t707982 - 26
2018-04-12T08:45:52,434 INFO  [00000009] :t707982 - 36         '0005','0007','0011','0013'="09"
NOTE: There were 95219365 observations read from the data set WORK.TESTE2.
2018-04-12T08:55:41,536 INFO  [00000018] :t707982 - NOTE: The data set WORK.TESTE2 has 95219365 observations and 9 variables.
2018-04-12T08:55:41,537 INFO  [00000018] :t707982 - NOTE: Compressing data set WORK.TESTE2 decreased size by 34.04 percent.
2018-04-12T08:55:41,538 INFO  [00000018] :t707982 -       Compressed is 92230 pages; un-compressed would require 139823 pages.
2018-04-12T08:55:42,230 INFO  [00000018] :t707982 - NOTE: PROCEDURE FORMAT used (Total process time):
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       real time           2:07.03
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       user cpu time       1:56.98
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       system cpu time     39.22 seconds
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       memory              3159502.32k

1) Extract all info between proc {format} and note: procedure {format}

2) If the first proc {format} doesn't have a note: procedure {format}, it needs to stop capturing when it founds another proc {format} and not return the note: procedure {format} from the second proc {format}, like in this example:

proc format;

2018-04-12T07:45:52,430 INFO  [00000009] :t707982 - 26
2018-04-12T07:45:52,430 INFO  [00000009] :t707982 - 27
2018-04-12T07:45:52,433 INFO  [00000009] :t707982 - 35         '0010','0019'="08"
2018-04-12T07:45:52,434 INFO  [00000009] :t707982 - 36         '0005','0007','0011','0013'="09"

NOTE: There were 95219365 observations read from the data set WORK.TESTE1.
2018-04-12T07:55:41,536 INFO  [00000018] :t707982 - NOTE: The data set WORK.TESTE1 has 95219365 observations and 9 variables.
2018-04-12T07:55:41,537 INFO  [00000018] :t707982 - NOTE: Compressing data set WORK.TESTE1 decreased size by 34.04 percent.
2018-04-12T07:55:41,538 INFO  [00000018] :t707982 -       Compressed is 92230 pages; un-compressed would require 139823 pages.

proc format;

2018-04-12T08:45:52,430 INFO  [00000009] :t707982 - 26
2018-04-12T08:45:52,434 INFO  [00000009] :t707982 - 36         '0005','0007','0011','0013'="09"
NOTE: There were 95219365 observations read from the data set WORK.TESTE2.
2018-04-12T08:55:41,536 INFO  [00000018] :t707982 - NOTE: The data set WORK.TESTE2 has 95219365 observations and 9 variables.
2018-04-12T08:55:41,537 INFO  [00000018] :t707982 - NOTE: Compressing data set WORK.TESTE2 decreased size by 34.04 percent.
2018-04-12T08:55:41,538 INFO  [00000018] :t707982 -       Compressed is 92230 pages; un-compressed would require 139823 pages.
2018-04-12T08:55:42,230 INFO  [00000018] :t707982 - NOTE: PROCEDURE FORMAT used (Total process time):
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       real time           2:07.03
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       user cpu time       1:56.98
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       system cpu time     39.22 seconds
2018-04-12T08:55:42,231 INFO  [00000018] :t707982 -       memory              3159502.32k

So, my problem is with the second scenario. My regex keeps capturing the note: procedure format from the second proc format, while it should ignore the first one and capture only the second case:

(?s)(?<=proc[ ])(?P<type>\w+).*?(?:(?<=NOTE:[ ]PROCEDURE[ ])|(?<!=proc[ ]))(?P=type).*?(?=memory)

I tried the negative look behind |(?<!=proc[ ]) with OR operator but still with no success.

you can see my regex in action here

Can you help me?

Body:
For that structure of the data, to get the data between proc {format} and note: procedure {format} you don't have to use the inline modifier (?s) to let the dot match a newline to prevent unnecessary backtracking.

If you want the data in between, you could add a capturing group and instead of using the positive lookbehind at the start, match proc format;

To get the data in between, you could match all lines that do not start with either proc format; or contain   NOTE: PROCEDURE

The data in between in is capture group 2

^proc (?P<type>\w+);\r?\n\s*((?:(?!proc |.* NOTE: PROCEDURE ).*\r?\n)*.*(?= NOTE: PROCEDURE ))

Explanation

^ Start of line

proc  Match literally

(?P<type>\w+); Named group type, match 1+ word chars

\r?\n\s* Match a newline and 0+ whitespace chars

( Capture group 2

(?: Non capture group

(?!proc |.* NOTE: PROCEDURE ) Assert what is directly on the right is not proc  or that the line contains  NOTE: PROCEDURE

.*\r?\n Match any char except a newline 0+ times followed by a newline

)* Close group and repeat 0+ times to match all the lines

.*(?= NOTE: PROCEDURE ) Match any char except a newline asserting what is on the right is  NOTE: PROCEDURE

) Close group 2

Regex demo for the first data | Regex demo for the second data


问:
Google cloud: accidentally deleted a default service account, where is the "projects.serviceAccounts.undelete" permission?
I have the Owner role over the whole project. I accidentally deleted a default service account, and now I can't start any VM instance.

I learned that I can undelete the service account with the gcloud alpha iam service-accounts undelete <ID> command, or a similar curl command curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" "https://iam.googleapis.com/v1/projects/<project_id>/serviceAccounts/<ID>:undelete", but both give me the following error:

```<code>PERMISSION_DENIED: Permission iam.serviceAccounts.undelete is required to perform this operation on service account
</code>```

I can't find the iam.serviceAccounts.undelete permission anywhere. The Owner role (that I have) has all other iam.serviceAccounts permissions (create, delete, update...) but not this one.

How can I run that command?

Edit: My bad, I was using a wrong serviceAccount ID the whole time, I missed the last digit when I did my copy/paste... Still the error message is strange.

答:
Expanding on @halfer's answer, you can potentialy find the deleted unique id by going through activity logs. Using the time should narrow the index down. Look for Delete service accountand then it should show as ${IAM account} deleted ${unique id}

Link: https://console.cloud.google.com/home/activity?project=${project}

Body:
I have the Owner role over the whole project. I accidentally deleted a default service account, and now I can't start any VM instance.

I learned that I can undelete the service account with the gcloud alpha iam service-accounts undelete <ID> command, or a similar curl command curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" "https://iam.googleapis.com/v1/projects/<project_id>/serviceAccounts/<ID>:undelete", but both give me the following error:

PERMISSION_DENIED: Permission iam.serviceAccounts.undelete is required to perform this operation on service account

I can't find the iam.serviceAccounts.undelete permission anywhere. The Owner role (that I have) has all other iam.serviceAccounts permissions (create, delete, update...) but not this one.

How can I run that command?

Edit: My bad, I was using a wrong serviceAccount ID the whole time, I missed the last digit when I did my copy/paste... Still the error message is strange.