问:
Calling fragment from acivity when a button is clicked
I am creating an app with  fragment ,here i want to call fragment continuously when a button is clicked.eg when a button next is clicked i want to dispaly 5 fragment when the button clicked every time.

Here is my xm code

the image shows my  xml design.

i want to display the fragment in the framelayout .

答:
try this may be it helps you   </p>

```<code>    FragmentManager manager;
    manager = getSupportFragmentManager();
    FragmentOne fragment = new FragmentOne();
    manager.beginTransaction().replace(R.id.frame_layout,fragment).commit();
</code>```

Body:
try this may be it helps you

    FragmentManager manager;
    manager = getSupportFragmentManager();
    FragmentOne fragment = new FragmentOne();
    manager.beginTransaction().replace(R.id.frame_layout,fragment).commit();


来源: stackexchange

问:
Access rights for Azure DevOps Services pipeline
What are the best practices for accesses permission for programmers working in Azure DevOps? I would like the programmers to be able to use it, by for example having the possibility to create branches.

As far as I can understand by reading documents such as
https://learn.microsoft.com/en-us/azure/devops/organizations/security/set-git-tfvc-repository-permissions?view=azure-devops#git-repository

The only permission needed is a contributor? Is this correct or have I misunderstood the whole thing? The organization I’m working for have for example set the contributor to be a member of :
Build Administrators, Endpoint creators, Release Administrators

答:
Creating users is different thing and assining rights is different thing. Your are looking for something named Policies.

Check for Branching policies in this case.

EDIT:

I was confused with the branching rights, however you can follow the Repository Permissions and Branch permissions to find how you can give permissions on your projects to users

ContentLicense: CC BY-SA 4.0


问:
How to retrieve images from database in ASP.NET MVC?
I have a model with a nvarchar image file that I want to show on the page. How can I do that without going back to the database?

How can it display images?

Although I was trying to do it, but I get an error:

Cannot convert string to byte'

答:
Due to my reputation I can't post a comment but your question is too vague to properly answer. Handling images can be done in multiple ways so you'll have to clarify how you're handling them right now. Also add the related code and possibly the database structure to your question.

In the current state of your question it is impossible to tell what is going wrong because you are giving little to no factors to work with. Post some of the source code!


问:
How do I check if each UITextField in an Array has a user input?
I have a list of UITextFields in an Array for users to key in phone numbers. When I click the Send Button, it will connect with my server to send an automated message to the numbers listed. This portion works well. What I want to do now is to check which of the UITextFields has a phone number in it and to check if it has the prefix + before it connects to my server. If any of the UITextField has a phone number without the prefix +, the border color of that UITextField should change colours. If the UITextField does not have a phone number, no action should be taken. How do I go about achieving that?

This is the portion of the code that I need help in

```<code>
    @IBAction func sendbutton(_ sender: Any) {

        var numArray: Array<Any>

        numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

        let myColor = UIColor.red

        for num in numArray {
            if (num as AnyObject).hasPrefix("+") {
                print("Has + symbol")

            } else {
                print("Does Not Have Symbol")

            }
        }

</code>```

答:
You can traverse over the array of textFields and for each textField validate the text for first character is "+". If not set its borderColor.

```<code>var textFields = [phonenumber, phonenumber1, phonenumber2, phonenumber3]
var numArray = [String]()

textFields.forEach {
    if let text = $0.text, text.first == "+" {
        numArray.append(text)
        $0.layer.borderWidth = 0.0 //To reset the textField if it didn't validate earlier
    } else {
        $0.layer.borderColor = UIColor.red.cgColor
        $0.layer.borderWidth = 1.0
    }
}
</code>```

Body:
I have a list of UITextFields in an Array for users to key in phone numbers. When I click the Send Button, it will connect with my server to send an automated message to the numbers listed. This portion works well. What I want to do now is to check which of the UITextFields has a phone number in it and to check if it has the prefix + before it connects to my server. If any of the UITextField has a phone number without the prefix +, the border color of that UITextField should change colours. If the UITextField does not have a phone number, no action should be taken. How do I go about achieving that?

This is the portion of the code that I need help in

    @IBAction func sendbutton(_ sender: Any) {

        var numArray: Array<Any>

        numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

        let myColor = UIColor.red

        for num in numArray {
            if (num as AnyObject).hasPrefix("+") {
                print("Has + symbol")

            } else {
                print("Does Not Have Symbol")

            }
        }

Body:
You can traverse over the array of textFields and for each textField validate the text for first character is "+". If not set its borderColor.

var textFields = [phonenumber, phonenumber1, phonenumber2, phonenumber3]
var numArray = [String]()

textFields.forEach {
    if let text = $0.text, text.first == "+" {
        numArray.append(text)
        $0.layer.borderWidth = 0.0 //To reset the textField if it didn't validate earlier
    } else {
        $0.layer.borderColor = UIColor.red.cgColor
        $0.layer.borderWidth = 1.0
    }
}


问:
is it possible to differentiate between string and enum of strings in typescript?
so I have

```<code>type newType = ResourcesKey | string;

enum ResourcesKey {
    FirstString= 'path',
    ...
    }
</code>```

I then have a function that takes the instance and I want to test if it's a string or an enum, but in typescript are the two considered the same?

```<code>Function(instance: newType)
{
   if (instance instanceof ResourcesKey) {

   }
}
</code>```

this returns an error
error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.

is there anything I can do to compare the instance to the type of the enum?

for example in C# I would probably be able to do something like

```<code>if (typeof (instance) == ResourcesKey) {
}
</code>```

I can work around it of course, but I'm wondering what the preferred course of action is

答:
instanceof would just work for classes anyway so you can't use it with an enum.

A runtime enums are just string, so testing for this means actually testing if the string value is in the enum. You can create a custom typeguard that will do the check and inform the compiler of the type:

```<code>type newType = ResourcesKey | string;

enum ResourcesKey {
    FirstString = 'path',

}

function isResourceKey(o: newType): o is ResourcesKey {
    return Object.keys(ResourcesKey).some(k => ResourcesKey[k as keyof typeof ResourcesKey] === o);
}

function doStuff(instance: newType) {
    if (isResourceKey(instance)) {
        console.log(`Res: ${instance}`) // instance: ResourcesKey
    } else {
        console.log(`Str: ${instance}`) // instance: string
    }
}

doStuff("")
doStuff(ResourcesKey.FirstString)
doStuff("path") // still resource
</code>```

Body:
so I have

type newType = ResourcesKey | string;

enum ResourcesKey {
    FirstString= 'path',
    ...
    }

I then have a function that takes the instance and I want to test if it's a string or an enum, but in typescript are the two considered the same?

Function(instance: newType)
{
   if (instance instanceof ResourcesKey) {

   }
}

this returns an error
error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.

is there anything I can do to compare the instance to the type of the enum?

for example in C# I would probably be able to do something like

if (typeof (instance) == ResourcesKey) {
}

I can work around it of course, but I'm wondering what the preferred course of action is

Body:
instanceof would just work for classes anyway so you can't use it with an enum.

A runtime enums are just string, so testing for this means actually testing if the string value is in the enum. You can create a custom typeguard that will do the check and inform the compiler of the type:

type newType = ResourcesKey | string;

enum ResourcesKey {
    FirstString = 'path',

}

function isResourceKey(o: newType): o is ResourcesKey {
    return Object.keys(ResourcesKey).some(k => ResourcesKey[k as keyof typeof ResourcesKey] === o);
}

function doStuff(instance: newType) {
    if (isResourceKey(instance)) {
        console.log(`Res: ${instance}`) // instance: ResourcesKey
    } else {
        console.log(`Str: ${instance}`) // instance: string
    }
}

doStuff("")
doStuff(ResourcesKey.FirstString)
doStuff("path") // still resource


问:
Why my getRequest() in saga doesn't see data from json.db after postRequest
My saga.ts :

```<code>export function* postSomething(object:object){
        yield postRequest(object);
        const Objects=yield getRequest();
        console.log(Objects);
        yield put(showObject(Objects));
}
</code>```

**db.json is my little database

My db.json is empty at the beginning, and after first postRequest(object), db.json will have one object,but when I try to get that object with getRequest I get [ ] (empty array)!?Why?

My console.log(Object) doesn't print anything.

Next time when I do postRequest(object) and post to my db.json one more object, that means db.json will have two objects, but after that, when I try to pull objects with getRequest(), my console.log print only one object?Why?

How to get all objects from db.json after postRequest() ?

postRequest(object)(post object to db.json using fetch,method "post") is service function which communicate with db.json,

getRequest()( fetch(url) which need to return all object from db.json )
.

答:
You should be using the call effect from redux-saga API:

```<code>export function* postSomething(object:object){
        yield call(postRequest(object));
        const Objects = yield call(getRequest());
        console.log(Objects);
        yield put(showObject(Objects));
}
</code>```

In general, it would be better pattern using 2 different sagas for handling each request. that way you can handle success/failure with redux in much more ease and clarity.

Body:
My saga.ts :

export function* postSomething(object:object){
        yield postRequest(object);
        const Objects=yield getRequest();
        console.log(Objects);
        yield put(showObject(Objects));
}

**db.json is my little database

My db.json is empty at the beginning, and after first postRequest(object), db.json will have one object,but when I try to get that object with getRequest I get [ ] (empty array)!?Why?

My console.log(Object) doesn't print anything.

Next time when I do postRequest(object) and post to my db.json one more object, that means db.json will have two objects, but after that, when I try to pull objects with getRequest(), my console.log print only one object?Why?

How to get all objects from db.json after postRequest() ?

postRequest(object)(post object to db.json using fetch,method "post") is service function which communicate with db.json,

getRequest()( fetch(url) which need to return all object from db.json )
.

Body:
You should be using the call effect from redux-saga API:

export function* postSomething(object:object){
        yield call(postRequest(object));
        const Objects = yield call(getRequest());
        console.log(Objects);
        yield put(showObject(Objects));
}

In general, it would be better pattern using 2 different sagas for handling each request. that way you can handle success/failure with redux in much more ease and clarity.


问:
Updating status of a button when button is pressed
"I have store 0 in Database now I want to update the status through
updateStatus() when button is clicked.I am not sure that the query I have
written is correct and I have no idea how to use UpdateStatus()."

"onClick() contains 5 buttons. e.g if the button btn_AllCalls is pressed then the status should be updated to var where var is the status I want to update.
but I have no idea how to do this.
onclick() function is used in another activity.
GetButton is Getters and Setter."

```<code>updateStatus(GetButton getButton){
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues content = new ContentValues();
        content.put(STATUS, getButton.getStat());
        db.update(ACTIVETABLE,content,"STATUS = ?",null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
onClick(View view) {
    switch(view.getId()) {
        case R.id.btn_AllCalls:
            var = 1;
            break;
        case R.id.btn_SpecificContactNumbers:
            var = 2;
            break;
        case R.id.btn_UserInput:
            var = 3;
            break;
        case R.id.btn_UnknownNumbers:
            var = 4;
            break;
        case R.id.btn_SavedContacts:
            var = 5;
            break;
    }
}
</code>```

答: In such cases there is a tag option. you may use it by getTag() and setTag()</p>

Body:
"I have store 0 in Database now I want to update the status through
updateStatus() when button is clicked.I am not sure that the query I have
written is correct and I have no idea how to use UpdateStatus()."

"onClick() contains 5 buttons. e.g if the button btn_AllCalls is pressed then the status should be updated to var where var is the status I want to update.
but I have no idea how to do this.
onclick() function is used in another activity.
GetButton is Getters and Setter."

updateStatus(GetButton getButton){
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues content = new ContentValues();
        content.put(STATUS, getButton.getStat());
        db.update(ACTIVETABLE,content,"STATUS = ?",null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
onClick(View view) {
    switch(view.getId()) {
        case R.id.btn_AllCalls:
            var = 1;
            break;
        case R.id.btn_SpecificContactNumbers:
            var = 2;
            break;
        case R.id.btn_UserInput:
            var = 3;
            break;
        case R.id.btn_UnknownNumbers:
            var = 4;
            break;
        case R.id.btn_SavedContacts:
            var = 5;
            break;
    }
}


问:
How to use babel directly from a script tag without installing babel itself
I'm writing react with all of these libs introduced from cdnjs.com. However, I find it reporting error: 'Uncaught TypeError: Cannot read property 'keys' of undefined' even if I don't write a single line of javascript code.

How could it happen?

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
<script text="text/babel">
//some code here

</script>
</code>```

答:
You can use babel standalone:

```

ContentLicense: CC BY-SA 3.0

Body:
You can use babel standalone:

<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>

<script type="text/babel">
  // your code
  console.log("hello world");
</script>


问:
Single colored barchart
I have currently tried a course and would like to replicate it on my r-studio however, why can I only show a single color bar plot provided the code below? Is it related to the base color of the fill function? Thanks!</p>

```<code>head(mtcars)
library(ggplot2)

# Bar chart
ggplot(mtcars, aes(x = cyl, fill = am)) +
  geom_bar(position = "fill")

# Convert bar chart to pie chart
ggplot(mtcars, aes(x = factor(1), fill = am)) +
  geom_bar(position = "fill") +
  facet_grid(. ~ cyl) + # Facets
  coord_polar(theta = "y") + # Coordinates
  theme_void() # theme
</code>```

答:
Welcome to SO! I think you only need to add the group option to the aes():

```<code>ggplot(mtcars, aes(x = cyl, fill = am, group = am)) + geom_bar(position = "fill")
</code>```

But maybe in this way it could be more readable:

```<code>ggplot(mtcars, aes(x = as.factor(cyl), fill = as.factor(am), group = as.factor(am))) +
  geom_bar(position = "fill") +
  xlab("CYL") +     # change x axis label
  labs(fill = "am") # change legend title
</code>```

Title: Single colored barchart

Body:
I have currently tried a course and would like to replicate it on my r-studio however, why can I only show a single color bar plot provided the code below? Is it related to the base color of the fill function? Thanks!

head(mtcars)
library(ggplot2)

# Bar chart
ggplot(mtcars, aes(x = cyl, fill = am)) +
  geom_bar(position = "fill")

# Convert bar chart to pie chart
ggplot(mtcars, aes(x = factor(1), fill = am)) +
  geom_bar(position = "fill") +
  facet_grid(. ~ cyl) + # Facets
  coord_polar(theta = "y") + # Coordinates
  theme_void() # theme

Body:
Welcome to SO! I think you only need to add the group option to the aes():

ggplot(mtcars, aes(x = cyl, fill = am, group = am)) + geom_bar(position = "fill")

But maybe in this way it could be more readable:

ggplot(mtcars, aes(x = as.factor(cyl), fill = as.factor(am), group = as.factor(am))) +
  geom_bar(position = "fill") +
  xlab("CYL") +     # change x axis label
  labs(fill = "am") # change legend title


问:
Permission denied on Cloud KMS key when using cloud storage
I am using cloud storage upload a file with kms key. Here is my code:

await storage.bucket(config.bucket).upload(file, {
  kmsKeyName: `projects/${process.env.PROJECT_ID}/locations/global/keyRings/test/cryptoKeys/nodejs-gcp`,
  destination: 'mmczblsq.kms.encrypted.doc'
});
```

<p>I have a <code>cloud-storage-admin.json</code> service account with <code>cloud storage admin</code> permission. Initialize the <code>storage</code> with this service account.</p>

<pre class="lang-js prettyprint-override"><code>const storage: Storage = new Storage({
  projectId: process.env.PROJECT_ID,
  keyFilename: path.resolve(__dirname, '../.gcp/cloud-storage-admin.json')
});
</code>```

And, I use gcloud kms keys add-iam-policy-binding add roles/cloudkms.cryptoKeyEncrypterDecrypter to cloud-storage-admin.json service account.

When I try to upload a file with kms key, still got this permission error:

Permission denied on Cloud KMS key. Please ensure that your Cloud Storage service account  has been authorized to use this key.

update

☁  nodejs-gcp [master] ⚡  gcloud kms keys get-iam-policy nodejs-gcp --keyring=test --location=global
bindings:
- members:
  - serviceAccount:cloud-storage-admin@<PROJECT_ID>.iam.gserviceaccount.com
  - serviceAccount:service-16536262744@gs-project-accounts.iam.gserviceaccount.com
  role: roles/cloudkms.cryptoKeyEncrypterDecrypter
etag: BwWJ2Pdc5YM=
version: 1
```

答:
When you use kmsKeyName, Google Cloud Storage is the entity calling KMS, not your service account. It's a bit confusing:

Your service account has permission to call the Cloud Storage API

The Cloud Storage service account then calls the KMS API in transit

You will need to get the Cloud Storage service account and grant that service account the ability to invoke Cloud KMS:

Option 1: Open the API explorer, authorize, and execute

Option 2: Install gcloud, authenticate to gcloud, install oauth2l, and run this curl command replacing [PROJECT_ID] with your project ID:

```<code>curl -X GET -H "$(oauth2l header cloud-platform)" \
  "https://www.googleapis.com/storage/v1/projects/[PROJECT_ID]/serviceAccount"
</code>```

Option 3: Trust me that it's in the format service-[PROJECT_NUMBER]@gs-project-accounts.iam.gserviceaccount.com and get your [PROJECT_NUMBER] from gcloud projects list or the web interface.

Body:
I am using cloud storage upload a file with kms key. Here is my code:

await storage.bucket(config.bucket).upload(file, {
  kmsKeyName: `projects/${process.env.PROJECT_ID}/locations/global/keyRings/test/cryptoKeys/nodejs-gcp`,
  destination: 'mmczblsq.kms.encrypted.doc'
});

I have a cloud-storage-admin.json service account with cloud storage admin permission. Initialize the storage with this service account.

const storage: Storage = new Storage({
  projectId: process.env.PROJECT_ID,
  keyFilename: path.resolve(__dirname, '../.gcp/cloud-storage-admin.json')
});

And, I use gcloud kms keys add-iam-policy-binding add roles/cloudkms.cryptoKeyEncrypterDecrypter to cloud-storage-admin.json service account.

When I try to upload a file with kms key, still got this permission error:

Permission denied on Cloud KMS key. Please ensure that your Cloud Storage service account  has been authorized to use this key.

update

☁  nodejs-gcp [master] ⚡  gcloud kms keys get-iam-policy nodejs-gcp --keyring=test --location=global
bindings:
- members:
  - serviceAccount:cloud-storage-admin@<PROJECT_ID>.iam.gserviceaccount.com
  - serviceAccount:service-16536262744@gs-project-accounts.iam.gserviceaccount.com
  role: roles/cloudkms.cryptoKeyEncrypterDecrypter
etag: BwWJ2Pdc5YM=
version: 1

Body:
When you use kmsKeyName, Google Cloud Storage is the entity calling KMS, not your service account. It's a bit confusing:

Your service account has permission to call the Cloud Storage API

The Cloud Storage service account then calls the KMS API in transit

You will need to get the Cloud Storage service account and grant that service account the ability to invoke Cloud KMS:

Option 1: Open the API explorer, authorize, and execute

Option 2: Install gcloud, authenticate to gcloud, install oauth2l, and run this curl command replacing [PROJECT_ID] with your project ID:

curl -X GET -H "$(oauth2l header cloud-platform)" \
  "https://www.googleapis.com/storage/v1/projects/[PROJECT_ID]/serviceAccount"

Option 3: Trust me that it's in the format service-[PROJECT_NUMBER]@gs-project-accounts.iam.gserviceaccount.com and get your [PROJECT_NUMBER] from gcloud projects list or the web interface.


问:
How to pass raw complex object to MVC action?
Problem: Can't parse File object to JSON string, when doing that only null values are gotten, while trying to send complex type to MVC controller.

I tried adding it into FormData object and passing it to controller, however, passing List of them was not successful, because it would either return an empty array or just plain null

model:

public class UploadedDocument
    {

        public HttpPostedFile File { get; set;}
        public string DocumentId { get; set;}
        public string DocumentType { get; set; }

    }
```

<p>controller:</p>

<pre class="lang-cs prettyprint-override"><code>        [HttpPost]
        [ActionName("UploadFile")]
        public ActionResult Upload(IEnumerable<UploadedDocument> documents)
        {
            return View();
        }
</code>```

upload function:

```<code>var _documents = [];

                for (var i = 0; i < arrayOfFiles.length; i++) {

                    var document = {
                        "File": arrayOfFiles[i].file,
                        "DocumentId": arrayOfFiles[i].documentId,
                        "DocumentType": arrayOfFiles[i].documentName
                    };

                    _documents.push(document);
                }

                $.ajax({
                    url: "@Url.Action("UploadFile", "Home")",
                    type: "POST",
                    data: {"documents":_documents}
                    });
            }
        });
</code>```

答:
Basically, I manage to handle single upload via ajax like below

Input Element

```<code>  <input type="file" name="customerpicture" id="customerpicture" />
</code>```

Formdata

```<code> function getFormData() {
        var data = new FormData();
        var files = $("#customerpicture").get(0).files;
        if (files.length > 0) {
            data.append("file", files[0]);
        }
        //data.append("Name", $("#name").val());

        return data;
    }
</code>```

Ajax Method

```<code>$('#InsertCustomer').click(function () {
        debugger;
            var antiForgeryToken = $("input[name=__RequestVerificationToken]").val();
            var url = '@Url.Action("Add_Customer", "Customer")';

                $.ajax({
                    type: 'POST',
                    headers: { "__RequestVerificationToken": antiForgeryToken },
                    url: url,
                    contentType: false,
                    processData: false,
                    data: getFormData(),
                    success: function (res) {
                            $('#custinsertmodal').modal('hide');
                            $('#custinsertmodal').find("input,textarea,select")
                                .val('')
                                .end()
                                .find("input[type=checkbox], input[type=radio]")
                                .prop("checked", "")
                                .end();
                            bootbox.alert({ message: res.result });
                    }
                });
        });
</code>```

Controller

```<code> [HttpPost, ValidateHeaderAntiForgeryToken]
    public JsonResult Add_Customer()
    {
        var errMsg = string.Empty;
        byte[] tmpImage;
        try
        {
            //Customer Image Processing
            var file = Request.Files.Get("file");

            if (file != null && file.ContentLength > 0)
            {
                //Image Saving to Folder
                UploadHelper.UploadFile(file);

                //Image Saving to Database
                tmpImage = new byte[file.ContentLength];
                file.InputStream.Read(tmpImage, 0, file.ContentLength);

                CustomerModel model = new CustomerModel
                {

                    Signature = tmpImage
                };
                _setupRepo.CreateSignatory(model);
                return Json(new { error = false, result = $"Customer was successfully created" }, JsonRequestBehavior.AllowGet);

        }
        catch (Exception ex)
        {
            errMsg = ex.Message.ToString();
            return Json(new { error = true, result = errMsg }, JsonRequestBehavior.AllowGet);
        }
    }
</code>```

Body:
Problem: Can't parse File object to JSON string, when doing that only null values are gotten, while trying to send complex type to MVC controller.

I tried adding it into FormData object and passing it to controller, however, passing List of them was not successful, because it would either return an empty array or just plain null

model:

public class UploadedDocument
    {

        public HttpPostedFile File { get; set;}
        public string DocumentId { get; set;}
        public string DocumentType { get; set; }

    }

controller:

        [HttpPost]
        [ActionName("UploadFile")]
        public ActionResult Upload(IEnumerable<UploadedDocument> documents)
        {
            return View();
        }

upload function:

var _documents = [];

                for (var i = 0; i < arrayOfFiles.length; i++) {

                    var document = {
                        "File": arrayOfFiles[i].file,
                        "DocumentId": arrayOfFiles[i].documentId,
                        "DocumentType": arrayOfFiles[i].documentName
                    };

                    _documents.push(document);
                }

                $.ajax({
                    url: "@Url.Action("UploadFile", "Home")",
                    type: "POST",
                    data: {"documents":_documents}
                    });
            }
        });

Body:
Basically, I manage to handle single upload via ajax like below

Input Element

  <input type="file" name="customerpicture" id="customerpicture" />

Formdata

 function getFormData() {
        var data = new FormData();
        var files = $("#customerpicture").get(0).files;
        if (files.length > 0) {
            data.append("file", files[0]);
        }
        //data.append("Name", $("#name").val());

        return data;
    }

Ajax Method

$('#InsertCustomer').click(function () {
        debugger;
            var antiForgeryToken = $("input[name=__RequestVerificationToken]").val();
            var url = '@Url.Action("Add_Customer", "Customer")';

                $.ajax({
                    type: 'POST',
                    headers: { "__RequestVerificationToken": antiForgeryToken },
                    url: url,
                    contentType: false,
                    processData: false,
                    data: getFormData(),
                    success: function (res) {
                            $('#custinsertmodal').modal('hide');
                            $('#custinsertmodal').find("input,textarea,select")
                                .val('')
                                .end()
                                .find("input[type=checkbox], input[type=radio]")
                                .prop("checked", "")
                                .end();
                            bootbox.alert({ message: res.result });
                    }
                });
        });

Controller

 [HttpPost, ValidateHeaderAntiForgeryToken]
    public JsonResult Add_Customer()
    {
        var errMsg = string.Empty;
        byte[] tmpImage;
        try
        {
            //Customer Image Processing
            var file = Request.Files.Get("file");

            if (file != null && file.ContentLength > 0)
            {
                //Image Saving to Folder
                UploadHelper.UploadFile(file);

                //Image Saving to Database
                tmpImage = new byte[file.ContentLength];
                file.InputStream.Read(tmpImage, 0, file.ContentLength);

                CustomerModel model = new CustomerModel
                {

                    Signature = tmpImage
                };
                _setupRepo.CreateSignatory(model);
                return Json(new { error = false, result = $"Customer was successfully created" }, JsonRequestBehavior.AllowGet);

        }
        catch (Exception ex)
        {
            errMsg = ex.Message.ToString();
            return Json(new { error = true, result = errMsg }, JsonRequestBehavior.AllowGet);
        }
    }


问:
How to convert mysqli result to JSON?
I have a mysqli query which I need to format as JSON for a mobile application.

I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)

```<code>$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');

$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);

// create xml format
$doc = new DomDocument('1.0');

// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);

// add node for each row
while($row = $stmt->fetch()) :

    $occ = $doc->createElement('data');
    $occ = $root->appendChild($occ);

    $child = $doc->createElement('section');
    $child = $occ->appendChild($child);
    $value = $doc->createTextNode($title);
    $value = $child->appendChild($value);

endwhile;

$xml_string = $doc->saveXML();

header('Content-Type: application/xml; charset=ISO-8859-1');

// output xml jQuery ready

echo $xml_string;
</code>```

答:
There is one essential thing about JSON - the data must be UTF-8 encoded. Therefore, the proper encoding must be set for the database connection.

The rest is as silly as any other database operation

```<code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$db->set_charset('utf8mb4');

$sql = 'SELECT DISTINCT title FROM sections ORDER BY title ASC';
$data = $db->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);
</code>```

Title: How to convert mysqli result to JSON?

Body:
I have a mysqli query which I need to format as JSON for a mobile application.

I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)

$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');

$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);

// create xml format
$doc = new DomDocument('1.0');

// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);

// add node for each row
while($row = $stmt->fetch()) :

    $occ = $doc->createElement('data');
    $occ = $root->appendChild($occ);

    $child = $doc->createElement('section');
    $child = $occ->appendChild($child);
    $value = $doc->createTextNode($title);
    $value = $child->appendChild($value);

endwhile;

$xml_string = $doc->saveXML();

header('Content-Type: application/xml; charset=ISO-8859-1');

// output xml jQuery ready

echo $xml_string;

Body:
There is one essential thing about JSON - the data must be UTF-8 encoded. Therefore, the proper encoding must be set for the database connection.

The rest is as silly as any other database operation

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$db->set_charset('utf8mb4');

$sql = 'SELECT DISTINCT title FROM sections ORDER BY title ASC';
$data = $db->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);


问:
How to efficiently utilize 10+ computers to import data
We have flat files (CSV) with >200,000,000 rows, which we import into a star schema with 23 dimension tables. The biggest dimension table has 3 million rows. At the moment we run the importing process on a single computer and it takes around 15 hours. As this is too long time, we want to utilize something like 40 computers to do the importing.

My question

How can we efficiently utilize the 40 computers to do the importing. The main worry is that there will be a lot of time spent replicating the dimension tables across all the nodes as they need to be identical on all nodes. This could mean that if we utilized 1000 servers to do the importing in the future, it might actually be slower than utilize a single one, due to the extensive network communication and coordination between the servers.

Does anyone have suggestion?

EDIT:

The following is a simplification of the CSV files:

```<code>"avalue";"anothervalue"
"bvalue";"evenanothervalue"
"avalue";"evenanothervalue"
"avalue";"evenanothervalue"
"bvalue";"evenanothervalue"
"avalue";"anothervalue"
</code>```

After importing, the tables look like this:

dimension_table1

```<code>id  name
1   "avalue"
2   "bvalue"
</code>```

dimension_table2

```<code>id  name
1   "anothervalue"
2   "evenanothervalue"
</code>```

Fact table

```<code>  dimension_table1_ID       dimension_table2_ID
    1                      1
    2                      2
    1                       2
    1                       2
    2                       2
    1                       1
</code>```

答:
Loading CSV data into a database is slow because it needs to read, split and validate the data.

So what you should try is this:

Setup a local database on each computer. This will get rid of the network latency.

Load a different part of the data on each computer. Try to give each computer the same chunk. If that isn't easy for some reason, give each computer, say, 10'000 rows. When they are done, give them the next chunk.

Dump the data with the DB tools

Load all dumps into a single DB

Make sure that your loader tool can import data into a table which already contains data. If you can't do this, check your DB documentation for "remote table". A lot of databases allow to make a table from another DB server visible locally.

That allows you to run commands like insert into TABLE (....) select .... from REMOTE_SERVER.TABLE

If you need primary keys (and you should), you will also have the problem to assign PKs during the import into the local DBs. I suggest to add the PKs to the CSV file.

[EDIT] After checking with your edits, here is what you should try:

Write a small program which extract the unique values in the first and second column of the CSV file. That could be a simple script like:

```<code> cut -d";" -f1 | sort -u | nawk ' { print FNR";"$0 }'
</code>```

This is a pretty cheap process (a couple of minutes even for huge files). It gives you ID-value files.

Write a program which reads the new ID-value files, caches them in memory and then reads the huge CSV files and replaces the values with the IDs.

If the ID-value files are too big, just do this step for the small files and load the huge ones into all 40 per-machine DBs.

Split the huge file into 40 chunks and load each of them on each machine.

If you had huge ID-value files, you can use the tables created on each machine to replace all the values that remained.

Use backup/restore or remote tables to merge the results.

Or, even better, keep the data on the 40 machines and use algorithms from parallel computing to split the work and merge the results. That's how Google can create search results from billions of web pages in a few milliseconds.

See here for an introduction.

Body:
We have flat files (CSV) with >200,000,000 rows, which we import into a star schema with 23 dimension tables. The biggest dimension table has 3 million rows. At the moment we run the importing process on a single computer and it takes around 15 hours. As this is too long time, we want to utilize something like 40 computers to do the importing.

My question

How can we efficiently utilize the 40 computers to do the importing. The main worry is that there will be a lot of time spent replicating the dimension tables across all the nodes as they need to be identical on all nodes. This could mean that if we utilized 1000 servers to do the importing in the future, it might actually be slower than utilize a single one, due to the extensive network communication and coordination between the servers.

Does anyone have suggestion?

EDIT:

The following is a simplification of the CSV files:

"avalue";"anothervalue"
"bvalue";"evenanothervalue"
"avalue";"evenanothervalue"
"avalue";"evenanothervalue"
"bvalue";"evenanothervalue"
"avalue";"anothervalue"

After importing, the tables look like this:

dimension_table1

id  name
1   "avalue"
2   "bvalue"

dimension_table2

id  name
1   "anothervalue"
2   "evenanothervalue"

Fact table

  dimension_table1_ID       dimension_table2_ID
    1                      1
    2                      2
    1                       2
    1                       2
    2                       2
    1                       1

Body:
Loading CSV data into a database is slow because it needs to read, split and validate the data.

So what you should try is this:

Setup a local database on each computer. This will get rid of the network latency.

Load a different part of the data on each computer. Try to give each computer the same chunk. If that isn't easy for some reason, give each computer, say, 10'000 rows. When they are done, give them the next chunk.

Dump the data with the DB tools

Load all dumps into a single DB

Make sure that your loader tool can import data into a table which already contains data. If you can't do this, check your DB documentation for "remote table". A lot of databases allow to make a table from another DB server visible locally.

That allows you to run commands like insert into TABLE (....) select .... from REMOTE_SERVER.TABLE

If you need primary keys (and you should), you will also have the problem to assign PKs during the import into the local DBs. I suggest to add the PKs to the CSV file.

[EDIT] After checking with your edits, here is what you should try:

Write a small program which extract the unique values in the first and second column of the CSV file. That could be a simple script like:

 cut -d";" -f1 | sort -u | nawk ' { print FNR";"$0 }'

This is a pretty cheap process (a couple of minutes even for huge files). It gives you ID-value files.

Write a program which reads the new ID-value files, caches them in memory and then reads the huge CSV files and replaces the values with the IDs.

If the ID-value files are too big, just do this step for the small files and load the huge ones into all 40 per-machine DBs.

Split the huge file into 40 chunks and load each of them on each machine.

If you had huge ID-value files, you can use the tables created on each machine to replace all the values that remained.

Use backup/restore or remote tables to merge the results.

Or, even better, keep the data on the 40 machines and use algorithms from parallel computing to split the work and merge the results. That's how Google can create search results from billions of web pages in a few milliseconds.

See here for an introduction.


问:
Share Eclipse Settings With Team
We have a very common use case: we want to standardize all our Eclipse settings like formatter, warnings, save actions etc.

This question got the answer to just use project settings for that, but here's why that won't work for us:

We have way too many projects. We have about 500 Maven / Tycho reactors (many with branches) which in turn contain of usually 3-5 Java projects. Copying project settings for all of these is tedious, error prone and not update-friendly.

So we decided to import workspace setting for each workspace, but that's not optimal either. E.g. I already have about 100 workspaces, so it's almost as tedious and error prone as the project settings.

Let's not even talk about the fact that most of us have more then one Eclipse installation.

Right now I'm thinking about creating a custom plug-in / fragment for Eclipse, which programmatically adds our company's formatter and other settings to the workspace. It would only need to be installed once, and could be updated via the built-in update mechanism.

But I really can't believe nobody has a similiar problem. So I wondering, if there is a build-in way to share Eclipse settings with a big team with many projects?

答:
Eclipse Oomph is licensed under EPL 1.0 - I can't see why that shouldn't be allowed for companies.

Wrt https://stackoverflow.com/a/37799711/10235188 also Yatta Profiles for Eclipse is mentioned to share Eclipse preferences like Code Formatter and other settings.

Title: Share Eclipse Settings With Team


问:
How to get back the previous/old editor in wp admin in updated version >5
Wp updated version >5 is creating a problem in wp admin editor, is there any way to switch the editor to the previous one ?</p>

答:
You can use the below plugin.

https://wordpress.org/plugins/disable-gutenberg/


问:
EF Core with SQLite on Mono: e_sqlite3 not found
We are using Entity Framework Core 2.2.4 together with an SQLite database targeting .NET Framework 4.7.2. Following Nuget packages were installed:

```<code>Microsoft.Data.Sqlite
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools
</code>```

On my development machine (Windows 10) everything works fine but when trying to run the application with Mono on our 32-bit Linux machine, the following exception occurs:

```<code>FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: The type
initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
---> System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.DllNotFoundException: e_sqlite3
at (wrapper managed-to-native)
SQLitePCL.SQLite3Provider_e_sqlite3+NativeMethods.sqlite3_libversion_number()
  at SQLitePCL.SQLite3Provider_e_sqlite3.SQLitePCL.ISQLite3Provider.sqlite3_libversion_number () [0x00000] in <61bb3ca1db9c41ea88f280f0b1600d58>:0
  at SQLitePCL.raw.SetProvider (SQLitePCL.ISQLite3Provider imp) [0x00008] in <3d4b21fb9c764efbb11f6e3b02efff52>:0
  at SQLitePCL.Batteries_V2.Init () [0x00005] in <f5d9c86a14864b5d99b8bdece1b8292c>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
   --- End of inner exception stack trace ---
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00048] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
  at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
  at Microsoft.Data.Sqlite.Utilities.BundleInitializer.Initialize () [0x0002f] in <b46e232ade014524baa458345f270c50>:0
  at Microsoft.Data.Sqlite.SqliteConnection..cctor () [0x00000] in <b46e232ade014524baa458345f270c50>:0
   --- End of inner exception stack trace ---
  at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
  at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.CreateDbConnection () [0x00006] in <74192050a4d342039620dc7ef6678f71>:0
  at Microsoft.EntityFrameworkCore.Internal.LazyRef`1[T].get_Value () [0x00008] in <adf771f92e754fe1bb85c5850cd0c16b>:0
  at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection () [0x00000] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open (System.Boolean errorsExpected) [0x00000] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.Open (System.Boolean errorsExpected) [0x00000] in <74192050a4d342039620dc7ef6678f71>:0
  at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Exists () [0x0000c] in <74192050a4d342039620dc7ef6678f71>:0
  at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists () [0x0000b] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate (System.String targetMigration) [0x00012] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate (Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade databaseFacade) [0x00010] in <69f795dffc844780bfcfff4ff8415a92>:0
  at TestEfCorePlusSqlite.Program.Main (System.String[] args) [0x0000e] in <c4fad569c9a241ef887b5b2ddbc0225f>:0
</code>```

Since the application is built with Any CPU configuration, x86 and x64 folders are created in bin/Debug, both containing an e_sqlite3.dll. I already tried to copy the x86 dll to bin/Debug but the error still occurred.

What I've tried so far:

installing Microsoft.EntityFrameworkCore.Sqlite.Core together with
SQLitePCLRaw.bundle_e_sqlite3 as suggested here

installing Microsoft.EntityFrameworkCore.Sqlite (or
Microsoft.Data.Sqlite or SQLitePCLRaw.bundle_green) as suggested here

different combinations of SQLitePCLRaw.* packages

What do I have to do to get EF Core and SQlite running on Mono?

答: After a refreshing weekend I took another glance at the problem. I found the official Mono documentation regarding DllNotFoundException and used MONO_LOG_LEVEL=debug mono YourApp.exe to find out which lib Mono is trying to load. It was /usr/lib/libe_sqlite3.so which was not available on my system. All I did was to copy the available /usr/lib/libsqlite3.so and rename it to libe_sqlite3.so. I'm not sure if this is the preferred way but my application works.

Body:
We are using Entity Framework Core 2.2.4 together with an SQLite database targeting .NET Framework 4.7.2. Following Nuget packages were installed:

Microsoft.Data.Sqlite
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools

On my development machine (Windows 10) everything works fine but when trying to run the application with Mono on our 32-bit Linux machine, the following exception occurs:

FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: The type
initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
---> System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.DllNotFoundException: e_sqlite3
at (wrapper managed-to-native)
SQLitePCL.SQLite3Provider_e_sqlite3+NativeMethods.sqlite3_libversion_number()
  at SQLitePCL.SQLite3Provider_e_sqlite3.SQLitePCL.ISQLite3Provider.sqlite3_libversion_number () [0x00000] in <61bb3ca1db9c41ea88f280f0b1600d58>:0
  at SQLitePCL.raw.SetProvider (SQLitePCL.ISQLite3Provider imp) [0x00008] in <3d4b21fb9c764efbb11f6e3b02efff52>:0
  at SQLitePCL.Batteries_V2.Init () [0x00005] in <f5d9c86a14864b5d99b8bdece1b8292c>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
   --- End of inner exception stack trace ---
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00048] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
  at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <a89b9d7c1a66468eb33312af7ed3a74e>:0
  at Microsoft.Data.Sqlite.Utilities.BundleInitializer.Initialize () [0x0002f] in <b46e232ade014524baa458345f270c50>:0
  at Microsoft.Data.Sqlite.SqliteConnection..cctor () [0x00000] in <b46e232ade014524baa458345f270c50>:0
   --- End of inner exception stack trace ---
  at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
  at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.CreateDbConnection () [0x00006] in <74192050a4d342039620dc7ef6678f71>:0
  at Microsoft.EntityFrameworkCore.Internal.LazyRef`1[T].get_Value () [0x00008] in <adf771f92e754fe1bb85c5850cd0c16b>:0
  at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection () [0x00000] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open (System.Boolean errorsExpected) [0x00000] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.Open (System.Boolean errorsExpected) [0x00000] in <74192050a4d342039620dc7ef6678f71>:0
  at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Exists () [0x0000c] in <74192050a4d342039620dc7ef6678f71>:0
  at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists () [0x0000b] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate (System.String targetMigration) [0x00012] in <69f795dffc844780bfcfff4ff8415a92>:0
  at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate (Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade databaseFacade) [0x00010] in <69f795dffc844780bfcfff4ff8415a92>:0
  at TestEfCorePlusSqlite.Program.Main (System.String[] args) [0x0000e] in <c4fad569c9a241ef887b5b2ddbc0225f>:0

Since the application is built with Any CPU configuration, x86 and x64 folders are created in bin/Debug, both containing an e_sqlite3.dll. I already tried to copy the x86 dll to bin/Debug but the error still occurred.

What I've tried so far:

installing Microsoft.EntityFrameworkCore.Sqlite.Core together with
SQLitePCLRaw.bundle_e_sqlite3 as suggested here

installing Microsoft.EntityFrameworkCore.Sqlite (or
Microsoft.Data.Sqlite or SQLitePCLRaw.bundle_green) as suggested here

different combinations of SQLitePCLRaw.* packages

What do I have to do to get EF Core and SQlite running on Mono?


问:
How to fix the "Role doesn't exist" error?
I just created a new Ruby on rails project using this, in order to deploy it with Heroku

```<code>rails new -d postgresql LG_1
</code>```

Then I used rails s to run my server and found this error :

```<code>role "esteban" does not exist.
</code>```

I've been looking for solutions for an hour, but none of them worked. Using createuser just gives me the does-not-exist error, and I'm not very comfortable with Rails.

The versions I'm using :

```<code>Ruby 2.4.4
Rails 5.2.3
Pg (gem) 1.1.4
</code>```

Here is my database.yml file (without the 75 lines of comments) :

```<code>default: &default
    adapter: postgresql
    encoding: unicode
    host: /var/run/postgresql
    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
    <<: *default
    database: LG_1_development

test:
     <<: *default
     database: LG_1_test

production:
    <<: *default
    database: LG_1_production
    username: LG_1
    password: <%= ENV['LG_1_DATABASE_PASSWORD'] %>
</code>```

I did not edit this file.

EDIT : I found the solution. I had to open the pg_hba.conf file and manually add a new user called "esteban"

答:
Did you install new Gem for project?

If you did I think what you didn't database migration.

Please run following commands.

```<code>$heroku run rake db:migrate

$heroku ps:scale web=1

$heroku ps

$heroku open
</code>```

Body:
I just created a new Ruby on rails project using this, in order to deploy it with Heroku

rails new -d postgresql LG_1

Then I used rails s to run my server and found this error :

role "esteban" does not exist.

I've been looking for solutions for an hour, but none of them worked. Using createuser just gives me the does-not-exist error, and I'm not very comfortable with Rails.

The versions I'm using :

Ruby 2.4.4
Rails 5.2.3
Pg (gem) 1.1.4

Here is my database.yml file (without the 75 lines of comments) :

default: &default
    adapter: postgresql
    encoding: unicode
    host: /var/run/postgresql
    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
    <<: *default
    database: LG_1_development

test:
     <<: *default
     database: LG_1_test

production:
    <<: *default
    database: LG_1_production
    username: LG_1
    password: <%= ENV['LG_1_DATABASE_PASSWORD'] %>

I did not edit this file.

EDIT : I found the solution. I had to open the pg_hba.conf file and manually add a new user called "esteban"

Body:
Did you install new Gem for project?

If you did I think what you didn't database migration.

Please run following commands.

$heroku run rake db:migrate

$heroku ps:scale web=1

$heroku ps

$heroku open


问:
Return value as -0 from oracle sql
is there any way to return 0 as -0 from oracle sql/plsql so that we can do some validation , this is just to make sure if the value 0 is rounded from a negative value or positive value.

If there is any alternate approach, to handle this , please let me know, rounding the value in Javascript is not exactly as rounding in oracle sql.

答:
my answer is do not round in Oracle: if javascript receives a 0 it can not know if it was -0.001 or +0.001 so keep it simple, pass the exact value to js and do something like this:

```<code>if(value < 0) {
doSomethin();
} else {
doElse();
</code>```

if for some reason you have to round it in Oracle you have to give back some more info to js like: 0 "from negative" and in js:

```<code>if(text === "from negative") {
 doSomething();
} else {
doElse();
}
</code>```

Title: Return value as -0 from oracle sql

Body:
my answer is do not round in Oracle: if javascript receives a 0 it can not know if it was -0.001 or +0.001 so keep it simple, pass the exact value to js and do something like this:

if(value < 0) {
doSomethin();
} else {
doElse();

if for some reason you have to round it in Oracle you have to give back some more info to js like: 0 "from negative" and in js:

if(text === "from negative") {
 doSomething();
} else {
doElse();
}


问:
If I renew my distribution certificate, do I need to renew my notification certificates as well?
My distribution certificate will expire in about a month. I renewed it recently, do I need to renew my Apple Push Services certificate as well?

I am asking this because after I renewed my distribution certificate, I am not receiving any remote notifications on an XCode build.

答:
You have to renew all the certificates which are expired or going to expire for Distribution/Development process.

You should have to renew your APNS certificate based on its expiration If the expiration date of both of the certificate Distribution and APNS is the same.


问:
I want to populate Many2one field based on Selection Field
I want to populate Customer/Vendor Many2one field based on Selection Field which has two selection 1.Sale Order, 2.Purchase Order. If it is Sale Order then Many2one field should have Customers from sale.order model and if it is Purchase Order then Many2one field should have Vendors from purchase.order model.

from odoo import models, fields, api, _

class ProductRejection(models.Model):

```<code>_name = 'product.rejection'

pr_type_of_order = fields.Selection([('SO', 'Sale Order'), ('PO', 'Purchase Order')], string="Order Type")
pr_customer_name = fields.Many2one('sale.order',string="Vendor/Customer")
pr_order_no = fields.Many2one('sale.order',string="PO/SO No.")
pr_rejection_date = fields.Date("Date Of Rejection")
pr_product_name = fields.Many2one('product.product',string='Product Name')
pr_presentation = fields.Char("Presentation")
pr_reason = fields.Text("Reason Of Rejection")
pr_notes = fields.Text("Receiving Notes")
pr_status = fields.Selection([('new','New'),('confirm','Confirmed')],string="Status")

@api.onchange('pr_type_of_order')
def update_customer(self):
  result = {}
  if self.pr_type_of_order == 'SO':
    sale_customer_obj = self.env['sale.order']
    sale_customer_ids = sale_customer_obj.search(['partner_id'])
    for record in sale_customer_ids:
        cust_name = []
        cust_name.append(record.id)
        result = {'domain': {'pr_customer_name': [('id', 'in', cust_name)]}}
    return result
  else:
      if self.pr_type_of_order == 'PO':
        sale_customer_obj = self.env['purchase.order']
        sale_customer_ids = sale_customer_obj.search(['partner_id'])
        for record in sale_customer_ids:
            cust_name1 = []
            cust_name1.append(record.id)
            result = {'domain': {'pr_customer_name': [('id', 'in', cust_name1)]}}
        return result
</code>```

答: You take m2o of purchase.order and sale.order Now from the selection field, give attrs over .xml file. In which try to hide/unhide other fields. Now from that m2o, you can easily get filter from customer / vendor. Now apart from that if you don't have any other usage of sale.order than just take m2o of 'res.partner' and set the domain over this fields on the base of selection field value.

Body:
I want to populate Customer/Vendor Many2one field based on Selection Field which has two selection 1.Sale Order, 2.Purchase Order. If it is Sale Order then Many2one field should have Customers from sale.order model and if it is Purchase Order then Many2one field should have Vendors from purchase.order model.

from odoo import models, fields, api, _

class ProductRejection(models.Model):

_name = 'product.rejection'

pr_type_of_order = fields.Selection([('SO', 'Sale Order'), ('PO', 'Purchase Order')], string="Order Type")
pr_customer_name = fields.Many2one('sale.order',string="Vendor/Customer")
pr_order_no = fields.Many2one('sale.order',string="PO/SO No.")
pr_rejection_date = fields.Date("Date Of Rejection")
pr_product_name = fields.Many2one('product.product',string='Product Name')
pr_presentation = fields.Char("Presentation")
pr_reason = fields.Text("Reason Of Rejection")
pr_notes = fields.Text("Receiving Notes")
pr_status = fields.Selection([('new','New'),('confirm','Confirmed')],string="Status")

@api.onchange('pr_type_of_order')
def update_customer(self):
  result = {}
  if self.pr_type_of_order == 'SO':
    sale_customer_obj = self.env['sale.order']
    sale_customer_ids = sale_customer_obj.search(['partner_id'])
    for record in sale_customer_ids:
        cust_name = []
        cust_name.append(record.id)
        result = {'domain': {'pr_customer_name': [('id', 'in', cust_name)]}}
    return result
  else:
      if self.pr_type_of_order == 'PO':
        sale_customer_obj = self.env['purchase.order']
        sale_customer_ids = sale_customer_obj.search(['partner_id'])
        for record in sale_customer_ids:
            cust_name1 = []
            cust_name1.append(record.id)
            result = {'domain': {'pr_customer_name': [('id', 'in', cust_name1)]}}
        return result


问:
Yii2 Failing to instantiate component or class "db"
I use a Yii2 console application to run migrations. It's a very basic app, that goes like this (yii.php in the / folder of the project):

```<code><?php

    require __DIR__ . '/vendor/autoload.php';
    require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
    $config = require __DIR__ . '/config/console.php';

    (new yii\console\Application($config))->run();

?>
</code>```

So when i run

```<code>php yii.php
</code>```

Everything's fine, but when i run

```<code>php yii.php migrate/create create_user_table
</code>```

I am getting an error message:

```<code>Error: Failed to instantiate component or class "db".
</code>```

My Yii is v2.0.15.1

UPD 19:32 30/12/2018
When I add a db config to a config/console.php like this:

```<code>    return [
    'id' => 'school-console',
    'basePath' => dirname(__DIR__),
    'db' => [
              'class' => 'yii\db\Connection',
              'dsn' => 'mysql:host=localhost;dbname=school',
              'username' => 'root',
              'password' => 'Taras1love',
              'charset' => 'utf8',
    ]
];
</code>```

I get this:

```<code>Error: Setting read-only property: yii\console\Application::db
</code>```

答:
I found that I got this problem if I ran yii directly from vendor/bin.
If I went to the console directory and ran it from there using ./yii, I did not get this error and was able to create the migration.

In other words:

```<code>cd <project-root>/vendor/bin
yii migrate/create xxx
</code>```

did not work

But:

```<code>cd <project-root>/console
./yii migrate/create xxx
</code>```

did work

Body:
I use a Yii2 console application to run migrations. It's a very basic app, that goes like this (yii.php in the / folder of the project):

<?php

    require __DIR__ . '/vendor/autoload.php';
    require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
    $config = require __DIR__ . '/config/console.php';

    (new yii\console\Application($config))->run();

?>

So when i run

php yii.php

Everything's fine, but when i run

php yii.php migrate/create create_user_table

I am getting an error message:

Error: Failed to instantiate component or class "db".

My Yii is v2.0.15.1

UPD 19:32 30/12/2018
When I add a db config to a config/console.php like this:

    return [
    'id' => 'school-console',
    'basePath' => dirname(__DIR__),
    'db' => [
              'class' => 'yii\db\Connection',
              'dsn' => 'mysql:host=localhost;dbname=school',
              'username' => 'root',
              'password' => 'Taras1love',
              'charset' => 'utf8',
    ]
];

I get this:

Error: Setting read-only property: yii\console\Application::db

Body:
I found that I got this problem if I ran yii directly from vendor/bin.
If I went to the console directory and ran it from there using ./yii, I did not get this error and was able to create the migration.

In other words:

cd <project-root>/vendor/bin
yii migrate/create xxx

did not work

But:

cd <project-root>/console
./yii migrate/create xxx

did work


问:
how to use FilterSet in django with date field
I have a dat_transacao field and I'd like to create a range with it, but it didn't work. I created dat_inicial and dat_final in filters.py, but the screen didn't filter the records by these fields. Something is wrong but I don't know what is it. Anyone can help me please?
Thanks.

models.py:

```<code>class transacao(models.Model):
    dat_transacao = models.DateTimeField('Geração da Transação', auto_now=True)
    pessoa = models.ForeignKey(pessoa, default='', blank=True, null=True) # Chave estrangeira da Classe Pessoa
    tipotransacao = models.ForeignKey(tipotransacao, default='', blank=True, null=True) # Chave estrangeira da Classe Tipo de Transação
    servico = models.ForeignKey(servico, default='', blank=True, null=True) # Chave estrangeira da Classe Servico (que pode ser NULL)
    bloco = models.ForeignKey(bloco, default='', blank=True, null=True) # Chave estrangeira da Classe Bloco
</code>```

filters.py:

```<code>from .models import *
import django_filters
#from django_filters import DateTimeFilter

class livrorazaoFilter(django_filters.FilterSet):

    dat_inicial = django_filters.DateTimeFilter(name='dat_transacao',lookup_type=('gte'))
    dat_final = django_filters.DateTimeFilter(name='dat_transacao',lookup_type=('lte'))

    class Meta:
        model = transacao
        fields = ['dat_inicial', 'dat_final', 'tipotransacao', 'pessoa', 'bloco']
</code>```

views.py

```<code>def transacao_livrorazao(request, id=None):
    instancia_transacao = transacao.objects.all().order_by('-dat_transacao')
    instancia_transacaofilter = livrorazaoFilter(request.GET, queryset=instancia_transacao)
    context = {
            "queryset": instancia_transacao,
            "filter": instancia_transacaofilter,
            "instancia_transacao": instancia_transacao
    }
    return render(request, 'livrorazao/livrorazao.html', context)
</code>```

livrorazao.html:

```<code><!DOCTYPE html>
<html dir="ltr">

        <form class=" bd-form-2 " action="#" name="form-name" method="get">
            {% csrf_token %}

        <p>Período</p>
        <p>De</p>
            <input type="date" name='filter.form.dat_inicial' id="dat_inicial"  class="bd-form-input" >
        <p>até</p>
            <input type="date" name='filter.form.dat_final' id="dat_final"  class="bd-form-input" >
        <p>Tipo de Transação</p>
             {{ filter.form.tipotransacao }}

         <button type="submit">Consultar</button>
        </form>

        <br>
        <table width="100%" border="0" cellspacing="1" cellpadding="2">
        <tbody><tr>
            <th>ID Transação</th>
            <th>Data/Hora</th>
            <th>TipoTransação</th>
            <th>Blockchain</th>
        </tr>

      {% for instance in filter.qs  %}
        <tr>
            <td>{{ instance.id }}</td>
            <td>{{ instance.dat_transacao }}</td>
            <td>{{ instance.tipotransacao }}</td>
            <!--<td>{{ instance.pessoa }}</td>-->
            <td>{{ instance.bloco }}</td>
        </tr>
      {% endfor %}

</tbody></table>
</html>
</code>```

答:
my solution is similar to what @cezar posted. However, changing attrs={'class': 'datepicker'} to attrs={'type': 'date'} was what worked for me.

my frontend form display is managed using django-widget-tweaks

Here is an extract of what works for me:

models.py

```<code>class Applications(models.Model):
    #...
    status = models.CharField(max_length=10, choices=STATUS)
    start_date = models.DateTimeField(auto_now_add=True)
</code>```

filters.py

```<code>from .models import Applications
import django_filters

class ApplicationFilter(django_filters.FilterSet):
    start_date = django_filter.DateTimeFromRangeFilter(widget=django.widgets.RangeWidget(
    attrs={'type': 'date'}))

    class Meta:
        model = Applications
        fields = ['status', 'start_date']
</code>```

views.py

```<code>from django.shortcuts import render
from .models import Applications
from .filters import ApplicationFilter

def application_search(request):
    #... I stripped the view function down to what concerns filters.py
    application_list = Application.objects.all()
    application_filter = ApplicationFilter(request.GET, queryset=application_list)

    return render(
        request,
        "applications.html,
        {'filter': application_filter}
    )
</code>```

applications.html (with bootstrap)

```<code>...
{% load bootstrap4 %}{% load widget_tweaks %}
<form method="GET" class="form-inline">
<div class=form-group>
<label style="margin-right: 20px">Filter: </label>
{% render_field filter.form.status class="form-control"%}
<label style="margin-left: 20px; margin-right: 10px;">From </label>
{% render_field filter.form.start_date class="form-control" %}
<button style="margin-left: 10px" class="btn btn-primary btn-md">
 GO
</button>
</div>
</form>
...
</code>```

P.S: By default, I'd added django_filters to settings.py

Here's how the form looks

Body:
I have a dat_transacao field and I'd like to create a range with it, but it didn't work. I created dat_inicial and dat_final in filters.py, but the screen didn't filter the records by these fields. Something is wrong but I don't know what is it. Anyone can help me please?
Thanks.

models.py:

class transacao(models.Model):
    dat_transacao = models.DateTimeField('Geração da Transação', auto_now=True)
    pessoa = models.ForeignKey(pessoa, default='', blank=True, null=True) # Chave estrangeira da Classe Pessoa
    tipotransacao = models.ForeignKey(tipotransacao, default='', blank=True, null=True) # Chave estrangeira da Classe Tipo de Transação
    servico = models.ForeignKey(servico, default='', blank=True, null=True) # Chave estrangeira da Classe Servico (que pode ser NULL)
    bloco = models.ForeignKey(bloco, default='', blank=True, null=True) # Chave estrangeira da Classe Bloco

filters.py:

from .models import *
import django_filters
#from django_filters import DateTimeFilter

class livrorazaoFilter(django_filters.FilterSet):

    dat_inicial = django_filters.DateTimeFilter(name='dat_transacao',lookup_type=('gte'))
    dat_final = django_filters.DateTimeFilter(name='dat_transacao',lookup_type=('lte'))

    class Meta:
        model = transacao
        fields = ['dat_inicial', 'dat_final', 'tipotransacao', 'pessoa', 'bloco']

views.py

def transacao_livrorazao(request, id=None):
    instancia_transacao = transacao.objects.all().order_by('-dat_transacao')
    instancia_transacaofilter = livrorazaoFilter(request.GET, queryset=instancia_transacao)
    context = {
            "queryset": instancia_transacao,
            "filter": instancia_transacaofilter,
            "instancia_transacao": instancia_transacao
    }
    return render(request, 'livrorazao/livrorazao.html', context)

livrorazao.html:

<!DOCTYPE html>

        <form class=" bd-form-2 " action="#" name="form-name" method="get">
            {% csrf_token %}

Período

De

            <input type="date" name='filter.form.dat_inicial' id="dat_inicial"  class="bd-form-input" >

até

            <input type="date" name='filter.form.dat_final' id="dat_final"  class="bd-form-input" >

Tipo de Transação

             {{ filter.form.tipotransacao }}

         <button type="submit">Consultar</button>
        </form>

            ID Transação
            Data/Hora
            TipoTransação
            Blockchain

      {% for instance in filter.qs  %}

            {{ instance.id }}
            {{ instance.dat_transacao }}
            {{ instance.tipotransacao }}

            {{ instance.bloco }}

      {% endfor %}

Body:
my solution is similar to what @cezar posted. However, changing attrs={'class': 'datepicker'} to attrs={'type': 'date'} was what worked for me.

my frontend form display is managed using django-widget-tweaks

Here is an extract of what works for me:

models.py

class Applications(models.Model):
    #...
    status = models.CharField(max_length=10, choices=STATUS)
    start_date = models.DateTimeField(auto_now_add=True)

filters.py

from .models import Applications
import django_filters

class ApplicationFilter(django_filters.FilterSet):
    start_date = django_filter.DateTimeFromRangeFilter(widget=django.widgets.RangeWidget(
    attrs={'type': 'date'}))

    class Meta:
        model = Applications
        fields = ['status', 'start_date']

views.py

from django.shortcuts import render
from .models import Applications
from .filters import ApplicationFilter

def application_search(request):
    #... I stripped the view function down to what concerns filters.py
    application_list = Application.objects.all()
    application_filter = ApplicationFilter(request.GET, queryset=application_list)

    return render(
        request,
        "applications.html,
        {'filter': application_filter}
    )

applications.html (with bootstrap)

...
{% load bootstrap4 %}{% load widget_tweaks %}
<form method="GET" class="form-inline">
<div class=form-group>
<label style="margin-right: 20px">Filter: </label>
{% render_field filter.form.status class="form-control"%}
<label style="margin-left: 20px; margin-right: 10px;">From </label>
{% render_field filter.form.start_date class="form-control" %}
<button style="margin-left: 10px" class="btn btn-primary btn-md">
 GO
</button>
</div>
</form>
...

P.S: By default, I'd added django_filters to settings.py

Here's how the form looks


问:
Getting contacts error - how to fix that?
My problem is that I am listing contacts, the phone numbers show up just fine however I can not get the names to work.

I have tried several ways to gain the 'DISPLAY_NAME' however none of them have worked

```<code>    private void initializeRecyclerView() {
        mUserList = findViewById(R.id.userList);
        mUserList.setNestedScrollingEnabled(false);
        mUserList.setHasFixedSize(false);
        mUserListLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
        mUserList.setLayoutManager(mUserListLayoutManager);
        mUserListAdapter = new UserListAdapter(userList);
        mUserList.setAdapter(mUserListAdapter);
        getContactsList();
    }

This is my adaptor ^^

    private void getContactsList(){
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while(phones.moveToNext()){
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            UserObject mContact = new UserObject(name, phone);
            userList.add(mContact);
            mUserListAdapter.notifyDataSetChanged();
        }
    }
</code>```

答:
You need to add PROJECTION

You can put this method in your code

```<code> public Cursor getContact(Context context) {
        String[] PROJECTION = new String[]{
                ContactsContract.RawContacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
               };
        Uri uri = CommonDataKinds.Phone.CONTENT_URI;

        String order = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";// LIMIT " + limit + " offset " + lastId + "";
        try {
            return context.getContentResolver().query(uri, PROJECTION, null, null, order);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
</code>```

And get name using

```<code>ContactsContract.Contacts.DISPLAY_NAME
</code>```

Happy coding

Body:
My problem is that I am listing contacts, the phone numbers show up just fine however I can not get the names to work.

I have tried several ways to gain the 'DISPLAY_NAME' however none of them have worked

    private void initializeRecyclerView() {
        mUserList = findViewById(R.id.userList);
        mUserList.setNestedScrollingEnabled(false);
        mUserList.setHasFixedSize(false);
        mUserListLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
        mUserList.setLayoutManager(mUserListLayoutManager);
        mUserListAdapter = new UserListAdapter(userList);
        mUserList.setAdapter(mUserListAdapter);
        getContactsList();
    }

This is my adaptor ^^

    private void getContactsList(){
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while(phones.moveToNext()){
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            UserObject mContact = new UserObject(name, phone);
            userList.add(mContact);
            mUserListAdapter.notifyDataSetChanged();
        }
    }

Body:
You need to add PROJECTION

You can put this method in your code

 public Cursor getContact(Context context) {
        String[] PROJECTION = new String[]{
                ContactsContract.RawContacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
               };
        Uri uri = CommonDataKinds.Phone.CONTENT_URI;

        String order = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";// LIMIT " + limit + " offset " + lastId + "";
        try {
            return context.getContentResolver().query(uri, PROJECTION, null, null, order);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

And get name using

ContactsContract.Contacts.DISPLAY_NAME

Happy coding


问:
Is there an implicit default constructor in C++?
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?</p>

答:
C++ does not guarantee zeroing out memory.  Java and C# do (in a manner of speaking).

Some compilers might, but don't depend on that.

OwnerDisplayName: Skilldrick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jason Cohen

LastEditorDisplayName: Jason Cohen


问:
CodeBuild (AWS) from CodePipeline (AWS) is not working
I have created a code build project from code pipeline wizard with all the necessary required options and valid IAM role. I have added IAM role policy as well which is required for accessing and writing the data inside S3 bucket. below mentioned policy I have already considered for accessing S3.

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Resource": [
            "arn:aws:logs:aws/codebuild",
            "arn:aws:logs:aws/codebuild:*"
        ],
        "Action": [
            "logs:CreateLogGroup",
            "logs:CreateLogStream",
            "logs:PutLogEvents"
        ]
    },
    {
        "Effect": "Allow",
        "Resource": [
            "arn:aws:s3:::pipeline”,
            "arn:aws:s3::: pipeline/*"
        ],
        "Action": [
            "s3:PutObject",
            "s3:GetObject",
            "s3:GetObjectVersion",
            "s3:GetBucketAcl",
            "s3:GetBucketLocation"
        ]
    }
]
</code>```

}

Once I initiated a pipeline, code build is getting failed and I am getting below mentioned error

```<code>DOWNLOAD_SOURCE Failed:
CLIENT_ERROR: symlink /codebuild/output/.../libcrypto.1.0.0.dylib: no such file or directory for primary source and source version arn:aws:s3:::codepipeline-bucketSource/Ap4g3sv.zip
</code>```

I have researched a lot, have been through the various AWS documents but could not find the solution.

答:
Finally after a lot of research I found out that it was a permission issue only. I had to change the policy as mentioned below:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucketAcl",
                "s3:GetBucketLocation"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}
</code>```

After adding this modification my code build and pipeline started working.

Body:
I have created a code build project from code pipeline wizard with all the necessary required options and valid IAM role. I have added IAM role policy as well which is required for accessing and writing the data inside S3 bucket. below mentioned policy I have already considered for accessing S3.

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Resource": [
            "arn:aws:logs:aws/codebuild",
            "arn:aws:logs:aws/codebuild:*"
        ],
        "Action": [
            "logs:CreateLogGroup",
            "logs:CreateLogStream",
            "logs:PutLogEvents"
        ]
    },
    {
        "Effect": "Allow",
        "Resource": [
            "arn:aws:s3:::pipeline”,
            "arn:aws:s3::: pipeline/*"
        ],
        "Action": [
            "s3:PutObject",
            "s3:GetObject",
            "s3:GetObjectVersion",
            "s3:GetBucketAcl",
            "s3:GetBucketLocation"
        ]
    }
]

}

Once I initiated a pipeline, code build is getting failed and I am getting below mentioned error

DOWNLOAD_SOURCE Failed:
CLIENT_ERROR: symlink /codebuild/output/.../libcrypto.1.0.0.dylib: no such file or directory for primary source and source version arn:aws:s3:::codepipeline-bucketSource/Ap4g3sv.zip

I have researched a lot, have been through the various AWS documents but could not find the solution.

Body:
Finally after a lot of research I found out that it was a permission issue only. I had to change the policy as mentioned below:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucketAcl",
                "s3:GetBucketLocation"
            ],
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        }
    ]
}

After adding this modification my code build and pipeline started working.


问:
The new added field doesn’t show up when I reload the page
I am facing an issue and I don’t know how to resolve it.
I added a field on a webpage using JavaScript, ( when the user clicks on a button a new field should be added and it must be a static I mean it doesn’t suppose to be disappeared when move to another page or refreshing the page)the field appears but when I refresh the page it disappears.

Is there a solution for this?

答:
Usually the local variables which are set by JS will be cleared when refreshing page, so what you can do is,

1) make use of LocalStorage API or

2) if you have a server, create some API calls, store the value in DB, if the user logs in from different browser, he can see the field.


问:
Failing the whole Test Suite if one Test Case fails while running dependent test through VSTS
I have dependent test cases in my suite. If my first test fails it marks all other test as fail as well. So at the end it show that all all the test cases has failed which is not true.

Is there a way though which I can mark the test as 'failed due to dependent test failure' or something else so that it shows that it failed because the dependent test failed.
Is there a way to add a new state in test instead of only have pass, fail, not executed states.

I have added a common flag in our tests which marks the tests as failed when any dependent test fails.
As you can see in the code below.
It marks the test as Assert.Fail inside else part if the previous test has failed.
Is there a way to mark it in some other state and not failed for example : 'Failed due to dependent test failure'.

```<code>bool hasPreviousTestCasePassed = false
[TestMethod]
    public void DemoTest1()
    {
     try
        {
          ////perform all the test steps
          hasPreviousTestCasePassed = true;
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }

 [TestMethod]
    public void DemoTest2()
    {
        try
        {
            if (hasPreviousTestCasePassed)
            {
              ///perform all the test steps and mark flag as true after all steps
             hasPreviousTestCasePassed = true;
            }
            else
            {
               Assert.Fail("Execution for " + TestContext.TestName + " is aborted as the previous test case failed.");
            }
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }
</code>```

Expected result would be to have a way to mark a test as Failed due to dependent test failure and not just mark it as failed.

The Idea behind doing this is that when my first test fails then it marks all the test as failed and the outcome says that all the test has been fail which is not actually true because they got executed.

So I want a way to show case the dependent failure in a separate state so that the results are more clear.

答:
You could also consider not using dependant tests at all, if possible.
I understand you need to execute some tests in a specific order because you need the program to be in a specific state before you can test some specific functionality.

What you could do is make your program under test load in a specific state, in which you can test specific functionality. This way, your tests will be independent from each other and could turn testing specific functions from taking hours into taking minutes.

I'm currently working on tests for a POS cash register. The cash register can produce documents like receipts, delivery notes, invoices, etc. To do specific tests on those type of documents, I just load a relevant document from db to work on, thus quickly getting that POS in a specific state. I made these documents prior to testing, the data is always the same, but highly configurable.

Body:
I have dependent test cases in my suite. If my first test fails it marks all other test as fail as well. So at the end it show that all all the test cases has failed which is not true.

Is there a way though which I can mark the test as 'failed due to dependent test failure' or something else so that it shows that it failed because the dependent test failed.
Is there a way to add a new state in test instead of only have pass, fail, not executed states.

I have added a common flag in our tests which marks the tests as failed when any dependent test fails.
As you can see in the code below.
It marks the test as Assert.Fail inside else part if the previous test has failed.
Is there a way to mark it in some other state and not failed for example : 'Failed due to dependent test failure'.

bool hasPreviousTestCasePassed = false
[TestMethod]
    public void DemoTest1()
    {
     try
        {
          ////perform all the test steps
          hasPreviousTestCasePassed = true;
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }

 [TestMethod]
    public void DemoTest2()
    {
        try
        {
            if (hasPreviousTestCasePassed)
            {
              ///perform all the test steps and mark flag as true after all steps
             hasPreviousTestCasePassed = true;
            }
            else
            {
               Assert.Fail("Execution for " + TestContext.TestName + " is aborted as the previous test case failed.");
            }
        }
        catch (Exception ex)
        {
            hasPreviousTestCasePassed = false;
        }
    }

Expected result would be to have a way to mark a test as Failed due to dependent test failure and not just mark it as failed.

The Idea behind doing this is that when my first test fails then it marks all the test as failed and the outcome says that all the test has been fail which is not actually true because they got executed.

So I want a way to show case the dependent failure in a separate state so that the results are more clear.


问:
I want to change Gift card text how should i override this
I want to change Gift card text how should i override this.

$label = apply_filters( 'yith_ywgc_cart_totals_gift_card_label', esc_html( __( 'Gift card:', 'yith-woocommerce-gift-cards' ) . ' ' . $code ), $code );

答:
You need to use yith_ywgc_cart_totals_gift_card_label filter to change the label/text. Please give a try to below code snippet. Hope it will resolve your issue

```<code>add_filter('yith_ywgc_cart_totals_gift_card_label', 'yith_ywgc_cart_totals_gift_card_label_callback', 10, 2);
function yith_ywgc_cart_totals_gift_card_label_callback($title, $code){
    $title = "Xyz";
    return $title;
}
</code>```

Body:
You need to use yith_ywgc_cart_totals_gift_card_label filter to change the label/text. Please give a try to below code snippet. Hope it will resolve your issue

add_filter('yith_ywgc_cart_totals_gift_card_label', 'yith_ywgc_cart_totals_gift_card_label_callback', 10, 2);
function yith_ywgc_cart_totals_gift_card_label_callback($title, $code){
    $title = "Xyz";
    return $title;
}


问:
Position elements on screen using Javascript
I am attempting to use Javascript to position some of my elements on the screen/window. I am doing this to make sure that what ever the dimensions of the users screen, my elements will always be in the centre.

I know that padding & margin can also achieve this, but I am using a custom movement script called raphael.js, & in order to move my elements I need to set out my elements absolutely (its a custom home page, where you click blocks(that are links) & they fly off the screen).

My javascript function to move my elements fails to move my elements. Any suggestions on how to position my elements using javascript would be really helpful.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="dropDownMenu.js"></script>

    <title></title>
    <script src="javascript/raphael.js"></script> <!-- I am using a custom drawing/moving script which is why I cant put the img(id=bkImg) inside the div element -->
    <script LANGUAGE="JavaScript" type = "text/javascript">
    <!--
        function getScreenSize()
        {
            var res = {"width": 630, "height": 460};

            if (document.body)
            {
                 if (document.body.offsetWidth)  res["width"]  = document.body.offsetWidth;
                 if (document.body.offsetHeight) res["height"] = document.body.offsetHeight;
            }

            if (window.innerWidth)  res["width"]  = window.innerWidth;
            if (window.innerHeight) res["height"] = window.innerHeight;

            alert( res["width"] );
            alert( res["height"] );

            return res;
        }

        function positionBlocksAccordingToScreenSize()
        {
            // The problem is that the blocks position does not change but they should?

            var scrDim      = getScreenSize();
            var BK_WIDTH    = 800;
            var BK_HEIGHT   = 600;
            var X_OFFSET    = (scrDim["width"]-BK_WIDTH) / 2; // variable that changes according to the width of the screen
            var BLOCK_POS_X = [160, 80, 280, 20, 200, 400];
            var BLOCK_POS_Y = [26, 203, 203, 380, 380, 380];

            for ( var i=1; i<=5; i++ )
            {
                //document.getElementById("block"+i).setAttribute( "offsetLeft", X_OFFSET + BLOCK_POS_X[i] ); // doesn't work
                //document.getElementById("block"+i).setAttribute( "offsetTop", BLOCK_POS_Y[i] ); // doesn't work
                document.getElementById("block"+i).style.left = X_OFFSET + BLOCK_POS_X[i]; // doesn't work
                document.getElementById("block"+i).style.top  = BLOCK_POS_Y[i]; // doesn't work
            }
        }

    -->
    </script>
    <style type="text/css" media="all">
        <!--
        @import url("styles.css");

        #blockMenu { z-index: -5; padding: 0; position: absolute; width: 800px;
                     height: 600px; /*background-image: url("images/menuBk.png");*/ }
        #bkImg     { z-index: -5; position: relative; }

        #block1 { z-index: 60; position: absolute; top: 26px; left: 160px; margin: 0; padding: 0; }
        #block2 { z-index: 50; position: absolute; top: 203px; left: 80px; margin: 0; padding: 0; }
        #block3 { z-index: 40; position: absolute; top: 203px; left: 280px; margin: 0; padding: 0; }
        #block4 { z-index: 30; position: absolute; top: 380px; left: 20px; margin: 0; padding: 0; }
        #block5 { z-index: 20; position: absolute; top: 380px; left: 200px; margin: 0; padding: 0; }
        #block6 { z-index: 10; position: absolute; top: 380px; left: 400px; margin: 0; padding: 0; }

        -->
    </style>
</head>

<body onload="positionBlocksAccordingToScreenSize()" style="margin-top: 10%; text-align: center; margin-bottom: 10%; position: relative;">

    <img id="bkImg" src="images/menuBk.png" width="800px;" height="600px" alt=""/>
    <!-- The above image should be displayed behind the below div. I am using the raphael.js movement script, so I cannot place
         this image inside the div, because it will get erased when I call raphael.clear(); -->
    <div id="blockMenu">
        <div id="block1"><a href="javascript:onBlockClick('block1')"><img src="images/block1.png" width="200" height="200"/></a></div>
        <div id="block2"><a href="javascript:onBlockClick('block2')"><img src="images/block2.png" width="200" height="200"/></a></div>
        <div id="block3"><a href="javascript:onBlockClick('block3')"><img src="images/block3.png" width="200" height="200"/></a></div>
        <div id="block4"><a href="javascript:onBlockClick('block4')"><img src="images/block4.png" width="200" height="200"/></a></div>
        <div id="block5"><a href="javascript:onBlockClick('block5')"><img src="images/block5.png" width="200" height="200"/></a></div>
        <div id="block6"><a href="javascript:onBlockClick('block6')"><img src="images/block6.png" width="200" height="200"/></a></div>
    </div>

</body>
</html>
</code>```

答:
"Would you be able to suggest a line of jQuery code that could place my elements correctly?"

The following code uses jQuery and will center an absolutely positioned element on load and on window resize.

http://jsfiddle.net/Fu3L6/

HTML...

```<code><div id="element">Test</div>
</code>```

CSS...

```<code>#element {
  position: absolute;
  background-color: red;
  width: 200px;
}
</code>```

jQuery...

```<code>
$(document).ready(function () {

    centerInViewport('#element');

    $(window).resize(function () {
        centerInViewport('#element');
    });

});

function centerInViewport(e) {
    $docWidth = $(document).width();
    $elWidth = $(e).width();
    $offset = ($docWidth - $elWidth) / 2;
    $(e).css("marginLeft", $offset + "px");
}
</code>```

Body:
I am attempting to use Javascript to position some of my elements on the screen/window. I am doing this to make sure that what ever the dimensions of the users screen, my elements will always be in the centre.

I know that padding & margin can also achieve this, but I am using a custom movement script called raphael.js, & in order to move my elements I need to set out my elements absolutely (its a custom home page, where you click blocks(that are links) & they fly off the screen).

My javascript function to move my elements fails to move my elements. Any suggestions on how to position my elements using javascript would be really helpful.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title></title>

Body:
"Would you be able to suggest a line of jQuery code that could place my elements correctly?"

The following code uses jQuery and will center an absolutely positioned element on load and on window resize.

http://jsfiddle.net/Fu3L6/

HTML...

<div id="element">Test</div>

CSS...

#element {
  position: absolute;
  background-color: red;
  width: 200px;
}

jQuery...

$(document).ready(function () {

    centerInViewport('#element');

    $(window).resize(function () {
        centerInViewport('#element');
    });

});

function centerInViewport(e) {
    $docWidth = $(document).width();
    $elWidth = $(e).width();
    $offset = ($docWidth - $elWidth) / 2;
    $(e).css("marginLeft", $offset + "px");
}