问:
Load edit form Checkboxes with data from API - Angular Reactive Form
I am trying to fill checkbox with values from an API when a form is in edit mode.
 when I hard code the values of checkbox it is working stackblitz working, but when I load the data from the service through http request, I got the following error in console. also i attached the  new stackblitz that has the error

答:
I figured out the problem, I forgot to use *ngIf.  I corrected the stackblitz

In the component html template file, Just wrap the form inside a **
**

```<code><div *ngIf="rentPeriodList">
  <form [formGroup]="myForm" (ngSubmit)="submit()">
    <label
      formArrayName="rentPeriods"
      *ngFor="let rentPeriod of rentPeriodsArr.controls; index as i"
    >
      <input type="checkbox" [formControlName]="i" />
      {{ rentPeriodList[i].name }}
    </label>

    <button>submit</button>
  </form>
</div>
</code>```

Body:
I figured out the problem, I forgot to use *ngIf.  I corrected the stackblitz

In the component html template file, Just wrap the form inside a **<div *ngIf="rentPeriodList">**

<div *ngIf="rentPeriodList">
  <form [formGroup]="myForm" (ngSubmit)="submit()">
    <label
      formArrayName="rentPeriods"
      *ngFor="let rentPeriod of rentPeriodsArr.controls; index as i"
    >
      <input type="checkbox" [formControlName]="i" />
      {{ rentPeriodList[i].name }}
    </label>

    <button>submit</button>
  </form>
</div>


来源: stackexchange

问:
Input string was not in a correct format wtih cm.Parameters.AddWithValue
I got this error message : input string was not in a correct format

It throws this error message at these two codes:

```<code>cm.Parameters.AddWithValue("@price", double.Parse(frmCancelDetails.Instance.txtPrice.Text));
cm.Parameters.AddWithValue("@qty", int.Parse(frmCancelDetails.Instance.txtQty.Text));
</code>```

Also, when (double.Parse) and (int.Parse) are deleted, another message is thrown at the end of the code:

error converting data type varchar to numeric

Here is the full code

```<code>public void SaveCancelOrder(string user)
    {
        cn.Open();
        cm = new SqlCommand("insert into tblCancel (transno, pcode, price, qty, sdate, voidby, canelledby, reason, action)values(@transno, @pcode, @price, @qty, @sdate, @voidby, @canelledby, @reason, @action)", cn);
        cm.Parameters.AddWithValue("@transno"   , frmCancelDetails.Instance.txtTransNo.Text);
        cm.Parameters.AddWithValue("@pcode"     , frmCancelDetails.Instance.txtPcode.Text);
        cm.Parameters.AddWithValue("@price"   , double.Parse(frmCancelDetails.Instance.txtPrice.Text));
        cm.Parameters.AddWithValue("@qty"       , int.Parse(frmCancelDetails.Instance.txtQty.Text));
        cm.Parameters.AddWithValue("@sdate"     ,  DateTime.Now);
        cm.Parameters.AddWithValue("@voidby"    , user);
        cm.Parameters.AddWithValue("@canelledby", frmCancelDetails.Instance.txtCanceledBy.Text);
        cm.Parameters.AddWithValue("@reason"    , frmCancelDetails.Instance.txtReason.Text);
        cm.Parameters.AddWithValue("@action"    , frmCancelDetails.Instance.comAddToInventory.Text);
        cm.ExecuteNonQuery();
        cn.Close();
    }
</code>```

答: Maybe you need to round Price to 2 decimals?</p>

ContentLicense: CC BY-SA 4.0

Body:
I got this error message : input string was not in a correct format

It throws this error message at these two codes:

cm.Parameters.AddWithValue("@price", double.Parse(frmCancelDetails.Instance.txtPrice.Text));
cm.Parameters.AddWithValue("@qty", int.Parse(frmCancelDetails.Instance.txtQty.Text));

Also, when (double.Parse) and (int.Parse) are deleted, another message is thrown at the end of the code:

error converting data type varchar to numeric

Here is the full code

public void SaveCancelOrder(string user)
    {
        cn.Open();
        cm = new SqlCommand("insert into tblCancel (transno, pcode, price, qty, sdate, voidby, canelledby, reason, action)values(@transno, @pcode, @price, @qty, @sdate, @voidby, @canelledby, @reason, @action)", cn);
        cm.Parameters.AddWithValue("@transno"   , frmCancelDetails.Instance.txtTransNo.Text);
        cm.Parameters.AddWithValue("@pcode"     , frmCancelDetails.Instance.txtPcode.Text);
        cm.Parameters.AddWithValue("@price"   , double.Parse(frmCancelDetails.Instance.txtPrice.Text));
        cm.Parameters.AddWithValue("@qty"       , int.Parse(frmCancelDetails.Instance.txtQty.Text));
        cm.Parameters.AddWithValue("@sdate"     ,  DateTime.Now);
        cm.Parameters.AddWithValue("@voidby"    , user);
        cm.Parameters.AddWithValue("@canelledby", frmCancelDetails.Instance.txtCanceledBy.Text);
        cm.Parameters.AddWithValue("@reason"    , frmCancelDetails.Instance.txtReason.Text);
        cm.Parameters.AddWithValue("@action"    , frmCancelDetails.Instance.comAddToInventory.Text);
        cm.ExecuteNonQuery();
        cn.Close();
    }


问:
Display all line numbers for user names starting with "admin" from passwd file
How do I find all the occurance of a particular text in a file with a shell script. (Not using grep command)</p>

答:
A POSIX shell-only solution could be

n=0
while n=$((n+1)); IFS=':' read -r u _
do
  case "$u" in
    admin*) echo $n;;
  esac
done < /etc/passwd
```


问:
Duplicate keys with Amazon Athena and Open JSONx Serde
I have the following data due to an error:

```<code>{
  "eventType": "something",
  "details": {
    "userName": "NotSet",
    "username": "test@email.com"
  },
  "createdAt": 3
}
</code>```

Creating the table works:

```<code>CREATE EXTERNAL TABLE tbl (
         eventType string,
         `createdAt` string,
         details string
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
 LOCATION 's3://xx/yy'
</code>```

However when I query (tried details to string, struct, map, always same) I get the duplicate key error:

```<code>HIVE_CURSOR_ERROR: Row is not a valid JSON Object - JSONException: Duplicate key "username"
</code>```

They are duplicate if you use them as row columns, but not as map keys, or even string, why does it fail? The org.apache.hive.hcatalog.data.JsonSerDe can skip but I do not like it since %99.5 data is like this. The org.apache.hive.hcatalog.data.JsonSerDe fails always.

答:
It's now possible to set a parameter in order to cater for keys that only differs by the case. The name is case.insensitive and should be set to FALSE

Example:

```<code>ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES ("case.insensitive" = "FALSE")
</code>```

https://docs.aws.amazon.com/athena/latest/ug/json-serde.html#openx-json-serde

Body:
I have the following data due to an error:

{
  "eventType": "something",
  "details": {
    "userName": "NotSet",
    "username": "test@email.com"
  },
  "createdAt": 3
}

Creating the table works:

CREATE EXTERNAL TABLE tbl (
         eventType string,
         `createdAt` string,
         details string
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
 LOCATION 's3://xx/yy'

However when I query (tried details to string, struct, map, always same) I get the duplicate key error:

HIVE_CURSOR_ERROR: Row is not a valid JSON Object - JSONException: Duplicate key "username"

They are duplicate if you use them as row columns, but not as map keys, or even string, why does it fail? The org.apache.hive.hcatalog.data.JsonSerDe can skip but I do not like it since %99.5 data is like this. The org.apache.hive.hcatalog.data.JsonSerDe fails always.

Body:
It's now possible to set a parameter in order to cater for keys that only differs by the case. The name is case.insensitive and should be set to FALSE

Example:

ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES ("case.insensitive" = "FALSE")

https://docs.aws.amazon.com/athena/latest/ug/json-serde.html#openx-json-serde


问:
Text doesn't appear over CameraPreview layout
I'm trying to create a camera screen in my app that resembles a scanner apps screen. The final design should look something like this:

I was able to create the camera+layout screen by using CameraPreview widget and providing a layout child:

```<code>@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.black,
    body: GestureDetector(
        onLongPress: () async {
          // some logic
        },
        child: Column(children: [
          Stack(children: [
            Text("Center your camera over the indicator ", style: TextStyle(color: Colors.white)),
            Padding(
              padding: EdgeInsets.only(top: 70.0),
              child: FutureBuilder<void>(
                future: _initializeControllerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    // If the Future is complete, display the preview.
                    return CameraPreview(_controller,
                        child: MaterialPreviewOverlay(
                          overlayColor: overlayColor,
                        ));
                  } else {
                    // Otherwise, display a loading indicator.
                    return const Center(child: CircularProgressIndicator());
                  }
                },
              ),
            )
          ])
        ])),
  );
}
</code>```

The MaterialPreviewOverlay doesn't have too much logic, mainly it calls the painter that looks like this:

```<code>@override
void paint(Canvas canvas, Size size) {
  final screenRect = Rect.fromLTWH(0, 0, size.width, size.height);
  final cutOutWidth = screenRect.width - 80;
  final cutOutHeight = cutOutWidth * 1.7;
  final cutOut = RRect.fromRectAndCorners(
      Rect.fromCenter(
          center: screenRect.center,
          width: cutOutWidth,
          height: cutOutHeight),
      bottomLeft: const Radius.circular(40),
      topRight: const Radius.circular(40),
      topLeft: const Radius.circular(40)
  );
  final cutOutPath = Path.combine(PathOperation.difference,
      Path()..addRect(screenRect), Path()..addRRect(cutOut));
  final borderPaint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 5 // strokeWidth is painted 50/50 outwards and inwards.
    ..color = overlayColor;//.withAlpha(160);
  canvas
    ..drawPath(cutOutPath, backgroundPaint)
    ..drawRRect(cutOut.deflate(borderPaint.strokeWidth / 2), borderPaint);
}
</code>```

For some reason the Text widget isn't shown at all. I tried with Stack (like in the provided code example) and without. If I put the text below the FutureBuilder widget the text is shown (both with and without using Stack) and if I add an appBar to the Scaffold the text is also shown beneath the app bar. But I do not need the app bar, why wouldn't the text appear in my example?

答:
After trying to align the Stack widget using (alignment: AlignmentDirectional.topCenter) with no success, I saw it does work if I put, for example, AlignmentDirectional.bottomCenter.

Then I realized that text does appear in topCenter but is hidden by the iPhone notch. Padding it, solved the issue.

Body:
I'm trying to create a camera screen in my app that resembles a scanner apps screen. The final design should look something like this:

I was able to create the camera+layout screen by using CameraPreview widget and providing a layout child:

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.black,
    body: GestureDetector(
        onLongPress: () async {
          // some logic
        },
        child: Column(children: [
          Stack(children: [
            Text("Center your camera over the indicator ", style: TextStyle(color: Colors.white)),
            Padding(
              padding: EdgeInsets.only(top: 70.0),
              child: FutureBuilder<void>(
                future: _initializeControllerFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    // If the Future is complete, display the preview.
                    return CameraPreview(_controller,
                        child: MaterialPreviewOverlay(
                          overlayColor: overlayColor,
                        ));
                  } else {
                    // Otherwise, display a loading indicator.
                    return const Center(child: CircularProgressIndicator());
                  }
                },
              ),
            )
          ])
        ])),
  );
}

The MaterialPreviewOverlay doesn't have too much logic, mainly it calls the painter that looks like this:

@override
void paint(Canvas canvas, Size size) {
  final screenRect = Rect.fromLTWH(0, 0, size.width, size.height);
  final cutOutWidth = screenRect.width - 80;
  final cutOutHeight = cutOutWidth * 1.7;
  final cutOut = RRect.fromRectAndCorners(
      Rect.fromCenter(
          center: screenRect.center,
          width: cutOutWidth,
          height: cutOutHeight),
      bottomLeft: const Radius.circular(40),
      topRight: const Radius.circular(40),
      topLeft: const Radius.circular(40)
  );
  final cutOutPath = Path.combine(PathOperation.difference,
      Path()..addRect(screenRect), Path()..addRRect(cutOut));
  final borderPaint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 5 // strokeWidth is painted 50/50 outwards and inwards.
    ..color = overlayColor;//.withAlpha(160);
  canvas
    ..drawPath(cutOutPath, backgroundPaint)
    ..drawRRect(cutOut.deflate(borderPaint.strokeWidth / 2), borderPaint);
}

For some reason the Text widget isn't shown at all. I tried with Stack (like in the provided code example) and without. If I put the text below the FutureBuilder widget the text is shown (both with and without using Stack) and if I add an appBar to the Scaffold the text is also shown beneath the app bar. But I do not need the app bar, why wouldn't the text appear in my example?


问:
Is it safe to accept url from user to show in our website?
I wanna show users websites in their profiles but I don't know after I validate the user's input format to be the valid URL (https://userwebsite.com), is it safe to use that input in a tag () to redirect other users to that website? if it's not safe is there any way to check the URL??

how facebook and others handle this situation like example below

href="https://www.facebook.com/pages/Restaurant-El-Reda-libanesische-und-iranische-Spezialit%C3%A4ten/169985763015422" rel="nofollow noreferrer">https://www.facebook.com/pages/Restaurant-El-Reda-libanesische-und-iranische-Spezialit%C3%A4ten/169985763015422

答:
This is a great question. There are many sites that provide the ability for users to enter URLs that are then provided as links. This has been bread and butter of forums for a long time.

The challenge is that we want to make sure that the URL is valid and doesn't encourage people to visit malicious sites. For the first part (is the URL valid) there are plenty of libraries out there that can check the URL for example urlparse for python. (Sorry I don't know PHP well enough to provide the equivalent example).

The second part is a little more interesting and depends on your circumstances. If you are running a non commercial site then Google Safe Browsing offers an API which I believe will allow you to filter out malicious links. If you are running a commercial site then there are alternatives for example SophosLabs Intelix.

In summary I believe that it is safe to do what you are asking as long as:

You validate that the URL is valid

You put reasonable checks in place to prevent users posting links to malicious content

You provide appropriate disclaimers to cover you against the content on external sites

Body:
I wanna show users websites in their profiles but I don't know after I validate the user's input format to be the valid URL (https://userwebsite.com), is it safe to use that input in a tag () to redirect other users to that website? if it's not safe is there any way to check the URL??

how facebook and others handle this situation like example below

https://www.facebook.com/pages/Restaurant-El-Reda-libanesische-und-iranische-Spezialit%C3%A4ten/169985763015422


问:
Search Box results within Modal
I am trying to build some search functionality within a modal. When a user clicks a button it will open a modal with a search box. I then want the results of the search to be shown within the same modal?

```<code><div class="modal" id="select2modal">
    <div class="modal-dialog" role="document">
        <div class="modal-content modal-content-demo">
            <div class="modal-header">
                <h6 class="modal-title">Search for product to add</h6><button aria-label="Close" class="close" data-dismiss="modal" type="button"><span aria-hidden="true">×</span></button>
            </div>
            <div class="modal-body">
                <h6>product Search</h6>
                <div class="card-body pb-2">
                    <form method=POST action="{% url 'searchproduct' %}">
                        {% csrf_token %}
                        <div class="input-group mb-2">
                                <input type="text" class="form-control border-right-0 pl-3" name="search" placeholder="Enter product Name" value="">
                                <span class="input-group-append">
                                <button class="btn ripple btn-primary" type="submit"><i class="fa fa-search"></i></button>
                            </span>
                        </div>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn ripple btn-primary" type="button">Add product</button>
                <button class="btn ripple btn-secondary" data-dismiss="modal" type="button">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

view

```<code>def search_product(request):
    searched = request.POST['searched']

    return render(request, 'index.html',{'searched':searched})
</code>```

I don't think i should be doing return render(request, 'index.html',{'searched':searched}) think I should just be returning searched

The problem is this relies on the page being refreshed that closes the modal.

So what is the correct way - Do I need to use JavaScript or something.

UPDATE:
I have added jquery now

```<code>        <script type="text/javascript">
            $(document).on('submit','#post-form', function(e){
                e.preventDefault();

                $.ajax({
                    type:'POST',
                    url: '/searchproduct',
                    data:{
                        searched:$('#search').val(),
                        csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                    },
                    success: function (){

                    }

                });
            });

        </script>
</code>```

Which seems is doing a POST and returning 200 but the data returned data isn't being shown in the modal.

```<code>def search_product(request):
    searched = request.POST['searched']
    returned_products = Product.objects.filter(product_name__contains=searched)

    return {'searched':searched,'returned_products':returned_products}
</code>```

and then within my modal i am using:

```<code>{% for t in returned_products %}
{{t.product_name}}
{% endfor %}
</code>```

UPDATE 17/02

I think i have made some progress, but i still not getting the results back within the modal, but my search is returning a 200 rather than a error now.

In my AJAX:

```<code>
<script type="text/javascript">
    $(document).on('submit','#post-form', function(e){
        e.preventDefault();

        $.ajax({
            type:'POST',
            url: '/searchproducts',
            data:{
                searched:$('#search').val(),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
            },
            success: function (data){
                $('jresponse').html(returned_products);
            }

        });
    });
</code>```

I'm returning returned_products and within my modal I have

```<code><div id="jresponse">
{{ returned_products }}
</div>
```
My view
```
def products(request):
    searched = request.POST['searched']
    returned_products = Product.objects.filter(product_name__contains=searched).values()

    return JsonResponse({"returned_products":list(returned_products)})
```

```

答: I think the best way to approach this is to use JavaScript and Ajax calls in your frontend/template and HTTP responses with JSON data in your view/backend. You would not do a form submit but instead POST HTTP calls via Ajax to your view (which most likely would be triggered by the button you already have in place). Your view would then respond with a HTTP response which has to be interpreted and incorporated again by JavaScript in your frontend. A good way to structure your response is using JSON format, which can be easily interpreted using JavaScript. Django Rest Framework can make this easier for bigger projects, but it might be good enough to build the JSON responses more or less manually at small projects.</p>

Title: Search Box results within Modal

Body:
I am trying to build some search functionality within a modal. When a user clicks a button it will open a modal with a search box. I then want the results of the search to be shown within the same modal?

Search for product to add
<button aria-label="Close" class="close" data-dismiss="modal" type="button">×</button>

product Search

                    <form method=POST action="{% url 'searchproduct' %}">
                        {% csrf_token %}

                                <input type="text" class="form-control border-right-0 pl-3" name="search" placeholder="Enter product Name" value="">

                                <button class="btn ripple btn-primary" type="submit"></button>

                    </form>

                <button class="btn ripple btn-primary" type="button">Add product</button>
                <button class="btn ripple btn-secondary" data-dismiss="modal" type="button">Close</button>

view

def search_product(request):
    searched = request.POST['searched']

    return render(request, 'index.html',{'searched':searched})

I don't think i should be doing return render(request, 'index.html',{'searched':searched}) think I should just be returning searched

The problem is this relies on the page being refreshed that closes the modal.

So what is the correct way - Do I need to use JavaScript or something.

UPDATE:
I have added jquery now

Which seems is doing a POST and returning 200 but the data returned data isn't being shown in the modal.

def search_product(request):
    searched = request.POST['searched']
    returned_products = Product.objects.filter(product_name__contains=searched)

    return {'searched':searched,'returned_products':returned_products}

and then within my modal i am using:

{% for t in returned_products %}
{{t.product_name}}
{% endfor %}

UPDATE 17/02

I think i have made some progress, but i still not getting the results back within the modal, but my search is returning a 200 rather than a error now.

In my AJAX:


问:
How to replace .env file placeholders with deployment variables in bitbucket pipeline
I have a bitbucket repository.
I have Deployment environment variables in bitbucket:

```<code>BITBUCKET_VARIABLE_PORT : 8080
</code>```

In my bitbucket-pipelines.yaml script I can Write the variable into the .env file like this:

```<code><...>
step: &deploy-to-environment
        name: Deploy to environment
        deployment: environment
        caches:
          - node
        script:
          - echo Create .env file
          - echo "PORT=$BITBUCKET_VARIABLE_PORT" > .env
          - cat .env
<...>
</code>```

But I would like to avoid rewriting the whole lines of .env file.

Is it possible to implement the following?

I would like to have .env file with placeholders (.env file content):

```<code>    <...>
    PORT=<BITBUCKET_VARIABLE_PORT>
    HOST=<BITBUCKET_VARIABLE_HOST>
    <...>
</code>```

Replace these placeholders in yaml script section:

```<code>    <...>
        step: &deploy-to-environment
                name: Deploy to environment
                deployment: environment
                caches:
                  - node
                script:
                  - <replace_placeholders_here_in_script>
    <...>
</code>```

答:
I had the same issue lately and didn't want to include 1 by 1 the env variable, what I ended up doing:

#1 Create in repository a .env.example file (This file will hold variable that required for this repository without values or default values that are not sensitive)

```<code>APP_NAME=MyApp
APP_ENV=
APP_KEY=
APP_DEBUG=true
</code>```

Then I created a pipeline.sh

echo "[+] Building enviroment variables"

# Get contents of example file
ENV_CONTENT=$(cat ./.env.example)

# Output the content into sh script
echo "#! /bin/bash
echo \"
${ENV_CONTENT}
\"" > ./env.sh

# sed replace as key=${BITBUCKET_ENV_VARIABLE:-default_value_from_example}
sed -i -E "s/^([A-Z_]+)=(.*)$/\1=\${\1:-\2}/g" ./env.sh

chmod +x ./build/env.sh

# Exec the env sh script and output content to .env file
./build/env.sh > ./build/.env
```

So in case you have defined in .env.example APP_NAME and also defined it in bitbucket Repository Variables the final .env will have key APP_NAME=value_of_bitbucket_variable

Body:
I have a bitbucket repository.
I have Deployment environment variables in bitbucket:

BITBUCKET_VARIABLE_PORT : 8080

In my bitbucket-pipelines.yaml script I can Write the variable into the .env file like this:

<...>
step: &deploy-to-environment
        name: Deploy to environment
        deployment: environment
        caches:
          - node
        script:
          - echo Create .env file
          - echo "PORT=$BITBUCKET_VARIABLE_PORT" > .env
          - cat .env
<...>

But I would like to avoid rewriting the whole lines of .env file.

Is it possible to implement the following?

I would like to have .env file with placeholders (.env file content):

    <...>
    PORT=<BITBUCKET_VARIABLE_PORT>
    HOST=<BITBUCKET_VARIABLE_HOST>
    <...>

Replace these placeholders in yaml script section:

    <...>
        step: &deploy-to-environment
                name: Deploy to environment
                deployment: environment
                caches:
                  - node
                script:
                  - <replace_placeholders_here_in_script>
    <...>

Body:
I had the same issue lately and didn't want to include 1 by 1 the env variable, what I ended up doing:

#1 Create in repository a .env.example file (This file will hold variable that required for this repository without values or default values that are not sensitive)

APP_NAME=MyApp
APP_ENV=
APP_KEY=
APP_DEBUG=true

Then I created a pipeline.sh

echo "[+] Building enviroment variables"

# Get contents of example file
ENV_CONTENT=$(cat ./.env.example)

# Output the content into sh script
echo "#! /bin/bash
echo \"
${ENV_CONTENT}
\"" > ./env.sh

# sed replace as key=${BITBUCKET_ENV_VARIABLE:-default_value_from_example}
sed -i -E "s/^([A-Z_]+)=(.*)$/\1=\${\1:-\2}/g" ./env.sh

chmod +x ./build/env.sh

# Exec the env sh script and output content to .env file
./build/env.sh > ./build/.env

So in case you have defined in .env.example APP_NAME and also defined it in bitbucket Repository Variables the final .env will have key APP_NAME=value_of_bitbucket_variable


问:
Without Interactivity.dll: Alternative to MVVMLight's EventToCommand
In our current C# project, we use the MVVM light framework and its EventToCommand feature to bind events to commands (as also mentioned in this SO thread).
We use it for example like this:

```<code><i:Interaction.Triggers>
    <i:EventTrigger EventName="GotFocus">
        <cmd:EventToCommand CommandParameter="{Binding SelectedItem, ElementName=SelectTree}"
                            Command="{Binding Path=SelectTreeGotFocusCommand, Mode=OneWay}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
</code>```

My question is: What is the easiest way to achieve the same behaviour (i.e., EventToCommand, not limited to GotFocus) without using System.Windows.Interactivity?

To avoid the XY problem, here is some background:

We are developing an addon for an already existing main application, on which we do not have any influence. Our addon is served as a dll which is used by this main application.

So far, we used XAML code as given above (i.e., using System.Windows.Interactivity and EventToCommand). However, the last release of the main application contains an old version of System.Windows.Interactivity (so far, it was not included at all) which doesn't support this.

This means that using the old Interactivity.dll will cause our addon to be non-functional. However, overwriting the dll with the new version we need will cause issues with parts of the main application.

I read about using two different versions of the same dll in a project (for example here) but this seems to be quite involved. Since there are only a few places we use this construction, I thought that replacing it with code not using Interactivity.dll might be easier.

答:
If you switch to the Microsoft.Xaml.Behaviors.Wpf nuget package and change your namespace declarations to

```<code>xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
</code>```

you can use the InvokeCommandAction like so:

```<code><i:Interaction.Triggers>
    <i:EventTrigger EventName="GotFocus"}">
        <i:InvokeCommandAction Command="..." CommandParameter="..."/>
    </i:EventTrigger>
</i:Interaction.Triggers>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In our current C# project, we use the MVVM light framework and its EventToCommand feature to bind events to commands (as also mentioned in this SO thread).
We use it for example like this:

        <cmd:EventToCommand CommandParameter="{Binding SelectedItem, ElementName=SelectTree}"
                            Command="{Binding Path=SelectTreeGotFocusCommand, Mode=OneWay}" />

My question is: What is the easiest way to achieve the same behaviour (i.e., EventToCommand, not limited to GotFocus) without using System.Windows.Interactivity?

To avoid the XY problem, here is some background:

We are developing an addon for an already existing main application, on which we do not have any influence. Our addon is served as a dll which is used by this main application.

So far, we used XAML code as given above (i.e., using System.Windows.Interactivity and EventToCommand). However, the last release of the main application contains an old version of System.Windows.Interactivity (so far, it was not included at all) which doesn't support this.

This means that using the old Interactivity.dll will cause our addon to be non-functional. However, overwriting the dll with the new version we need will cause issues with parts of the main application.

I read about using two different versions of the same dll in a project (for example here) but this seems to be quite involved. Since there are only a few places we use this construction, I thought that replacing it with code not using Interactivity.dll might be easier.

Body:
If you switch to the Microsoft.Xaml.Behaviors.Wpf nuget package and change your namespace declarations to

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

you can use the InvokeCommandAction like so:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="GotFocus"}">
        <i:InvokeCommandAction Command="..." CommandParameter="..."/>
    </i:EventTrigger>
</i:Interaction.Triggers>


问:
Keras installation failed with Rstudio RcppTOML had non-zero exit status
I am struggling to install keras on my Rstudio version 2021.09.2 Build 382 (R version 3.6.0 (2019-04-26)) on Linux Centos 7. I am having this error message:

```<code>ERROR: compilation failed for package ‘RcppTOML’
* removing ‘/usr/lib64/R/library/RcppTOML’
ERROR: dependency ‘RcppTOML’ is not available for package ‘reticulate’
* removing ‘/usr/lib64/R/library/reticulate’
ERROR: dependency ‘reticulate’ is not available for package ‘tfautograph’
* removing ‘/usr/lib64/R/library/tfautograph’
ERROR: dependency ‘reticulate’ is not available for package ‘tfruns’
* removing ‘/usr/lib64/R/library/tfruns’
ERROR: dependencies ‘reticulate’, ‘tfruns’, ‘tfautograph’ are not available for package ‘tensorflow’
* removing ‘/usr/lib64/R/library/tensorflow’
ERROR: dependencies ‘reticulate’, ‘tensorflow’, ‘tfruns’ are not available for package ‘keras’
* removing ‘/usr/lib64/R/library/keras’
</code>```

I tried to install manually directly from the tar, but I still have the same error.

```<code>1: In install.packages("keras") :
  installation of package ‘RcppTOML’ had non-zero exit status
2: In install.packages("keras") :
  installation of package ‘reticulate’ had non-zero exit status
3: In install.packages("keras") :
  installation of package ‘tfautograph’ had non-zero exit status
4: In install.packages("keras") :
  installation of package ‘tfruns’ had non-zero exit status
5: In install.packages("keras") :
  installation of package ‘tensorflow’ had non-zero exit status
6: In install.packages("keras") :
  installation of package ‘keras’ had non-zero exit status
</code>```

Any idea how to solve it?
Thanks.

答:
I finally understood, there is a bug on CentOS 7: RcppTOML fails to compile with g++ 4.8.5 (20150623), but installs with g++ 5.3.1 (20160406) from scl-devtoolset-4.

```<code>sudo yum install centos-release-scl
sudo yum install devtoolset-7-gcc*
scl enable devtoolset-7 bash
</code>```

These lines fixed the issue

Body:
I am struggling to install keras on my Rstudio version 2021.09.2 Build 382 (R version 3.6.0 (2019-04-26)) on Linux Centos 7. I am having this error message:

ERROR: compilation failed for package ‘RcppTOML’
* removing ‘/usr/lib64/R/library/RcppTOML’
ERROR: dependency ‘RcppTOML’ is not available for package ‘reticulate’
* removing ‘/usr/lib64/R/library/reticulate’
ERROR: dependency ‘reticulate’ is not available for package ‘tfautograph’
* removing ‘/usr/lib64/R/library/tfautograph’
ERROR: dependency ‘reticulate’ is not available for package ‘tfruns’
* removing ‘/usr/lib64/R/library/tfruns’
ERROR: dependencies ‘reticulate’, ‘tfruns’, ‘tfautograph’ are not available for package ‘tensorflow’
* removing ‘/usr/lib64/R/library/tensorflow’
ERROR: dependencies ‘reticulate’, ‘tensorflow’, ‘tfruns’ are not available for package ‘keras’
* removing ‘/usr/lib64/R/library/keras’

I tried to install manually directly from the tar, but I still have the same error.

1: In install.packages("keras") :
  installation of package ‘RcppTOML’ had non-zero exit status
2: In install.packages("keras") :
  installation of package ‘reticulate’ had non-zero exit status
3: In install.packages("keras") :
  installation of package ‘tfautograph’ had non-zero exit status
4: In install.packages("keras") :
  installation of package ‘tfruns’ had non-zero exit status
5: In install.packages("keras") :
  installation of package ‘tensorflow’ had non-zero exit status
6: In install.packages("keras") :
  installation of package ‘keras’ had non-zero exit status

Any idea how to solve it?
Thanks.

Body:
I finally understood, there is a bug on CentOS 7: RcppTOML fails to compile with g++ 4.8.5 (20150623), but installs with g++ 5.3.1 (20160406) from scl-devtoolset-4.

sudo yum install centos-release-scl
sudo yum install devtoolset-7-gcc*
scl enable devtoolset-7 bash

These lines fixed the issue


问:
Mockito Exception: Underlying exception : java.lang.IllegalArgumentException: Could not create type

What I am trying to Do

I am trying to test my class using cucumber and also make extent report on it. I am getting 2 errors in it 1 related to Mockito which is high priority and 2nd related to extent reporting.

My Code

```<code>public class ClassA{
    private DataService dataService;

    public int methodA(String dataA, String dataB, String dataC){
        int x;
        //do Something
        return x;
    }
}

public class ClassATest{
    @InjectMock
    private ClassA classA;

    @Mock
    private DataService dataService;

    @BeforeClass
    @io.cucumber.java.Before
    public void setUp() throws NoSuchFieldException, SecurityException, Exception {

        System.out.println("---- Before ----");
        MockitoAnnotations.initMocks(this);

        int value = 10;
        Mockito.when(dataService.methodA(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(value);

    }
}
</code>```

My pom.xml

```<code>    <!-- cucumber dependencies -->

    <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-assembly-plugin -->
    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.2-beta-5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.9.4</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-testng</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>3.13.0</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-testng</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- Mockito -->
    <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.2.7</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy -->
    <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy</artifactId>
        <version>1.12.7</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy-agent -->
    <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy-agent</artifactId>
        <version>1.0.3</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.objenesis/objenesis -->
    <dependency>
        <groupId>org.objenesis</groupId>
        <artifactId>objenesis</artifactId>
        <version>3.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.masterthought</groupId>
        <artifactId>cucumber-reporting</artifactId>
        <version>5.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-testng</artifactId>
        <version>4.8.1</version>
    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java8</artifactId>
        <version>4.8.1</version>

    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>4.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest</artifactId>
        <version>2.2</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.aventstack/extentreports-cucumber4-adapter -->
    <dependency>
        <groupId>com.aventstack</groupId>
        <artifactId>extentreports-cucumber4-adapter</artifactId>
        <version>1.0.12</version>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-java</artifactId>
            </exclusion>

            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>

        <!-- CUCUMBER PLUGINS -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>false</downloadJavadocs>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>
                <testFailureIgnore>true</testFailureIgnore>
            </configuration>
        </plugin>
        <plugin>
            <groupId>net.masterthought</groupId>
            <artifactId>maven-cucumber-reporting</artifactId>
            <version>5.0.0</version>
            <executions>
                <execution>
                    <id>execution</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <projectName>test-ng</projectName>
                        <!-- optional, per documentation set this to "true" to bypass generation
                            of Cucumber Reports entirely, defaults to false if not specified -->
                        <skip>false</skip>
                        <!-- output directory for the generated report -->
                        <outputDirectory>target/cucumber-reports/advanced-reports</outputDirectory>
                        <cucumberOutput>target/cucumber-reports/cucumber.json</cucumberOutput>
                        <buildNumber>1</buildNumber>
                        <parallelTesting>false</parallelTesting>
                        <!-- optional, defaults to outputDirectory if not specified -->
                        <inputDirectory>${project.build.directory}/cucumber-reports</inputDirectory>
                        <jsonFiles>
                            <!-- supports wildcard or name pattern -->
                            <param>**/*.json</param>
                        </jsonFiles>
                        <!-- optional, defaults to outputDirectory if not specified -->
                        <classificationDirectory>${project.build.directory}/cucumber-reports</classificationDirectory>
                        <checkBuildResult>false</checkBuildResult>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>
</code>```

Things I have tried

Changing the way to mock using Mockito.mock() instead of annotation.

Changing Mockito dependency version.

Adding Byte-Buddy dependency.

Changing Byte-Buddy dependency version.

My Error regarding Mockito##

Mockito can only mock non-private & non-final classes. If you're not
sure why you're getting this error, please report to the mailing list.

Java               : 1.8 JVM vendor name    : Oracle Corporation JVM
vendor version : 25.231-b11 JVM name           : Java HotSpot(TM)
64-Bit Server VM JVM version        : 1.8.0_231-b11 JVM info

: mixed mode OS name            : Windows 10 OS version         : 10.0

Underlying exception : java.lang.IllegalArgumentException: Could not
create type   at
com.persivia.ptf.notes.consumer.test.NotesProcessThreadTest.setUp(NotesProcessThreadTest.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)     at
cucumber.runtime.Utils$1.call(Utils.java:26)  at
cucumber.runtime.Timeout.timeout(Timeout.java:16)     at
cucumber.runtime.Utils.invoke(Utils.java:20)  at
cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:65)
at
cucumber.runner.HookDefinitionMatch.runStep(HookDefinitionMatch.java:16)
at cucumber.runner.TestStep.executeStep(TestStep.java:65)   at
cucumber.runner.TestStep.run(TestStep.java:50)    at
cucumber.runner.TestCase.run(TestCase.java:42)    at
cucumber.runner.Runner.runPickle(Runner.java:50)  at
io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:79)
at
io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)     at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
at
org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
at
org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at
org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
at
org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.util.ArrayList.forEach(ArrayList.java:1257)     at
org.testng.TestRunner.privateRun(TestRunner.java:794)     at
org.testng.TestRunner.run(TestRunner.java:596)    at
org.testng.SuiteRunner.runTest(SuiteRunner.java:377)  at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)  at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)   at
org.testng.SuiteRunner.run(SuiteRunner.java:276)  at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)  at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)   at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)     at
org.testng.TestNG.runSuitesLocally(TestNG.java:1134)  at
org.testng.TestNG.runSuites(TestNG.java:1063)     at
org.testng.TestNG.run(TestNG.java:1031)   at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77) Caused
by: java.lang.IllegalArgumentException: Could not create type     at
net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:140)  at
net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)     at
net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
at
org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at
org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at
org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at
org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62)   at
org.mockito.Mockito.mock(Mockito.java:1908)   at
org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44)
at
org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)
at
org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at
org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
at
org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
at
org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:49)
at
org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
at
org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
... 44 more Caused by: java.lang.NoSuchMethodError:
net.bytebuddy.dynamic.loading.MultipleParentClassLoader$Builder.appendMostSpecific(Ljava/util/Collection;)Lnet/bytebuddy/dynamic/loading/MultipleParentClassLoader$Builder;
at
org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:83)
at
org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at
org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)     ... 62
more

My Error regarding Extent Reporting

INFO: Unexpected error net.masterthought.cucumber.ValidationException:
None report file was added!   at
net.masterthought.cucumber.ReportParser.parseJsonFiles(ReportParser.java:62)
at
net.masterthought.cucumber.ReportBuilder.generateReports(ReportBuilder.java:88)
at
net.masterthought.cucumber.CucumberReportGeneratorMojo.execute(CucumberReportGeneratorMojo.java:209)
at
org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at
org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
at
org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)   at
org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)    at
org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)  at
org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)  at
org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)   at
org.apache.maven.cli.MavenCli.main(MavenCli.java:193)     at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)     at
org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
at
org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
at
org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
at
org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)

答:
I'm not familiar with cucumber, so i'm not sure if this solution is transferable to your use case. And my example was written using JUnit 5, thus some different imports.

I'm missing your DataService class and how it relies to ClassA, so i had to make assumptions/simplifications.

```<code>public class DataService {
    public int methodA(String a, String b, String c) {
        return Integer.MIN_VALUE;
    }
}

public class ClassA {
    private DataService dataService;

    public int methodA(String a, String b, String c) {
        int x;
        x = dataService.methodA(a, b, c);
        return x;
    }
}
</code>```

And finally the test

```<code>public class ClassATest {
    @InjectMock
    private ClassA classA;

    @Mock
    private DataService dataService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        Mockito.when(dataService.methodA(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenReturn(1);
    }

    @Test
    void test() {
        Assertions.assertEquals(1, dataService.methodA("", "", ""));
    }
}
</code>```

Thus the main difference to your version is, that the mocking is initialized before each method and not before class.

Body:
What I am trying to Do

I am trying to test my class using cucumber and also make extent report on it. I am getting 2 errors in it 1 related to Mockito which is high priority and 2nd related to extent reporting.

My Code

public class ClassA{
    private DataService dataService;

    public int methodA(String dataA, String dataB, String dataC){
        int x;
        //do Something
        return x;
    }
}

public class ClassATest{
    @InjectMock
    private ClassA classA;

    @Mock
    private DataService dataService;

    @BeforeClass
    @io.cucumber.java.Before
    public void setUp() throws NoSuchFieldException, SecurityException, Exception {

        System.out.println("---- Before ----");
        MockitoAnnotations.initMocks(this);

        int value = 10;
        Mockito.when(dataService.methodA(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(value);

    }
}

My pom.xml

    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.2-beta-5</version>
    </dependency>

    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.9.4</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-testng</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>3.13.0</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-testng</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.2.7</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy</artifactId>
        <version>1.12.7</version>
    </dependency>

    <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy-agent</artifactId>
        <version>1.0.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.objenesis</groupId>
        <artifactId>objenesis</artifactId>
        <version>3.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.masterthought</groupId>
        <artifactId>cucumber-reporting</artifactId>
        <version>5.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-testng</artifactId>
        <version>4.8.1</version>
    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java8</artifactId>
        <version>4.8.1</version>

    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>4.8.1</version>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest</artifactId>
        <version>2.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.aventstack</groupId>
        <artifactId>extentreports-cucumber4-adapter</artifactId>
        <version>1.0.12</version>
        <exclusions>
            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-java</artifactId>
            </exclusion>

            <exclusion>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>false</downloadJavadocs>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>
                <testFailureIgnore>true</testFailureIgnore>
            </configuration>
        </plugin>
        <plugin>
            <groupId>net.masterthought</groupId>
            <artifactId>maven-cucumber-reporting</artifactId>
            <version>5.0.0</version>
            <executions>
                <execution>
                    <id>execution</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <projectName>test-ng</projectName>

                        <skip>false</skip>

                        <outputDirectory>target/cucumber-reports/advanced-reports</outputDirectory>
                        <cucumberOutput>target/cucumber-reports/cucumber.json</cucumberOutput>
                        <buildNumber>1</buildNumber>
                        <parallelTesting>false</parallelTesting>

                        <inputDirectory>${project.build.directory}/cucumber-reports</inputDirectory>
                        <jsonFiles>

                            <param>**/*.json</param>
                        </jsonFiles>

                        <classificationDirectory>${project.build.directory}/cucumber-reports</classificationDirectory>
                        <checkBuildResult>false</checkBuildResult>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

Things I have tried

Changing the way to mock using Mockito.mock() instead of annotation.

Changing Mockito dependency version.

Adding Byte-Buddy dependency.

Changing Byte-Buddy dependency version.

My Error regarding Mockito##

Mockito can only mock non-private & non-final classes. If you're not
sure why you're getting this error, please report to the mailing list.

Java               : 1.8 JVM vendor name    : Oracle Corporation JVM
vendor version : 25.231-b11 JVM name           : Java HotSpot(TM)
64-Bit Server VM JVM version        : 1.8.0_231-b11 JVM info

: mixed mode OS name            : Windows 10 OS version         : 10.0

Underlying exception : java.lang.IllegalArgumentException: Could not
create type   at
com.persivia.ptf.notes.consumer.test.NotesProcessThreadTest.setUp(NotesProcessThreadTest.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)     at
cucumber.runtime.Utils$1.call(Utils.java:26)  at
cucumber.runtime.Timeout.timeout(Timeout.java:16)     at
cucumber.runtime.Utils.invoke(Utils.java:20)  at
cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:65)
at
cucumber.runner.HookDefinitionMatch.runStep(HookDefinitionMatch.java:16)
at cucumber.runner.TestStep.executeStep(TestStep.java:65)   at
cucumber.runner.TestStep.run(TestStep.java:50)    at
cucumber.runner.TestCase.run(TestCase.java:42)    at
cucumber.runner.Runner.runPickle(Runner.java:50)  at
io.cucumber.testng.TestNGCucumberRunner.runScenario(TestNGCucumberRunner.java:79)
at
io.cucumber.testng.AbstractTestNGCucumberTests.runScenario(AbstractTestNGCucumberTests.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)     at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
at
org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
at
org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at
org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
at
org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.util.ArrayList.forEach(ArrayList.java:1257)     at
org.testng.TestRunner.privateRun(TestRunner.java:794)     at
org.testng.TestRunner.run(TestRunner.java:596)    at
org.testng.SuiteRunner.runTest(SuiteRunner.java:377)  at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)  at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)   at
org.testng.SuiteRunner.run(SuiteRunner.java:276)  at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)  at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)   at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)     at
org.testng.TestNG.runSuitesLocally(TestNG.java:1134)  at
org.testng.TestNG.runSuites(TestNG.java:1063)     at
org.testng.TestNG.run(TestNG.java:1031)   at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77) Caused
by: java.lang.IllegalArgumentException: Could not create type     at
net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:140)  at
net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)     at
net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
at
org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at
org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at
org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at
org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62)   at
org.mockito.Mockito.mock(Mockito.java:1908)   at
org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44)
at
org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)
at
org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at
org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
at
org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
at
org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:49)
at
org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
at
org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
... 44 more Caused by: java.lang.NoSuchMethodError:
net.bytebuddy.dynamic.loading.MultipleParentClassLoader$Builder.appendMostSpecific(Ljava/util/Collection;)Lnet/bytebuddy/dynamic/loading/MultipleParentClassLoader$Builder;
at
org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:83)
at
org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at
org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)     ... 62
more

My Error regarding Extent Reporting

INFO: Unexpected error net.masterthought.cucumber.ValidationException:
None report file was added!   at
net.masterthought.cucumber.ReportParser.parseJsonFiles(ReportParser.java:62)
at
net.masterthought.cucumber.ReportBuilder.generateReports(ReportBuilder.java:88)
at
net.masterthought.cucumber.CucumberReportGeneratorMojo.execute(CucumberReportGeneratorMojo.java:209)
at
org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
at
org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
at
org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)   at
org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)    at
org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)  at
org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)  at
org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)   at
org.apache.maven.cli.MavenCli.main(MavenCli.java:193)     at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)     at
org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
at
org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
at
org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
at
org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)

Body:
I'm not familiar with cucumber, so i'm not sure if this solution is transferable to your use case. And my example was written using JUnit 5, thus some different imports.

I'm missing your DataService class and how it relies to ClassA, so i had to make assumptions/simplifications.

public class DataService {
    public int methodA(String a, String b, String c) {
        return Integer.MIN_VALUE;
    }
}

public class ClassA {
    private DataService dataService;

    public int methodA(String a, String b, String c) {
        int x;
        x = dataService.methodA(a, b, c);
        return x;
    }
}

And finally the test

public class ClassATest {
    @InjectMock
    private ClassA classA;

    @Mock
    private DataService dataService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        Mockito.when(dataService.methodA(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenReturn(1);
    }

    @Test
    void test() {
        Assertions.assertEquals(1, dataService.methodA("", "", ""));
    }
}

Thus the main difference to your version is, that the mocking is initialized before each method and not before class.


问:
print matrix with indicies python
I have a matrix in Python defined like this:

```<code>matrix = [['A']*4 for i in range(4)]
</code>```

How do I print it in the following format:

```<code>   0  1  2  3
0  A  A  A  A
1  A  A  A  A
2  A  A  A  A
3  A  A  A  A
</code>```

答:
Use pandas for showing any matrix with indices:

>>> import pandas as pd
>>> pd.DataFrame(matrix)
   0  1  2  3
0  A  A  A  A
1  A  A  A  A
2  A  A  A  A
3  A  A  A  A
```

Title: print matrix with indicies python

Body:
I have a matrix in Python defined like this:

matrix = [['A']*4 for i in range(4)]

How do I print it in the following format:

   0  1  2  3
0  A  A  A  A
1  A  A  A  A
2  A  A  A  A
3  A  A  A  A


问:
Plotly vertical 3D surface plot in z-x plane not showing up
I want to plot a plane in the z-x plane, but I am having problems.

I am able to successfully plot the plane into the z-y plane with the following code:

```<code>import plotly.graph_objects as go
import numpy as np

x1 = np.zeros(100)
y1 = np.linspace(-5, 5, 100)
z1 = np.linspace(-2.5, 2.5, 50)
rc = np.random.rand(100,50)  # random surface colors
plane = go.Surface(x=x1, y=y1, z=np.array([z1] * len(x1)), surfacecolor=rc)

figure = go.Figure()
figure.add_traces([plane])
figure.show()
</code>```

This gives the following figure:

To plot the same in the z-x plane, this should be achievable (from my understanding) by simply swapping the x and y parameters of the surface plot:

```<code>plane = go.Surface(x=y1, y=x1, z=np.array([z1] * len(x1)), surfacecolor=rc)
</code>```

However, now the surface plot never shows up in the figure.
There is no error message or warning and looking at the data representation, all the data fields seem to be set the way they should.

So what am I missing?
Thanks for your feedback

答:
I was having the exact same problem and google sent me here. Searching for a solution, I came across this answer: https://stackoverflow.com/a/62504443

According to the answer, you have to transpose the array of the z argument.

```<code>    plane = go.Surface(x=y1, y=x1, z=np.array([z1] * len(x1)).T, surfacecolor=rc)
</code>```

For the surface coloring you would have change to

```<code>    rc = np.random.rand(100,100)
</code>```

Body:
I want to plot a plane in the z-x plane, but I am having problems.

I am able to successfully plot the plane into the z-y plane with the following code:

import plotly.graph_objects as go
import numpy as np

x1 = np.zeros(100)
y1 = np.linspace(-5, 5, 100)
z1 = np.linspace(-2.5, 2.5, 50)
rc = np.random.rand(100,50)  # random surface colors
plane = go.Surface(x=x1, y=y1, z=np.array([z1] * len(x1)), surfacecolor=rc)

figure = go.Figure()
figure.add_traces([plane])
figure.show()

This gives the following figure:

To plot the same in the z-x plane, this should be achievable (from my understanding) by simply swapping the x and y parameters of the surface plot:

plane = go.Surface(x=y1, y=x1, z=np.array([z1] * len(x1)), surfacecolor=rc)

However, now the surface plot never shows up in the figure.
There is no error message or warning and looking at the data representation, all the data fields seem to be set the way they should.

So what am I missing?
Thanks for your feedback

Body:
I was having the exact same problem and google sent me here. Searching for a solution, I came across this answer: https://stackoverflow.com/a/62504443

According to the answer, you have to transpose the array of the z argument.

    plane = go.Surface(x=y1, y=x1, z=np.array([z1] * len(x1)).T, surfacecolor=rc)

For the surface coloring you would have change to

    rc = np.random.rand(100,100)


问:
Bokeh widget not showing
I am taking my first steps at creating a bokeh interactive visualization app, and I am trying to create a few dropdown menus for data selection.

Before implementing it on my own data I've tried reproducing widgets from the Bokeh tutorial.

My code

```<code>from math import pi

import pandas as pd

from bokeh.palettes import Category20c
from bokeh.plotting import figure
from bokeh.transform import cumsum
from bokeh.io import show, output_file, output_notebook, curdoc
from bokeh.models import ColumnDataSource, Select
from bokeh.layouts import widgetbox
from bokeh.resources import INLINE
import bokeh.io

bokeh.io.output_notebook(INLINE)

# Create two dropdown Select widgets: select1, select2
select1 = Select(title="First", options=["A", "B"], value="A")
select2 = Select(title="Second", options=["1", "2", "3"], value="1")

# Define a callback function: callback
def callback(attr, old, new):
    # If select1 is 'A'
    if select1.value == "A":
        # Set select2 options to ['1', '2', '3']
        select2.options = ["1", "2", "3"]

        # Set select2 value to '1'
        select2.value = "1"
    else:
        # Set select2 options to ['100', '200', '300']
        select2.options = ["100", "200", "300"]

        # Set select2 value to '100'
        select2.value = "100"

# Attach the callback to the 'value' property of select1
select1.on_change("value", callback)

# Create layout and add to current document
layout = widgetbox(select1, select2)
curdoc().add_root(layout)
</code>```

After excepting the code all I get is a warning, but I see nothing.

What am I doing wrong?

Thank you

p.s.
I know I am calling a lot more then I need, I would use all packages later on, or just remove them.

答:
You can replace WidgetBox with Column to avoid the warning, but the real problem is that you don't display anything.

Add "show(layout)" at the end of the notebook if you want to display it.

Title: Bokeh widget not showing

Body:
I am taking my first steps at creating a bokeh interactive visualization app, and I am trying to create a few dropdown menus for data selection.

Before implementing it on my own data I've tried reproducing widgets from the Bokeh tutorial.

My code

from math import pi

import pandas as pd

from bokeh.palettes import Category20c
from bokeh.plotting import figure
from bokeh.transform import cumsum
from bokeh.io import show, output_file, output_notebook, curdoc
from bokeh.models import ColumnDataSource, Select
from bokeh.layouts import widgetbox
from bokeh.resources import INLINE
import bokeh.io

bokeh.io.output_notebook(INLINE)

# Create two dropdown Select widgets: select1, select2
select1 = Select(title="First", options=["A", "B"], value="A")
select2 = Select(title="Second", options=["1", "2", "3"], value="1")

# Define a callback function: callback
def callback(attr, old, new):
    # If select1 is 'A'
    if select1.value == "A":
        # Set select2 options to ['1', '2', '3']
        select2.options = ["1", "2", "3"]

        # Set select2 value to '1'
        select2.value = "1"
    else:
        # Set select2 options to ['100', '200', '300']
        select2.options = ["100", "200", "300"]

        # Set select2 value to '100'
        select2.value = "100"

# Attach the callback to the 'value' property of select1
select1.on_change("value", callback)

# Create layout and add to current document
layout = widgetbox(select1, select2)
curdoc().add_root(layout)

After excepting the code all I get is a warning, but I see nothing.

What am I doing wrong?

Thank you

p.s.
I know I am calling a lot more then I need, I would use all packages later on, or just remove them.


问:
BuildConfig not getting created correctly (Gradle Android)
I am trying to convert our Android application to a gradle build.  I have the project and it's libraries building successfully.   I am now trying to create separate apks for our various environments (dev/test/prod have different urls for the restful services they consume).

In searching around, the best way that I feel to do this is with making different BuildConfig for each environment.   This is what I tried:

```<code>import java.util.regex.Pattern

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:+'
    }
}

apply plugin: 'android'

task('increaseVersionCode') << {
    def manifestFile = file("AndroidManifest.xml")
    def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
    manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig') {
        task.dependsOn 'increaseVersionCode'
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.0.0'
    compile files('libs/commons-io-2.4.jar',
                  'libs/google-play-services.jar',
                  'libs/gson-2.2.4.jar',
                  'libs/universal-image-loader-1.8.6.jar',
                  'libs/wakeful-1.0.1.jar')
    compile project(':pulltorefresh_lib')
    compile project(':edgeeffect_lib')
    compile project(':viewpagerindicator_lib')
}

android {
    buildToolsVersion "18.1.1"
    compileSdkVersion "Google Inc.:Google APIs:18"

    defaultConfig {
       minSdkVersion 14
       targetSdkVersion 18
    }

    buildTypes {
        debug {
            packageNameSuffix ".debug"
        }
        dev.initWith(buildTypes.debug)
        dev {
            buildConfigField "String", "URL_SEARCH", "\"https://dev-search.example.com\";"
            buildConfigField "String", "URL_CONNECT", "\"https://dev-connect.example.com\";"
            buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://dev-mobilenews.example.com/newslist\";"
            buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://dev-mobilenews.example.com/newsdetail\";"
            buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://dev-mobilenews.example.com/registerendpoints\";"
        }
        prod.initWith(buildTypes.release)
        prod {
            buildConfigField "String", "URL_SEARCH", "\"https://search.example.com\";"
            buildConfigField "String", "URL_CONNECT", "\"https://connect.example.com\";"
            buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://mobilenews.example.com/newslist\";"
            buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://mobilenews.example.com/newsdetail\";"
            buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://mobilenews.pdc-np-cf.lmig.com/registerendpoints\";"
        }
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}
</code>```

The problem is that my BuildConfig.java doesn't seem to get the static variables injected, therefore I get errors similar to:

```<code>/Users/path/to/project/MainActivity.java:348: error: cannot find symbol
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_SEARCH)));
                                                                              ^
  symbol:   variable URL_SEARCH
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:359: error: cannot find symbol
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_CONNECT)));
                                                                              ^
  symbol:   variable URL_CONNECT
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:600: error: cannot find symbol
            HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_REGISTERENDPOINTS);
                                                        ^
  symbol:   variable URL_SVC_REGISTERENDPOINTS
  location: class BuildConfig
/Users/path/to/project/service/AlarmNotificationService.java:145: error: cannot find symbol
        String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
                                       ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:240: error: cannot find symbol
        String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
                                       ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:530: error: cannot find symbol
            HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_NEWSDETAIL);
                                                        ^
  symbol:   variable URL_SVC_NEWSDETAIL
  location: class BuildConfig
6 errors
</code>```

My build/source/buildConfig/debug/com/.../BuildConfig.java file contains:

```<code>/**
 * Automatically generated file. DO NOT MODIFY
 */
package com....;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String PACKAGE_NAME = "com.....debug";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 5;
}
</code>```

What am I doing wrong?

答:
In my case there was an string field resValue "string", "app_name", "MyApp" in strings.xml as well as in product flavours.

I did Invalidate Caches then Rebuild then android studion given the actual error of duplicate resources.

so Invalidate caches -> Rebuild -> Remove string resources which were already in buildconfigfield resvalue worked for me

I was using Android Studio Bumblebee 2021.1.1

Body:
I am trying to convert our Android application to a gradle build.  I have the project and it's libraries building successfully.   I am now trying to create separate apks for our various environments (dev/test/prod have different urls for the restful services they consume).

In searching around, the best way that I feel to do this is with making different BuildConfig for each environment.   This is what I tried:

import java.util.regex.Pattern

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:+'
    }
}

apply plugin: 'android'

task('increaseVersionCode') << {
    def manifestFile = file("AndroidManifest.xml")
    def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
    manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig') {
        task.dependsOn 'increaseVersionCode'
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.0.0'
    compile files('libs/commons-io-2.4.jar',
                  'libs/google-play-services.jar',
                  'libs/gson-2.2.4.jar',
                  'libs/universal-image-loader-1.8.6.jar',
                  'libs/wakeful-1.0.1.jar')
    compile project(':pulltorefresh_lib')
    compile project(':edgeeffect_lib')
    compile project(':viewpagerindicator_lib')
}

android {
    buildToolsVersion "18.1.1"
    compileSdkVersion "Google Inc.:Google APIs:18"

    defaultConfig {
       minSdkVersion 14
       targetSdkVersion 18
    }

    buildTypes {
        debug {
            packageNameSuffix ".debug"
        }
        dev.initWith(buildTypes.debug)
        dev {
            buildConfigField "String", "URL_SEARCH", "\"https://dev-search.example.com\";"
            buildConfigField "String", "URL_CONNECT", "\"https://dev-connect.example.com\";"
            buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://dev-mobilenews.example.com/newslist\";"
            buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://dev-mobilenews.example.com/newsdetail\";"
            buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://dev-mobilenews.example.com/registerendpoints\";"
        }
        prod.initWith(buildTypes.release)
        prod {
            buildConfigField "String", "URL_SEARCH", "\"https://search.example.com\";"
            buildConfigField "String", "URL_CONNECT", "\"https://connect.example.com\";"
            buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://mobilenews.example.com/newslist\";"
            buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://mobilenews.example.com/newsdetail\";"
            buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://mobilenews.pdc-np-cf.lmig.com/registerendpoints\";"
        }
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

The problem is that my BuildConfig.java doesn't seem to get the static variables injected, therefore I get errors similar to:

/Users/path/to/project/MainActivity.java:348: error: cannot find symbol
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_SEARCH)));
                                                                              ^
  symbol:   variable URL_SEARCH
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:359: error: cannot find symbol
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_CONNECT)));
                                                                              ^
  symbol:   variable URL_CONNECT
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:600: error: cannot find symbol
            HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_REGISTERENDPOINTS);
                                                        ^
  symbol:   variable URL_SVC_REGISTERENDPOINTS
  location: class BuildConfig
/Users/path/to/project/service/AlarmNotificationService.java:145: error: cannot find symbol
        String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
                                       ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:240: error: cannot find symbol
        String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
                                       ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:530: error: cannot find symbol
            HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_NEWSDETAIL);
                                                        ^
  symbol:   variable URL_SVC_NEWSDETAIL
  location: class BuildConfig
6 errors

My build/source/buildConfig/debug/com/.../BuildConfig.java file contains:

/**
 * Automatically generated file. DO NOT MODIFY
 */
package com....;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String PACKAGE_NAME = "com.....debug";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 5;
}

What am I doing wrong?


问:
Center a Pseudo Element
First time really using the pseudo :after selector. Not sure if the problem I'm running into is a limitation of it or I'm just missing something obvious.

Here's my live code.

```<code>li.current:after {
    border-width: 1px 1px 0 0;
    content: ' ';
    background: #256f9e;
    display: block;
    height: 13px;
    position: absolute;
    width: 10px;
    top: 6;
    margin:0px auto;
    z-index: 99;
    transform: rotate(-224deg);
    -webkit-transform: rotate(-224deg);
    -moz-transform: rotate(-224deg);
    -ms-transform: rotate(-224deg);
    -o-transform: rotate(-224deg);
    transform-origin: 50% 50%;
    -webkit-transform-origin: 50% 50%;
    -moz-transform-origin: 50% 50%;
    -ms-transform-origin: 50% 50%;
    -o-transform-origin: 50% 50%;
    text-align: center;
    float: center;
}
</code>```

I've created a little triangle (Or rather a box that has been rotated to look like a triangle). I want it centered within the

 but can't figure it out using my normal methods.
The things that have failed (in no particular order):

```<code>text-align: center;
float: center;
margin: 0 auto;
margin-right: 0;
margin-left: 0;
</code>```

What am I missing? I doubt it matters, but I'm using AngularJS. Thought I'd mention it in case there is a known conflict between Angular & Pseudo selectors (which I doubt).
Thanks.

答:
With transform: translate() centering can be accomplished without a fixed size. This is because translate(<x>%) will use the (psuedo-)element's own size, while left and margin-left will use the container's size. By using these together we can therefore find the exact center-point.

tl;dr

To center vertically:

.container {
  position: relative;
}

.container:after {
  top: 50%;
  transform: translateY(-50%);
}
```
<p>To center horizontally:</p>
<pre class="lang-css prettyprint-override"><code>.container {
  position: relative;
}

.container:after {
  left: 50%;
  transform: translateX(-50%);
}
</code>```

Full example

.container {
  position: relative;
  display: inline-block;
  background: #4aa;
  color: white;
  padding: .5ex 1ex;
}

.container:after {
  content: ":after";
  position: absolute;
  background: #a4a;
  color: white;
  padding: .5ex 1ex;

  /* position below container */
  top: 100%;

  /* move right by 50% of containers width */
  left: 50%;

  /* move left by 50% of own width */
  transform: translateX(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="container">
  Container with content
</p></code>```

Title: Center a Pseudo Element

Body:
First time really using the pseudo :after selector. Not sure if the problem I'm running into is a limitation of it or I'm just missing something obvious.

Here's my live code.

li.current:after {
    border-width: 1px 1px 0 0;
    content: ' ';
    background: #256f9e;
    display: block;
    height: 13px;
    position: absolute;
    width: 10px;
    top: 6;
    margin:0px auto;
    z-index: 99;
    transform: rotate(-224deg);
    -webkit-transform: rotate(-224deg);
    -moz-transform: rotate(-224deg);
    -ms-transform: rotate(-224deg);
    -o-transform: rotate(-224deg);
    transform-origin: 50% 50%;
    -webkit-transform-origin: 50% 50%;
    -moz-transform-origin: 50% 50%;
    -ms-transform-origin: 50% 50%;
    -o-transform-origin: 50% 50%;
    text-align: center;
    float: center;
}

I've created a little triangle (Or rather a box that has been rotated to look like a triangle). I want it centered within the

 but can't figure it out using my normal methods.
The things that have failed (in no particular order):

text-align: center;
float: center;
margin: 0 auto;
margin-right: 0;
margin-left: 0;

What am I missing? I doubt it matters, but I'm using AngularJS. Thought I'd mention it in case there is a known conflict between Angular & Pseudo selectors (which I doubt).
Thanks.

Body:
With transform: translate() centering can be accomplished without a fixed size. This is because translate(<x>%) will use the (psuedo-)element's own size, while left and margin-left will use the container's size. By using these together we can therefore find the exact center-point.

tl;dr

To center vertically:

.container {
  position: relative;
}

.container:after {
  top: 50%;
  transform: translateY(-50%);
}

To center horizontally:

.container {
  position: relative;
}

.container:after {
  left: 50%;
  transform: translateX(-50%);
}

Full example

.container {
  position: relative;
  display: inline-block;
  background: #4aa;
  color: white;
  padding: .5ex 1ex;
}

.container:after {
  content: ":after";
  position: absolute;
  background: #a4a;
  color: white;
  padding: .5ex 1ex;

  /* position below container */
  top: 100%;

  /* move right by 50% of containers width */
  left: 50%;

  /* move left by 50% of own width */
  transform: translateX(-50%);
}

<p class="container">
  Container with content
</p>


问:
Git Push into Production (FTP)
I would like to know if there is an easy way to push a GIT repository into production (on a FTP server) ?
Thanks</p>

答:
If you're on a mac and have Transmit, I'd recommend the following git-tranmit script (https://gist.github.com/379750). It uses DockSend to send only the last updated files. If you're not familiar with DockSend, check out http://www.panic.com/blog/2010/11/15-secrets-of-transmit/.

Setup:

cp git-transit /usr/sbin/.

cd /usr/sbin

chmod +x git-transmit

Setup drop send for your live app

Run git-transmit in your git repository.

ContentLicense: CC BY-SA 2.5

Title: Git Push into Production (FTP)