问:
Excel 2016: open and close an Excel file programmatically from sharepoint
I have this test code that attempts to start a hidden Excel process, load an Excel file from a location ("fileToOpen"), do something with the file and then close the file and finally close the Excel process. I'm performing my test in Excel 2016.

```<code>Sub test()
    Dim excelapp As Object
    Dim wbk As Workbook

    Set excelapp = CreateObject("excel.Application")
    excelapp.Visible = True

    On Error GoTo error_handler

    Set wbk = excelapp.Workbooks.Open(filename:=fileToOpen, ReadOnly:=True)

    ' Do something

    wbk.Close SaveChanges:=False
    excelapp.Quit
    Set excelapp = Nothing

    Exit Sub

error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    excelapp.Quit
    Set excelapp = Nothing
End Sub
</code>```

For some reason the Excel process stays alive after the excelapp.Quit when the file is loaded from SharePoint, but is killed when the file is loaded from a local drive. This also worked fine in Excel 2010, i.e. the Excel process was properly terminated.

Any help is appreciated on how to properly close the file after reading it.

答:
Try changing the

```<code>wbk.Close SaveChanges:=False
    excelapp.Quit
    Set excelapp = Nothing
</code>```

to this

```<code>    wbk.Close SaveChanges:=False
    Application.Quit
    Application.DisplayAlerts = False
    Set excelapp = Nothing
</code>```

and the

```<code>    error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    excelapp.Quit
    Set excelapp = Nothing
</code>```

to this

```<code>    error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    Application.Quit
    Application.DisplayAlerts = False
    Set excelapp = Nothing
</code>```

Body:
I have this test code that attempts to start a hidden Excel process, load an Excel file from a location ("fileToOpen"), do something with the file and then close the file and finally close the Excel process. I'm performing my test in Excel 2016.

Sub test()
    Dim excelapp As Object
    Dim wbk As Workbook

    Set excelapp = CreateObject("excel.Application")
    excelapp.Visible = True

    On Error GoTo error_handler

    Set wbk = excelapp.Workbooks.Open(filename:=fileToOpen, ReadOnly:=True)

    ' Do something

    wbk.Close SaveChanges:=False
    excelapp.Quit
    Set excelapp = Nothing

    Exit Sub

error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    excelapp.Quit
    Set excelapp = Nothing
End Sub

For some reason the Excel process stays alive after the excelapp.Quit when the file is loaded from SharePoint, but is killed when the file is loaded from a local drive. This also worked fine in Excel 2010, i.e. the Excel process was properly terminated.

Any help is appreciated on how to properly close the file after reading it.

Body:
Try changing the

wbk.Close SaveChanges:=False
    excelapp.Quit
    Set excelapp = Nothing

to this

    wbk.Close SaveChanges:=False
    Application.Quit
    Application.DisplayAlerts = False
    Set excelapp = Nothing

and the

    error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    excelapp.Quit
    Set excelapp = Nothing

to this

    error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    Application.Quit
    Application.DisplayAlerts = False
    Set excelapp = Nothing


来源: stackexchange

问:
get the sum of related items that contained in one group the returned on condition
this is related to another question get first record in group by result base on condition
to make it clear, I'll start from the beginning
this is my database structure create database testGroupfirst; go

```<code>use testGroupfirst;
go

create table testTbl (

id int primary key identity,name nvarchar(50) ,year int ,degree int , place  nvarchar(50)

)

insert into testTbl values ('jack',2015,50,'giza')
insert into testTbl values ('jack',2016,500,'cai')
insert into testTbl values ('jack',2017,660,'alex')
insert into testTbl values ('jack',2018,666,'giza')
insert into testTbl values ('jack',2011,50,'alex')
insert into testTbl values ('rami',2015,5054,'giza')
insert into testTbl values ('rami',2016,1500,'cai')
insert into testTbl values ('rami',2017,66220,'giza')
insert into testTbl values ('rami',2018,6656,'alex')
insert into testTbl values ('rami',2011,540,'cai')
insert into testTbl values ('jack',2010,50,'cai')
select * from testTbl
</code>```

this is the result till now

to get the latest 2 orders, etc  from a group by this could be solved by this code

```<code>SELECT name, year, degree, place
FROM
(SELECT name,degree, year,  place,
    ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
     FROM testTbl
) t
WHERE rn in(1,2,3);

--another way
select t.*
from testTbl t
    cross apply (select top 2 id from testTbl t2 where t2.name = t.name order by degree desc) r
where t.id = r.id
</code>```

i need to get aggregate function like sum to get the sum of all related items in one group
i make a code like this

```<code>select t.*, sum (t.degree) as sumtest
from testTbl t
    cross apply (select top 2 id ,degree  , sum (degree) as sumtest from testTbl t2 where t2.place = t.place group by id,degree order by degree  ) r
where t.id = r.id group by t.id,t.name,t.place,t.year,t.degree
</code>```

but it didn't work like I thought as I need to make aggregate value not scalar for every item itself , i need to get the sum of all items in one group
what i need to get is what shown in this pic

答:
This could be one approach</p>

```<code>  select
  name,
  SUM(degree) sumtest
  into #test
  from testTbl
  group by name

  select b.*, a.sumtest from #test a
  join
  testTbl b on b.name = a.name
</code>```

ContentLicense: CC BY-SA 3.0

Body:
this is related to another question get first record in group by result base on condition
to make it clear, I'll start from the beginning
this is my database structure create database testGroupfirst; go

use testGroupfirst;
go

create table testTbl (

id int primary key identity,name nvarchar(50) ,year int ,degree int , place  nvarchar(50)

)

insert into testTbl values ('jack',2015,50,'giza')
insert into testTbl values ('jack',2016,500,'cai')
insert into testTbl values ('jack',2017,660,'alex')
insert into testTbl values ('jack',2018,666,'giza')
insert into testTbl values ('jack',2011,50,'alex')
insert into testTbl values ('rami',2015,5054,'giza')
insert into testTbl values ('rami',2016,1500,'cai')
insert into testTbl values ('rami',2017,66220,'giza')
insert into testTbl values ('rami',2018,6656,'alex')
insert into testTbl values ('rami',2011,540,'cai')
insert into testTbl values ('jack',2010,50,'cai')
select * from testTbl

this is the result till now

to get the latest 2 orders, etc  from a group by this could be solved by this code

SELECT name, year, degree, place
FROM
(SELECT name,degree, year,  place,
    ROW_NUMBER() OVER (PARTITION BY name ORDER BY degree desc) rn
     FROM testTbl
) t
WHERE rn in(1,2,3);

--another way
select t.*
from testTbl t
    cross apply (select top 2 id from testTbl t2 where t2.name = t.name order by degree desc) r
where t.id = r.id

i need to get aggregate function like sum to get the sum of all related items in one group
i make a code like this

select t.*, sum (t.degree) as sumtest
from testTbl t
    cross apply (select top 2 id ,degree  , sum (degree) as sumtest from testTbl t2 where t2.place = t.place group by id,degree order by degree  ) r
where t.id = r.id group by t.id,t.name,t.place,t.year,t.degree

but it didn't work like I thought as I need to make aggregate value not scalar for every item itself , i need to get the sum of all items in one group
what i need to get is what shown in this pic

Body:
This could be one approach

  select
  name,
  SUM(degree) sumtest
  into #test
  from testTbl
  group by name

  select b.*, a.sumtest from #test a
  join
  testTbl b on b.name = a.name


问:
Create animated gif from a set of jpeg images
I need something that can be scripted on windows 7. This image will be used in banners.</p>

答:
Based on the answers of Simon P Stevens and dwurf I came up with this simplified solution:

```<code>ffmpeg -f image2 -framerate 1 -i image%d.jpg video.gif
</code>```

This results in a rate of 1 second per image.  Adjust the framerate value according to your needs.

ContentLicense: CC BY-SA 2.5

Body:
Based on the answers of Simon P Stevens and dwurf I came up with this simplified solution:

ffmpeg -f image2 -framerate 1 -i image%d.jpg video.gif

This results in a rate of 1 second per image.  Adjust the framerate value according to your needs.


问:
How can I set the focus of a ListBox in XAML?
I have this ListBox:

```<code><ListBox Name="lbColor">
    <ListBoxItem Content="Blue"/>
    <ListBoxItem Content="Red"/>
    <ListBoxItem Content="Orange"/>
</ListBox>
</code>```

This code pre-selects the choice alright, but doesn't set the focus, how can I do that?

```<code>public Window1()
{
    InitializeComponent();

    lbColor.SelectedIndex = 1;
    lbColor.Focus = 1;
}
</code>```

答: I think, that you have to inherit from UIElement-Class and set true to UIElement.IsFocusable. Now you should be able to set the focus to the listbox with lblcolor.Focus()! I hope that this will help.</p>

OwnerDisplayName: Edward Tanguay

Body:
I have this ListBox:

<ListBox Name="lbColor">
    <ListBoxItem Content="Blue"/>
    <ListBoxItem Content="Red"/>
    <ListBoxItem Content="Orange"/>
</ListBox>

This code pre-selects the choice alright, but doesn't set the focus, how can I do that?

public Window1()
{
    InitializeComponent();

    lbColor.SelectedIndex = 1;
    lbColor.Focus = 1;
}


问:
Android bootanimation modification prevention

I want to know if there is a way to include your Android bootanimation.zip inside frameworks.apk(or another place not easily accessible) when building from source so that it gets loaded instead of the one in /system/media/bootanimation.zip
So when a user replaces the bootanimation in /system/media it still loads the default one built into frameworks.apk or some other place that Android can access to stop a user from modifying the bootanimation easily.

Or another scenario, a user replaces the bootanimation but then on the next boot Android checks if there is a size, file difference on the bootanimation.zip with a predetermined value(or original file) and if it differs, then it copies a spare bootanimation.zip located somewhere(if possible in frameworks.apk, so users can't get it easily, without decompiling it) and then copies the original bootanimation over the one in /system/media.
Then on the next boot, the bootanimation will be the original one and users will be baffled why it changed again. Is there a way to write such a script to run on boot or include it in some runtime file in /system/bin perhaps?

You can change the default location of the bootanimation.zip, but where would be a good place to hide it and what to rename it too, will also need to keep it small under 5MB and without .zip extension? But this method might be easily discovered.

It is for protecting my work, so others can't take credit for it.
So I just want to make it a little harder for someone that tries to do such a thing.

答: You can store the boot animation somewhere with a different name. And then implement a service in init.rc for copying your boot animation to /system/media after checking the current bootanimation.zip file's checksum. If the user had replaced the bootanimation.zip then the checksum will be different compared to your bootanimation.zip.</p>


问:
Drillthrough function in Power BI column chart - show day numbers instead of dates
I have created 2 different column charts in my Power BI report. The charts show the report usage by month and day (Day 1-31) - in this case for October. Only one month can be selected at a time.

I have added a drill-through function to the chart so the user can access a more detailed report. This works fine with the first chart when the Date field is placed under Axis (example: 2017-11-14).

When I instead try to use the Year, Month, Day fields under Axis only the day is being sent through to the drill-through report. For example November 6'th 2017 is being picked up at 6'th of each month. It seems that the drill-though function is only using the lowest level of data.

The first option works fine, however I would like it to look the the chart below where you see the number of each day instead of the entire date.

Any thoughts or suggestions?

Edit:

This is what the drillthrough filters look like on the drillthrough report page (I have selected November 9'th on the other page):

(År = Year, Månad = Month, Dag = Day)

答:
I finally managed to solve the issue:

I selected the drill down arrow on the right (in the top-left corner of the visualization) to drill down to the lowest level and not the arrow in the middle which I thought did the exact same thing except with more steps.

Now the drillthrough function works and all the values are passed to the next report!


问:
How can I watch an object created in a "with block"?
I have an no named object created in a "with block".

```<code>With Factory.CreateSomeObject()
    .SomeProp = someValue
    ...
End With
</code>```

My question is: how can I inspect the object when the debugger is in break mode?

答:
When I set a breakpoint on a line within a With block, The object returned from the function shows up in the Locals window.  This is using VS2015.  Further, if I right click on the function name on the With line and choose "Add Watch", the object is visible in the watch window.

My code:

```<code>Module Module1
    Sub Main()

        With FunctionThatCreatesAnA()
            Console.WriteLine("{0}, {1}", .SomeString, .SomeInteger)
        End With

        Console.ReadLine()
    End Sub

    Function FunctionThatCreatesAnA() As ClassA
        Return New ClassA With {.SomeString = "Blah Blah", .SomeInteger = 42}
    End Function
End Module

Public Class ClassA
    Public Property SomeString() As String
    Public Property SomeInteger() As Integer
End Class
</code>```

Locals window:

Watch window:

Body:
I have an no named object created in a "with block".

With Factory.CreateSomeObject()
    .SomeProp = someValue
    ...
End With

My question is: how can I inspect the object when the debugger is in break mode?

Body:
When I set a breakpoint on a line within a With block, The object returned from the function shows up in the Locals window.  This is using VS2015.  Further, if I right click on the function name on the With line and choose "Add Watch", the object is visible in the watch window.

My code:

Module Module1
    Sub Main()

        With FunctionThatCreatesAnA()
            Console.WriteLine("{0}, {1}", .SomeString, .SomeInteger)
        End With

        Console.ReadLine()
    End Sub

    Function FunctionThatCreatesAnA() As ClassA
        Return New ClassA With {.SomeString = "Blah Blah", .SomeInteger = 42}
    End Function
End Module

Public Class ClassA
    Public Property SomeString() As String
    Public Property SomeInteger() As Integer
End Class

Locals window:

Watch window:


答: SMIL animation, the type that uses the <animate> element, is not supported by IE or Edge.  You could try the FakeSmile polyfill.

Title: Problems with animating SVG in IE

Body:
can You help mi with that... i've got SVG and it's working fine in Chrome and other but of course there are problems with IE.
Is there any options to make it work with IE (as I know there aren't)? So maybe You can show an option for code that recognize user browser and when it's Chrome, Firefox or Safari it will run animated svg and if it's IE it will show other image.
I've tried with <comment> but i can't make it working...
Thx for any help...

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 193" enable-background="new 0 0 374 193">

 <path id="linia" d="M620.6,157.9c3.9,0,4.8,1.8,4.4,4.6l-3.6,29.4c-1.8,14.1-11.3,28.1-43,28.1c-27.9,0-37.9-12-37.9-25
				c0-1.1,0.2-3,0.3-4.4l6.9-56.8c1.6-14.1,11.3-28.1,43-28.1c27.9,0,37.9,12,37.9,25.1c0,1-0.2,2.6-0.3,4.4l-0.5,4.4
				c-0.3,3.4-1.8,4.9-5.3,4.9h-16.9c-3.4,0-4.6-2-4.1-4.9l0.2-1.1c0.2-1.1,0.2-2,0.2-2.6c0-5.4-4.8-8-12.3-8
				c-7.9,0-14.3,3.1-15.3,10.7l-5.9,47.3c-0.2,1.1-0.3,2.5-0.3,3.3c0,6.1,4.6,8.7,12.5,8.7c8.9,0,14.3-3.1,15.1-10.7l0.8-7.1H583
				c-3.4,0-4.8-1.5-4.3-4.8l1.6-12.8c0.3-3.4,2-4.6,5.4-4.6H620.6z" fill="none" stroke="#CF0a2c" stroke-width="1" stroke-miterlimit="10">
  <animate id="1" attributeName="fill" from="#fff" to="#CF0A2C" begin="2s" dur="1s" fill="freeze" repeatCount="1"></animate>
 </path>

</svg>


问:
System.Data.Entity.ModelConfiguration missing in EF core
Trying to load all the configurations dynamically on OnModelCreating for Entity framework  core.
what is the other way around if ModelConfiguration is missing.</p>

答:
It's even easier in Core 2.0 now

```<code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace MyApp.DAL.EntityConfigurations
{
    public class StudentConfiguration : IEntityTypeConfiguration<Student>
    {
        public void Configure(EntityTypeBuilder<Student> modelBuilder)
        {

            modelBuilder.Property(f => f.Name).IsRequired();

        }
    }
}
</code>```

Then in your db context:

```<code>public DbSet<Student> Students{ get; set; }

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Customizations must go after base.OnModelCreating(builder)

    builder.ApplyConfiguration(new StudentConfig());
    builder.ApplyConfiguration(new SomeOtherConfig());

    // etc.
    // etc..
}
</code>```

Body:
It's even easier in Core 2.0 now

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace MyApp.DAL.EntityConfigurations
{
    public class StudentConfiguration : IEntityTypeConfiguration<Student>
    {
        public void Configure(EntityTypeBuilder<Student> modelBuilder)
        {

            modelBuilder.Property(f => f.Name).IsRequired();

        }
    }
}

Then in your db context:

public DbSet<Student> Students{ get; set; }

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Customizations must go after base.OnModelCreating(builder)

    builder.ApplyConfiguration(new StudentConfig());
    builder.ApplyConfiguration(new SomeOtherConfig());

    // etc.
    // etc..
}


问:
Why image not taking the whole width of the browser on MAC?
I developed a website that contain some images , some of them are main images with about 3000px in width .

I'm using this to make the image fill the whole width and it's working with me during testing but the client said that it's not taking the whole width and sent me screenshots :

```<code>img{
  display:block;
  max-width:100%
  height:auto;
}
</code>```

Here is the demo link of the website:
http://www.zhtml.aba.ae

How to make it work?

He was browsing it from Chrome Browser on MAC

答:
See the differences by changing your browser: You'll understand the difference.</p>

```<code><style>
div.e1 {
    width:400px;
    margin: auto;
    border: 5px solid #73AD21;
}

div.e2 {
    max-width:400px;
    margin: auto;
    border: 5px solid #73AD21;
}
</style>

<div class="e1">width: 400px;</div>
<br>

<div class="e2">max-width: 400px;</div>

<p>blablabla</p>
</code>```

Body:
I developed a website that contain some images , some of them are main images with about 3000px in width .

I'm using this to make the image fill the whole width and it's working with me during testing but the client said that it's not taking the whole width and sent me screenshots :

img{
  display:block;
  max-width:100%
  height:auto;
}

Here is the demo link of the website:
http://www.zhtml.aba.ae

How to make it work?

He was browsing it from Chrome Browser on MAC

Body:
See the differences by changing your browser: You'll understand the difference.

<style>
div.e1 {
    width:400px;
    margin: auto;
    border: 5px solid #73AD21;
}

div.e2 {
    max-width:400px;
    margin: auto;
    border: 5px solid #73AD21;
}
</style>

<div class="e1">width: 400px;</div>
<br>

<div class="e2">max-width: 400px;</div>

<p>blablabla</p>


问:
Bluetooth Thermal printer print half String
Please help me, I waste my whole day but could not figure out Why my Thermal Printer print half text in receipt. It's work perfectly in 58mm Mini Bluetooth Thermal Printer. But when I come in Thermal Printer LESHP 80mm Wireless Bluetooth Thermal this printer only print half text in receipt.

Here my code:

```<code>void findBT() {

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {

        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {

                if (device.getName().contains("Printer")) {

                    mmDevice = device;

                }
            }

        }
        else {
            Toast.makeText(this,"device not pair.",Toast.LENGTH_LONG).show();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
 void SendDateBT() throws IOException {
    try {

        // Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();
        mmOutputStream.write(mytext.getBytes());

        mmOutputStream.flush();
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

I call this two function when I want to print receipt :

```<code>findBT();
SendDatBt();
</code>```

答:
I'm using a pause after write the data , trying with 1-2 seconds before flush and close the connection.
This is the application that I wrote: https://play.google.com/store/apps/details?id=pe.diegoveloper.printerserverapp</p>

Body:
Please help me, I waste my whole day but could not figure out Why my Thermal Printer print half text in receipt. It's work perfectly in 58mm Mini Bluetooth Thermal Printer. But when I come in Thermal Printer LESHP 80mm Wireless Bluetooth Thermal this printer only print half text in receipt.

Here my code:

void findBT() {

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {

        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {

                if (device.getName().contains("Printer")) {

                    mmDevice = device;

                }
            }

        }
        else {
            Toast.makeText(this,"device not pair.",Toast.LENGTH_LONG).show();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
 void SendDateBT() throws IOException {
    try {

        // Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();
        mmOutputStream.write(mytext.getBytes());

        mmOutputStream.flush();
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

I call this two function when I want to print receipt :

findBT();
SendDatBt();


问:
pandas.eval with a boolean series with missing data

Description

I am using pandas.eval on a boolean series with missing data.

To do this I use an indexer to mark non-null values and .loc to only apply .eval on the rows with non-missing data.

Applying the logical not operator using the expression ~bool or not(bool) returns -1 or -2.

I understand that this is because my boolean series is casted as object type because of the missing values, but I am wondering :

Why the -1 and -2 output ?

What would be the proper way to use .eval on a boolean series with missing data ?

Example

Here is a reproducible example using pandas 0.20.3.

```<code>df = pd.DataFrame({'bool': [True, False, None]})
    bool
0   True
1  False
2   None

indexer = ~pd.isnull(df['bool'])
0     True
1     True
2    False
Name: bool, dtype: bool

df.loc[indexer].eval('~bool')
0    -2
1    -1
Name: bool, dtype: object
</code>```

答:
For eval, ~ maps to op.invert as seen in the source code here.

```<code>_unary_ops_syms = '+', '-', '~', 'not'
_unary_ops_funcs = op.pos, op.neg, op.invert, op.invert
_unary_ops_dict = dict(zip(_unary_ops_syms, _unary_ops_funcs))
</code>```

Thus when your Series is of good old object type, what you're seeing here is

```<code>>>> ~True
-2
>>> ~False
-1

# or with your Series
>>> ~pd.Series(True, dtype='object')
0    -2
dtype: object
</code>```

Where you want

```<code>>>> ~pd.Series(True)
0    False
dtype: bool
</code>```

The outputs ~True -> -2 and ~False -> -1 are because bool is a subclass of int in Python, and -2, -1 are the bitwise complements of 1 and 0 respectively.

The obvious solution is to either convert the Series to bool type beforehand with astype(bool) in an extra setp, or if for some reason you cannot do so before the eval,

```<code>>>> df.loc[indexer].eval('~bool.astype("bool")')
0    False
1     True
Name: bool, dtype: bool
</code>```

Body:
Description

I am using pandas.eval on a boolean series with missing data.

To do this I use an indexer to mark non-null values and .loc to only apply .eval on the rows with non-missing data.

Applying the logical not operator using the expression ~bool or not(bool) returns -1 or -2.

I understand that this is because my boolean series is casted as object type because of the missing values, but I am wondering :

Why the -1 and -2 output ?

What would be the proper way to use .eval on a boolean series with missing data ?

Example

Here is a reproducible example using pandas 0.20.3.

df = pd.DataFrame({'bool': [True, False, None]})
    bool
0   True
1  False
2   None

indexer = ~pd.isnull(df['bool'])
0     True
1     True
2    False
Name: bool, dtype: bool

df.loc[indexer].eval('~bool')
0    -2
1    -1
Name: bool, dtype: object

Body:
For eval, ~ maps to op.invert as seen in the source code here.

_unary_ops_syms = '+', '-', '~', 'not'
_unary_ops_funcs = op.pos, op.neg, op.invert, op.invert
_unary_ops_dict = dict(zip(_unary_ops_syms, _unary_ops_funcs))

Thus when your Series is of good old object type, what you're seeing here is

>>> ~True
-2
>>> ~False
-1

# or with your Series
>>> ~pd.Series(True, dtype='object')
0    -2
dtype: object

Where you want

>>> ~pd.Series(True)
0    False
dtype: bool

The outputs ~True -> -2 and ~False -> -1 are because bool is a subclass of int in Python, and -2, -1 are the bitwise complements of 1 and 0 respectively.

The obvious solution is to either convert the Series to bool type beforehand with astype(bool) in an extra setp, or if for some reason you cannot do so before the eval,

>>> df.loc[indexer].eval('~bool.astype("bool")')
0    False
1     True
Name: bool, dtype: bool


问:
Synchronize 2 processes using a mutex
I have 2 processes:

The first one creates a memory mapped region, a mutex and spawns
the second process. Then writes some pairs of numbers in the memory mapped region.

The second one opens the memory mapped region, opens the mutex and then reads the numbers written by the process 1.

I intended the first process to write a pair of numbers and the second one to immediately read it.

The process 2 seems to be starving.

What did I do wrong?

Process 1:

```<code>#include "stdafx.h"
#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
    DWORD memSize = 400 * sizeof(DWORD);
    HANDLE map_file = CreateFileMapping(NULL, NULL, PAGE_READWRITE, 0, memSize, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Parent) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);
    if (map_ptr == NULL)
    {
        _tprintf(_T("(Parent) PTR is null \n"));
    }

    HANDLE hMutex = CreateMutex(NULL, TRUE, _T("mt"));
    LPTSTR szCmdline = _tcsdup(TEXT("C:\\Users\\cristi\\source\\repos\\process_synchronization_reader\\Debug\\process_synchronization_reader.exe"));
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    if (!CreateProcess(NULL, szCmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        _tprintf(_T("Process created\n"));
    }

    _tprintf(_T("pare ca s-a creat"));
    for (int i = 1; i <= 200; ++i)
    {
        WaitForSingleObject(hMutex, INFINITE);

        _tprintf(_T("(Parent %d) writing from the parent\n"), i);
        DWORD a, b;

        CopyMemory((LPVOID) &a, map_ptr, sizeof(DWORD));
        map_ptr += sizeof (DWORD);

        CopyMemory((LPVOID) &b, map_ptr, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        ReleaseMutex(hMutex);
    }

    int n;
    cin >> n;
    CloseHandle(map_file);

    return 0;
}
</code>```

Process 2:

```<code>#include "stdafx.h"
#include <windows.h>

int main()
{
    HANDLE map_file = OpenFileMapping(FILE_MAP_READ, FALSE, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Child) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);

    if (map_ptr == NULL)
    {
        _tprintf(_T("(Child) PTR is null \n"));
    }

    _tprintf(_T("(CHILD) BEfore reading the first number\n"));
    HANDLE hMutex = OpenMutex(SYNCHRONIZE, TRUE, _T("mt"));
    for (int i = 1; i <= 200; i++)
    {
        WaitForSingleObject(hMutex, INFINITE);
        DWORD a = i;
        DWORD b = 2 * i;

        CopyMemory((LPVOID) map_ptr, &a, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        CopyMemory((LPVOID) map_ptr, &b, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        _tprintf(_T("[================================================]\n"));
        _tprintf(_T("( %d %d )\n"), a, b);
        _tprintf(_T("[=================================================]\n"));

        ReleaseMutex(hMutex);
    }

    return 0;
}
</code>```

答:
for got sequential write/read from shared memory we need 2 events (let name it Low and High).

first thread:

write data

signal Low event

wait on High event or break loop

goto 1

second thread:

wait on Low event

read data

break loop or signal High event

goto 1

unlike this solution mutex can not provide a sequence of reading / writing. mutex guarantee that until  one thread will be access shared data (read or write) another thread will be not do this in concurrent. but this can not prevent several times in a row for write or read. really - insert messagebox in begin of process 2 - before he first time try acquire mutex - first process already many time acquire and release mutex. or if one thread will be suspended between release and wait for mutex - meanwhile another thread many time wait and release it. so code can look like:

```<code>struct SHARED_DATA
{
    ULONG id;
    ULONG nLoops;
    BOOL bTask;
};

DWORD proc2(SHARED_DATA* p)
{
    if (HANDLE hLowEvent = OpenEvent(SYNCHRONIZE, FALSE, L"LowEvent"))
    {
        if (HANDLE hHighEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, L"hHighEvent"))
        {
            ULONG id = GetCurrentThreadId();

            for(;;)
            {
                if (WaitForSingleObject(hLowEvent, INFINITE) != WAIT_OBJECT_0)
                {
                    break;
                }

                // ++ checking for sequence
                if (p->id == id)
                {
                    __debugbreak();// must never be
                }

                p->id = id;
                // -- checking for sequence

                if (!p->bTask)
                {
                    // no more task
                    break;
                }

                // task done
                p->bTask = FALSE;

                // signal to #1
                if (!SetEvent(hHighEvent))
                {
                    break;
                }
            }

            CloseHandle(hHighEvent);
        }
        CloseHandle(hLowEvent);
    }

    return 0;
}

DWORD proc1(SHARED_DATA* p)
{
    if (HANDLE hLowEvent = CreateEvent(0, FALSE, FALSE, L"LowEvent"))
    {
        if (HANDLE hHighEvent = CreateEvent(0, FALSE, FALSE, L"hHighEvent"))
        {
            ULONG id = GetCurrentThreadId();

            p->nLoops = 0x1000;
            p->id = 0;
            p->bTask = FALSE;

            // exec proc2 here
            goto __1;

            do
            {
                if (WaitForSingleObject(hHighEvent, INFINITE) != WAIT_OBJECT_0)
                {
                    break;
                }

                if (p->bTask)
                {
                    __debugbreak();
                }

                // ++ checking for sequence
                if (p->id == id)
                {
                    __debugbreak();// must never be
                }
__1:
                p->id = id;
                // -- checking for sequence

                p->bTask = 0 < --p->nLoops;

                // signal to #2
                if (!SetEvent(hLowEvent))
                {
                    break;
                }

            } while (p->nLoops);

            CloseHandle(hHighEvent);
        }
        CloseHandle(hLowEvent);
    }

    return 0;
}
</code>```

Title: Synchronize 2 processes using a mutex

Body:
I have 2 processes:

The first one creates a memory mapped region, a mutex and spawns
the second process. Then writes some pairs of numbers in the memory mapped region.

The second one opens the memory mapped region, opens the mutex and then reads the numbers written by the process 1.

I intended the first process to write a pair of numbers and the second one to immediately read it.

The process 2 seems to be starving.

What did I do wrong?

Process 1:

#include "stdafx.h"
#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
    DWORD memSize = 400 * sizeof(DWORD);
    HANDLE map_file = CreateFileMapping(NULL, NULL, PAGE_READWRITE, 0, memSize, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Parent) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);
    if (map_ptr == NULL)
    {
        _tprintf(_T("(Parent) PTR is null \n"));
    }

    HANDLE hMutex = CreateMutex(NULL, TRUE, _T("mt"));
    LPTSTR szCmdline = _tcsdup(TEXT("C:\\Users\\cristi\\source\\repos\\process_synchronization_reader\\Debug\\process_synchronization_reader.exe"));
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    if (!CreateProcess(NULL, szCmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        _tprintf(_T("Process created\n"));
    }

    _tprintf(_T("pare ca s-a creat"));
    for (int i = 1; i <= 200; ++i)
    {
        WaitForSingleObject(hMutex, INFINITE);

        _tprintf(_T("(Parent %d) writing from the parent\n"), i);
        DWORD a, b;

        CopyMemory((LPVOID) &a, map_ptr, sizeof(DWORD));
        map_ptr += sizeof (DWORD);

        CopyMemory((LPVOID) &b, map_ptr, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        ReleaseMutex(hMutex);
    }

    int n;
    cin >> n;
    CloseHandle(map_file);

    return 0;
}

Process 2:

#include "stdafx.h"
#include <windows.h>

int main()
{
    HANDLE map_file = OpenFileMapping(FILE_MAP_READ, FALSE, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Child) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);

    if (map_ptr == NULL)
    {
        _tprintf(_T("(Child) PTR is null \n"));
    }

    _tprintf(_T("(CHILD) BEfore reading the first number\n"));
    HANDLE hMutex = OpenMutex(SYNCHRONIZE, TRUE, _T("mt"));
    for (int i = 1; i <= 200; i++)
    {
        WaitForSingleObject(hMutex, INFINITE);
        DWORD a = i;
        DWORD b = 2 * i;

        CopyMemory((LPVOID) map_ptr, &a, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        CopyMemory((LPVOID) map_ptr, &b, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        _tprintf(_T("[================================================]\n"));
        _tprintf(_T("( %d %d )\n"), a, b);
        _tprintf(_T("[=================================================]\n"));

        ReleaseMutex(hMutex);
    }

    return 0;
}

Body:
for got sequential write/read from shared memory we need 2 events (let name it Low and High).

first thread:

write data

signal Low event

wait on High event or break loop

goto 1

second thread:

wait on Low event

read data

break loop or signal High event

goto 1

unlike this solution mutex can not provide a sequence of reading / writing. mutex guarantee that until  one thread will be access shared data (read or write) another thread will be not do this in concurrent. but this can not prevent several times in a row for write or read. really - insert messagebox in begin of process 2 - before he first time try acquire mutex - first process already many time acquire and release mutex. or if one thread will be suspended between release and wait for mutex - meanwhile another thread many time wait and release it. so code can look like:

struct SHARED_DATA
{
    ULONG id;
    ULONG nLoops;
    BOOL bTask;
};

DWORD proc2(SHARED_DATA* p)
{
    if (HANDLE hLowEvent = OpenEvent(SYNCHRONIZE, FALSE, L"LowEvent"))
    {
        if (HANDLE hHighEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, L"hHighEvent"))
        {
            ULONG id = GetCurrentThreadId();

            for(;;)
            {
                if (WaitForSingleObject(hLowEvent, INFINITE) != WAIT_OBJECT_0)
                {
                    break;
                }

                // ++ checking for sequence
                if (p->id == id)
                {
                    __debugbreak();// must never be
                }

                p->id = id;
                // -- checking for sequence

                if (!p->bTask)
                {
                    // no more task
                    break;
                }

                // task done
                p->bTask = FALSE;

                // signal to #1
                if (!SetEvent(hHighEvent))
                {
                    break;
                }
            }

            CloseHandle(hHighEvent);
        }
        CloseHandle(hLowEvent);
    }

    return 0;
}

DWORD proc1(SHARED_DATA* p)
{
    if (HANDLE hLowEvent = CreateEvent(0, FALSE, FALSE, L"LowEvent"))
    {
        if (HANDLE hHighEvent = CreateEvent(0, FALSE, FALSE, L"hHighEvent"))
        {
            ULONG id = GetCurrentThreadId();

            p->nLoops = 0x1000;
            p->id = 0;
            p->bTask = FALSE;

            // exec proc2 here
            goto __1;

            do
            {
                if (WaitForSingleObject(hHighEvent, INFINITE) != WAIT_OBJECT_0)
                {
                    break;
                }

                if (p->bTask)
                {
                    __debugbreak();
                }

                // ++ checking for sequence
                if (p->id == id)
                {
                    __debugbreak();// must never be
                }
__1:
                p->id = id;
                // -- checking for sequence

                p->bTask = 0 < --p->nLoops;

                // signal to #2
                if (!SetEvent(hLowEvent))
                {
                    break;
                }

            } while (p->nLoops);

            CloseHandle(hHighEvent);
        }
        CloseHandle(hLowEvent);
    }

    return 0;
}


问:
How to recursively merge two objects?
I have the following two objects:

```<code>var objectA = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0
        },
    ]
};

var objectB = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "sharpe": 2.5
        },
    ]
};
</code>```

and I'd like to get:

```<code>var objectC = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0,
            "sharpe": 2.5
        },
    ]
};
</code>```

答:
Just use Object.assign to merge objects:

var json1 = {"a":[
               {
                 "col": 1,
                 "row": 1,
                 "pnl": 1.0
               },
               {
                 "col": 1,
                 "row": 2,
                 "pnl": 2.0
               },
           ]};

var json2 = {"a":[
               {
                 "col": 1,
                 "row": 1,
                 "sharpe": 1.5
               },
               {
                 "col": 1,
                 "row": 2,
                 "sharpe": 2.5
               },
           ]};

 var objectC = { a: json1.a.map((el, index) => Object.assign({}, el, json2.a[index])) };
 console.log(objectC);```

Title: How to recursively merge two objects?

Body:
I have the following two objects:

var objectA = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0
        },
    ]
};

var objectB = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "sharpe": 2.5
        },
    ]
};

and I'd like to get:

var objectC = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0,
            "sharpe": 2.5
        },
    ]
};


问:
Changing CSS on disabled selected elements
I have a form with code similar to:

```<code><form class="eng-select" action="action.php" method="POST">
    <select name="position">
        <option value="disabled" disabled selected>Engineer</option>
        <option value="entry-1">John Doe</option>
        <option value="entry-2">David Smith</option>
        <option value="entry-3">Michael Silk</option>
    </select>
</form>
</code>```

Which produces a dropdown like this:

However I would like to change the css color of the disabled selected entry (what the user sees when they load the page - the picture above). Is this possible, and if so what would the proper CSS call be?

I have looked at similar posts for IE here that mention:

```<code>select option [disabled] { background-color: blue; }
</code>```

but this does not work for me (I am using Google Chrome).

To clarify - I would like to change the CSS before the user clicks and opens the dropdown box.

答:
use below css for disabled select  option

select option:disabled {
   background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="eng-select" action="action.php" method="POST">
    <select name="position">
        <option value="disabled" disabled selected>Engineer</option>
        <option value="entry-1">John Doe</option>
        <option value="entry-2">David Smith</option>
        <option value="entry-3">Michael Silk</option>
    </select>
</form></code>```

Body:
I have a form with code similar to:

<form class="eng-select" action="action.php" method="POST">
    <select name="position">
        <option value="disabled" disabled selected>Engineer</option>
        <option value="entry-1">John Doe</option>
        <option value="entry-2">David Smith</option>
        <option value="entry-3">Michael Silk</option>
    </select>
</form>

Which produces a dropdown like this:

However I would like to change the css color of the disabled selected entry (what the user sees when they load the page - the picture above). Is this possible, and if so what would the proper CSS call be?

I have looked at similar posts for IE here that mention:

select option [disabled] { background-color: blue; }

but this does not work for me (I am using Google Chrome).

To clarify - I would like to change the CSS before the user clicks and opens the dropdown box.

Body:
use below css for disabled select  option

select option:disabled {
   background-color: blue;
}

<form class="eng-select" action="action.php" method="POST">
    <select name="position">
        <option value="disabled" disabled selected>Engineer</option>
        <option value="entry-1">John Doe</option>
        <option value="entry-2">David Smith</option>
        <option value="entry-3">Michael Silk</option>
    </select>
</form>


问:
C# HP QC ALM REST API: Upload attachments to Defect
I am working on ASP.Net project. I have to upload attachment to the defect in HP QC ALM 12.5x.

Authentication part is already done and successfully working.

On uploading defect to the attachment, receiving WebException was unhandled: The remote server returned an error: (415) Unsupported Media Type.

I have written the below code

```<code>string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HPALMUrl + "/rest/domains/" + HPALMDomain + "/projects/" + HPALMProject + "/attachments");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
request.ContentType = "Content-Type: multipart/form-data; boundary=" + boundary;
request.AllowWriteStreamBuffering = false;
request.ContentLength = imageBytes.Length;
authRequest.KeepAlive = true;
request.CookieContainer = createSessionRequest.CookieContainer; //successfully authenticated cookie

string contentDisposition = "form-data; entity.type=\"{0}\"; entity.id=\"{1}\"; filename=\"{2}\"; Content-Type=\"{3}\"";
request.Headers.Add("Content-Disposition", string.Format(contentDisposition, "defect", "4", "Defect Attachment.png", "application/octet-stream")); //I am not clear with passing content disposition. Please let me know if this should be modified.
</code>```

I am trying to upload Image file like below

```<code>string path = @"C:\TestAttachment.png";
byte[] imageBytes = System.IO.File.ReadAllBytes(path);
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
    using (MemoryStream memoryStream = new MemoryStream(imageBytes))
    {
        byte[] buffer = new byte[imageBytes.Length];
        int bytesRead = 0;
        while ((bytesRead = memoryStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            requestStream.Write(buffer, 0, bytesRead);
        }
    }
}

var response = (HttpWebResponse)request.GetResponse(); //Receiving Error here

string responseText = string.Empty;
if (response.StatusCode == HttpStatusCode.OK)
    responseText = "Update completed";
else
    responseText = "Error in update";
</code>```

Please let me know what I am doing wrong.

I am also unsure of passing the content disposition mentioned in rest api.

Thanks in Advance!

答:
```<code>def upload_result_file(self, defect_id, report_file):
    '''
        Function    :   upload_result_file
        Description :   Upload test result to ALM
    '''
    payload = open(report_file, 'rb')
    headers = {}
    headers['Content-Type'] = "application/octet-stream"
    headers['slug'] = "test-results" + report_file[report_file.rfind(".")+1: ]
    response = self.alm_session.post(ALM_URL + ALM_MIDPOINT + "/defects/" +
                                     str(defect_id) + "/attachments/",
                                     headers=headers, data=payload)
    if not (response.status_code == 200 or response.status_code == 201):
        print "Attachment step failed!", response.text, response.url, response.status_code
    return
</code>```

Body:
I am working on ASP.Net project. I have to upload attachment to the defect in HP QC ALM 12.5x.

Authentication part is already done and successfully working.

On uploading defect to the attachment, receiving WebException was unhandled: The remote server returned an error: (415) Unsupported Media Type.

I have written the below code

string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HPALMUrl + "/rest/domains/" + HPALMDomain + "/projects/" + HPALMProject + "/attachments");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
request.ContentType = "Content-Type: multipart/form-data; boundary=" + boundary;
request.AllowWriteStreamBuffering = false;
request.ContentLength = imageBytes.Length;
authRequest.KeepAlive = true;
request.CookieContainer = createSessionRequest.CookieContainer; //successfully authenticated cookie

string contentDisposition = "form-data; entity.type=\"{0}\"; entity.id=\"{1}\"; filename=\"{2}\"; Content-Type=\"{3}\"";
request.Headers.Add("Content-Disposition", string.Format(contentDisposition, "defect", "4", "Defect Attachment.png", "application/octet-stream")); //I am not clear with passing content disposition. Please let me know if this should be modified.

I am trying to upload Image file like below

string path = @"C:\TestAttachment.png";
byte[] imageBytes = System.IO.File.ReadAllBytes(path);
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
    using (MemoryStream memoryStream = new MemoryStream(imageBytes))
    {
        byte[] buffer = new byte[imageBytes.Length];
        int bytesRead = 0;
        while ((bytesRead = memoryStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            requestStream.Write(buffer, 0, bytesRead);
        }
    }
}

var response = (HttpWebResponse)request.GetResponse(); //Receiving Error here

string responseText = string.Empty;
if (response.StatusCode == HttpStatusCode.OK)
    responseText = "Update completed";
else
    responseText = "Error in update";

Please let me know what I am doing wrong.

I am also unsure of passing the content disposition mentioned in rest api.

Thanks in Advance!


问:
Implementation of std::disjunction in the Standard Library
I've seen the implementation of std::disjunction in the Standard Library (source):

```<code>template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
    : std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };
</code>```

I am curious about the need to specialize disjunction<B1> as B1. Why is it better than my naive implementation of it?

```<code>template<class...>              struct or_t
    : std::false_type {};
template<class B1, class... Bn> struct or_t<B1, Bn...>
    : std::integral_constant<bool, bool(B1::value) || bool(or_t<Bn...>::value)> {};
</code>```

答:
You return std::integral_constant.

std::disjunction returns one of the given type (which might have additional member).

Body:
I've seen the implementation of std::disjunction in the Standard Library (source):

template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
    : std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };

I am curious about the need to specialize disjunction<B1> as B1. Why is it better than my naive implementation of it?

template<class...>              struct or_t
    : std::false_type {};
template<class B1, class... Bn> struct or_t<B1, Bn...>
    : std::integral_constant<bool, bool(B1::value) || bool(or_t<Bn...>::value)> {};


问:
finding the average after a BubbleSort Method
I am an IT students, and i really need to finish writing this code, i am almost done with it, its sorting the numbers using Bubble sort but the things is, that we have to find the mean at the end, and i have no idea how to do this. can anybody help me?
my code looks like this, and till here it also works, I just need to add the rest to it:

```<code>public static void main(String[] args) {
    int num, i, j;
    double temp;
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the amount of Numbers you want to sort:");
    num = input.nextInt();

    double array[] = new double[num];

    System.out.println("Enter " + num + " Number: ");

    for (i = 0; i < num; i++)
        array[i] = input.nextDouble();

    for (i = 0; i < (num - 1); i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    System.out.println("Sorted list:");

    for (i = 0; i < num; i++)
        System.out.println(array[i]);
}
</code>```

}

Thanks :)

答:
You just need to edit a bit. Just add a variable average to your program , int variable if you need an integer average or float if you need a precise result (as I follow in below code). Sum all the elements to a variable sum (integer element) and then divide it by total number of elements ( basic math!!!). That's it, print it and you are done.

your program should look like :

```<code>public static void main(String[] args) {
int num, i, j, sum=0;
float avg=0;
double temp;
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);

System.out.println("Enter the amount of Numbers you want to sort:");
num = input.nextInt();

double array[] = new double[num];

System.out.println("Enter " + num + " Number: ");

for (i = 0; i < num; i++)
    array[i] = input.nextDouble();

for (i = 0; i < (num - 1); i++) {
    for (j = 0; j < num - i - 1; j++) {
        if (array[j] > array[j + 1]) {
            temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}

System.out.println("Sorted list:");

for (i = 0; i < num; i++)
    System.out.println(array[i]);

for (i = 0; i < num; i++)
 sum = sum+array[i];
avg=sum/num;
System.out.println("Average : "+avg);
 }
}
</code>```

Body:
I am an IT students, and i really need to finish writing this code, i am almost done with it, its sorting the numbers using Bubble sort but the things is, that we have to find the mean at the end, and i have no idea how to do this. can anybody help me?
my code looks like this, and till here it also works, I just need to add the rest to it:

public static void main(String[] args) {
    int num, i, j;
    double temp;
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the amount of Numbers you want to sort:");
    num = input.nextInt();

    double array[] = new double[num];

    System.out.println("Enter " + num + " Number: ");

    for (i = 0; i < num; i++)
        array[i] = input.nextDouble();

    for (i = 0; i < (num - 1); i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    System.out.println("Sorted list:");

    for (i = 0; i < num; i++)
        System.out.println(array[i]);
}

}

Thanks :)

Body:
You just need to edit a bit. Just add a variable average to your program , int variable if you need an integer average or float if you need a precise result (as I follow in below code). Sum all the elements to a variable sum (integer element) and then divide it by total number of elements ( basic math!!!). That's it, print it and you are done.

your program should look like :

public static void main(String[] args) {
int num, i, j, sum=0;
float avg=0;
double temp;
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);

System.out.println("Enter the amount of Numbers you want to sort:");
num = input.nextInt();

double array[] = new double[num];

System.out.println("Enter " + num + " Number: ");

for (i = 0; i < num; i++)
    array[i] = input.nextDouble();

for (i = 0; i < (num - 1); i++) {
    for (j = 0; j < num - i - 1; j++) {
        if (array[j] > array[j + 1]) {
            temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}

System.out.println("Sorted list:");

for (i = 0; i < num; i++)
    System.out.println(array[i]);

for (i = 0; i < num; i++)
 sum = sum+array[i];
avg=sum/num;
System.out.println("Average : "+avg);
 }
}


问:
AngularJS with jQuery for selecting parent element
I'm posting my html and directive code. I have two spans, which I have attached ng-click to. On ng-click I want to check the classes of their parents parent item (.parent-portlet), but what I have so far is not working correctly as all of the parent portlets get selected instead of only the current one.

     Remove

     Add Back

```

<p>this is what I have in my directive: </p>

<pre class="lang-js prettyprint-override"><code>scope.removePortlet = function(portlet) {
  var port = $('.remove').parent().parent();
  port.addClass('removed');
  port.addClass('edit-portlet');
};

scope.addPortlet = function(portlet) {
  var port = $('.add-back').parent().parent();
  if (portlet.hasClass('removed')) {
    port.removeClass('removed');
    port.removeClass('edit-portlet');
  }
};
</code>```

The problem with this code is that var portlet catches all of the portlets(parents) and I want to catch only the one related to the click action. How can I achieve that? I tried to pass this to my jquery select like so:

```<code>var portlet = $('.add-back', this).parent().parent();
</code>```

but that didn't work. Any ideas how this can be achieved?

Thanks in advance.

答:
Pass in the $event to the ng-click like this:

```<code><span ng-click="removePortlet($event)"></span>
</code>```

Then, just modify your code like this:

```<code>scope.removePortlet = function(ev) {
  var port = $(ev.target).parent().parent();
  port.addClass('removed');
  port.addClass('edit-portlet');
};

scope.addPortlet = function(ev) {
  var port = $(ev.target).parent().parent();
  if ($(ev.target).hasClass('removed')) {
    port.removeClass('removed');
    port.removeClass('edit-portlet');
  }
};
</code>```

Grabbing the "event's target" will ensure that you are only addressing the item that was actually clicked.  And note that angular uses $event to pass the event to a function.

I would also clean it up a bit combining the class modification lines and targeting the specific parent (in case you ever modify the DOM) using .closest():

```<code>scope.removePortlet = function(ev) {
  var port = $(ev.target).closest('.parent-portlet');
  port.addClass('removed, edit-portlet');
};

scope.addPortlet = function(ev) {
  var port = $(ev.target).closest('.parent-portlet');
  if (portlet.hasClass('removed')) {
    port.removeClass('removed, edit-portlet');
  }
};
</code>```

Body:
I'm posting my html and directive code. I have two spans, which I have attached ng-click to. On ng-click I want to check the classes of their parents parent item (.parent-portlet), but what I have so far is not working correctly as all of the parent portlets get selected instead of only the current one.

     Remove

     Add Back

this is what I have in my directive:

scope.removePortlet = function(portlet) {
  var port = $('.remove').parent().parent();
  port.addClass('removed');
  port.addClass('edit-portlet');
};

scope.addPortlet = function(portlet) {
  var port = $('.add-back').parent().parent();
  if (portlet.hasClass('removed')) {
    port.removeClass('removed');
    port.removeClass('edit-portlet');
  }
};

The problem with this code is that var portlet catches all of the portlets(parents) and I want to catch only the one related to the click action. How can I achieve that? I tried to pass this to my jquery select like so:

var portlet = $('.add-back', this).parent().parent();

but that didn't work. Any ideas how this can be achieved?

Thanks in advance.

Body:
Pass in the $event to the ng-click like this:

<span ng-click="removePortlet($event)"></span>

Then, just modify your code like this:

scope.removePortlet = function(ev) {
  var port = $(ev.target).parent().parent();
  port.addClass('removed');
  port.addClass('edit-portlet');
};

scope.addPortlet = function(ev) {
  var port = $(ev.target).parent().parent();
  if ($(ev.target).hasClass('removed')) {
    port.removeClass('removed');
    port.removeClass('edit-portlet');
  }
};

Grabbing the "event's target" will ensure that you are only addressing the item that was actually clicked.  And note that angular uses $event to pass the event to a function.

I would also clean it up a bit combining the class modification lines and targeting the specific parent (in case you ever modify the DOM) using .closest():

scope.removePortlet = function(ev) {
  var port = $(ev.target).closest('.parent-portlet');
  port.addClass('removed, edit-portlet');
};

scope.addPortlet = function(ev) {
  var port = $(ev.target).closest('.parent-portlet');
  if (portlet.hasClass('removed')) {
    port.removeClass('removed, edit-portlet');
  }
};


问:
Camera Plugin is not working on PhoneGap Build for Android
I am creating a PhoneGap app. I installed camera app with "phonegap plugin add cordova-plugin-camera". It works fine in phonegap aplication but after i do a successful build and upload it to phonegap build, none of these buttons are working on my android phone. I am posting my index, config and manifest below. Thank you for your help.

Index.html

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" href="jq/jquery.mobile-1.4.5.css" />
<script type="text/javascript" src="cordova.js"></script>
<script src="jq/jquery-3.2.1.js"></script>
<script src="jq/jquery.mobile-1.4.5.js"></script>
<title>Blank App</title>
<script type="text/javascript" charset="utf-8">
var pictureSource;
var destinationType;

document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}

function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}

function onPhotoURISuccess(imageURI) {
alert("inside large image")
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}

function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}

function capturePhotoEdit() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail,
{ quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}

function getPhoto(source) {
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}

function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
</code>```

Config.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.helloworld" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
<name>App005</name>
<description>
    A blank PhoneGap app.
</description>
<author email="support@phonegap.com" href="http://phonegap.com">
    PhoneGap Team
</author>
<content src="index.html" />
<access origin="*" />
<engine name="android" spec="~6.3.0" />
<plugin name="cordova-plugin-camera" spec="~3.0.0" />
</widget>
</code>```

AndroidManifest.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="com.phonegap.helloworld" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
<intent-filter android:label="@string/launcher_name">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="android.support.v4.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
</application>
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
</code>```

答:
I was using newer versions of plugins. I changed them to older versions and now everything works fine.</p>

```<code><plugin name="cordova-plugin-camera" spec="2.4.1" />
<plugin name="cordova-plugin-compat" spec="1.2.0" />
<plugin name="cordova-plugin-whitelist" spec="1.3.3" />
<plugin name="cordova-plugin-file" spec="4.3.1" />
<plugin name="cordova-plugin-file-transfer" spec="1.6.1" />
<plugin name="cordova-plugin-media-capture" spec="1.4.3" />
</code>```

Body:
I am creating a PhoneGap app. I installed camera app with "phonegap plugin add cordova-plugin-camera". It works fine in phonegap aplication but after i do a successful build and upload it to phonegap build, none of these buttons are working on my android phone. I am posting my index, config and manifest below. Thank you for your help.

Index.html

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" href="jq/jquery.mobile-1.4.5.css" />

<title>Blank App</title>

<button onclick="capturePhoto();">Capture Photo</button>

<button onclick="capturePhotoEdit();">Capture Editable Photo</button>

<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button>

<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button>

Config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.helloworld" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
<name>App005</name>
<description>
    A blank PhoneGap app.
</description>
<author email="support@phonegap.com" href="http://phonegap.com">
    PhoneGap Team
</author>
<content src="index.html" />
<access origin="*" />
<engine name="android" spec="~6.3.0" />
<plugin name="cordova-plugin-camera" spec="~3.0.0" />
</widget>

AndroidManifest.xml

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="com.phonegap.helloworld" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
<intent-filter android:label="@string/launcher_name">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="android.support.v4.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
</application>
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

Body:
I was using newer versions of plugins. I changed them to older versions and now everything works fine.

<plugin name="cordova-plugin-camera" spec="2.4.1" />
<plugin name="cordova-plugin-compat" spec="1.2.0" />
<plugin name="cordova-plugin-whitelist" spec="1.3.3" />
<plugin name="cordova-plugin-file" spec="4.3.1" />
<plugin name="cordova-plugin-file-transfer" spec="1.6.1" />
<plugin name="cordova-plugin-media-capture" spec="1.4.3" />


问:
My app keeps stopping / crashing in emulator (after OS reinstall)
I am doing some Android courses and part of my assignments I have to build a mock-up music player app. The app doesn't have to have any functionality so it's mostly xml code.
While I try to run it in the emulator, the app keeps crashing with messages like: "Vibes has stopped" or "Vibes keeps stoping".

What might be important to add is that I recently reinstalled the os on my Mac (did a full wipe). I am now running macOS High Sierra. I had some compatibility problems with HAXM, but it was solved with the latest update from Intel on the HAXM component.
Java is installed, so I am not sure if there is anything else I am missing here.

I have also tried importing older projects, which worked before, and have the same issue. So based on this, I doubt that the code is the problem here.

Any advice is more than welcome! :-)

Here is manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alexcojocaru.vibes">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Library"
        android:label="Music Library"/>
    <activity android:name=".Discover"
        android:label="Discover Music"></activity>
</application>
</code>```

And here is the correct log:

11-15 14:45:13.248 10725-10725/com.example.alexcojocaru.vibes E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.alexcojocaru.vibes, PID: 10725
                                                                                java.lang.RuntimeException: Canvas: trying to draw too large(144000000bytes) bitmap.
                                                                                at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:229)
                                                                                at android.view.RecordingCanvas.drawBitmap(RecordingCanvas.java:97)
                                                                                at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:529)
                                                                                at android.view.View.getDrawableRenderNode(View.java:19381)
                                                                                at android.view.View.drawBackground(View.java:19317)
                                                                                at android.view.View.draw(View.java:19114)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18073)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.draw(View.java:19126)
                                                                                at com.android.internal.policy.DecorView.draw(DecorView.java:785)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18073)
                                                                                at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:643)
                                                                                at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:649)
                                                                                at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:757)
                                                                                at android.view.ViewRootImpl.draw(ViewRootImpl.java:2980)
                                                                                at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2794)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2347)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:723)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:658)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

答: I think this post may help you. You seem to use a very large image somewhere, which is too large to draw on the android canvas.</p>

Body:
I am doing some Android courses and part of my assignments I have to build a mock-up music player app. The app doesn't have to have any functionality so it's mostly xml code.
While I try to run it in the emulator, the app keeps crashing with messages like: "Vibes has stopped" or "Vibes keeps stoping".

What might be important to add is that I recently reinstalled the os on my Mac (did a full wipe). I am now running macOS High Sierra. I had some compatibility problems with HAXM, but it was solved with the latest update from Intel on the HAXM component.
Java is installed, so I am not sure if there is anything else I am missing here.

I have also tried importing older projects, which worked before, and have the same issue. So based on this, I doubt that the code is the problem here.

Any advice is more than welcome! :-)

Here is manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alexcojocaru.vibes">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Library"
        android:label="Music Library"/>
    <activity android:name=".Discover"
        android:label="Discover Music"></activity>
</application>

And here is the correct log:

11-15 14:45:13.248 10725-10725/com.example.alexcojocaru.vibes E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.alexcojocaru.vibes, PID: 10725
                                                                                java.lang.RuntimeException: Canvas: trying to draw too large(144000000bytes) bitmap.
                                                                                at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:229)
                                                                                at android.view.RecordingCanvas.drawBitmap(RecordingCanvas.java:97)
                                                                                at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:529)
                                                                                at android.view.View.getDrawableRenderNode(View.java:19381)
                                                                                at android.view.View.drawBackground(View.java:19317)
                                                                                at android.view.View.draw(View.java:19114)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18073)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18064)
                                                                                at android.view.View.draw(View.java:18851)
                                                                                at android.view.ViewGroup.drawChild(ViewGroup.java:4214)
                                                                                at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4000)
                                                                                at android.view.View.draw(View.java:19126)
                                                                                at com.android.internal.policy.DecorView.draw(DecorView.java:785)
                                                                                at android.view.View.updateDisplayListIfDirty(View.java:18073)
                                                                                at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:643)
                                                                                at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:649)
                                                                                at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:757)
                                                                                at android.view.ViewRootImpl.draw(ViewRootImpl.java:2980)
                                                                                at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2794)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2347)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:723)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:658)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)


问:
put numpy array items into "bins"
I have a numpy array with some integers, e.g.,

```<code>a = numpy.array([1, 6, 6, 4, 1, 1, 4])
</code>```

I would now like to put all items into "bins" of equal values such that the bin with label 1 contains all indices of a that have the value 1. For the above example:

```<code>bins = {
    1: [0, 4, 5],
    6: [1, 2],
    4: [3, 6],
    }
</code>```

A combination of unique and wheres does the trick,

```<code>uniques = numpy.unique(a)
bins = {u: numpy.where(a == u)[0] for u in uniques}
</code>```

but this doesn't seem ideal since the number of unique entries may be large.

答:
Defaultdict with append would do the trick:</p>

```<code>from collections import defaultdict

d = defaultdict(list)

for ix, val in enumerate(a):
  d[val].append(ix)
</code>```

Title: put numpy array items into "bins"

Body:
I have a numpy array with some integers, e.g.,

a = numpy.array([1, 6, 6, 4, 1, 1, 4])

I would now like to put all items into "bins" of equal values such that the bin with label 1 contains all indices of a that have the value 1. For the above example:

bins = {
    1: [0, 4, 5],
    6: [1, 2],
    4: [3, 6],
    }

A combination of unique and wheres does the trick,

uniques = numpy.unique(a)
bins = {u: numpy.where(a == u)[0] for u in uniques}

but this doesn't seem ideal since the number of unique entries may be large.

Body:
Defaultdict with append would do the trick:

from collections import defaultdict

d = defaultdict(list)

for ix, val in enumerate(a):
  d[val].append(ix)


问:
Detect via javascript whether Silverlight is installed
Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?

I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.

Edit: From link provided in accepted answer:

Include Silverlight.js (from Silverlight SDK)

```<code>Silverlight.isInstalled("2.0");
</code>```

答:
```<code>        if (Silverlight.isInstalled("1.0")) {
            try {
                alert("Silverlight Version 1.0 or above is installed");
            }
            catch (err) {
                alert(err.Description);
            }
        }
        else {
            alert("No Silverlight is installed");
        }
</code>```

from this video.

Silverlight.isInstalled is always true so version string such as "1.0" must be provided to make it useful.

OwnerDisplayName: Mark Ingram

Body:
Is there a javascript function I can use to detect whether a specific silverlight version is installed in the current browser?

I'm particularly interested in the Silverlight 2 Beta 2 version. I don't want to use the default method of having an image behind the silverlight control which is just shown if the Silverlight plugin doesn't load.

Edit: From link provided in accepted answer:

Include Silverlight.js (from Silverlight SDK)

Silverlight.isInstalled("2.0");

LastEditorDisplayName: Mark Ingram

Body:
        if (Silverlight.isInstalled("1.0")) {
            try {
                alert("Silverlight Version 1.0 or above is installed");
            }
            catch (err) {
                alert(err.Description);
            }
        }
        else {
            alert("No Silverlight is installed");
        }

from this video.

Silverlight.isInstalled is always true so version string such as "1.0" must be provided to make it useful.


问:
Remove unmixed numbers from file
Say I have a file called input.txt that looks like this

```<code>I listened to 4 u2 albums today
meet me at 5
squad 4ever
</code>```

I want to filter out the numbers that are on their own, so "4" and "5" should go but "u2" and "4ever" should remain the same. i.e the output should be

```<code>I listened to u2 albums today
meet me at
squad 4ever
</code>```

I've been trying to use this code

```<code>for line in fileinput.input("input.txt", inplace=True):
    new_s = ""
    for word in line.split(' '):
        if not all(char.isdigit() for char in word):
            new_s += word
            new_s += ' '
    print(new_s, end='')
</code>```

Which is pretty similar to the code I found here: Removing numbers mixed with letters from string

But instead of the wanted output I get

```<code>I listened to u2 albums today
 meet me at 5
 squad 4ever
</code>```

As you can see there are two problems here, first only the first line loses the digit I want it to lose, "5" is still present in the second line. The second problem is the extra white space at the beginning of a new line.

I've been playing around with the code for a while and browsing stackoverflow, but can't find where the problem is coming from. Any insights?

答:
str.split(' ') does not remove the trailing newlines from each line. They end up attached to the last word of the line. So for your first problem, the '5' doesn't get removed because it's actually '5\n', and the \n is not a digit.

The second problem is related. When you print the last word of each line, it contains that newline, plus you're adding a space on to the end. That space shows up as the first character of the next line.

The simplest solution is simply to change line.split(' ') to line.split(). Without any arguments, split() will remove all whitespace, including the newlines. You'll also need to remove the end='' from your print so that the newlines are added back in.

Title: Remove unmixed numbers from file

Body:
Say I have a file called input.txt that looks like this

I listened to 4 u2 albums today
meet me at 5
squad 4ever

I want to filter out the numbers that are on their own, so "4" and "5" should go but "u2" and "4ever" should remain the same. i.e the output should be

I listened to u2 albums today
meet me at
squad 4ever

I've been trying to use this code

for line in fileinput.input("input.txt", inplace=True):
    new_s = ""
    for word in line.split(' '):
        if not all(char.isdigit() for char in word):
            new_s += word
            new_s += ' '
    print(new_s, end='')

Which is pretty similar to the code I found here: Removing numbers mixed with letters from string

But instead of the wanted output I get

I listened to u2 albums today
 meet me at 5
 squad 4ever

As you can see there are two problems here, first only the first line loses the digit I want it to lose, "5" is still present in the second line. The second problem is the extra white space at the beginning of a new line.

I've been playing around with the code for a while and browsing stackoverflow, but can't find where the problem is coming from. Any insights?