问:
How to create custom background for UITableView section?
I'm trying to create a custom background for my tableview section. The look I'm going for is this:

How do I customize the tableview section background/layer please, rather than just the individual cells?

Edit: Just to clarify - I'm talking about the white background under 'Latest Transactions'. So the top of the section is rounded (as is bottom) but all the rows are rectangular.

答:
To create a section header in tableView, use UITableViewDelegate's tableView(_:viewForHeaderInSection:) and tableView(_:heightForHeaderInSection:) methods.

```<code>func getHeaderText(for section: Int) -> String? {
    switch section {
    case 0:
        return "Latest Transactions"
    default:
        return "Other Transactions"
    }
    //Add other cases for different sections
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 70.0)))
    headerView.backgroundColor = .clear
    let label = UILabel(frame: CGRect(x: 20, y: 0, width: headerView.bounds.width - 40, height: headerView.bounds.height))
    label.text = self.getHeaderText(for: section)
    label.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold)
    headerView.addSubview(label)
    return headerView
    //Customize the headerView as per your requirement
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 70.0
}
</code>```

In the above code, you can configure the header label in getHeaderText(for:) for each section.

Also, I've created the headerView programatically. You can use a .xib for creating a custom headerView as well. That's completely your choice.

You can customize the headerView as per your requirements either programatically or in the interface.

Body:
To create a section header in tableView, use UITableViewDelegate's tableView(_:viewForHeaderInSection:) and tableView(_:heightForHeaderInSection:) methods.

func getHeaderText(for section: Int) -> String? {
    switch section {
    case 0:
        return "Latest Transactions"
    default:
        return "Other Transactions"
    }
    //Add other cases for different sections
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 70.0)))
    headerView.backgroundColor = .clear
    let label = UILabel(frame: CGRect(x: 20, y: 0, width: headerView.bounds.width - 40, height: headerView.bounds.height))
    label.text = self.getHeaderText(for: section)
    label.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold)
    headerView.addSubview(label)
    return headerView
    //Customize the headerView as per your requirement
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 70.0
}

In the above code, you can configure the header label in getHeaderText(for:) for each section.

Also, I've created the headerView programatically. You can use a .xib for creating a custom headerView as well. That's completely your choice.

You can customize the headerView as per your requirements either programatically or in the interface.


来源: stackexchange

问:
AWS Lambda randomly gives back 502 as status
I'm having a lambda function which makes use of Graphql and webscraping to return some data as response. Sometimes it works without giving an error like 502, sometimes it doesn't. To me it looks like the 502 errors are completely random, because I send the same requests with the same data all the time.

My timeout is set to 5 minutes in AWS console.

These are the errors I get (in browser):

Failed to load [BIG URL] No 'Access-Control-Allow-Origin' header is
  present on the requested resource. Origin '[mydomainurl]' is therefore
  not allowed access. The response had HTTP status code 502.

spread.js:25 GET
  [BIG URL] 502 ()

However when I go to the Network tab in Chrome and view the copied link address in browser, I get a JSON response back with the data I want. I cannot find the error in CloudWatch.

Headers

Response headers

```<code>content-length: 36
content-type: application/json
date: Fri, 13 Apr 2018 06:17:06 GMT
status: 502
via: 1.1 67284fcf464f6f1529cc1e521669622c.cloudfront.net (CloudFront)
x-amz-apigw-id: FRC2oEiuDoEF_YQ=
x-amz-cf-id: O1VfzIVPySw657r6WV34EvcPMTyeT7eFUBnM3P30NXBmdjTeWHfryw==
x-amzn-requestid: 4766f279-3ee2-11e8-9e72-bdddab0f02d6
x-cache: Error from cloudfront
</code>```

Request headers

```<code>:authority: wqbgu8c3ql.execute-api.eu-west-1.amazonaws.com
:method: GET
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7
origin: [url]
referer: [url]
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
</code>```

Response:
{"message": "Internal server error"}

My handler.js

```<code>'use strict'

const {
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLNonNull
} = require('graphql')

const schema = require('./schema/schema');

module.exports.query = (event, context, callback) => graphql(schema, event.queryStringParameters.query)
.then(
  result => callback(null, {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin" : "*"
    },
    body: JSON.stringify(result)
  }),
  err => callback(err)
)
</code>```

Maybe there's something wrong in the way I return the err in the callback?

答:
For Python use the following

```<code>def returnresponse(status_code, message):
    myjson = {}
    myjson['statusCode']=status_code
    myjson['body']=json.dumps(message)
    myjson['headers']={}
    myjson['headers']['Access-Control-Allow-Origin']="*"
    myjson['headers']['Content-Type']="application/json"
    return myjson
</code>```

you can remove the Content-Type header from the above.
At the end of your lambda type :

```<code>return returnresponse(200, "hello world")
</code>```

Also check your code where you make the API call. In my case I used javascript. If you're using javascript remove the "datatype: json" unless you're returning json data in body.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a lambda function which makes use of Graphql and webscraping to return some data as response. Sometimes it works without giving an error like 502, sometimes it doesn't. To me it looks like the 502 errors are completely random, because I send the same requests with the same data all the time.

My timeout is set to 5 minutes in AWS console.

These are the errors I get (in browser):

Failed to load [BIG URL] No 'Access-Control-Allow-Origin' header is
  present on the requested resource. Origin '[mydomainurl]' is therefore
  not allowed access. The response had HTTP status code 502.

spread.js:25 GET
  [BIG URL] 502 ()

However when I go to the Network tab in Chrome and view the copied link address in browser, I get a JSON response back with the data I want. I cannot find the error in CloudWatch.

Headers

Response headers

content-length: 36
content-type: application/json
date: Fri, 13 Apr 2018 06:17:06 GMT
status: 502
via: 1.1 67284fcf464f6f1529cc1e521669622c.cloudfront.net (CloudFront)
x-amz-apigw-id: FRC2oEiuDoEF_YQ=
x-amz-cf-id: O1VfzIVPySw657r6WV34EvcPMTyeT7eFUBnM3P30NXBmdjTeWHfryw==
x-amzn-requestid: 4766f279-3ee2-11e8-9e72-bdddab0f02d6
x-cache: Error from cloudfront

Request headers

:authority: wqbgu8c3ql.execute-api.eu-west-1.amazonaws.com
:method: GET
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7
origin: [url]
referer: [url]
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

Response:
{"message": "Internal server error"}

My handler.js

'use strict'

const {
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLNonNull
} = require('graphql')

const schema = require('./schema/schema');

module.exports.query = (event, context, callback) => graphql(schema, event.queryStringParameters.query)
.then(
  result => callback(null, {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin" : "*"
    },
    body: JSON.stringify(result)
  }),
  err => callback(err)
)

Maybe there's something wrong in the way I return the err in the callback?

Body:
For Python use the following

def returnresponse(status_code, message):
    myjson = {}
    myjson['statusCode']=status_code
    myjson['body']=json.dumps(message)
    myjson['headers']={}
    myjson['headers']['Access-Control-Allow-Origin']="*"
    myjson['headers']['Content-Type']="application/json"
    return myjson

you can remove the Content-Type header from the above.
At the end of your lambda type :

return returnresponse(200, "hello world")

Also check your code where you make the API call. In my case I used javascript. If you're using javascript remove the "datatype: json" unless you're returning json data in body.

ContentLicense: CC BY-SA 4.0


问:
How to fix 'str' object is not a mapping error
I will start saying its't a duplicated question. My problem is a little different in an url with Django 2.2.

An view triggers 'str' object is not a mapping error when return HttpResponseRedirect to another view in same application.

I really don't know what's wrong. I use same method in other application in same project and it works.

Project urls.py

urlpatterns = [
    url(r'^$', Home.as_view()),
    path('dashboard/', include('dashboard.urls')),
    path('main/', include('main.urls'))
]
```

<p>Application urls.py</p>

<pre class="lang-py prettyprint-override"><code>urlpatterns = [
  path('', views.Section.as_view(), name='main-form')
]
</code>```

Application views.py

class Home(View):
  def get(self, request):
    return render(request, 'index.html', context={})

  def post(self, request):
    return HttpResponseRedirect(reverse('main-form'))

class Section(View):

  def get(self, request):
    return HttpResponse("Test Ok")
```

After post home form it should redirect to main-form view (Section view class) but I get error.

It triggers same error if I use the url in a template url {% url 'main-form' %}

If I navigate manually to view from address bar, view renders fine.

Whats wrong?

答:
Try to include an app name for your django app urls.py file like

```<code>app_name ='smth'

urlpatterns = [
  path('', views.Section.as_view(), name='main-form')
]

</code>```

Then in your template view file include: href={% url 'smth:main-form' %}

Body:
I will start saying its't a duplicated question. My problem is a little different in an url with Django 2.2.

An view triggers 'str' object is not a mapping error when return HttpResponseRedirect to another view in same application.

I really don't know what's wrong. I use same method in other application in same project and it works.

Project urls.py

urlpatterns = [
    url(r'^$', Home.as_view()),
    path('dashboard/', include('dashboard.urls')),
    path('main/', include('main.urls'))
]

Application urls.py

urlpatterns = [
  path('', views.Section.as_view(), name='main-form')
]

Application views.py

class Home(View):
  def get(self, request):
    return render(request, 'index.html', context={})

  def post(self, request):
    return HttpResponseRedirect(reverse('main-form'))

class Section(View):

  def get(self, request):
    return HttpResponse("Test Ok")

After post home form it should redirect to main-form view (Section view class) but I get error.

It triggers same error if I use the url in a template url {% url 'main-form' %}

If I navigate manually to view from address bar, view renders fine.

Whats wrong?

Body:
Try to include an app name for your django app urls.py file like

app_name ='smth'

urlpatterns = [
  path('', views.Section.as_view(), name='main-form')
]

Then in your template view file include: href={% url 'smth:main-form' %}


问:
Start BottomSheetFragment for result
I want to get results from BottomSheetFragment. I tried to do it through getActivity().setResult(Activity.RESULT_OK, null); inside

```<code>    @Override
public void onDismiss(DialogInterface dialog) {
    getActivity().setResult(Activity.RESULT_OK, null);
    super.onDismiss(dialog);
}
</code>```

but activity's method onActivityResult not called. What am I doing wrong?

```<code>    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(this, requestCode, Toast.LENGTH_SHORT).show();
    super.onActivityResult(requestCode, resultCode, data);
}
</code>```

Dialog start method

```<code>BottomSheetDialogFragment bottomSheetFragment = new BottomSheetDialogFragment();
            Bundle bundle = new Bundle();
            bottomSheetFragment.setArguments(bundle);
            bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
</code>```

答:
onActivityResult() is used for getting a result from another Activity.

More on this: https://developer.android.com/training/basics/intents/result

If you want to send some data from Fragment to Activity, you can do it either by defining an interface or call a method in the Activity by casting it to the specific Activity.

```<code>class MainActivity extends AppCompatActivity {

 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
  YourBottomSheetDialogFragment bottomSheetFragment = new YourBottomSheetDialogFragment();
  Bundle bundle = new Bundle();
  bottomSheetFragment.setArguments(bundle);
  bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
 }

 public void setResultFromFragment(String data) {
  ...
 }
}

/**
* Calling Activity's method from Fragment
*/
class YourBottomSheetDialogFragment extends BottomSheetDialogFragment {

 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ((MainActivity) getActivity()).setResultFromFragment("");
 }
}
</code>```

Title: Start BottomSheetFragment for result

Body:
I want to get results from BottomSheetFragment. I tried to do it through getActivity().setResult(Activity.RESULT_OK, null); inside

    @Override
public void onDismiss(DialogInterface dialog) {
    getActivity().setResult(Activity.RESULT_OK, null);
    super.onDismiss(dialog);
}

but activity's method onActivityResult not called. What am I doing wrong?

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(this, requestCode, Toast.LENGTH_SHORT).show();
    super.onActivityResult(requestCode, resultCode, data);
}

Dialog start method

BottomSheetDialogFragment bottomSheetFragment = new BottomSheetDialogFragment();
            Bundle bundle = new Bundle();
            bottomSheetFragment.setArguments(bundle);
            bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());

Body:
onActivityResult() is used for getting a result from another Activity.

More on this: https://developer.android.com/training/basics/intents/result

If you want to send some data from Fragment to Activity, you can do it either by defining an interface or call a method in the Activity by casting it to the specific Activity.

class MainActivity extends AppCompatActivity {

 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
  YourBottomSheetDialogFragment bottomSheetFragment = new YourBottomSheetDialogFragment();
  Bundle bundle = new Bundle();
  bottomSheetFragment.setArguments(bundle);
  bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
 }

 public void setResultFromFragment(String data) {
  ...
 }
}

/**
* Calling Activity's method from Fragment
*/
class YourBottomSheetDialogFragment extends BottomSheetDialogFragment {

 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ((MainActivity) getActivity()).setResultFromFragment("");
 }
}


问:
Mark as deprecated function parameters in C++14
Reading this blog post and its comments, I have noticed that it gives as an example the possibility of marking specific function parameters as deprecated, as in (exaple taken from the post):

```<code>// Deprecate a function parameter
int triple([[deprecated]] int x);
</code>```

Now I was wondering, what is a good use case for such a feature? No one in the comments of that post or anywhere else I have searched seem to have a clue.

EDIT:

To see it in action, there is a compilable example on goldbolt

答:
The rule is that the attribute is valid on, amongst other things, variable declarations (broadly). It's not specifically permitted for such declarations found in function arguments.

The original proposal, N3394, doesn't mention such a use case, either, and neither does the documentation for the original feature in GCC (which regardless accepts the equivalent usage) or in VS (I didn't check Clang).

As such, I think it's an "accident" that this is permitted, not something that anyone really had in mind as being useful.

Could it be useful to document deprecated defaulted arguments, as Artyer explores? Yes, potentially, and vaguely. But as Artyer also found, mainstream compilers don't actually react to this usage in a helpful manner.

So, at the present time, it's not useful, and the language feature wasn't particularly designed to be useful in this case.

Body:
Reading this blog post and its comments, I have noticed that it gives as an example the possibility of marking specific function parameters as deprecated, as in (exaple taken from the post):

// Deprecate a function parameter
int triple([[deprecated]] int x);

Now I was wondering, what is a good use case for such a feature? No one in the comments of that post or anywhere else I have searched seem to have a clue.

EDIT:

To see it in action, there is a compilable example on goldbolt


问:
How to make pedestrians appear at AreaNode with attractors from a pedSource
I am working on an evacuation project for a floor and would like to create a distribution of pedestrians from the pedSource block. These pedestrians will already appear in an area when I run the simulation. I want to obtain a fixed number of pedestrians in one area while the rest is distributed to other areas.

I have made a collection of areas that pedestrians will appear using allLocations (area, area1, area2 and OfficeArea). The event is triggered by an event and using a delay block. The max amount of pedestrians at the given floor is 100

Image of block flowchart

Image of floor layout plan

This is the code I tried where pedestrians would appear in the areas:

```<code>    allLocations.get(uniform_discr(0, allLocations.size()-1))
</code>```

I expect a fixed 10 number of pedestrians in the office area and positioned where I set the attractors, but the actual result shows more than 10 number of pedestrians and do not appear at the set attractor.

Image of actual result

答:
Setting an attractor as a target for pedestrians is according to the documentation only working for the blocks pedWait and pedGoTo (I could actually only get it to work with pedWait, not with pedGoTo). Therefore you cannot initialize agents directly onto attractors using the initial location or the jumpTo() function.

You have several options as a workaround:

Extract the x,y coordinates of the attractor, and use the type point(x,y) to define the initial location or the location for the jumpTo()

Instead of using (graphical) attractors consider just defining points by code directly

Use very small individual areas instead of one large area with attractors

Use a pedWait block in your process flow and let your pedestrians 'walk' to their initial positions. Give the model a short time until everybody is on the desired location before starting your evacuation. You can also run the model in super fast mode during this initial phase, so that it will barely be visible.

Body:
I am working on an evacuation project for a floor and would like to create a distribution of pedestrians from the pedSource block. These pedestrians will already appear in an area when I run the simulation. I want to obtain a fixed number of pedestrians in one area while the rest is distributed to other areas.

I have made a collection of areas that pedestrians will appear using allLocations (area, area1, area2 and OfficeArea). The event is triggered by an event and using a delay block. The max amount of pedestrians at the given floor is 100

Image of block flowchart

Image of floor layout plan

This is the code I tried where pedestrians would appear in the areas:

    allLocations.get(uniform_discr(0, allLocations.size()-1))

I expect a fixed 10 number of pedestrians in the office area and positioned where I set the attractors, but the actual result shows more than 10 number of pedestrians and do not appear at the set attractor.

Image of actual result


问:
qt performance – OpenGL
i wan't to use Native OpenGL in the paint function of my widgets(QPainter), to improve performance.
i saw that there is function QPainter::begin/endNativePainting(), that can help me.
but i can't find examples for that...
i wanted to know if those functions are low cost, or evry use of them reduce performance?
2.can i define beginNativePainting() and endNativePainting(), in general for all the widgets i use, instead of using that in every paint function i have.

tnx for any help....

答:
There is some basic example code right in the documentation: http://doc.qt.io/qt-4.8/qpainter.html#beginNativePainting

The functions themselves should be fairly low-cost, but calling them might still cause a noticeably overhead, because Qt has to flush its internal painting queue on the beginNativePainting() call and probably has to assume that everything is changed as soon as endNativePainting() is called.

For the second part I am not sure if I understand what you are aiming at. Basically if you have a QPainter object, you can call beginNativePainting() once. But you have to match it with an endNativePainting() call. So the usual place would be the paint() method.

Title: qt performance – OpenGL


问:
How to validate an array that can contain items that are objects of different types
I have a schema where I have an array (inside the transmit object) which could possibly have one of two options (A or B).

I have attached both the schema and sample data (that is actually getting validated, when it should have thrown an error).

under transmitDataDef->items, I have tried "anyOf", "oneOf", "type" and they all yield no-errors even though the data does not match (data contains optionC that is not defined anywhere)

I am using jsonschema python library. I have also tried this schema + data in https://www.jsonschemavalidator.net/ with same results.

Schema:

```<code>{
  "definitions": {
    "optionADef": {
      "type": "object",
      "properties": {
        "pattern": {
          "type": "string",
          "enum": [
            "random",
            "fixed"
          ]
        },
        "startbyte": {
          "type": "number"
        }
      },
      "required": [
        "startbyte"
      ],
      "additionalProperties": false
    },
    "optionBSubItemDef": {
      "type": "object",
      "properties": {
        "value": {
          "type": "number",
          "minimum": 0
        }
      }
    },
    "optionBSettingsDef": {
      "type": "object",
      "properties": {
        "sequence": {
          "type": "number",
          "minimum": 0
        }
      }
    },
    "optionBDataDef": {
      "type": "object",
      "properties": {
        "subitem": {
          "ref": "#/definitions/optionBSubItemDef"
        }
      }
    },
    "optionBDef": {
      "type": "object",
      "properties": {
        "_data": {
          "ref": "#/definitions/optionBDataDef"
        },
        "_settings": {
          "$ref": "#/definitions/optionBSettingsDef"
        }
      },
      "required": [
        "_data"
      ],
      "additionalProperties": false
    },
    "transmitDataDef": {
      "type": "array",
      "minItems": 1,
      "maxItems": 1,
      "items": {
        "anyOf": [
          {
            "type": "object",
            "properties": {
              "optionA": {
                "ref": "#/definitions/optionADef"
              }
            },
            "additionalProperties": false
          },
          {
            "type": "object",
            "properties": {
              "optionB": {
                "ref": "#/definitions/optionBDef"
              }
            },
            "additionalProperties": false
          }
        ]
      }
    },
    "transmitSettingsDef": {
      "type": "object",
      "properties": {
        "length": {
          "type": "number",
          "minimum": 0,
          "maximim": 8
        }
      }
    },
    "transmitDef": {
      "type": "object",
      "properties": {
        "_data": {
          "ref": "#/definitions/transmitDataDef"
        },
        "_settings": {
          "$ref": "#/definitions/transmitSettingsDef"
        }
      },
      "required": [
        "_data"
      ],
      "additionalProperties": false
    },
    "bundleDef": {
      "type": "object",
      "properties": {
        "transmit": {
          "$ref": "#/definitions/transmitDef"
        }
      },
      "oneOf": [
        {
          "required": [
            "transmit"
          ]
        }
      ],
      "additionalProperties": false
    }
  },
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "bundle": {
      "$ref": "#/definitions/bundleDef"
    }
  },
  "required": [
    "name",
    "bundle"
  ]
}

</code>```

Sample data:

```<code>{
  "name": "test1",
  "bundle": {
    "transmit": {
      "_settings": {
        "length": 0
      },
      "_data": [
        {
          "optionC": {
            "_settings": {
              "sequence": 150
            },
            "data1": [
              {
                "subitem": {
                  "value": 100
                }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

I expect the validation to catch "optionC" and flag it as an error. If I had optionB instead of optionC, i expect it to flag "data1" as an invalid item.

答:
You have the right approach. I validated this using the following schema and instance using https://jsonschema.dev

Schema:

```<code>{
  "properties": {
    "_data": {
      "type": "array",
      "items" : {
        "anyOf": [
          {
            "type": "object",
            "properties": {
              "inline": true
            },
            "additionalProperties": false
          },
          {
            "type": "object",
            "properties": {
              "rewrite": true
            },
            "additionalProperties": false
          }
        ]
      }
    }
  }
}
</code>```

Instance :

```<code>{
  "_data": [
    {
      "optionC": {
        "_settings": {
          "sequence": 150
        },
        "data1": [
          {
            "subitem": {
              "value": 100
            }
          }
        ]
      }
    }
  ]
}
</code>```

There is a problem with something other than your use of "anyOf", which is correct.

It's actually something FAR simpler...

You've used "ref" as opposed to "$ref" in your schema in quite a few places. Unknown keywords are ignored, and so your references were not working.

If it's any consolation, it took me quite a while to debug!

Body:
I have a schema where I have an array (inside the transmit object) which could possibly have one of two options (A or B).

I have attached both the schema and sample data (that is actually getting validated, when it should have thrown an error).

under transmitDataDef->items, I have tried "anyOf", "oneOf", "type" and they all yield no-errors even though the data does not match (data contains optionC that is not defined anywhere)

I am using jsonschema python library. I have also tried this schema + data in https://www.jsonschemavalidator.net/ with same results.

Schema:

{
  "definitions": {
    "optionADef": {
      "type": "object",
      "properties": {
        "pattern": {
          "type": "string",
          "enum": [
            "random",
            "fixed"
          ]
        },
        "startbyte": {
          "type": "number"
        }
      },
      "required": [
        "startbyte"
      ],
      "additionalProperties": false
    },
    "optionBSubItemDef": {
      "type": "object",
      "properties": {
        "value": {
          "type": "number",
          "minimum": 0
        }
      }
    },
    "optionBSettingsDef": {
      "type": "object",
      "properties": {
        "sequence": {
          "type": "number",
          "minimum": 0
        }
      }
    },
    "optionBDataDef": {
      "type": "object",
      "properties": {
        "subitem": {
          "ref": "#/definitions/optionBSubItemDef"
        }
      }
    },
    "optionBDef": {
      "type": "object",
      "properties": {
        "_data": {
          "ref": "#/definitions/optionBDataDef"
        },
        "_settings": {
          "$ref": "#/definitions/optionBSettingsDef"
        }
      },
      "required": [
        "_data"
      ],
      "additionalProperties": false
    },
    "transmitDataDef": {
      "type": "array",
      "minItems": 1,
      "maxItems": 1,
      "items": {
        "anyOf": [
          {
            "type": "object",
            "properties": {
              "optionA": {
                "ref": "#/definitions/optionADef"
              }
            },
            "additionalProperties": false
          },
          {
            "type": "object",
            "properties": {
              "optionB": {
                "ref": "#/definitions/optionBDef"
              }
            },
            "additionalProperties": false
          }
        ]
      }
    },
    "transmitSettingsDef": {
      "type": "object",
      "properties": {
        "length": {
          "type": "number",
          "minimum": 0,
          "maximim": 8
        }
      }
    },
    "transmitDef": {
      "type": "object",
      "properties": {
        "_data": {
          "ref": "#/definitions/transmitDataDef"
        },
        "_settings": {
          "$ref": "#/definitions/transmitSettingsDef"
        }
      },
      "required": [
        "_data"
      ],
      "additionalProperties": false
    },
    "bundleDef": {
      "type": "object",
      "properties": {
        "transmit": {
          "$ref": "#/definitions/transmitDef"
        }
      },
      "oneOf": [
        {
          "required": [
            "transmit"
          ]
        }
      ],
      "additionalProperties": false
    }
  },
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "bundle": {
      "$ref": "#/definitions/bundleDef"
    }
  },
  "required": [
    "name",
    "bundle"
  ]
}

Sample data:

{
  "name": "test1",
  "bundle": {
    "transmit": {
      "_settings": {
        "length": 0
      },
      "_data": [
        {
          "optionC": {
            "_settings": {
              "sequence": 150
            },
            "data1": [
              {
                "subitem": {
                  "value": 100
                }
              }
            ]
          }
        }
      ]
    }
  }
}

I expect the validation to catch "optionC" and flag it as an error. If I had optionB instead of optionC, i expect it to flag "data1" as an invalid item.

Body:
You have the right approach. I validated this using the following schema and instance using https://jsonschema.dev

Schema:

{
  "properties": {
    "_data": {
      "type": "array",
      "items" : {
        "anyOf": [
          {
            "type": "object",
            "properties": {
              "inline": true
            },
            "additionalProperties": false
          },
          {
            "type": "object",
            "properties": {
              "rewrite": true
            },
            "additionalProperties": false
          }
        ]
      }
    }
  }
}

Instance :

{
  "_data": [
    {
      "optionC": {
        "_settings": {
          "sequence": 150
        },
        "data1": [
          {
            "subitem": {
              "value": 100
            }
          }
        ]
      }
    }
  ]
}

There is a problem with something other than your use of "anyOf", which is correct.

It's actually something FAR simpler...

You've used "ref" as opposed to "$ref" in your schema in quite a few places. Unknown keywords are ignored, and so your references were not working.

If it's any consolation, it took me quite a while to debug!


问:
delete a document in firebase when you know the field value
Context: In the frontend the user can enter of delete dates for availability. This is how I added a date:

```<code>Firestore.instance.collection('availableDates').add({
        'availableDates':date});
</code>```

But I also need to delete a document from a collection in Firestore. I don't know the document id but I know the the field value which is unique. How would I go about deleting the document if I know the field value within the document. Here is a screen shot of firestore:

答:
You can fetch the document first and then delete the document. For example:

var collection = FirebaseFirestore.instance.collection('countries');
var snapshot = await collection.where('city', isEqualTo: 'CA').get();
await snapshot.docs.first.reference.delete();
```

Body:
Context: In the frontend the user can enter of delete dates for availability. This is how I added a date:

Firestore.instance.collection('availableDates').add({
        'availableDates':date});

But I also need to delete a document from a collection in Firestore. I don't know the document id but I know the the field value which is unique. How would I go about deleting the document if I know the field value within the document. Here is a screen shot of firestore:


问:
Dangers with unscoped multiline MACROS
Is there a way to protect this MACRO from unscoped if/for statements?

```<code>#define FOO(X, Y, ...) X->bar(_##Y->thatVar, __VA_ARGS__);\
post_op(X, Y)
</code>```

The order of bar and post_op is important and the result of post_op is ignorable to the application

i.e.

```<code>if(true)
    auto z = FOO(a,b);
else //compile error
    abort();
</code>```

答:
Just use a lambda to reaggregate your statements back into an expression. Use it wherever an expression may appear, to your heart's content. Even in an expression statement inside an if with no braces.

```<code>#define FOO(X, Y, ...) [&] { \
  auto ret = X->bar(_##Y->thatVar, __VA_ARGS__);\
  post_op(X, Y); \
  return ret; }()
</code>```

Title: Dangers with unscoped multiline MACROS

Body:
Is there a way to protect this MACRO from unscoped if/for statements?

#define FOO(X, Y, ...) X->bar(_##Y->thatVar, __VA_ARGS__);\
post_op(X, Y)

The order of bar and post_op is important and the result of post_op is ignorable to the application

i.e.

if(true)
    auto z = FOO(a,b);
else //compile error
    abort();

Body:
Just use a lambda to reaggregate your statements back into an expression. Use it wherever an expression may appear, to your heart's content. Even in an expression statement inside an if with no braces.

#define FOO(X, Y, ...) [&] { \
  auto ret = X->bar(_##Y->thatVar, __VA_ARGS__);\
  post_op(X, Y); \
  return ret; }()


问:
Maven fails to find local artifact
Occasionally maven complains that a particular dependency, which is built and packaged locally, cannot be found in the local repository while building another project that has it as a dependency.  We get an error like:

Failed to execute goal on project X: Could not resolve dependencies for project X: Failure to find Y in [archiva repository] was cached in the local repository, resolution will not be reattempted until the update interval of internal has elapsed or updates are forced ->

Where X is the project being built, and Y is the supposedly missing artifact.  If you look in the local repository, the artifact is there.  This artifact is never installed in our archiva repository, so the problem is purely based in the local repository.

We have tried various profiles in settings.xml, and of course "mvn -U".  Neither do any good, nor should they because this artifact never goes any further than the local repository.

The only two things that seem to work are to wait a very long time until maven smartens up, or to completely delete the local repository.  Presumably the waiting option is related to the aforementioned update interval.

We have experienced this problem with maven 3.0.2 and 3.0.3.  We are using Archiva 1.0.3 (but again this shouldn't be a factor).  Any help would be greatly appreciated.

答:
Even I faced this issue and solved it with 2 ways:

1) In your IDE select project and clean all projects then install all the maven dependencies by right clicking on project -> go to maven and Update project dependencies select all projects at once to install the same. Once this is done run the particular project

2)  Else What you can do is check in the pom.xml for the dependencies for which you are getting error and "mvn clean install" those dependent project first and the install maven dependencies of the current project in which you facing issue. By this the dependencies of the local project will be build and jars will be created.

Title: Maven fails to find local artifact


问:
How to create unique Id per request for REST API in Spring-boot?
I need to make my logs (log4j engine) to be more informative with a unique id per request for my REST API in Spring-Boot application.

I want to avoid using a superclass which got requestId field and extend from it.

I tried to look for a good example over the web, but it wasn't so clear.

Is there any best practice that I can use?

答:
There are several best practices used as follows:

Use AOP Refer :AOP used for controller layer

Use MDC

Use MDC with AOP
MDC with AOP


问:
Creating a SQL totals table
What I am trying to accomplish is a SQL table that contains several different totals based off of 5 other tables. This would be so that when my application needs those totals, it would not need to perform the sum since it is a rather large query.

I would like to know if there is a recommended method to have a totals table that constantly updates based on changes made in other tables. I have thought of replacing it with an indexed view or having triggers on each of the tables that are being summed, but it seems inefficient to rerun the sum query every time a field is updated. One other thing I thought of would be to have a trigger on update and every time the data changes, I would just add or remove the difference from the stored total. My end goal is to have some totals that are constantly up to date.

The table is showing totals per product. (e.g. total qty from table1 + total qty from table2)

If this is too general, I can give more specifics about table structure.

答: I ended up putting these in a queue when the underlying data was changed, and using a scheduled task to update the totals at a regular interval. We decided the tradeoff in data freshness was worth not having to recalculate the total with every transaction. </p>

Title: Creating a SQL totals table


问:
Using $concat with $project is giving error : 'MongoError: $concat only supports strings, not double'?
I have a mongoose model in which some fields are like :

```<code>var AssociateSchema = new Schema({
    personalInformation: {
       familyName: { type: String },
       givenName: { type: String }
    }
})
</code>```

I want to perform a '$regex' on the concatenation of familyName and givenName (something like 'familyName + " " + 'givenName'), for this purpose I'm using aggregate framework with $concat inside $project to produce a 'fullName' field and then '$regex' inside $match to search on that field. The code in mongoose for my query is:

```<code>Associate.aggregate([
    { $project: {fullName: { $concat: [
    'personalInformation.givenName','personalInformation.familyName']}}},
    $match: { fullName: { 'active': true, $regex: param, $options: 'i' } }}
])
</code>```

But it's giving me error:

MongoError: $concat only supports strings, not double on the first
  stage of my aggregate pipeline i.e $project stage.

Can anyone point out what I'm doing wrong ?

答:
I also got this error and then discovered that indeed one of the documents in the collection was to blame. They way I fished it out was by filtering by field type as explained in the docs:

```<code>db.addressBook.find( { "zipCode" : { $type : "double" } } )
</code>```

I found the field had the value NaN, which to my eyes wouldn't be a number, but mongodb interprets it as such.

Body:
I have a mongoose model in which some fields are like :

var AssociateSchema = new Schema({
    personalInformation: {
       familyName: { type: String },
       givenName: { type: String }
    }
})

I want to perform a '$regex' on the concatenation of familyName and givenName (something like 'familyName + " " + 'givenName'), for this purpose I'm using aggregate framework with $concat inside $project to produce a 'fullName' field and then '$regex' inside $match to search on that field. The code in mongoose for my query is:

Associate.aggregate([
    { $project: {fullName: { $concat: [
    'personalInformation.givenName','personalInformation.familyName']}}},
    $match: { fullName: { 'active': true, $regex: param, $options: 'i' } }}
])

But it's giving me error:

MongoError: $concat only supports strings, not double on the first
  stage of my aggregate pipeline i.e $project stage.

Can anyone point out what I'm doing wrong ?

Body:
I also got this error and then discovered that indeed one of the documents in the collection was to blame. They way I fished it out was by filtering by field type as explained in the docs:

db.addressBook.find( { "zipCode" : { $type : "double" } } )

I found the field had the value NaN, which to my eyes wouldn't be a number, but mongodb interprets it as such.


问:
Windows service - supplying arguments in "path to executable"
I cannot figure out how to pass (constant) arguments into my Windows service when it is started. I'm using the standard .NET classes like ServiceBase to implement (and ServiceProcessInstaller and ServiceInstaller to install) my service.

On the general tab of a Windows Service properties dialog box (once installed), there's a "Path to executable" in which I can see that some of the standard Windows services have command line arguments specified. System.ServiceProcess.ServiceBase.OnStart takes string[] args, which I presume would enable these arguments to be accessed from within .NET code.

Are there some properties on ServiceProcessInstaller or ServiceInstaller that I can set to allow me to pass startup arguments to my own service, or does anyone know how it's supposed to be done?

答:
Well, it's about 10 months after you post and I had the same issue.  Once I read this thread and others, I decided to see what the .NET Framework is doing behind the scenes and verified that there is no documented way to do this.  There is; however, a very simple undocumented way of doing this.  In the parent Installer class, either override the Install method, or implement the BeforeInstall event.  It doesn't matter which, you can use either of the following:

```<code>public override void Install(System.Collections.IDictionary stateSaver)
{
    base.Install(stateSaver);

    base.Context.Parameters["assemblyPath"] = string.Format("\"{0}\" /service", base.Context.Parameters["assemblyPath"]);
}
</code>```

or:

```<code>private void Installer_BeforeInstall(object sender, InstallEventArgs e)
{
    base.Context.Parameters["assemblyPath"] = string.Format("\"{0}\" /service", base.Context.Parameters["assemblyPath"]);
}
</code>```

The "assemblyPath" parameter will be initialized with the full path to the executable from within the AssemblyInstaller class.  The value of this parameter is written to the ImagePath value in the registry.  Quotes will be placed around this value if none exist, so make sure you place them where you need them (i.e. around the initial value at least).  In the line above, I placed quotes around the execution file path and added " /service" to the end as a parameter.

This will apply to all services that use that parent Installer class.  If you have services that you either don't want the parameters added to, or that need different parameters, you can nest Installer classes and place the code on those instead of the root Installer class.  This isn't documented anywhere, could possibly break in the future, and may not work on non-Microsoft versions of the .NET Framework, but it does work for now.

I hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
Well, it's about 10 months after you post and I had the same issue.  Once I read this thread and others, I decided to see what the .NET Framework is doing behind the scenes and verified that there is no documented way to do this.  There is; however, a very simple undocumented way of doing this.  In the parent Installer class, either override the Install method, or implement the BeforeInstall event.  It doesn't matter which, you can use either of the following:

public override void Install(System.Collections.IDictionary stateSaver)
{
    base.Install(stateSaver);

    base.Context.Parameters["assemblyPath"] = string.Format("\"{0}\" /service", base.Context.Parameters["assemblyPath"]);
}

or:

private void Installer_BeforeInstall(object sender, InstallEventArgs e)
{
    base.Context.Parameters["assemblyPath"] = string.Format("\"{0}\" /service", base.Context.Parameters["assemblyPath"]);
}

The "assemblyPath" parameter will be initialized with the full path to the executable from within the AssemblyInstaller class.  The value of this parameter is written to the ImagePath value in the registry.  Quotes will be placed around this value if none exist, so make sure you place them where you need them (i.e. around the initial value at least).  In the line above, I placed quotes around the execution file path and added " /service" to the end as a parameter.

This will apply to all services that use that parent Installer class.  If you have services that you either don't want the parameters added to, or that need different parameters, you can nest Installer classes and place the code on those instead of the root Installer class.  This isn't documented anywhere, could possibly break in the future, and may not work on non-Microsoft versions of the .NET Framework, but it does work for now.

I hope this helps.


问:
Stacktrace is obfuscated in the Google Play console
I have a few apps on the store, and I'm seeing occasional crash reports.  However, the stacktrace remains obfuscated, even though the mapping file is showing as having been uploaded.

I'm using Android Studio, including the default settings for the new R8 code-shrinker.  A sample of the stacktrace is shown below.

```<code>  at android.support.v4.app.Fragment.Y (Fragment.java:31)
  at android.support.v4.app.Fragment.getResources (Fragment.java)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment.ca (PersonalInfoFragment.java:49)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment.access$400 (PersonalInfoFragment.java)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment$8.onSharedPreferenceChanged (PersonalInfoFragment.java:2)
  at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners (SharedPreferencesImpl.java:607)
  at android.app.SharedPreferencesImpl$EditorImpl.apply (SharedPreferencesImpl.java:489)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment$4.onItemSelected (PersonalInfoFragment.java:39)
  at android.widget.AdapterView.fireOnSelected (AdapterView.java:947)
  at android.widget.AdapterView.dispatchOnItemSelected (AdapterView.java:936)
  at android.widget.AdapterView.access$300 (AdapterView.java:56)
  at android.widget.AdapterView$SelectionNotifier.run (AdapterView.java:901)
  at android.os.Handler.handleCallback (Handler.java:907)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:216)
  at android.app.ActivityThread.main (ActivityThread.java:7593)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)
</code>```

答: This is because you enabled obfuscation using proguard. </p>

Body:
I have a few apps on the store, and I'm seeing occasional crash reports.  However, the stacktrace remains obfuscated, even though the mapping file is showing as having been uploaded.

I'm using Android Studio, including the default settings for the new R8 code-shrinker.  A sample of the stacktrace is shown below.

  at android.support.v4.app.Fragment.Y (Fragment.java:31)
  at android.support.v4.app.Fragment.getResources (Fragment.java)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment.ca (PersonalInfoFragment.java:49)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment.access$400 (PersonalInfoFragment.java)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment$8.onSharedPreferenceChanged (PersonalInfoFragment.java:2)
  at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners (SharedPreferencesImpl.java:607)
  at android.app.SharedPreferencesImpl$EditorImpl.apply (SharedPreferencesImpl.java:489)
  at com.mysoftwarecompany.myappname.PersonalInfoFragment$4.onItemSelected (PersonalInfoFragment.java:39)
  at android.widget.AdapterView.fireOnSelected (AdapterView.java:947)
  at android.widget.AdapterView.dispatchOnItemSelected (AdapterView.java:936)
  at android.widget.AdapterView.access$300 (AdapterView.java:56)
  at android.widget.AdapterView$SelectionNotifier.run (AdapterView.java:901)
  at android.os.Handler.handleCallback (Handler.java:907)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:216)
  at android.app.ActivityThread.main (ActivityThread.java:7593)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)


Title: How I convert my list to this desired list

Body:
I have a two columns data, the first column gene ID and the second column expression value

like below

6876    -2.735085846
59  -2.559180326
72  -2.41504926
4638    -1.785835164

I want something like

> str(geneList)
 Named num [1:12495] 4.57 4.51 4.42 4.14 3.88 ...
 - attr(*, "names")= chr [1:12495] "4312" "8318" "10874" "55143" ...

But when I am doing

X = as.character(t(read.table(text ="
6876    -2.735085846
59  -2.559180326
72  -2.41504926
4638    -1.785835164")))

I am getting

> str(X)
 chr [1:1418] "6876" "-2.735085846" "59" "-2.559180326" "72" "-2.41504926" "4638" "-1.785835164" "10398" "-1.588650179" ...
>

How I can make something like geneList?

Body:
Just use setNames after reading in the data with read.table.

X <- read.table(text = "
6876    -2.735085846
59  -2.559180326
72  -2.41504926
4638    -1.785835164
")

geneList <- setNames(X[[2]], X[[1]])
#     6876        59        72      4638
#-2.735086 -2.559180 -2.415049 -1.785835

And to match your expected output:

str(geneList)
# Named num [1:4] -2.74 -2.56 -2.42 -1.79
# - attr(*, "names")= chr [1:4] "6876" "59" "72" "4638"


问:
Remove Screen from navigation stack

App structure -

Home Screen - Have button navigate to shopping cart

ShoppingCart Screen - have button navigate to shop screen

Shop Screen - Have button navigate to shopping cart

Using - react-native: 0.59.5, react-navigation: ^3.8.1

step 1 - go to shopping cart from home

step 2 - go to shop from shopping cart

step 3 - add some items to cart in shop

step 4 - go to shopping cart from shop - problem goes here.

in step 4 action show the previous screen of shoppingCart( that appeared screen at step 1 ).There are no new added items in the cart only have previous states.

I haven't any idea how to slolve this ? can anyone help ?

答:
Put event listener inside componentDidMount:

```<code>componentDidMount() {
        this.willFocusSubscription = this.props.navigation.addListener('willFocus', payload => {
            console.log('[print action for test:]', payload);
            if (['Navigation/INIT', 'Navigation/NAVIGATE', 'Navigation/POP_TO_TOP'].includes(payload.action.type)) {
                this.doSomething()
            }
        });
    }
</code>```

Title: Remove Screen from navigation stack

Body:
Put event listener inside componentDidMount:

componentDidMount() {
        this.willFocusSubscription = this.props.navigation.addListener('willFocus', payload => {
            console.log('[print action for test:]', payload);
            if (['Navigation/INIT', 'Navigation/NAVIGATE', 'Navigation/POP_TO_TOP'].includes(payload.action.type)) {
                this.doSomething()
            }
        });
    }


问:
Firebase message with high priority not waking device from Doze android 6+
I have migrated my project from using GCM to use Firebase. Push notification comes through ok when the device is awake or been asleep recently but if I leave the device for say an hour, no push is sent until I wakeup the device.

The Android docs say that if you need to wake a device to deliver a message, then use FireBase with priority set to high. It also says that device Admin apps are not subject to Doze restrictions, my app is a device admin app.

I thought I would mention that when I migrated the project from GCM to FCM, I only specified the package name in the firebase console and not the fingerprint.

What I have tried.

Set priority to high

```<code>{
  "time_to_live": 300000,
  "delay_while_idle": false,
  "android": {
    "priority": "high"
  },
  "data": {
    "message": "PING_DEVICE",
    "time": "21/01/2018 16:20:28",
    "pushguid": "10062"
  },
  "registration_ids": [
    "eOMT........"
  ]
}
</code>```

Time to live is set so the message will come through eventually. delay_while_idle is set to false, this is ignored by FCM after sept 2016.

Device admin apps are not subject to Doze, mine is a device admin app but I have also explicitly added the app to the Doze whitelist found in Setting -> Battery -> Optimization. This was done manually through the settings app and NOT programmatically in code.

I have left my device to go to sleep for 3 hours and no push come through. I have also used adb to put the device into Doze. When adb puts the device in Doze no push is received, when adb takes the device out of Doze, the push comes through.

further thoughts I haven't tried.

My pushes are data messages. This is because I don't want the push to come to the notification bar on the device and have the user click it to execute the functionality. The user has no interaction with the device admin app. So a data message is handled by

```<code>onMessageReceived(RemoteMessage remoteMessage)
</code>```

I believe notification messages do wake up the device, which is what I need but I want the app to handle the push, not the user. Could I have messages that are both notification and data but have onMessageRecievied handle the functionality?

Has anybody experienced anything similar or have any solutions to this?

[EDIT1]
I have found the following link below that says you can send a message which is both notification and data, but if the app is in the background, the notification is displayed but the data is only executed when the user clicks the notification. This is not what I want as I would like the data to execute in onMessageRecived straight away.

notification with data

[EDIT2]
I have added the following code and permission to the app. The app now asks the user to whitelist the app for Doze, so I clicked yes. I then via adb put the device in Doze and sent a push. Nothing came through until I took the device back out of doze mode. So, unfortunately, this does not work.

```<code>if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent();
            String packageName = getPackageName();
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);
            }
        }

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
</code>```

[EDIT3]

I have done further testing to try to isolate the problem and take my web application code out of the equation. I put the device into Doze via adb and the used FireBase console to send the push instead. The push came through correctly This tells me there is a problem with my web application code that sends all the push info to the fcm endpoint. I will get the code tonight and post later.

[EDIT4]
i have just done some more testing. I placed the device into doze then used FireBase console to send a data message with 2 key-value pairs. When the device is in Doze and the app is in the foreground (on the screen), the push comes through and onMessageReceived executes. This is great. However, if the app is in the BG then only a notification is displayed. I understand that from the docs, the data messages are dispatched to the launcher activity via an Intent, but my launcher app does not handle the pushes.The class that handles the pushes is called MyAndroidFirebaseMsgService and extends FirebaseMessagingService.

Do i have to route the intent to this class in case the app is in the BG? Seems a bit starnge to have to do this. It was never the case in GCM.

Also, i do not want the app launching from a push as this is very invasive as the device user could be using a different app. My app is also a device admin app, so 99% of the time there is no user interaction, it is just a client that executes policies on the device.

[edit5]

```<code>internal static void SendNotification (  Dictionary<string, string> nameValues ,  List<string> theregIDs , string sPushName)
         {
            string stringregIds =  string.Join("\",\"", theregIDs) ;

             JavaScriptSerializer js = new JavaScriptSerializer();
            string keyValueJson = js.Serialize(nameValues);

            string TIME_TO_LIVE = "604800";

            string DELAY_WHILE_IDLE = "false";

            string ENDPOINTADDRESS = @"https://fcm.googleapis.com/fcm/send";

            postData = String.Concat("{\"time_to_live\":", TIME_TO_LIVE,  ",\"delay_while_idle\": ", DELAY_WHILE_IDLE,  ",  \"android\":{\"priority\":\"high\" } ,\"data\": { \"message\" : " + "\"" + sPushName + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\""
                , keyValueJson
               , "},\"registration_ids\":[\"" + stringregIds + "\"]}");

            WebRequest myWebRequest = null;
            WebResponse myWebResponse = null;
            try
            {
                myWebRequest = WebRequest.Create(ENDPOINTADDRESS);
                myWebRequest.Method = "post";
                myWebRequest.ContentType = "application/json";
                //  myWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                myWebRequest.Headers.Add("Authorization: key=" + Our_Api_Key);
                myWebRequest.Headers.Add("Sender:id=" + Our_Sender_Id);

                Byte[] BA = Encoding.UTF8.GetBytes(postData);
                myWebRequest.ContentLength = BA.Length;

                using (Stream dataStreamOut = myWebRequest.GetRequestStream())
                {
                    dataStreamOut.Write(BA, 0, BA.Length);

                }

                using (myWebResponse = myWebRequest.GetResponse())
                {
                    using (Stream dataStream = myWebResponse.GetResponseStream())
                    {
                        using (StreamReader tReader = new StreamReader(dataStream))
                        {
                            strServerResponse = tReader.ReadToEnd();
                        }

                    }
                }

            }
            catch (WebException ex)
            {

            }

         }//
</code>```

thanks

答:
Setting a time_to_live of 0 solved the problem for me.

I think it's because a very small time_to_live will tell FCM that this message is only worth delivering right this instant. So in an attempt to deliver it ASAP, it will ignore battery optimizations like the Android P's "app standby buckets".
Be careful though, as setting a small time_to_live might mean not delivering the notification at all in some cases. I don't think you should be applying it to all kinds of push notifications.

For more details about time_to_live: https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message

Body:
I have migrated my project from using GCM to use Firebase. Push notification comes through ok when the device is awake or been asleep recently but if I leave the device for say an hour, no push is sent until I wakeup the device.

The Android docs say that if you need to wake a device to deliver a message, then use FireBase with priority set to high. It also says that device Admin apps are not subject to Doze restrictions, my app is a device admin app.

I thought I would mention that when I migrated the project from GCM to FCM, I only specified the package name in the firebase console and not the fingerprint.

What I have tried.

Set priority to high

{
  "time_to_live": 300000,
  "delay_while_idle": false,
  "android": {
    "priority": "high"
  },
  "data": {
    "message": "PING_DEVICE",
    "time": "21/01/2018 16:20:28",
    "pushguid": "10062"
  },
  "registration_ids": [
    "eOMT........"
  ]
}

Time to live is set so the message will come through eventually. delay_while_idle is set to false, this is ignored by FCM after sept 2016.

Device admin apps are not subject to Doze, mine is a device admin app but I have also explicitly added the app to the Doze whitelist found in Setting -> Battery -> Optimization. This was done manually through the settings app and NOT programmatically in code.

I have left my device to go to sleep for 3 hours and no push come through. I have also used adb to put the device into Doze. When adb puts the device in Doze no push is received, when adb takes the device out of Doze, the push comes through.

further thoughts I haven't tried.

My pushes are data messages. This is because I don't want the push to come to the notification bar on the device and have the user click it to execute the functionality. The user has no interaction with the device admin app. So a data message is handled by

onMessageReceived(RemoteMessage remoteMessage)

I believe notification messages do wake up the device, which is what I need but I want the app to handle the push, not the user. Could I have messages that are both notification and data but have onMessageRecievied handle the functionality?

Has anybody experienced anything similar or have any solutions to this?

[EDIT1]
I have found the following link below that says you can send a message which is both notification and data, but if the app is in the background, the notification is displayed but the data is only executed when the user clicks the notification. This is not what I want as I would like the data to execute in onMessageRecived straight away.

notification with data

[EDIT2]
I have added the following code and permission to the app. The app now asks the user to whitelist the app for Doze, so I clicked yes. I then via adb put the device in Doze and sent a push. Nothing came through until I took the device back out of doze mode. So, unfortunately, this does not work.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent();
            String packageName = getPackageName();
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);
            }
        }

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

[EDIT3]

I have done further testing to try to isolate the problem and take my web application code out of the equation. I put the device into Doze via adb and the used FireBase console to send the push instead. The push came through correctly This tells me there is a problem with my web application code that sends all the push info to the fcm endpoint. I will get the code tonight and post later.

[EDIT4]
i have just done some more testing. I placed the device into doze then used FireBase console to send a data message with 2 key-value pairs. When the device is in Doze and the app is in the foreground (on the screen), the push comes through and onMessageReceived executes. This is great. However, if the app is in the BG then only a notification is displayed. I understand that from the docs, the data messages are dispatched to the launcher activity via an Intent, but my launcher app does not handle the pushes.The class that handles the pushes is called MyAndroidFirebaseMsgService and extends FirebaseMessagingService.

Do i have to route the intent to this class in case the app is in the BG? Seems a bit starnge to have to do this. It was never the case in GCM.

Also, i do not want the app launching from a push as this is very invasive as the device user could be using a different app. My app is also a device admin app, so 99% of the time there is no user interaction, it is just a client that executes policies on the device.

[edit5]

internal static void SendNotification (  Dictionary<string, string> nameValues ,  List<string> theregIDs , string sPushName)
         {
            string stringregIds =  string.Join("\",\"", theregIDs) ;

             JavaScriptSerializer js = new JavaScriptSerializer();
            string keyValueJson = js.Serialize(nameValues);

            string TIME_TO_LIVE = "604800";

            string DELAY_WHILE_IDLE = "false";

            string ENDPOINTADDRESS = @"https://fcm.googleapis.com/fcm/send";

            postData = String.Concat("{\"time_to_live\":", TIME_TO_LIVE,  ",\"delay_while_idle\": ", DELAY_WHILE_IDLE,  ",  \"android\":{\"priority\":\"high\" } ,\"data\": { \"message\" : " + "\"" + sPushName + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\""
                , keyValueJson
               , "},\"registration_ids\":[\"" + stringregIds + "\"]}");

            WebRequest myWebRequest = null;
            WebResponse myWebResponse = null;
            try
            {
                myWebRequest = WebRequest.Create(ENDPOINTADDRESS);
                myWebRequest.Method = "post";
                myWebRequest.ContentType = "application/json";
                //  myWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                myWebRequest.Headers.Add("Authorization: key=" + Our_Api_Key);
                myWebRequest.Headers.Add("Sender:id=" + Our_Sender_Id);

                Byte[] BA = Encoding.UTF8.GetBytes(postData);
                myWebRequest.ContentLength = BA.Length;

                using (Stream dataStreamOut = myWebRequest.GetRequestStream())
                {
                    dataStreamOut.Write(BA, 0, BA.Length);

                }

                using (myWebResponse = myWebRequest.GetResponse())
                {
                    using (Stream dataStream = myWebResponse.GetResponseStream())
                    {
                        using (StreamReader tReader = new StreamReader(dataStream))
                        {
                            strServerResponse = tReader.ReadToEnd();
                        }

                    }
                }

            }
            catch (WebException ex)
            {

            }

         }//

thanks


问:
How to add days to Date?
How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?

答:
```<code>var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
</code>```

Be careful, because this can be tricky.  When setting tomorrow, it only works because its current value matches the year and month for today.  However, setting to a date number like "32" normally will still work just fine to move it to the next month.

OwnerDisplayName: Ashesh

Title: How to add days to Date?

Body:
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

Be careful, because this can be tricky.  When setting tomorrow, it only works because its current value matches the year and month for today.  However, setting to a date number like "32" normally will still work just fine to move it to the next month.

OwnerDisplayName: Joel Coehoorn

LastEditorDisplayName: Joel Coehoorn


问:
What is the best way to give variable/argument from one class to another using C#
What are the "good practices" in passing argiments/variables between classes? Better is using get and set or maybe giving that for example class1.a = class2.b?

Maybe exists better ways? Thanks for help.

答:
I don't really know how you want to use this, so it's kind of difficult to give such gerenal advice in a short answer.

On the most basic level I'd say you can just use getter and setter like this:

```<code>public class Class1 {
    public int A { get; set; }
}

public class Class2 {

    public int B { get; private set; }

    public Class2 {
        B = 42;
    }
}

public class SomeClass {

    Class1 class1 = new Class1();
    Class2 class2 = new Class2();

    ...

    private void SomeMethod() {
        class1.A = class2.B;
    }

    ...

}
</code>```

I agree with st_stefanov that you wouldn't want to use public variables.

Body:
I don't really know how you want to use this, so it's kind of difficult to give such gerenal advice in a short answer.

On the most basic level I'd say you can just use getter and setter like this:

public class Class1 {
    public int A { get; set; }
}

public class Class2 {

    public int B { get; private set; }

    public Class2 {
        B = 42;
    }
}

public class SomeClass {

    Class1 class1 = new Class1();
    Class2 class2 = new Class2();

    ...

    private void SomeMethod() {
        class1.A = class2.B;
    }

    ...

}

I agree with st_stefanov that you wouldn't want to use public variables.


问:
Redimensioning array of ranges into a single array containing only the values of each range element
I have multiple worksheets with ranges which I collect into an array of ranges, and I cant do Union since it does not work across worksheets.
Since I want to create a chart where the time-series or FullSeriesCollection are based on the elements of my combined ranges, I thought that redimensioning the array of ranges into a single array might serve as my solution.
Perhaps there is an easier solution that I am not seeing.

I tried to outline the general case below. The ranges are dynamic in my code, but here I just set them arbitrarily.

```<code>Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            ReDim Preserve arrDate(j)
            arrDate(j) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub
</code>```

When I use this code I get an array with 22 elements corresponding to the range of rng_3. What I want to end up with after the nested loop is an array that contains the elements from all ranges in 1 single array with 1 dimension.

The reason I want this in the end is I want to create chart using the array values.

答:
Your code is fine, the only error is that you are reusing the same variable from your inner loop, which would reset on each outer loop. To get around that, just use an additional variable as such:

Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer, X As Long

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            X = X + 1                       'Add an additional counter
            ReDim Preserve arrDate(X)
            arrDate(X) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub
```

<p><strong>EDIT:</strong> slight variation, to improve the speed as per @Tom suggestion... see comments for further details.</p>

<pre class="lang-vb prettyprint-override"><code>Sub Collection()

Dim arrDate() As Variant: ReDim arrDate(1 To 1)
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer, X As Long

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(1)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

'Dimension the holding array outside the main data loop, unless you need to do this inside based on various conditions
For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    X = X + UBound(arrRngTotal(k))
Next k
ReDim Preserve arrDate(1 To X): X = 0

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            X = X + 1
            arrDate(X) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub
</code>```

Body:
I have multiple worksheets with ranges which I collect into an array of ranges, and I cant do Union since it does not work across worksheets.
Since I want to create a chart where the time-series or FullSeriesCollection are based on the elements of my combined ranges, I thought that redimensioning the array of ranges into a single array might serve as my solution.
Perhaps there is an easier solution that I am not seeing.

I tried to outline the general case below. The ranges are dynamic in my code, but here I just set them arbitrarily.

Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            ReDim Preserve arrDate(j)
            arrDate(j) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub

When I use this code I get an array with 22 elements corresponding to the range of rng_3. What I want to end up with after the nested loop is an array that contains the elements from all ranges in 1 single array with 1 dimension.

The reason I want this in the end is I want to create chart using the array values.

Body:
Your code is fine, the only error is that you are reusing the same variable from your inner loop, which would reset on each outer loop. To get around that, just use an additional variable as such:

Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer, X As Long

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            X = X + 1                       'Add an additional counter
            ReDim Preserve arrDate(X)
            arrDate(X) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub

EDIT: slight variation, to improve the speed as per @Tom suggestion... see comments for further details.

Sub Collection()

Dim arrDate() As Variant: ReDim arrDate(1 To 1)
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer, X As Long

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(1)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

'Dimension the holding array outside the main data loop, unless you need to do this inside based on various conditions
For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    X = X + UBound(arrRngTotal(k))
Next k
ReDim Preserve arrDate(1 To X): X = 0

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            X = X + 1
            arrDate(X) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub


问:
Unable to create regular expression for diffrent URL's
I am new to Jmeter and want to create a regular expression which can capture both the urls's below:

I am trying using this expression:

```<code>movies/(.+?)/(.+?)&amp
</code>```

Its not working for both the url's:

```<code>https://in.bookmyshow.com/bengaluru/movies/avengers-endgame/ET00090482&
https://in.bookmyshow.com/movies/the-tashkent-files/ET00069063/&
</code>```

答:
Your expression: movies/(.+?)/(.+?)&amp

Since you searching 2 groups: Movie name(avengers-endgame) and ID(ET00090482), you need to take the template as $1$$2$ in Regular Expression Extractor in JMeter

Also, please check the sections - Apply to and Fields to check to be selected as per the requirement

Reference:

How to use Regular Expression Extractor in JMeter

Body:
I am new to Jmeter and want to create a regular expression which can capture both the urls's below:

I am trying using this expression:

movies/(.+?)/(.+?)&amp

Its not working for both the url's:

https://in.bookmyshow.com/bengaluru/movies/avengers-endgame/ET00090482&
https://in.bookmyshow.com/movies/the-tashkent-files/ET00069063/&


问:
How to extract columns with varying names of a data frame into a list?
I have a data frame df with one date column and 50 other columns with individual stock prices that are named after the respective stock.
The first couple of columns of the data frame basically look like this:

```<code>df
Date        Adidas  Allianz  Shell  IBM  ...
2015-12-01  130     45       200    39
2015-12-02  131     46       199    40
...
</code>```

I want to perform several actions (like calculating the daily return etc.) for which I always want a new column for the output.

As I want to retain an overview, my idea was to extract each stock column together with the Date column and put them in a new data frame to basically create 50 new data frames, one for each stock. Then, I would create a list of these 50 data frames to then perform all following actions with lapply-functions on the list.
I do not want to type each column name into R individually, so is there any function with which I can extract one column after the other and put them into a new data frame always together with the Date column?

My new data should look kind of like this:

```<code>list

dfAdidas
Date        Adidas
2015-12-01  130
2015-12-02  131
...

dfAllianz
Date        Allianz
2015-12-01  45
2015-12-02  46
...
</code>```

and so on.

Thankful for any tips or recommendations how to do this easier!

答:
Use lapply and cbind every column with the first column. It will return you a list of dataframes.

```<code>lapply(df[-1], function(x) cbind(df[1], x))

#$Adidas
#        Date   x
#1 2015-12-01 130
#2 2015-12-02 131

#$Allianz
#        Date  x
#1 2015-12-01 45
#2 2015-12-02 46

#$Shell
#        Date   x
#1 2015-12-01 200
#2 2015-12-02 199

#$IBM
#        Date  x
#1 2015-12-01 39
#2 2015-12-02 40
</code>```

Or using Map

```<code>Map(cbind.data.frame, x = df[1], y = df[-1])
</code>```

The alternative purrr versions using map and map2 would be

```<code>purrr::map(df[-1], ~cbind(df[1], y = .))
purrr::map2(df[-1], df[1], cbind.data.frame)
</code>```

Body:
I have a data frame df with one date column and 50 other columns with individual stock prices that are named after the respective stock.
The first couple of columns of the data frame basically look like this:

df
Date        Adidas  Allianz  Shell  IBM  ...
2015-12-01  130     45       200    39
2015-12-02  131     46       199    40
...

I want to perform several actions (like calculating the daily return etc.) for which I always want a new column for the output.

As I want to retain an overview, my idea was to extract each stock column together with the Date column and put them in a new data frame to basically create 50 new data frames, one for each stock. Then, I would create a list of these 50 data frames to then perform all following actions with lapply-functions on the list.
I do not want to type each column name into R individually, so is there any function with which I can extract one column after the other and put them into a new data frame always together with the Date column?

My new data should look kind of like this:

list

dfAdidas
Date        Adidas
2015-12-01  130
2015-12-02  131
...

dfAllianz
Date        Allianz
2015-12-01  45
2015-12-02  46
...

and so on.

Thankful for any tips or recommendations how to do this easier!

Body:
Use lapply and cbind every column with the first column. It will return you a list of dataframes.

lapply(df[-1], function(x) cbind(df[1], x))

#$Adidas
#        Date   x
#1 2015-12-01 130
#2 2015-12-02 131

#$Allianz
#        Date  x
#1 2015-12-01 45
#2 2015-12-02 46

#$Shell
#        Date   x
#1 2015-12-01 200
#2 2015-12-02 199

#$IBM
#        Date  x
#1 2015-12-01 39
#2 2015-12-02 40

Or using Map

Map(cbind.data.frame, x = df[1], y = df[-1])

The alternative purrr versions using map and map2 would be

purrr::map(df[-1], ~cbind(df[1], y = .))
purrr::map2(df[-1], df[1], cbind.data.frame)


问:
how to send email at backend of application in iPhone?
hi
I want to send an email when user open the application but that email should be sent at back end so that user can not judge that application send an email.
any body can help me?
thanx</p>

答:
If this is for the purpose of simply knowing that someone ran the program, I would check out www.Flurry.com, free analytics for your app and very easy to integrate. (I have no connection with Flurry except as a user.)

Sending e-mail behind the scenes is not hard, necessarily, but you have to basically establish a network connection to a server that has a mail server (MTA), and then you have to "speak" SMTP to it, and a whole lot of things can go wrong in the process. :-) (I spent 10 years writing e-mail servers, so I know of what I speak. :-)

Check out Flurry. :-)


问:
Swift - Get device's WIFI IP Address
I need to get IP Address of iOS device in Swift. This is not a duplicate of other questions about this! I need to get only WiFi IP address, if there is no wifi ip address - I need to handle it. There are a few questions about it on Stack Overflow, but there are only functions that return ip addresses. For example (from How to get Ip address in swift):

```<code>func getIFAddresses() -> [String] {
    var addresses = [String]()

    // Get list of all interfaces on the local machine:
    var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
    if getifaddrs(&ifaddr) == 0 {

        // For each interface ...
        for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
            let flags = Int32(ptr.memory.ifa_flags)
            var addr = ptr.memory.ifa_addr.memory

            // Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {

                    // Convert interface address to a human readable string:
                    var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
                    if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
                        nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String.fromCString(hostname) {
                                addresses.append(address)
                            }
                    }
                }
            }
        }
        freeifaddrs(ifaddr)
    }

    return addresses
}
</code>```

Here I get 2 values - address from mobile internet(I think) and WiFi address I need. Is there any other way to get ONLY WiFi IP Address?

答:
To get IPAddress for wifi , wired, and cellular - swift 5

```<code>func getIPAddress() -> String {
    var address: String?
    var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
    if getifaddrs(&ifaddr) == 0 {
        var ptr = ifaddr
        while ptr != nil {
            defer { ptr = ptr?.pointee.ifa_next }

            guard let interface = ptr?.pointee else { return "" }
            let addrFamily = interface.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {

                // wifi = ["en0"]
                // wired = ["en2", "en3", "en4"]
                // cellular = ["pdp_ip0","pdp_ip1","pdp_ip2","pdp_ip3"]

                let name: String = String(cString: (interface.ifa_name))
                if  name == "en0" || name == "en2" || name == "en3" || name == "en4" || name == "pdp_ip0" || name == "pdp_ip1" || name == "pdp_ip2" || name == "pdp_ip3" {
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(interface.ifa_addr, socklen_t((interface.ifa_addr.pointee.sa_len)), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
                    address = String(cString: hostname)
                }
            }
        }
        freeifaddrs(ifaddr)
    }
    return address ?? ""
}
</code>```

How to use

```<code>let strIPAddress : String = self.getIPAddress()
print("IPAddress :: \(strIPAddress)")
</code>```

Note : Add this below in your project's Bridging-Header file

```<code>#include<ifaddrs.h>
</code>```

Title: Swift - Get device's WIFI IP Address

Body:
I need to get IP Address of iOS device in Swift. This is not a duplicate of other questions about this! I need to get only WiFi IP address, if there is no wifi ip address - I need to handle it. There are a few questions about it on Stack Overflow, but there are only functions that return ip addresses. For example (from How to get Ip address in swift):

func getIFAddresses() -> [String] {
    var addresses = [String]()

    // Get list of all interfaces on the local machine:
    var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
    if getifaddrs(&ifaddr) == 0 {

        // For each interface ...
        for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
            let flags = Int32(ptr.memory.ifa_flags)
            var addr = ptr.memory.ifa_addr.memory

            // Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {

                    // Convert interface address to a human readable string:
                    var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
                    if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
                        nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String.fromCString(hostname) {
                                addresses.append(address)
                            }
                    }
                }
            }
        }
        freeifaddrs(ifaddr)
    }

    return addresses
}

Here I get 2 values - address from mobile internet(I think) and WiFi address I need. Is there any other way to get ONLY WiFi IP Address?

Body:
To get IPAddress for wifi , wired, and cellular - swift 5

func getIPAddress() -> String {
    var address: String?
    var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
    if getifaddrs(&ifaddr) == 0 {
        var ptr = ifaddr
        while ptr != nil {
            defer { ptr = ptr?.pointee.ifa_next }

            guard let interface = ptr?.pointee else { return "" }
            let addrFamily = interface.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {

                // wifi = ["en0"]
                // wired = ["en2", "en3", "en4"]
                // cellular = ["pdp_ip0","pdp_ip1","pdp_ip2","pdp_ip3"]

                let name: String = String(cString: (interface.ifa_name))
                if  name == "en0" || name == "en2" || name == "en3" || name == "en4" || name == "pdp_ip0" || name == "pdp_ip1" || name == "pdp_ip2" || name == "pdp_ip3" {
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(interface.ifa_addr, socklen_t((interface.ifa_addr.pointee.sa_len)), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
                    address = String(cString: hostname)
                }
            }
        }
        freeifaddrs(ifaddr)
    }
    return address ?? ""
}

How to use

let strIPAddress : String = self.getIPAddress()
print("IPAddress :: \(strIPAddress)")

Note : Add this below in your project's Bridging-Header file

#include<ifaddrs.h>


问:
How to remove the last characters in a file name using Bash?
I have several .txt files in a folder, their names look as follows:

```<code>file1.txt
file2.txt
file2.txt_newfile.txt
file3.txt
file4.txt
file4.txt_newfile.txt
file5.txt_newfile.txt
...
</code>```

I am trying to remove _newfile.txt from the file names. If the file is present, it should be overwritten by the new file (e.g. file2.txt will be replaced, but file5.txt will just be renamed).

Expected output:

```<code>file1.txt
file2.txt # this was file2.txt_newfile.txt
file3.txt
file4.txt # file4.txt_newfile.txt
file5.txt #file5.txt_newfile.txt
...
</code>```

I tried the following code:

```<code>for i in $(find . -name "*_newfile.txt" -print); do
mv -f "$file" "${file%????????????}"
done
</code>```

However, I get the following error:

```<code>mv: rename  to : No such file or directory
</code>```

What am I doing wrong and how can I rename these files?

答:
You're populating variable i with find's output, but referencing variable file, which is undeclared, in mv invocation. So it expands to mv -f '' '', that's why you get a No such file or directory error.

You better do that like this:

```<code>find -type f -name '*_newfile.txt' -exec sh -c '
for fname; do
  mv -- "$fname" "${fname%_newfile.txt}"
done' _ {} +
</code>```

If these files are all in the same folder, you don't even need find, just a for loop will do the same:

```<code>for fname in *_newfile.txt; do
  mv -- "$fname" "${fname%_newfile.txt}"
done
</code>```

Body:
I have several .txt files in a folder, their names look as follows:

file1.txt
file2.txt
file2.txt_newfile.txt
file3.txt
file4.txt
file4.txt_newfile.txt
file5.txt_newfile.txt
...

I am trying to remove _newfile.txt from the file names. If the file is present, it should be overwritten by the new file (e.g. file2.txt will be replaced, but file5.txt will just be renamed).

Expected output:

file1.txt
file2.txt # this was file2.txt_newfile.txt
file3.txt
file4.txt # file4.txt_newfile.txt
file5.txt #file5.txt_newfile.txt
...

I tried the following code:

for i in $(find . -name "*_newfile.txt" -print); do
mv -f "$file" "${file%????????????}"
done

However, I get the following error:

mv: rename  to : No such file or directory

What am I doing wrong and how can I rename these files?

Body:
You're populating variable i with find's output, but referencing variable file, which is undeclared, in mv invocation. So it expands to mv -f '' '', that's why you get a No such file or directory error.

You better do that like this:

find -type f -name '*_newfile.txt' -exec sh -c '
for fname; do
  mv -- "$fname" "${fname%_newfile.txt}"
done' _ {} +

If these files are all in the same folder, you don't even need find, just a for loop will do the same:

for fname in *_newfile.txt; do
  mv -- "$fname" "${fname%_newfile.txt}"
done


问:
git pull remote branch cannot find remote ref
I'm not sure why this doesn't work.  When I do git branch -a, this is what I see:

I'm trying to pull from the DownloadManager on the online GitHub repository.  I have tried

git pull, but then it complains about not knowing which branch to pull from

git pull origin, doesn't know which branch

git pull origin downloadmanager gives fatal: Couldn't find remote ref downloadmanager.  Unexpected end of commands stream

git pull origin remotes/origin/DownloadManager gives fatal couldn't find remote ref remotes/origin/DownloadManager.  Unexpected end of commands stream

Is there something I'm missing?  In Xcode, When I try to connect to the repository, nothing ever shows up.  I have been able to push to it in the past.  But I can't push again until I pull the most recent changes.

答: check your branch on your repo. maybe someone delete it.</p>


问:
Format
 contents as though it were a print preview of A4/USLetter
I have a
 whose contents represent an invoice that my server will print. Some of the stuff inside the
 are contentEditable=true.  Each page should have various headers and footers etc.

I want the contents of this
 to be presented to appear like a print preview.

Its easy to set the width of the
 to be A4, or whatever page size.

But how to make the
 height the appropriate multiple for the number of pages, and how to get the content within the
 to jump across page boundaries?

答:
Good Question Will:

The main idea behind that would be not to create a finite height adjustment but rather an automatic height - assuming that you don't have a border on your div

I would implement the following style:

```<code>[DivSelector]{
    width: [Your full A4 width - any print margins ];
    /* set minimum height to 1 page height */
    min-height: [A4 PageHeight in Px];
    height: auto;
    overflow: auto; /*  ensure that your content remains within the div */
}
</code>```

I have tried this before but with an A3 display. Ofcourse when you print, your printer will add it's own margin so it's important to make your page with to width: [FullPage Width - PageMarginSetOnPrinter]

Title: Format <div> contents as though it were a print preview of A4/USLetter

Body:
Good Question Will:

The main idea behind that would be not to create a finite height adjustment but rather an automatic height - assuming that you don't have a border on your div

I would implement the following style:

[DivSelector]{
    width: [Your full A4 width - any print margins ];
    /* set minimum height to 1 page height */
    min-height: [A4 PageHeight in Px];
    height: auto;
    overflow: auto; /*  ensure that your content remains within the div */
}

I have tried this before but with an A3 display. Ofcourse when you print, your printer will add it's own margin so it's important to make your page with to width: [FullPage Width - PageMarginSetOnPrinter]