问:
Jmeter - extract json data from dynamic payload using 'and' statement
I want to extract value from dynamic JSON.

This generation is different every time when is executed.
I need to get ex: XLIfccMNLv1asVam3QuatowCmrp8IYuE0FUDMYncegs=
which is generated in the different location in the Json file, with different value

I tried with.

$.payload[?(@.eventType == 'AAA')].entityId

which is working fine.
But, i want more stronger query.

Is it possible to use && statement with the query something like:

```<code>$.payload[?(@.eventType == 'AAA')&&(@.outgoingCurrency== 'EUR')].entityId
</code>```

My payload:

```<code>{
   "payload":[
      {
         "entityId":"qvr_IlDhTdzldeccxguNR84sE0N78DUfNGzwH-3pY7Y=",
         "accountHolderId":"dvwxpTxVHdo2n1d5ytO6WyhnI2nuaEuzsh47agPpSFU=",
         "processorType":"DUMMY",
         "eventType":"AAA",
         "outgoingCurrency":"USD",
         "holdPeriodInHours":11,
         "disabled":false
      },
      {
         "entityId":"XLIfccMNLv1asVam3QuatowCmrp8IYuE0FUDMYncegs=",
         "accountHolderId":"Xoo8uAM90qRT7kceDUJBIIqafUuUdH2fH_Ia2z1TY5w=",
         "processorType":"DUMMY",
         "eventType":"BBB",
         "outgoingCurrency":"EUR",
         "holdPeriodInHours":10,
         "disabled":false
      },
      {
         "entityId":"yBoHvYkyszaQpaFe1zvqCY416_vYiq7iivA9bWJhiTg=",
         "processorType":"BMO_CPR",
         "eventType":"AAA",
         "disabled":false
      }

   ]
}
</code>```

答:
You need to use the operation && inside the expression:
$.payload[?(@.outgoingCurrency== 'EUR' && @.eventType == 'AAA')].entityId.

For more details see: https://goessner.net/articles/JsonPath/

Body:
I want to extract value from dynamic JSON.

This generation is different every time when is executed.
I need to get ex: XLIfccMNLv1asVam3QuatowCmrp8IYuE0FUDMYncegs=
which is generated in the different location in the Json file, with different value

I tried with.

$.payload[?(@.eventType == 'AAA')].entityId

which is working fine.
But, i want more stronger query.

Is it possible to use && statement with the query something like:

$.payload[?(@.eventType == 'AAA')&&(@.outgoingCurrency== 'EUR')].entityId

My payload:

{
   "payload":[
      {
         "entityId":"qvr_IlDhTdzldeccxguNR84sE0N78DUfNGzwH-3pY7Y=",
         "accountHolderId":"dvwxpTxVHdo2n1d5ytO6WyhnI2nuaEuzsh47agPpSFU=",
         "processorType":"DUMMY",
         "eventType":"AAA",
         "outgoingCurrency":"USD",
         "holdPeriodInHours":11,
         "disabled":false
      },
      {
         "entityId":"XLIfccMNLv1asVam3QuatowCmrp8IYuE0FUDMYncegs=",
         "accountHolderId":"Xoo8uAM90qRT7kceDUJBIIqafUuUdH2fH_Ia2z1TY5w=",
         "processorType":"DUMMY",
         "eventType":"BBB",
         "outgoingCurrency":"EUR",
         "holdPeriodInHours":10,
         "disabled":false
      },
      {
         "entityId":"yBoHvYkyszaQpaFe1zvqCY416_vYiq7iivA9bWJhiTg=",
         "processorType":"BMO_CPR",
         "eventType":"AAA",
         "disabled":false
      }

   ]
}


来源: stackexchange

问:
Setup a headless device to connect to a wifi network
I have a device with no screen + a microcontroller + a wifi module.

So far so good but basically I'd like to setup my device so it can connect to a wifi network, so I made an app to do that.

The strategy is:

put the device in wifi AP mode with a custom ssid like "Device XXXX"

connect to this ssid "Device XXXX"

Ask the user for its home wifi credentials

send the credentials to the device (for example using http) -> POST http://x.x.x.x/wifi_creds "Home" "homepassword"

poll the device to check whether it could connect to the "Home" network -> GET http://x.x.x.x/conn_status

Once it's connected, stop the AP mode -> POST http://x.x.x.x/wifi_ap_mode 0

This works pretty well, but it requires the user to manually connect to the "Device XXXX" ssid.
And actually on Android I can make things even easier by connecting automatically to this ssid, but I need to find the ssid first.

So my idea was to scan all the ssids and to connect to the first one that matches the pattern /^Device [0-9a-zA-Z]{4}/ (like Device 1234).

However this doesn't look like a good way to find a hotspot, and there might be a better way.
Also, I don't want to give it a default name as it could conflict with another ssid.

Is there another way to find my device (or my device ssid) without this trick?

I know that Google home is able to connect to a Chromecast allowing you to configure it while the Chromecast is in AP mode with a ssid that looks like "Chromecast XXXX" (when the bluetooth is disabled), and I'm not sure how they do it

答:
*I've assumed (perhaps wrongly) that your headless device is Android based. If it is Android and has Bluetooth, specifically Bluetooth Low Energy and is above Android 5.0:

You could get the device to act as a Bluetooth beacon which constantly broadcasts it's SSID.

So your app first scans for Bluetooth beacons - the beacon payload could be any arbitrary data - perhaps some known hard coded GUID to be sure you're talking to the correct Bluetooth beacon and also embed the SSID.

Now go and scan for the SSID and connect to it.

See this library for details on how to do this.

I believe you can even configure a kind of 'geofence' so that as soon as you come into range of the beacon your app wakes up and does the pairing.

ContentLicense: CC BY-SA 4.0


问:
I cant update the reserve of products in Database
I am building an e-shop, and I want to update the reserve on products in the database but the code is not working properly. Can you check it out, please</p>

```<code>if (filter_input(INPUT_GET,'checkout')){
$sql="UPDATE tblproduct SET apothema=18 WHERE id=1"}
</code>```

答:
```<code>if (filter_input(INPUT_GET,'checkout')){
$sql="UPDATE tblproduct SET apothema=18 WHERE id='1'";
// connect to database to run your query so the above query will execute
$run = $conn->query($sql);

//this is optional
//you can use like this to check if your connect is success and data is inserted.
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}
</code>```

I think the problem is only here WHERE id = '1' "; remember that you need to use that'value to compare'and don't forgot to put ; in the end too. One more thing, you need to connect to database and run query to insert data to your database.

Body:
I am building an e-shop, and I want to update the reserve on products in the database but the code is not working properly. Can you check it out, please

if (filter_input(INPUT_GET,'checkout')){
$sql="UPDATE tblproduct SET apothema=18 WHERE id=1"}

Body:
if (filter_input(INPUT_GET,'checkout')){
$sql="UPDATE tblproduct SET apothema=18 WHERE id='1'";
// connect to database to run your query so the above query will execute
$run = $conn->query($sql);

//this is optional
//you can use like this to check if your connect is success and data is inserted.
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}

I think the problem is only here WHERE id = '1' "; remember that you need to use that'value to compare'and don't forgot to put ; in the end too. One more thing, you need to connect to database and run query to insert data to your database.


问:
How I can do a reference code in my C# documentation?
I am doing the HTML format documentation for my C# code and I'd like to know if it's possible to do a reference inside my own code.

For example:

```<code>public class Test{
public bool Calculate(int x){ //code }
}

public class Check{
void Checking(int y, int x, int z){
//code
bool aux = Test.Calcultate(x);
//code
}
</code>```

When I'm doing the documentation like this:

```<code> /// <summary>
 ///
 /// </summary>
 /// <param name=""></param>
 /// <returns></returns>
</code>```

How I can do a reference into documentation from the method Checking to the method Calculate? I mean, if I'm watching the documentation of the method Checking, there must be a link to Calculate

答:
You can use the <see> tag. See its documentation. For example, put in the <remarks> section of the Checking function:

```<code><see cref="Calculate"/>
</code>```

and you will get a link to the documentation page of the Calculate function. Note that documentation tags work only in xml documentation comments. You can put them in comments in your code, but you will not get a link.

Body:
I am doing the HTML format documentation for my C# code and I'd like to know if it's possible to do a reference inside my own code.

For example:

public class Test{
public bool Calculate(int x){ //code }
}

public class Check{
void Checking(int y, int x, int z){
//code
bool aux = Test.Calcultate(x);
//code
}

When I'm doing the documentation like this:

 ///
 ///
 ///
 /// <param name=""></param>
 /// <returns></returns>

How I can do a reference into documentation from the method Checking to the method Calculate? I mean, if I'm watching the documentation of the method Checking, there must be a link to Calculate

Body:
You can use the <see> tag. See its documentation. For example, put in the <remarks> section of the Checking function:

<see cref="Calculate"/>

and you will get a link to the documentation page of the Calculate function. Note that documentation tags work only in xml documentation comments. You can put them in comments in your code, but you will not get a link.


问:
stop CaptureChangeMySQL when putSQL failed
I use nifi to consume mysql binlog and relay sql in another database, just like MySQL slave replication, as binlog is sequential I want to stop CaptureChangeMySQL in case when PutSQL failed, so that data in target database in slave will not be messed.

I set all queues's backpressure object threshold all to be 1, but it does not work, still execute following sql statement when PutSQL failed executing current sql.

答:
set Rollback On Failure = true.  If enabled, failed FlowFiles will stay in the input relationship without penalizing it and being processed repeatedly until it gets processed successfully or removed by other means. It is important to set adequate 'Yield Duration' to avoid retrying too frequently.

this also will affect all backpressures and theoretically capture will stop.


问:
Accessing different widget attributes in a given widget
Need to know how to access widget attributes from different attributes in kv language. I have a different application, will present a simpler version.

Not very sure of how to use widget tree id referencing or app or root. Nothing helped.

in my kv file

Widget 1  which is the root, has two widgets widget2, widget3.

widget 2 has an attribute var1

Widget 3 has a widget whose attribute var2 should change with variation in var1 value

答:
With id's.

```<code>rootWidget:
    Widget1:
        id: w1
        Widget2:
            id: w2
        Widget3:
            id: w3
    Widget4:
        id: w4
</code>```

You can access those three widgets in kv now:

```<code>root.orientation = "vertical"
w1.orientation = "vertical" "if this is a label for example"
w2.text = "if this is a label for example"
w3.property = something
w4.property = something
</code>```

Body:
With id's.

rootWidget:
    Widget1:
        id: w1
        Widget2:
            id: w2
        Widget3:
            id: w3
    Widget4:
        id: w4

You can access those three widgets in kv now:

root.orientation = "vertical"
w1.orientation = "vertical" "if this is a label for example"
w2.text = "if this is a label for example"
w3.property = something
w4.property = something


问:
How to conditional format a range of cells with a trigger word in one cell?
All of the common answers to this question do not quite cover what I am asking.

I would like to have a row at the top of my spreadsheet where in one cell (eg. A3, B3, C3 etc..) so I can type something like 'Week 1' which will then highlight/fill the colour of the column below that - So I would like to type 'Week 1' in cell B3, which then triggers a colour change in cells B4:B12, regardless of the value in those cells for example.

The trigger has to be me typing something like 'Week 1' or 'Week 2' in a particular column to then highlight the range in that same column.

答:
select target range: B4:B12

add new rule

choose "Use a formula to determine which cells to format"

the formula shall be =B3="Week 1"

Define the format

OK everything until all dialog windows are closed


问:
given incrementing ID values and a created date, create a SQL statement to find if any of the dates are out of step with the ID in oracle
Given a table like below:
created is a TIMESTAMP(6), and ID is NUMBER(20,0)

```<code>| ID | CREATED                    | ...
| 1  | 2019-11-01 14:19:28.611000 | ...
| 2  | 2019-11-01 14:19:28.680000 | ...
</code>```

Determine all the rows where CREATED dates are out of step with the incrementing ID values.

If the values are ordered by ID, is any CREATED < the previous CREATED value.

I have attempted it, and found that my version is cartesioning horribly, and not returning results. I am sure I am missing some efficiencies in the query.

As output I need the ID/CREATED of the rows that are out of step.

答:
Using ROW_NUMBER() you can generate order numbers by ID and CREATED and then match them to each other:

```<code>select *
  from (select t.*,
               row_number() over(order by id) as id_order,
               row_number() over(order by created, id) as created_order
          from t)
 where id_order <> created_order
</code>```

For created_order I sort by both created and id just in case if created contains duplicated values.

This query will return all of the affected rows. For example, for a data like this:

```<code>| ID | CREATED                    | ...
| 1  | 2019-11-01 14:19:28.611000 | ...
| 2  | 2019-11-01 14:19:28.680000 | ...
| 3  | 2019-11-01 14:19:28.612000 | ...
| 4  | 2019-11-01 14:19:28.613000 | ...
| 5  | 2019-11-01 14:19:28.681000 | ...
| 6  | 2019-11-01 14:19:28.681000 | ...
</code>```

the query will return rows 2, 3 and 4.

Body:
Given a table like below:
created is a TIMESTAMP(6), and ID is NUMBER(20,0)

| ID | CREATED                    | ...
| 1  | 2019-11-01 14:19:28.611000 | ...
| 2  | 2019-11-01 14:19:28.680000 | ...

Determine all the rows where CREATED dates are out of step with the incrementing ID values.

If the values are ordered by ID, is any CREATED < the previous CREATED value.

I have attempted it, and found that my version is cartesioning horribly, and not returning results. I am sure I am missing some efficiencies in the query.

As output I need the ID/CREATED of the rows that are out of step.

Body:
Using ROW_NUMBER() you can generate order numbers by ID and CREATED and then match them to each other:

select *
  from (select t.*,
               row_number() over(order by id) as id_order,
               row_number() over(order by created, id) as created_order
          from t)
 where id_order <> created_order

For created_order I sort by both created and id just in case if created contains duplicated values.

This query will return all of the affected rows. For example, for a data like this:

| ID | CREATED                    | ...
| 1  | 2019-11-01 14:19:28.611000 | ...
| 2  | 2019-11-01 14:19:28.680000 | ...
| 3  | 2019-11-01 14:19:28.612000 | ...
| 4  | 2019-11-01 14:19:28.613000 | ...
| 5  | 2019-11-01 14:19:28.681000 | ...
| 6  | 2019-11-01 14:19:28.681000 | ...

the query will return rows 2, 3 and 4.


问:
How to return array instead of array of object in rails json response
I have a model with the association download has_many download_links

I'm calling download_links in the downloadlink controller.

```<code>  def download_links
    @downloads = Download.all
    render json: { data:@downloads.as_json(:only=>[:id],
    include: {
        :downloadlink => {:only =>:url}
      }
    ), message:"success"}, status: :ok
  end
</code>```

the result in postman is just like this:

```<code>{
"data": [
    {
        "id": 1,
        "downloadlink": [
            {
                "url": "1920x1080.png"
            },
            {
                "url": "1366x766.png"
            },
            {
                "url": "1280x720.png"
            },
            {
                "url": "1024x768.png"
            }
        ]
    }
],
"message": "success"}
</code>```

now I want a result to be like this:

```<code>{
"data": [
    {
        "id": 1,
        "downloadlink": [
            "1920x1080.png",
            "1366x766.png",
            "1280x720.png",
            "1024x768.png"
        ]
    }
],
"message": "success"}
</code>```

答:
Considering download has_many download_links relation one way of doing it is:

```<code>def download_links
    @downloads = Download.includes(:download_links)
    render json: {
       data:@downloads.map{ |d| d.download_json }, message:"success"
    }, status: :ok
  end
</code>```

In downlad.rb model

```<code>has_many :download_links

def download_json
  self.as_json(
    only: [:id],
    methods: [:downloadlink_list]
  )
end

def downloadlink_list
  self.download_links.pluck(:url)
end
</code>```

Correct the name/association as per your naming convention.

Body:
I have a model with the association download has_many download_links

I'm calling download_links in the downloadlink controller.

  def download_links
    @downloads = Download.all
    render json: { data:@downloads.as_json(:only=>[:id],
    include: {
        :downloadlink => {:only =>:url}
      }
    ), message:"success"}, status: :ok
  end

the result in postman is just like this:

{
"data": [
    {
        "id": 1,
        "downloadlink": [
            {
                "url": "1920x1080.png"
            },
            {
                "url": "1366x766.png"
            },
            {
                "url": "1280x720.png"
            },
            {
                "url": "1024x768.png"
            }
        ]
    }
],
"message": "success"}

now I want a result to be like this:

{
"data": [
    {
        "id": 1,
        "downloadlink": [
            "1920x1080.png",
            "1366x766.png",
            "1280x720.png",
            "1024x768.png"
        ]
    }
],
"message": "success"}

Body:
Considering download has_many download_links relation one way of doing it is:

def download_links
    @downloads = Download.includes(:download_links)
    render json: {
       data:@downloads.map{ |d| d.download_json }, message:"success"
    }, status: :ok
  end

In downlad.rb model

has_many :download_links

def download_json
  self.as_json(
    only: [:id],
    methods: [:downloadlink_list]
  )
end

def downloadlink_list
  self.download_links.pluck(:url)
end

Correct the name/association as per your naming convention.


问:
UWP app to access only specific folder on user's machine
Declaring an App Capability in manifest file, we can have our UWP app access certain folders such as Pictures, Videos, Music etc.

Moreover, the broadFileSystemAccess capability allows apps to get the same access to the file system as the user who is currently running the app without any additional file-picker style prompts during runtime.

But how about even if the user has access to his/her entire system but wants a UWP app to access only a specific folder needed for the app to have read access. Can we implement such a functionality in a UWP app without using file-picker?

Why do I need that?: Our app reads files from a folder that is too big to be included inside the app and has tons of files of various types inside it. Only read-access is needed.

答:
But how about even if the user has access to his/her entire system but wants a UWP app to access only a specific folder needed for the app to have read access.

You could not create that folder only has read access capability for current user. And the folder's attribute is control on the system level. You could only create the folder and set attribute as read only for other user. And that could not be achieved(System.IO.File.SetAttributes) in uwp platform.

Yes, the folder is provided for download. But, I'm not sure if a UWP app can have an entire folder (specially a large data folder) downloaded inside it have it's code read it.

For the requirement, you could store the download in your app's LocalFolder and  there are no general size restriction on local data stored. And it only could be accessed for current app.

```<code>var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
</code>```

Certainly, you could also store the large data in the Download folder. For more info please refer this document.

Body:
But how about even if the user has access to his/her entire system but wants a UWP app to access only a specific folder needed for the app to have read access.

You could not create that folder only has read access capability for current user. And the folder's attribute is control on the system level. You could only create the folder and set attribute as read only for other user. And that could not be achieved(System.IO.File.SetAttributes) in uwp platform.

Yes, the folder is provided for download. But, I'm not sure if a UWP app can have an entire folder (specially a large data folder) downloaded inside it have it's code read it.

For the requirement, you could store the download in your app's LocalFolder and  there are no general size restriction on local data stored. And it only could be accessed for current app.

var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

Certainly, you could also store the large data in the Download folder. For more info please refer this document.


问:
merging two columns together Month and Year as MMM-YYYY
I have two columns First Column (MMM-Month) Second Column (YYYY-Year)

I would like to amalgamate these two columns to have MMM-YYYY in the next column.

tried to cast both columns into one but only could get the year

```<code>cast(convert(varchar(6),c.Year,112) as int)[Month/Year]
</code>```

答:
Assuming you're running SQL server DB, below is the code based on my understanding of the question </p>

```<code>c.CalendarMonthShortName + '-' + CAST(c.Year as varchar(4))
</code>```

Body:
I have two columns First Column (MMM-Month) Second Column (YYYY-Year)

I would like to amalgamate these two columns to have MMM-YYYY in the next column.

tried to cast both columns into one but only could get the year

cast(convert(varchar(6),c.Year,112) as int)[Month/Year]

Body:
Assuming you're running SQL server DB, below is the code based on my understanding of the question

c.CalendarMonthShortName + '-' + CAST(c.Year as varchar(4))


问:
Django 'model' object is not iterable
I have a table which shows me the employees registered. I want to generate a simple HTML page according to their DB which includes their name, id, designation, etc.

To do so, I pass an id to the view so it can get the respective user's details and show me. Everything works fine until the error occurs object is not iterable. Here is my code below.

report.html

{% if emp_item %}
 {% for some in emp_item %}
    <title> {{ some.employee_name }} Report</title>

{{ some.employee_name }}

        {{some.id}}
        {{some.Annual_leave}}
        {{some.Sick_leave}}
        {{some.allowed}}

{% endfor %}

No User

{% else %}
{% endif %}

```
<p><code>views.py</code></p>
<pre class="lang-py prettyprint-override"><code>@staff_member_required  # for admin login required
def report(request, id):
    emp_item = Employee.objects.get(id=id)
    context = {'emp_item': emp_item}
    return render(request, 'projectfiles/report.html', context)
</code>```

urls.py

    url(r'^(?i)Rejectleaves/$', views.rejected_leave_show,
        name='Reject_show'),  # user leaves

    url(r'^(?i)report/(?P<id>\d+)$', views.report,
        name='Report'),  # user Report
```
<p><code>models.py</code></p>
<pre class="lang-py prettyprint-override"><code>class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)
    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
</code>```

I want to see each individual user's data according to the process they have made.

答:
You are iterating over emp_item as an object list. But it is an object as Employee.objects.get(id=id) returns a single object rather than a queryset.

So what you need to do is remove the for-loop from the template as:

```<code>{% if emp_item %}
    <title> {{ emp_item.employee_name }} Report</title>

    <h3>{{ emp_item.employee_name }}</h3>
    ...and so on
{% else %}
<h2>No User</h2>
{% endif %}
</code>```

But if you use get while querying, there is a higher chance that you can get an exception of DoesNotExist. So it is better if you can use Employee.objects.filter(id=id) to avoid any exceptions.

The {% if emp_item %} in your template is of no use if you are querying using get.

For better use, you can use get while querying and send a message to the template if exception occurs. For example:

```<code>def report(request, id):
    try:
        emp_item = Employee.objects.get(id=id)
        return render(request, 'projectfiles/report.html', {'emp_item':emp_item})
    except Employee.DoesNotExist:
        return render(request, 'projectfiles/report.html', {'error': 'No data found.'})
</code>```

Then in template:

```<code>{% if error %}
    {{ error }}
{% else %}
    <title> {{ emp_item.employee_name }} Report</title>
    .... and so on to display other data
{% endif %}
</code>```

Title: Django 'model' object is not iterable

Body:
I have a table which shows me the employees registered. I want to generate a simple HTML page according to their DB which includes their name, id, designation, etc.

To do so, I pass an id to the view so it can get the respective user's details and show me. Everything works fine until the error occurs object is not iterable. Here is my code below.

report.html

{% if emp_item %}
 {% for some in emp_item %}
    <title> {{ some.employee_name }} Report</title>

{{ some.employee_name }}

        {{some.id}}
        {{some.Annual_leave}}
        {{some.Sick_leave}}
        {{some.allowed}}

{% endfor %}

No User

{% else %}
{% endif %}

views.py

@staff_member_required  # for admin login required
def report(request, id):
    emp_item = Employee.objects.get(id=id)
    context = {'emp_item': emp_item}
    return render(request, 'projectfiles/report.html', context)

urls.py

    url(r'^(?i)Rejectleaves/$', views.rejected_leave_show,
        name='Reject_show'),  # user leaves

    url(r'^(?i)report/(?P<id>\d+)$', views.report,
        name='Report'),  # user Report

models.py

class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)
    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)

I want to see each individual user's data according to the process they have made.

Body:
You are iterating over emp_item as an object list. But it is an object as Employee.objects.get(id=id) returns a single object rather than a queryset.

So what you need to do is remove the for-loop from the template as:

{% if emp_item %}
    <title> {{ emp_item.employee_name }} Report</title>

    <h3>{{ emp_item.employee_name }}</h3>
    ...and so on
{% else %}
<h2>No User</h2>
{% endif %}

But if you use get while querying, there is a higher chance that you can get an exception of DoesNotExist. So it is better if you can use Employee.objects.filter(id=id) to avoid any exceptions.

The {% if emp_item %} in your template is of no use if you are querying using get.

For better use, you can use get while querying and send a message to the template if exception occurs. For example:

def report(request, id):
    try:
        emp_item = Employee.objects.get(id=id)
        return render(request, 'projectfiles/report.html', {'emp_item':emp_item})
    except Employee.DoesNotExist:
        return render(request, 'projectfiles/report.html', {'error': 'No data found.'})

Then in template:

{% if error %}
    {{ error }}
{% else %}
    <title> {{ emp_item.employee_name }} Report</title>
    .... and so on to display other data
{% endif %}


问:
Python: Add contents of a csv file to a list
have a new issue with this that I could do with some help on.
Like before i am passing a csv (with comma as separator) into a list.
the first element in the list will always be an integer but the next two will be strings.
I'm trying to add a new line to the csv which will have an incremented number in the first element but I will also add hash strings in the other two elements.
It works on the first run as the file is empty but when it tries a second run I get an error

chain_list = [int(i) for i in lineList[-1].split(',')]

ValueError: invalid literal for int() with base 10: '9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794'

The first line of the file that i'm passing in contains:

1,0,9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794

My code looks like this at the minute. Not sure how to get around this?

#Check if chain_info.txt exists
CHAIN_FILE_exists = os.path.isfile(CHAIN_FILE)
#If chainfile is empty set element 0 in list to 1
if CHAIN_FILE_exists:
    if os.stat(CHAIN_FILE).st_size == 0:
        print('empty')
        fileHandle = open (CHAIN_FILE, 'a')
        fileHandle.write('1,0,0')
        fileHandle.close()
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        increment_value = 1
        print('1 chain list now is: ' + str(chain_list))
    else:
        #Read the last line of a file
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        #Take last line of file and add to a list called chain_list
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        #increment the first value in the list by 1, this will be used to determine the block number
        increment_value = (chain_list[0])
        increment_value = increment_value +1
        chain_list.remove (chain_list[0])
        chain_list.insert (0,increment_value)
        print('chain list now is: ' + str(chain_list))
        #Open file
        fileHandle = open (CHAIN_FILE, 'a')
        #Write the contents of the list to the chain file on a new line and separate with a comma
        fileHandle.write('\n' + str(chain_list[0]) + ',' + str(chain_list[1]))
        fileHandle.close()
else:
    print ('file does not exist')
```

答:
Try this.</p>

```<code>your_list = []
for i in lineList[-1].split(','):
    try:your_list.append(int(i))
    except:your_list.append(i)
</code>```

Body:
Try this.

your_list = []
for i in lineList[-1].split(','):
    try:your_list.append(int(i))
    except:your_list.append(i)


问:
How do I remove deleted databases from SSMS?
I have a similar problem to this one here : How to remove a list of accidently deleted databases from Sql Server Management Studio's tree-like list?
but the provided solution to that question hasn't helped me.

I have a number of database .mdf files that were created (and subsequently deleted from the folder) by VS's web testing.

My SSMS is now chock full of .mdf database files that no longer exist that I can't get rid of.

Current things I have tried (to no avail):

1. Refreshing the databases (at every level of the tree)

2. Right-click and deleting the databases. I receive the error:

3. Recreating the file in the given folder structure (Still doesn't recognise it)

If possible I'd like to avoid having to completely reinstall SS all over again.

答:
Open a query window on the master database, then:

```<code>Select * from sys.databases where state_desc <> 'ONLINE'
</code>```

Will give you a list of databases.

Then for each database in the name column of the query result, you can do:

```<code>drop database mydatabasename
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Open a query window on the master database, then:

Select * from sys.databases where state_desc <> 'ONLINE'

Will give you a list of databases.

Then for each database in the name column of the query result, you can do:

drop database mydatabasename


问:
Exception while starting Weblogic Managed Server
I tried to start Weblogic managed server and I'm getting the exception below:

```<code>Apr 11, 2011 10:08:16 PM PDT> <Error> <oracle.bam.adc.dse.common.DataSourceFactory> <BEA-000000> <[12] Exception occurred in method DataSourceFactory.getDataSource(jdbc/oracle/bam/adc)
Exception: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
  at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
  at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
  at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
  at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
  at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
  at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:254)
  at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:411)
  at javax.naming.InitialContext.lookup(InitialContext.java:392)
  at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:132)
  at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:105)
  at oracle.bam.adc.dse.common.StorageEngineFactory.startup(StorageEngineFactory.java:109)
  at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:234)
  at oracle.bam.adc.kernel.server.ADCService.startService(ADCService.java:83)
  at oracle.bam.server.BamServer$ServiceEntry$1.run(BamServer.java:1716)
  at java.security.AccessController.doPrivileged(Native Method)
  at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
  at oracle.security.jps.internal.jaas.AccActionExecutor.execute(AccActionExecutor.java:47)
  at oracle.security.jps.internal.jaas.CascadeActionExecutor$SubjectPrivilegedExceptionAction.run(CascadeActionExecutor.java:79)
  at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
  at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
  at weblogic.security.Security.runAs(Security.java:61)
  at oracle.security.jps.wls.jaas.WlsActionExecutor.execute(WlsActionExecutor.java:48)
  at oracle.security.jps.internal.jaas.CascadeActionExecutor.execute(CascadeActionExecutor.java:52)
  at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:153)
  at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:121)
  at oracle.bam.server.BamServer$ServiceEntry.start(BamServer.java:1722)
  at oracle.bam.server.BamServer.init(BamServer.java:272)
  at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:283)
  at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
  at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
  at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:64)
  at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:58)
  at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:48)
  at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:539)
  at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1985)
  at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:1959)
  at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1878)
  at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3153)
  at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1508)
  at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:482)
  at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
  at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
  at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
  at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
  at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:247)
  at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
  at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
  at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
  at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:27)
  at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:636)
  at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
  at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:205)
  at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:58)
  at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:161)
  at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:79)
  at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:184)
  at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:361)
  at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:51)
  at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:200)
  at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:30)
  at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:261)
  at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:246)
  at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:169)
  at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:123)
  at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:180)
  at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:96)
  at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
  at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
  at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)
>
<Apr 11, 2011 10:08:16 PM PDT> <Error> <HTTP> <BEA-101216> <Servlet: "BamServer" failed to preload on startup in Web application: "/oracle/bam".
java.lang.Exception: BAM data store server failed to start.
        at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:323)
        at oracle.bam.adc.kernel.server.ADCService.startService(ADCService.java:83)
        at oracle.bam.server.BamServer$ServiceEntry$1.run(BamServer.java:1716)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
        Truncated. see log file for complete stacktrace
Caused By: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
        at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
        at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
        at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
        Truncated. see log file for complete stacktrace
>
<Apr 11, 2011 10:08:16 PM PDT> <Error> <Deployer> <BEA-149231> <Unable to set the activation state to true for the application 'oracle-bam [Version=11.1.1]'.
weblogic.application.ModuleException: [HTTP:101216]Servlet: "BamServer" failed to preload on startup in Web application: "/oracle/bam".
java.lang.Exception: BAM data store server failed to start.
        at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:323)
        at oracle.bam.adc.kernel.server.ADCService.startService(ADCService.java:83)
        at oracle.bam.server.BamServer$ServiceEntry$1.run(BamServer.java:1716)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
        at oracle.security.jps.internal.jaas.AccActionExecutor.execute(AccActionExecutor.java:47)
        at oracle.security.jps.internal.jaas.CascadeActionExecutor$SubjectPrivilegedExceptionAction.run(CascadeActionExecutor.java:79)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
        at weblogic.security.Security.runAs(Security.java:61)
        at oracle.security.jps.wls.jaas.WlsActionExecutor.execute(WlsActionExecutor.java:48)
        at oracle.security.jps.internal.jaas.CascadeActionExecutor.execute(CascadeActionExecutor.java:52)
        at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:153)
        at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:121)
        at oracle.bam.server.BamServer$ServiceEntry.start(BamServer.java:1722)
        at oracle.bam.server.BamServer.init(BamServer.java:272)
        at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:283)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
        at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:64)
        at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:58)
        at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:48)
        at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:539)
        at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1985)
        at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:1959)
        at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1878)
        at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3153)
        at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1508)
        at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:482)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
        at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:247)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:27)
        at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:636)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:205)
        at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:58)
        at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:161)
        at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:79)
        at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:184)
        at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:361)
        at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:51)
        at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:200)
        at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:30)
        at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:261)
        at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:246)
        at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:169)
        at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:123)
        at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:180)
        at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:96)
        at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
        at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)
Caused by: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
        at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
        at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
        at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
        at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:254)
        at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:411)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:132)
        at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:105)
        at oracle.bam.adc.dse.common.StorageEngineFactory.startup(StorageEngineFactory.java:109)
        at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:234)
        ... 57 more

        at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1510)
        at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:482)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        Truncated. see log file for complete stacktrace
Caused By: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
        at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
        at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
        at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
        Truncated. see log file for complete stacktrace
>
<Apr 11, 2011 10:08:16 PM PDT> <Notice> <Log Management> <BEA-170027> <The Server has established connection with the Domain level Diagnostic Service successfully.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to ADMIN>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to RESUMING>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <Server> <BEA-002613> <Channel "Default[1]" is now listening on 127.0.0.1:9001 for protocols iiop, iiop, t3, t3, ldap, ldap, snmp, snmp, http, http.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <Server> <BEA-002613> <Channel "Default[2]" is now listening on 0:0:0:0:0:0:0:1:9001 for protocols iiop, t3, ldap, snmp, http.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <Server> <BEA-002613> <Channel "Default" is now listening on 10.152.105.211:9001 for protocols iiop, t3, ldap, snmp, http.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <WebLogicServer> <BEA-000332> <Started WebLogic Managed Server "ManagedServer" for domain "bpms_poc_domain" running in Development Mode>
<Apr 11, 2011 10:08:30 PM PDT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to RUNNING>
<Apr 11, 2011 10:08:30 PM PDT> <Notice> <WebLogicServer> <BEA-000360> <Server started in RUNNING mode>
</code>```

Due to this exception, my Oracle-BAM service doesn't start. I need to start the same.

Can someone give me pointers?

Regards,
Arvind K

答: Also, make sure the JDBC datasource is targeted to the managed server or cluster where BAM is targeted.  The Admin Console will let you get away with configuring a datasource but not targeting it to any servers or clusters.</p>

Body:
I tried to start Weblogic managed server and I'm getting the exception below:

Apr 11, 2011 10:08:16 PM PDT> <Error> <oracle.bam.adc.dse.common.DataSourceFactory> <BEA-000000> <[12] Exception occurred in method DataSourceFactory.getDataSource(jdbc/oracle/bam/adc)
Exception: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
  at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
  at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
  at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
  at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
  at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
  at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:254)
  at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:411)
  at javax.naming.InitialContext.lookup(InitialContext.java:392)
  at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:132)
  at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:105)
  at oracle.bam.adc.dse.common.StorageEngineFactory.startup(StorageEngineFactory.java:109)
  at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:234)
  at oracle.bam.adc.kernel.server.ADCService.startService(ADCService.java:83)
  at oracle.bam.server.BamServer$ServiceEntry$1.run(BamServer.java:1716)
  at java.security.AccessController.doPrivileged(Native Method)
  at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
  at oracle.security.jps.internal.jaas.AccActionExecutor.execute(AccActionExecutor.java:47)
  at oracle.security.jps.internal.jaas.CascadeActionExecutor$SubjectPrivilegedExceptionAction.run(CascadeActionExecutor.java:79)
  at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
  at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
  at weblogic.security.Security.runAs(Security.java:61)
  at oracle.security.jps.wls.jaas.WlsActionExecutor.execute(WlsActionExecutor.java:48)
  at oracle.security.jps.internal.jaas.CascadeActionExecutor.execute(CascadeActionExecutor.java:52)
  at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:153)
  at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:121)
  at oracle.bam.server.BamServer$ServiceEntry.start(BamServer.java:1722)
  at oracle.bam.server.BamServer.init(BamServer.java:272)
  at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:283)
  at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
  at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
  at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:64)
  at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:58)
  at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:48)
  at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:539)
  at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1985)
  at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:1959)
  at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1878)
  at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3153)
  at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1508)
  at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:482)
  at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
  at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
  at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
  at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
  at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:247)
  at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
  at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
  at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
  at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:27)
  at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:636)
  at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
  at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:205)
  at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:58)
  at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:161)
  at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:79)
  at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:184)
  at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:361)
  at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:51)
  at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:200)
  at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:30)
  at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:261)
  at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:246)
  at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:169)
  at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:123)
  at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:180)
  at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:96)
  at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
  at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
  at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)
>
<Apr 11, 2011 10:08:16 PM PDT> <Error> <HTTP> <BEA-101216> <Servlet: "BamServer" failed to preload on startup in Web application: "/oracle/bam".
java.lang.Exception: BAM data store server failed to start.
        at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:323)
        at oracle.bam.adc.kernel.server.ADCService.startService(ADCService.java:83)
        at oracle.bam.server.BamServer$ServiceEntry$1.run(BamServer.java:1716)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
        Truncated. see log file for complete stacktrace
Caused By: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
        at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
        at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
        at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
        Truncated. see log file for complete stacktrace
>
<Apr 11, 2011 10:08:16 PM PDT> <Error> <Deployer> <BEA-149231> <Unable to set the activation state to true for the application 'oracle-bam [Version=11.1.1]'.
weblogic.application.ModuleException: [HTTP:101216]Servlet: "BamServer" failed to preload on startup in Web application: "/oracle/bam".
java.lang.Exception: BAM data store server failed to start.
        at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:323)
        at oracle.bam.adc.kernel.server.ADCService.startService(ADCService.java:83)
        at oracle.bam.server.BamServer$ServiceEntry$1.run(BamServer.java:1716)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
        at oracle.security.jps.internal.jaas.AccActionExecutor.execute(AccActionExecutor.java:47)
        at oracle.security.jps.internal.jaas.CascadeActionExecutor$SubjectPrivilegedExceptionAction.run(CascadeActionExecutor.java:79)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
        at weblogic.security.Security.runAs(Security.java:61)
        at oracle.security.jps.wls.jaas.WlsActionExecutor.execute(WlsActionExecutor.java:48)
        at oracle.security.jps.internal.jaas.CascadeActionExecutor.execute(CascadeActionExecutor.java:52)
        at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:153)
        at oracle.bam.common.security.authentication.BamPrivilegedExceptionAction.execute(BamPrivilegedExceptionAction.java:121)
        at oracle.bam.server.BamServer$ServiceEntry.start(BamServer.java:1722)
        at oracle.bam.server.BamServer.init(BamServer.java:272)
        at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:283)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
        at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:64)
        at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:58)
        at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:48)
        at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:539)
        at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1985)
        at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:1959)
        at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1878)
        at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3153)
        at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1508)
        at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:482)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
        at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:247)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:27)
        at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:636)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:205)
        at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:58)
        at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:161)
        at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:79)
        at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:184)
        at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:361)
        at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:51)
        at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:200)
        at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:30)
        at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:261)
        at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:246)
        at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:169)
        at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:123)
        at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:180)
        at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:96)
        at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
        at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)
Caused by: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
        at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
        at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
        at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
        at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:254)
        at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:411)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:132)
        at oracle.bam.adc.dse.common.DataSourceFactory.getDataSource(DataSourceFactory.java:105)
        at oracle.bam.adc.dse.common.StorageEngineFactory.startup(StorageEngineFactory.java:109)
        at oracle.bam.adc.kernel.server.DataStoreServer.startup(DataStoreServer.java:234)
        ... 57 more

        at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1510)
        at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:482)
        at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
        at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
        Truncated. see log file for complete stacktrace
Caused By: javax.naming.NameNotFoundException: While trying to lookup 'jdbc.oracle.bam/adc' didn't find subcontext 'oracle'. Resolved 'jdbc'; remaining name 'oracle/bam/adc'
        at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
        at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:247)
        at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
        at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
        Truncated. see log file for complete stacktrace
>
<Apr 11, 2011 10:08:16 PM PDT> <Notice> <Log Management> <BEA-170027> <The Server has established connection with the Domain level Diagnostic Service successfully.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to ADMIN>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to RESUMING>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <Server> <BEA-002613> <Channel "Default[1]" is now listening on 127.0.0.1:9001 for protocols iiop, iiop, t3, t3, ldap, ldap, snmp, snmp, http, http.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <Server> <BEA-002613> <Channel "Default[2]" is now listening on 0:0:0:0:0:0:0:1:9001 for protocols iiop, t3, ldap, snmp, http.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <Server> <BEA-002613> <Channel "Default" is now listening on 10.152.105.211:9001 for protocols iiop, t3, ldap, snmp, http.>
<Apr 11, 2011 10:08:17 PM PDT> <Notice> <WebLogicServer> <BEA-000332> <Started WebLogic Managed Server "ManagedServer" for domain "bpms_poc_domain" running in Development Mode>
<Apr 11, 2011 10:08:30 PM PDT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to RUNNING>
<Apr 11, 2011 10:08:30 PM PDT> <Notice> <WebLogicServer> <BEA-000360> <Server started in RUNNING mode>

Due to this exception, my Oracle-BAM service doesn't start. I need to start the same.

Can someone give me pointers?

Regards,
Arvind K


问:
How to Remove Blank Frames in RecordRTC
I am stuck on some point. Please help me to figure it out.

When any peer connection (In Video Conferencing) is disconnected and I reconnect them, then a blank frame is added in Recording, I am using RecordRTC and testing it in Chrome 74.0
I think it is happening because When Peer Connection is disconnected then the RecordRTC already have the previous connected data Video Elements, And I just want to remove those blank Elements.

I am attaching the screenshot of Recorded Video please help me to figure it out.

Here in this image, you can see we There are 5 Screens, In which 2, 3, 4 are blank,
Because the Peer Connection is closed and reconnected.
So I want these 2 Working Screens(1, 5) [ 1= Local Stream, 5 = Remote Stream] in my blob or we can say which Recording.
Please help me to figure it out this issue.

Thank you

答:
Please use this solution,
We just need to give the condition to drow the first and last element on the canvas.
Update this code in function drawVideosToCanvas() .</p>

```<code>var videosLength = videos.length;
if(videosLength > 2){
    videosLength = 2;
}

var fullcanvas = false;
var remaining = [];

var length = videos.length;
videos.forEach(function(video,idx) {
    if (!video.stream) {
        video.stream = {};
    }
    if (video.stream.fullcanvas) {
        fullcanvas = video;
    } else {
        if(idx==0 || idx == (length-1)){
            if(video.stream.active)
                remaining.push(video);
        }
    }
});
</code>```

Title: How to Remove Blank Frames in RecordRTC

Body:
Please use this solution,
We just need to give the condition to drow the first and last element on the canvas.
Update this code in function drawVideosToCanvas() .

var videosLength = videos.length;
if(videosLength > 2){
    videosLength = 2;
}

var fullcanvas = false;
var remaining = [];

var length = videos.length;
videos.forEach(function(video,idx) {
    if (!video.stream) {
        video.stream = {};
    }
    if (video.stream.fullcanvas) {
        fullcanvas = video;
    } else {
        if(idx==0 || idx == (length-1)){
            if(video.stream.active)
                remaining.push(video);
        }
    }
});


问:
Python,ML error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
I am trying to categorized "DistAreaID" column of my dataset [cf_all] by grouping to its mean wrt Y.

Code:

```<code>round(cf_all.groupby("DistArea_ID")["Counterfeit_Sales"].mean(), 2)

for col in range(len(cf_all)):
    if cf_all["DistArea_ID"][col] in \
        ["Area013", "Area017", "Area018", "Area035", "Area045", "Area046", "Area049"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_2000"
    if cf_all["DistArea_ID"][col] in ["Area010", "Area019"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_400"
    if cf_all["DistArea_ID"][col] in ["Area027"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_3000"
</code>```

Error:

The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().
```

Can someone please guide me with this error?

答:
I suggest use Series.replace or Series.map with Series.fillna:

```<code>d = {"DistArea_2000": ["Area013", "Area017", "Area018",
                       "Area035", "Area045", "Area046", "Area049"],
     "DistArea_400": ["Area010", "Area019"],
     "DistArea_3000":["Area027"]}

#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}

cf_all["DistArea_ID"] = cf_all["DistArea_ID"].replace(d1)

#obviously faster
#cf_all["DistArea_ID"] = cf_all["DistArea_ID"].map(d1).fillna(cf_all["DistArea_ID"])
</code>```

Body:
I am trying to categorized "DistAreaID" column of my dataset [cf_all] by grouping to its mean wrt Y.

Code:

round(cf_all.groupby("DistArea_ID")["Counterfeit_Sales"].mean(), 2)

for col in range(len(cf_all)):
    if cf_all["DistArea_ID"][col] in \
        ["Area013", "Area017", "Area018", "Area035", "Area045", "Area046", "Area049"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_2000"
    if cf_all["DistArea_ID"][col] in ["Area010", "Area019"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_400"
    if cf_all["DistArea_ID"][col] in ["Area027"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_3000"

Error:

The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().

Can someone please guide me with this error?

Body:
I suggest use Series.replace or Series.map with Series.fillna:

d = {"DistArea_2000": ["Area013", "Area017", "Area018",
                       "Area035", "Area045", "Area046", "Area049"],
     "DistArea_400": ["Area010", "Area019"],
     "DistArea_3000":["Area027"]}

#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}

cf_all["DistArea_ID"] = cf_all["DistArea_ID"].replace(d1)

#obviously faster
#cf_all["DistArea_ID"] = cf_all["DistArea_ID"].map(d1).fillna(cf_all["DistArea_ID"])


问:
Selecting Only The Latest Version Of A Field
I have a table schema with ID, Title, Date

and data looks something like this:

```<code>1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000
</code>```

I need help with sql to give me the latest date of each title.
So the output for the above data is

```<code>2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
</code>```

答: Look at Max and group by in Books online</p>

Body:
I have a table schema with ID, Title, Date

and data looks something like this:

1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000

I need help with sql to give me the latest date of each title.
So the output for the above data is

2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633


问:
Pass value to a private property
I have a couple of private properties defined like so..

```<code>private var tableConfig : TableViewConfig<Company, CompanyCell>?

private var tabledata = [Company]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }
</code>```

Now there are 2 other properties defined like so...

```<code>  var model: Model?
  var companyCell: TableviewCell?
</code>```

Now, if get the value in model as Industry and the value in companyCell as IndustryCell, how can I update these values to private var tableConfig : TableViewConfig.... and private var tabledata = [Company]().... so that they will ultimately have the values like so..

```<code>private var tableConfig : TableViewConfig<Industry, IndustryCell>?

private var tabledata = [Industry]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }
</code>```

答:
As the attribute private implies properties and functions declared as private can only be accessed within the scope they are declared.

You have two options:

Change the access control to fileprivate (if the caller is in the same file) or internal or lower restriction.

Add an internal or lower restriction computed property or method in the scope of the private property to set it.

Title: Pass value to a private property

Body:
I have a couple of private properties defined like so..

private var tableConfig : TableViewConfig<Company, CompanyCell>?

private var tabledata = [Company]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }

Now there are 2 other properties defined like so...

  var model: Model?
  var companyCell: TableviewCell?

Now, if get the value in model as Industry and the value in companyCell as IndustryCell, how can I update these values to private var tableConfig : TableViewConfig.... and private var tabledata = [Company]().... so that they will ultimately have the values like so..

private var tableConfig : TableViewConfig<Industry, IndustryCell>?

private var tabledata = [Industry]() {
    didSet {
      tableConfig?.items = tabledata
    }
  }


答:
```<code>list1 = []
for ele in line:
   list1.append(ele[0])

list2 = []
for ele in line:
   list2.append(ele[0])

list3 = []
for ele in line:
   list3.append(ele[0])

your_list = []
your_list.append(list1[-1])
your_list.append(list2[-1])
your_list.append(list3[-1])
</code>```

Title: Python: Add contents of a csv file to a list

Body:
have a new issue with this that I could do with some help on.
Like before i am passing a csv (with comma as separator) into a list.
the first element in the list will always be an integer but the next two will be strings.
I'm trying to add a new line to the csv which will have an incremented number in the first element but I will also add hash strings in the other two elements.
It works on the first run as the file is empty but when it tries a second run I get an error

chain_list = [int(i) for i in lineList[-1].split(',')]

ValueError: invalid literal for int() with base 10: '9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794'

The first line of the file that i'm passing in contains:

1,0,9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794

My code looks like this at the minute. Not sure how to get around this?

#Check if chain_info.txt exists
CHAIN_FILE_exists = os.path.isfile(CHAIN_FILE)
#If chainfile is empty set element 0 in list to 1
if CHAIN_FILE_exists:
    if os.stat(CHAIN_FILE).st_size == 0:
        print('empty')
        fileHandle = open (CHAIN_FILE, 'a')
        fileHandle.write('1,0,0')
        fileHandle.close()
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        increment_value = 1
        print('1 chain list now is: ' + str(chain_list))
    else:
        #Read the last line of a file
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        #Take last line of file and add to a list called chain_list
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        #increment the first value in the list by 1, this will be used to determine the block number
        increment_value = (chain_list[0])
        increment_value = increment_value +1
        chain_list.remove (chain_list[0])
        chain_list.insert (0,increment_value)
        print('chain list now is: ' + str(chain_list))
        #Open file
        fileHandle = open (CHAIN_FILE, 'a')
        #Write the contents of the list to the chain file on a new line and separate with a comma
        fileHandle.write('\n' + str(chain_list[0]) + ',' + str(chain_list[1]))
        fileHandle.close()
else:
    print ('file does not exist')


问:
get array parameter from what user type in browser
how to get array parameter from what user type in browser with codeigniter3

this is my controller

```<code>class header extends CI_Controller{
    public function index(){

        $this->load->model('header_model');
        $hasil = $this->header_model->getData();
        var_dump($hasil);

    }
}
</code>```

and this is my model

```<code>class header_model extends CI_Model{
    public function getData(){

        $array = ["000118","000112","000117"];
        $this->db->select('NOMOR_DAFTAR, TANGGAL_DAFTAR');
        $this->db->where_in('NOMOR_DAFTAR',$array);
        return $this->db->get('tpb_header')->result_array();
    }
}
</code>```

$array above i want to get from what user type in browser

答:
You can use header(‘content-type application/json’) in codeigniter to return json array.

For example:

```<code>class header extends CI_Controller{
    public function index(){
        header("Content-type:application/json");
        $this->load->model('header_model');
        $hasil = $this->header_model->getData();
        //var_dump($hasil);
        echo json_encode($hasil);

    }
}
</code>```

Body:
how to get array parameter from what user type in browser with codeigniter3

this is my controller

class header extends CI_Controller{
    public function index(){

        $this->load->model('header_model');
        $hasil = $this->header_model->getData();
        var_dump($hasil);

    }
}

and this is my model

class header_model extends CI_Model{
    public function getData(){

        $array = ["000118","000112","000117"];
        $this->db->select('NOMOR_DAFTAR, TANGGAL_DAFTAR');
        $this->db->where_in('NOMOR_DAFTAR',$array);
        return $this->db->get('tpb_header')->result_array();
    }
}

$array above i want to get from what user type in browser

Body:
You can use header(‘content-type application/json’) in codeigniter to return json array.

For example:

class header extends CI_Controller{
    public function index(){
        header("Content-type:application/json");
        $this->load->model('header_model');
        $hasil = $this->header_model->getData();
        //var_dump($hasil);
        echo json_encode($hasil);

    }
}


问:
Sequelize: how to find a Max element
I am issue while forming a sequelize query :

My Native query is something.

```<code>       SELECT max(id),vehicleID FROM `vehicles` WHERE `vehicles`.`vsr_id`=342;
</code>```

For this i am trying to build Code which something like this.

```<code>    Vehicle.find({ where: { 'vsr_id': 342 }, order : [sequelize.fn('max', sequelize.col('id'))] }).success(function(vehicles){
       console.log("Something i got" + vehicles)
        })
</code>```

It throwing an error : sequelize Object [object Object] has no method 'col'
and i refered from this URL:
           http://sequelizejs.com/docs/latest/models#block-34-line-8

Any code missings from my end. Please help me out

FYI: Ignore semicolons

答:
```<code> Rate.findAll({
    where:{productId:pid},
    attributes:[[sequelize.fn('max', sequelize.col('rating')),'max']]
})
</code>```

Title: Sequelize: how to find a Max element

Body:
I am issue while forming a sequelize query :

My Native query is something.

       SELECT max(id),vehicleID FROM `vehicles` WHERE `vehicles`.`vsr_id`=342;

For this i am trying to build Code which something like this.

    Vehicle.find({ where: { 'vsr_id': 342 }, order : [sequelize.fn('max', sequelize.col('id'))] }).success(function(vehicles){
       console.log("Something i got" + vehicles)
        })

It throwing an error : sequelize Object [object Object] has no method 'col'
and i refered from this URL:
           http://sequelizejs.com/docs/latest/models#block-34-line-8

Any code missings from my end. Please help me out

FYI: Ignore semicolons


答:
Try the following:</p>

```<code>month + '-' + convert(varchar(6),year,112)[Month/Year]
</code>```

Title: merging two columns together Month and Year as MMM-YYYY

Body:
Try the following:

month + '-' + convert(varchar(6),year,112)[Month/Year]


问:
Encrypting config files for deployment
I have a windows service that reads from app.config.

I want some settings to be encrypted, however, I don't want to use the ProtectedConfigurationProvider classes provided in .NET because they encrypt files based on the machine they are running on using DPAPI.

What I wanted was a way for our administrator to deploy the config file already encrypted to many machines and have each machine decrypt them when needed.

I don't want to hardcode a password into the assembly either so I'm not sure how I can go about this.

答:
One possible way to do this would be to include the decryption key at the beginning of the file, and the key has been reprocessed in some fashion that you can determine from the key.  One possibility would be to pick, like, say sixteen different things, 0 being, say, rotate the first two bytes to the end; 1 being rotate the last two bytes to the front; 2 being add 1 to every byte; and so on for 14 additional functions.  Now add this value in front of the key as the "reprocess flag".

The first byte of the key would then be a branch table to one of 16 different routines to say what to do with the key.  Note that the reprocess flag doesn't have to be the first byte, it can be any byte in the key as long as you remember to throw that byte away when handling the key.

Then you process the key according to whatever decryption algorithm you would use.

Now, given this reprocess flag - especially if the entire key was in hexadecimal - would require someone follow the logic to determine which of the 16 different functions your code executed, then figure out the decryption method.  It's not going to stop everyone but it will probably do a fairly good job driving away all but the most determined.

OwnerDisplayName: Sir Psycho

ContentLicense: CC BY-SA 2.5

Title: Encrypting config files for deployment

LastEditorDisplayName: Steven A. Lowe

OwnerDisplayName: Paul Robinson


问:
How to make serialization run in parallel
guys,
If I have a tree structure, and I want to serialize the tree and sub nodes. how to do the serialization for each nodes in parallel.
If I assign each node with a independent task, the output data will be disordered.
Is there some pattern for concurrent serialization?

Edit: If the structure is not a tree, but a DAG? How to handle this structure? How to serialize DAG and make the serialization to be concurrent.

答:
This is an ideal problem for recursive parallelism, or Fork/Join parallelism.

At each level in the tree, spawn a task to serialize each of the nodes to a temporary buffer, then wait for those tasks and join the buffers. e.g. (assuming a binary tree)

```<code>std::string serialize_tree(tree t)
{
     std::future<std::string> left_rep=std::async(serialize_tree,tree.left_node);
     std::future<std::string> right_rep=std::async(serialize_tree,tree.right_node);
     return left_rep.get()+right_rep.get(); // plus any further formatting
}
</code>```

Obviously, you'll want to check for empty trees or leaf nodes, or whatever, but this should give you an idea.

EDIT: To handle a DAG, you can pass in the futures associated with the dependencies to the async calls, so each task explicitly waits for the tasks it requires to have finished.

Body:
This is an ideal problem for recursive parallelism, or Fork/Join parallelism.

At each level in the tree, spawn a task to serialize each of the nodes to a temporary buffer, then wait for those tasks and join the buffers. e.g. (assuming a binary tree)

std::string serialize_tree(tree t)
{
     std::future<std::string> left_rep=std::async(serialize_tree,tree.left_node);
     std::future<std::string> right_rep=std::async(serialize_tree,tree.right_node);
     return left_rep.get()+right_rep.get(); // plus any further formatting
}

Obviously, you'll want to check for empty trees or leaf nodes, or whatever, but this should give you an idea.

EDIT: To handle a DAG, you can pass in the futures associated with the dependencies to the async calls, so each task explicitly waits for the tasks it requires to have finished.


问:
uses-permission WRITE_EXTERNAL_STORAGE in ionic3
I am just stuck.

I wanted to Download MP3 file to my app.

I am able to download the same in browser while working on it,

As we know, there we need to provide WRITE_EXTERNAL_STORAGE permission.
To do so what I did is as below-

Opened platforms/android/AndroidManifest.xml

added

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

But its not working for me.
Let me share my Machine Setup-

cli packages: (/usr/local/lib/node_modules)

```<code>@ionic/cli-utils  : 1.12.0
ionic (Ionic CLI) : 3.12.0
</code>```

global packages:

```<code>cordova (Cordova CLI) : 7.0.1
</code>```

local packages:

```<code>@ionic/app-scripts : 2.1.4
Cordova Platforms  : android 6.2.3 ios 4.4.0
Ionic Framework    : ionic-angular 3.6.0
</code>```

I try for this
https://ionicframework.com/docs/native/android-permissions/

Also try  https://github.com/dpa99c/cordova-custom-config-example/blob/master/config.xml

There is a way for cordova and another way to provide permissions
How do I add "uses-permissions" tags to AndroidManifest.xml for a Cordova project?
I am unable to write it.

Help me plz...

答:
open your ts file and write this code

```<code>checkPermissions(){
        this.androidPermissions.requestPermissions(
           [
             this.androidPermissions.PERMISSION.CAMERA,
             this.androidPermissions.PERMISSION.GET_ACCOUNTS,
             this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE,
             this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE
           ]
        );
    }
</code>```

this resolved my problem.

Body:
I am just stuck.

I wanted to Download MP3 file to my app.

I am able to download the same in browser while working on it,

As we know, there we need to provide WRITE_EXTERNAL_STORAGE permission.
To do so what I did is as below-

Opened platforms/android/AndroidManifest.xml

added

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

But its not working for me.
Let me share my Machine Setup-

cli packages: (/usr/local/lib/node_modules)

@ionic/cli-utils  : 1.12.0
ionic (Ionic CLI) : 3.12.0

global packages:

cordova (Cordova CLI) : 7.0.1

local packages:

@ionic/app-scripts : 2.1.4
Cordova Platforms  : android 6.2.3 ios 4.4.0
Ionic Framework    : ionic-angular 3.6.0

I try for this
https://ionicframework.com/docs/native/android-permissions/

Also try  https://github.com/dpa99c/cordova-custom-config-example/blob/master/config.xml

There is a way for cordova and another way to provide permissions
How do I add "uses-permissions" tags to AndroidManifest.xml for a Cordova project?
I am unable to write it.

Help me plz...

Body:
open your ts file and write this code

checkPermissions(){
        this.androidPermissions.requestPermissions(
           [
             this.androidPermissions.PERMISSION.CAMERA,
             this.androidPermissions.PERMISSION.GET_ACCOUNTS,
             this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE,
             this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE
           ]
        );
    }

this resolved my problem.


问:
how to create short code to display particular testimonial using its post id?
i have created custom post type for testimonials in wordpress.i have added 89 testimonials and wants to display 2 which i wants to displany in home page .
so wanted to created shortcode which will display testimonials according to their Post ID.
can anyone please tell me the code for shortcode.

Below i am showing code i had written to create custom post type for testimonial . Pls tell me the code to create shortcode like this:-[testimonial posts_per_page="5" testimonial_id="123,145"]

```<code>function custom_post_testimonial_type() {

// Set UI labels for Custom Post Type
$labels = array(
    'name'=> _x( 'Testimonials', 'Post Type General Name', 'walker_theme' ),
 'singular_name'=> _x( 'Testimonial', 'Post Type Singular Name', 'walker_theme' ),
   'menu_name'=> __( 'Testimonials', 'walker_theme' ),
'parent_item_colon' => __( 'Testimonial', 'walker_theme' ),
'all_items'  => __( 'All Testimonials', 'walker_theme' ),
'view_item' => __( 'View Testimonial', 'walker_theme' ),
'add_new_item' => __( 'Add New Testimonial','walker_theme' ),
'add_new'  => __( 'Add New', 'walker_theme' ),
'edit_item'  => __( 'Edit Testimonial','walker_theme' ),
'update_item' => __( 'Update Testimonial','walker_theme' ),
'search_items' => __( 'Search Testimonial', 'walker_theme' ),
'not_found'           => __( 'Not Found', 'walker_theme' ),
'not_found_in_trash'  => __( 'Not found in Trash','walker_theme' ),
);

  // Set other options for Custom Post Type

$args = array(
'label'               => __( 'testimonials', 'walker_theme' ),
'description'         => __( 'Home page testimonials', 'walker_theme' ),
'labels'              => $labels,
    // Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'author','thumbnail', 'tags'),
    // You can associate this CPT with a taxonomy or custom
      taxonomy.
    'taxonomies'          => array( 'genres', 'post_tag' ),
    /* A hierarchical CPT is like Pages and can have
    * Parent and child items. A non-hierarchical CPT
    * is like Posts.
    */
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page',
);

// Registering your Custom Post Type
register_post_type( 'testimonials', $args );

    }

    add_action( 'init', 'custom_post_testimonial_type', 0 );
</code>```

答:
Hi let's add this code in the theme's functions.php file.

```<code>add_shortcode( 'testimonial', 'testimonial_shortcode_callback' );

function testimonial_shortcode_callback( $atts ) {
ob_start();

extract( shortcode_atts( array(
    'posts_per_page' => 5,
    'testimonial_id' => '',
), $atts ) );

// define query parameters based on attributes
$options = array(
    'post_type'      => 'testimonials',
    'posts_per_page' => $posts_per_page,
);

if ( ! empty( $testimonial_id ) ) {
    $options['post__in'] = array_map( 'trim', explode( ',', $testimonial_id ) );
}

$testimonial_query = new WP_Query( $options );
// run the loop based on the query
if ( $testimonial_query->have_posts() ) :
    ?>
    <ul class="testimonial-listing">
        <?php
        while ( $testimonial_query->have_posts() ) : $testimonial_query->the_post();
            ?>
            <li id="testimonial-<?php the_ID(); ?>">
                <?php the_content(); ?>
            </li>
        <?php
        endwhile;
        wp_reset_postdata();
        ?>
    </ul>
    <?php
    $testimonial_output = ob_get_clean();

    return $testimonial_output;
endif;
}
</code>```

Than use this shortcode as a example [testimonial posts_per_page="2" testimonial_id="123,145"]

Body:
i have created custom post type for testimonials in wordpress.i have added 89 testimonials and wants to display 2 which i wants to displany in home page .
so wanted to created shortcode which will display testimonials according to their Post ID.
can anyone please tell me the code for shortcode.

Below i am showing code i had written to create custom post type for testimonial . Pls tell me the code to create shortcode like this:-[testimonial posts_per_page="5" testimonial_id="123,145"]

function custom_post_testimonial_type() {

// Set UI labels for Custom Post Type
$labels = array(
    'name'=> _x( 'Testimonials', 'Post Type General Name', 'walker_theme' ),
 'singular_name'=> _x( 'Testimonial', 'Post Type Singular Name', 'walker_theme' ),
   'menu_name'=> __( 'Testimonials', 'walker_theme' ),
'parent_item_colon' => __( 'Testimonial', 'walker_theme' ),
'all_items'  => __( 'All Testimonials', 'walker_theme' ),
'view_item' => __( 'View Testimonial', 'walker_theme' ),
'add_new_item' => __( 'Add New Testimonial','walker_theme' ),
'add_new'  => __( 'Add New', 'walker_theme' ),
'edit_item'  => __( 'Edit Testimonial','walker_theme' ),
'update_item' => __( 'Update Testimonial','walker_theme' ),
'search_items' => __( 'Search Testimonial', 'walker_theme' ),
'not_found'           => __( 'Not Found', 'walker_theme' ),
'not_found_in_trash'  => __( 'Not found in Trash','walker_theme' ),
);

  // Set other options for Custom Post Type

$args = array(
'label'               => __( 'testimonials', 'walker_theme' ),
'description'         => __( 'Home page testimonials', 'walker_theme' ),
'labels'              => $labels,
    // Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'author','thumbnail', 'tags'),
    // You can associate this CPT with a taxonomy or custom
      taxonomy.
    'taxonomies'          => array( 'genres', 'post_tag' ),
    /* A hierarchical CPT is like Pages and can have
    * Parent and child items. A non-hierarchical CPT
    * is like Posts.
    */
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page',
);

// Registering your Custom Post Type
register_post_type( 'testimonials', $args );

    }

    add_action( 'init', 'custom_post_testimonial_type', 0 );

Body:
Hi let's add this code in the theme's functions.php file.

add_shortcode( 'testimonial', 'testimonial_shortcode_callback' );

function testimonial_shortcode_callback( $atts ) {
ob_start();

extract( shortcode_atts( array(
    'posts_per_page' => 5,
    'testimonial_id' => '',
), $atts ) );

// define query parameters based on attributes
$options = array(
    'post_type'      => 'testimonials',
    'posts_per_page' => $posts_per_page,
);

if ( ! empty( $testimonial_id ) ) {
    $options['post__in'] = array_map( 'trim', explode( ',', $testimonial_id ) );
}

$testimonial_query = new WP_Query( $options );
// run the loop based on the query
if ( $testimonial_query->have_posts() ) :
    ?>
    <ul class="testimonial-listing">
        <?php
        while ( $testimonial_query->have_posts() ) : $testimonial_query->the_post();
            ?>
            <li id="testimonial-<?php the_ID(); ?>">
                <?php the_content(); ?>
            </li>
        <?php
        endwhile;
        wp_reset_postdata();
        ?>
    </ul>
    <?php
    $testimonial_output = ob_get_clean();

    return $testimonial_output;
endif;
}

Than use this shortcode as a example [testimonial posts_per_page="2" testimonial_id="123,145"]