问:
Converting ImageProxy to Bitmap
So, I wanted to explore new Google's Camera API - CameraX.
What I want to do, is take an image from camera feed every second and then pass it into a function that accepts bitmap for machine learning purposes.

I read the documentation on Camera X Image Analyzer:

The image analysis use case provides your app with a CPU-accessible
  image to perform image processing, computer vision, or machine
  learning inference on. The application implements an Analyzer method
  that is run on each frame.

..which basically is what I need. So, I implemented this image analyzer like this:

```<code>imageAnalysis.setAnalyzer { image: ImageProxy, _: Int ->
    viewModel.onAnalyzeImage(image)
}
</code>```

What I get is image: ImageProxy. How can I transfer this ImageProxy to Bitmap?

I tried to solve it like this:

```<code>fun decodeBitmap(image: ImageProxy): Bitmap? {
    val buffer = image.planes[0].buffer
    val bytes = ByteArray(buffer.capacity()).also { buffer.get(it) }
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
</code>```

But it returns null - because decodeByteArray does not receive valid (?) bitmap bytes. Any ideas?

答:
There is another implementation of this conversion. At first YUV_420_888 is converted to NV21 and then RenderScript is used to convert to bitmap (so it is expected to be more effecient). Moreover it considers pixel stride which is more correct. Also it is from official android camera samples repo.

If anyone doesn't want to deal with RenderScript and synchronization here is the modified code:

```<code>fun ImageProxy.toBitmap(): Bitmap? {
    val nv21 = yuv420888ToNv21(this)
    val yuvImage = YuvImage(nv21, ImageFormat.NV21, width, height, null)
    return yuvImage.toBitmap()
}

private fun YuvImage.toBitmap(): Bitmap? {
    val out = ByteArrayOutputStream()
    if (!compressToJpeg(Rect(0, 0, width, height), 100, out))
        return null
    val imageBytes: ByteArray = out.toByteArray()
    return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}

private fun yuv420888ToNv21(image: ImageProxy): ByteArray {
    val pixelCount = image.cropRect.width() * image.cropRect.height()
    val pixelSizeBits = ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888)
    val outputBuffer = ByteArray(pixelCount * pixelSizeBits / 8)
    imageToByteBuffer(image, outputBuffer, pixelCount)
    return outputBuffer
}

private fun imageToByteBuffer(image: ImageProxy, outputBuffer: ByteArray, pixelCount: Int) {
    assert(image.format == ImageFormat.YUV_420_888)

    val imageCrop = image.cropRect
    val imagePlanes = image.planes

    imagePlanes.forEachIndexed { planeIndex, plane ->
        // How many values are read in input for each output value written
        // Only the Y plane has a value for every pixel, U and V have half the resolution i.e.
        //
        // Y Plane            U Plane    V Plane
        // ===============    =======    =======
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        val outputStride: Int

        // The index in the output buffer the next value will be written at
        // For Y it's zero, for U and V we start at the end of Y and interleave them i.e.
        //
        // First chunk        Second chunk
        // ===============    ===============
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        var outputOffset: Int

        when (planeIndex) {
            0 -> {
                outputStride = 1
                outputOffset = 0
            }
            1 -> {
                outputStride = 2
                // For NV21 format, U is in odd-numbered indices
                outputOffset = pixelCount + 1
            }
            2 -> {
                outputStride = 2
                // For NV21 format, V is in even-numbered indices
                outputOffset = pixelCount
            }
            else -> {
                // Image contains more than 3 planes, something strange is going on
                return@forEachIndexed
            }
        }

        val planeBuffer = plane.buffer
        val rowStride = plane.rowStride
        val pixelStride = plane.pixelStride

        // We have to divide the width and height by two if it's not the Y plane
        val planeCrop = if (planeIndex == 0) {
            imageCrop
        } else {
            Rect(
                    imageCrop.left / 2,
                    imageCrop.top / 2,
                    imageCrop.right / 2,
                    imageCrop.bottom / 2
            )
        }

        val planeWidth = planeCrop.width()
        val planeHeight = planeCrop.height()

        // Intermediate buffer used to store the bytes of each row
        val rowBuffer = ByteArray(plane.rowStride)

        // Size of each row in bytes
        val rowLength = if (pixelStride == 1 && outputStride == 1) {
            planeWidth
        } else {
            // Take into account that the stride may include data from pixels other than this
            // particular plane and row, and that could be between pixels and not after every
            // pixel:
            //
            // |---- Pixel stride ----|                    Row ends here --> |
            // | Pixel 1 | Other Data | Pixel 2 | Other Data | ... | Pixel N |
            //
            // We need to get (N-1) * (pixel stride bytes) per row + 1 byte for the last pixel
            (planeWidth - 1) * pixelStride + 1
        }

        for (row in 0 until planeHeight) {
            // Move buffer position to the beginning of this row
            planeBuffer.position(
                    (row + planeCrop.top) * rowStride + planeCrop.left * pixelStride)

            if (pixelStride == 1 && outputStride == 1) {
                // When there is a single stride value for pixel and output, we can just copy
                // the entire row in a single step
                planeBuffer.get(outputBuffer, outputOffset, rowLength)
                outputOffset += rowLength
            } else {
                // When either pixel or output have a stride > 1 we must copy pixel by pixel
                planeBuffer.get(rowBuffer, 0, rowLength)
                for (col in 0 until planeWidth) {
                    outputBuffer[outputOffset] = rowBuffer[col * pixelStride]
                    outputOffset += outputStride
                }
            }
        }
    }
}
</code>```

NOTE. There is a similar conversion in OpenCV android SDK.

Title: Converting ImageProxy to Bitmap

Body:
So, I wanted to explore new Google's Camera API - CameraX.
What I want to do, is take an image from camera feed every second and then pass it into a function that accepts bitmap for machine learning purposes.

I read the documentation on Camera X Image Analyzer:

The image analysis use case provides your app with a CPU-accessible
  image to perform image processing, computer vision, or machine
  learning inference on. The application implements an Analyzer method
  that is run on each frame.

..which basically is what I need. So, I implemented this image analyzer like this:

imageAnalysis.setAnalyzer { image: ImageProxy, _: Int ->
    viewModel.onAnalyzeImage(image)
}

What I get is image: ImageProxy. How can I transfer this ImageProxy to Bitmap?

I tried to solve it like this:

fun decodeBitmap(image: ImageProxy): Bitmap? {
    val buffer = image.planes[0].buffer
    val bytes = ByteArray(buffer.capacity()).also { buffer.get(it) }
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}

But it returns null - because decodeByteArray does not receive valid (?) bitmap bytes. Any ideas?

Body:
There is another implementation of this conversion. At first YUV_420_888 is converted to NV21 and then RenderScript is used to convert to bitmap (so it is expected to be more effecient). Moreover it considers pixel stride which is more correct. Also it is from official android camera samples repo.

If anyone doesn't want to deal with RenderScript and synchronization here is the modified code:

fun ImageProxy.toBitmap(): Bitmap? {
    val nv21 = yuv420888ToNv21(this)
    val yuvImage = YuvImage(nv21, ImageFormat.NV21, width, height, null)
    return yuvImage.toBitmap()
}

private fun YuvImage.toBitmap(): Bitmap? {
    val out = ByteArrayOutputStream()
    if (!compressToJpeg(Rect(0, 0, width, height), 100, out))
        return null
    val imageBytes: ByteArray = out.toByteArray()
    return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}

private fun yuv420888ToNv21(image: ImageProxy): ByteArray {
    val pixelCount = image.cropRect.width() * image.cropRect.height()
    val pixelSizeBits = ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888)
    val outputBuffer = ByteArray(pixelCount * pixelSizeBits / 8)
    imageToByteBuffer(image, outputBuffer, pixelCount)
    return outputBuffer
}

private fun imageToByteBuffer(image: ImageProxy, outputBuffer: ByteArray, pixelCount: Int) {
    assert(image.format == ImageFormat.YUV_420_888)

    val imageCrop = image.cropRect
    val imagePlanes = image.planes

    imagePlanes.forEachIndexed { planeIndex, plane ->
        // How many values are read in input for each output value written
        // Only the Y plane has a value for every pixel, U and V have half the resolution i.e.
        //
        // Y Plane            U Plane    V Plane
        // ===============    =======    =======
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y    U U U U    V V V V
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        val outputStride: Int

        // The index in the output buffer the next value will be written at
        // For Y it's zero, for U and V we start at the end of Y and interleave them i.e.
        //
        // First chunk        Second chunk
        // ===============    ===============
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y    V U V U V U V U
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        // Y Y Y Y Y Y Y Y
        var outputOffset: Int

        when (planeIndex) {
            0 -> {
                outputStride = 1
                outputOffset = 0
            }
            1 -> {
                outputStride = 2
                // For NV21 format, U is in odd-numbered indices
                outputOffset = pixelCount + 1
            }
            2 -> {
                outputStride = 2
                // For NV21 format, V is in even-numbered indices
                outputOffset = pixelCount
            }
            else -> {
                // Image contains more than 3 planes, something strange is going on
                return@forEachIndexed
            }
        }

        val planeBuffer = plane.buffer
        val rowStride = plane.rowStride
        val pixelStride = plane.pixelStride

        // We have to divide the width and height by two if it's not the Y plane
        val planeCrop = if (planeIndex == 0) {
            imageCrop
        } else {
            Rect(
                    imageCrop.left / 2,
                    imageCrop.top / 2,
                    imageCrop.right / 2,
                    imageCrop.bottom / 2
            )
        }

        val planeWidth = planeCrop.width()
        val planeHeight = planeCrop.height()

        // Intermediate buffer used to store the bytes of each row
        val rowBuffer = ByteArray(plane.rowStride)

        // Size of each row in bytes
        val rowLength = if (pixelStride == 1 && outputStride == 1) {
            planeWidth
        } else {
            // Take into account that the stride may include data from pixels other than this
            // particular plane and row, and that could be between pixels and not after every
            // pixel:
            //
            // |---- Pixel stride ----|                    Row ends here --> |
            // | Pixel 1 | Other Data | Pixel 2 | Other Data | ... | Pixel N |
            //
            // We need to get (N-1) * (pixel stride bytes) per row + 1 byte for the last pixel
            (planeWidth - 1) * pixelStride + 1
        }

        for (row in 0 until planeHeight) {
            // Move buffer position to the beginning of this row
            planeBuffer.position(
                    (row + planeCrop.top) * rowStride + planeCrop.left * pixelStride)

            if (pixelStride == 1 && outputStride == 1) {
                // When there is a single stride value for pixel and output, we can just copy
                // the entire row in a single step
                planeBuffer.get(outputBuffer, outputOffset, rowLength)
                outputOffset += rowLength
            } else {
                // When either pixel or output have a stride > 1 we must copy pixel by pixel
                planeBuffer.get(rowBuffer, 0, rowLength)
                for (col in 0 until planeWidth) {
                    outputBuffer[outputOffset] = rowBuffer[col * pixelStride]
                    outputOffset += outputStride
                }
            }
        }
    }
}

NOTE. There is a similar conversion in OpenCV android SDK.


来源: stackexchange

问:
Laravel multiple count in 1 Query
Im new to this Framework, i dont know how to optimize it using db::raw count and aliases and display it to my blade.php using @foreach

im trying to optimize my code, my goals is to count pallet_conditions and store it to my aliases, i dont want to count it one by one like what i did on this code

this is my code not optimize:

```<code>//computing the total rapairable
$repairable_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 1)
->count();
//REPAIRABLE

//computing the total good pallets
$good_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 0)
->count();
//GOOD
</code>```

this is the code, what i wanted to learn. just to minimize, and use aliases

```<code>$result = DB::table('liip_psrm_items')
->select(DB::raw('COUNT(liip_psrm_items.pallet_condition = 0 ) AS condition_1',
                 'COUNT(liip_psrm_items.pallet_condition = 1 ) AS condition_2'))
                ->where('psrm_items_id', '=' , $psrm_maintenance->id)
                ->get();
</code>```

答:
You can, first group by, then get count

Like :

DB::table('liip_psrm_items')
  ->groupBy('pallet_condition')
  ->select('pallet_condition', DB::raw('count(*) as total'))
  ->get();

```

ContentLicense: CC BY-SA 4.0

Title: Laravel multiple count in 1 Query

Body:
Im new to this Framework, i dont know how to optimize it using db::raw count and aliases and display it to my blade.php using @foreach

im trying to optimize my code, my goals is to count pallet_conditions and store it to my aliases, i dont want to count it one by one like what i did on this code

this is my code not optimize:

//computing the total rapairable
$repairable_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 1)
->count();
//REPAIRABLE

//computing the total good pallets
$good_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 0)
->count();
//GOOD

this is the code, what i wanted to learn. just to minimize, and use aliases

$result = DB::table('liip_psrm_items')
->select(DB::raw('COUNT(liip_psrm_items.pallet_condition = 0 ) AS condition_1',
                 'COUNT(liip_psrm_items.pallet_condition = 1 ) AS condition_2'))
                ->where('psrm_items_id', '=' , $psrm_maintenance->id)
                ->get();


问:
C2675 unary operator caused by wrong scope
I am currently working on my own Vector class for the purpose of learning C++ and got stuck here.

The error happens in my implementation of the overloaded -= operator. Because the subtraction of two vectors is similar to adding two vectors but using the negative, I try to reuse the code from the += operator by utilizing the - operator. Little confusing to write... so what I mean here... instead of directly implementing

v1 - v2

I want to implement

v1 + (-v2)

This is the code stripped down to the essential parts:

```<code>class Vector3 {
public:
    float m_x, m_y, m_z;

public:
    // creates a zero Vector3 (Vector3 with a magnitude of zero )
    Vector3()
        : m_x(0), m_y(0), m_z(0) {}

    // adds Vector3 v to this Vector3
    Vector3& operator +=(const Vector3& v) {
        m_x = v.m_x;
        m_y = v.m_y;
        m_z = v.m_z;
        return *this;
    }

    // substracts Vector3 v from this Vector3
    Vector3& operator -=(const Vector3& v) {
        return this->operator+=(-v);   // <--------ERROR
    }
};

// returns a clone of Vector3 v which is the negative of v
inline Vector3 operator -(const Vector3& v) {
    return Vector3(-v.m_x, -v.m_y, -v.m_z);
}
</code>```

The error happens in the marked line and reads: C2675 unary '-': 'const MathLib::Vector3' does not define this operator or a conversion to a type acceptable to the predefined operator.

and the minus of -v is marked by it.

I am aware of the fact that it is maybe easier to just directly implement the -= without reusing other functions but this is for the previous mentioned learning purpose and I guess that I miss something crucial regarding C References here.

答:
There is a bug in your operator+=(const Vector3& v). It performs assignment, but not the addition.

As for the unary - operator, if you want to use it in the class body, it should be accessible from the class body. Basically, you need to define you unary - operator

```<code>Vector3 operator-() const noexcept {
    return Vector3(-m_x, -m_y, -m_z);
}
</code>```

before operator-=.

Body:
I am currently working on my own Vector class for the purpose of learning C++ and got stuck here.

The error happens in my implementation of the overloaded -= operator. Because the subtraction of two vectors is similar to adding two vectors but using the negative, I try to reuse the code from the += operator by utilizing the - operator. Little confusing to write... so what I mean here... instead of directly implementing

v1 - v2

I want to implement

v1 + (-v2)

This is the code stripped down to the essential parts:

class Vector3 {
public:
    float m_x, m_y, m_z;

public:
    // creates a zero Vector3 (Vector3 with a magnitude of zero )
    Vector3()
        : m_x(0), m_y(0), m_z(0) {}

    // adds Vector3 v to this Vector3
    Vector3& operator +=(const Vector3& v) {
        m_x = v.m_x;
        m_y = v.m_y;
        m_z = v.m_z;
        return *this;
    }

    // substracts Vector3 v from this Vector3
    Vector3& operator -=(const Vector3& v) {
        return this->operator+=(-v);   // <--------ERROR
    }
};

// returns a clone of Vector3 v which is the negative of v
inline Vector3 operator -(const Vector3& v) {
    return Vector3(-v.m_x, -v.m_y, -v.m_z);
}

The error happens in the marked line and reads: C2675 unary '-': 'const MathLib::Vector3' does not define this operator or a conversion to a type acceptable to the predefined operator.

and the minus of -v is marked by it.

I am aware of the fact that it is maybe easier to just directly implement the -= without reusing other functions but this is for the previous mentioned learning purpose and I guess that I miss something crucial regarding C References here.

Body:
There is a bug in your operator+=(const Vector3& v). It performs assignment, but not the addition.

As for the unary - operator, if you want to use it in the class body, it should be accessible from the class body. Basically, you need to define you unary - operator

Vector3 operator-() const noexcept {
    return Vector3(-m_x, -m_y, -m_z);
}

before operator-=.


问:
webflux Mono response empty
I have a very simple spring webflux rest endpoint in my project.

```<code>@Bean
public RouterFunction authRoute() {
    return RouterFunctions.route(POST("/auth/signin").and(accept(APPLICATION_JSON)), this::signIn)
            .andRoute(POST("/auth/signup").and(accept(APPLICATION_JSON)), this::signUp)
            .andRoute(POST("/auth/test").and(accept(APPLICATION_JSON)), this::test);
}
</code>```

And /auth/test endpoint just reply back with the username supplied.

```<code>public Mono<ServerResponse> test(ServerRequest request) {
    System.out.println("Start test ");
    Mono<JwtRequest> jwtRequestMono = request.bodyToMono(JwtRequest.class);
    jwtRequestMono.subscribe(v -> System.out.println(v.getUsername() + ":" + v.getPassword()));
    return jwtRequestMono
            .flatMap(j -> ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(j.getUsername()));
}
</code>```

The problem I am facing is that the response body is empty, it should be the username. I also verified that when I return the hardcoded string, it passes. It fails when I depend on jwtRequestMono.flatMap(...

答:
This line is almost certainly your downfall:

```<code>jwtRequestMono.subscribe(v -> System.out.println(v.getUsername() + ":" + v.getPassword()));
</code>```

Your request can't be subscribed to multiple times - so you subscribe to it on this line (which works and prints out the values as expected), then the framework subscribes to it, and it blows up. I'd expect to see an exception and a 500 response returned when this happens by default, so chances are you're swallowing an exception somewhere.

Never subscribe within your own application. That's the frameworks job.

Instead, if you want to have a "side-effect" where you print the values as they come in, then use doOnNext() as part of your reactive chain:

```<code>return jwtRequestMono
        .doOnNext(v -> System.out.println(v.getUsername() + ":" + v.getPassword()))
        .flatMap(j -> ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(j.getUsername()));
</code>```

Title: webflux Mono response empty

Body:
I have a very simple spring webflux rest endpoint in my project.

@Bean
public RouterFunction authRoute() {
    return RouterFunctions.route(POST("/auth/signin").and(accept(APPLICATION_JSON)), this::signIn)
            .andRoute(POST("/auth/signup").and(accept(APPLICATION_JSON)), this::signUp)
            .andRoute(POST("/auth/test").and(accept(APPLICATION_JSON)), this::test);
}

And /auth/test endpoint just reply back with the username supplied.

public Mono<ServerResponse> test(ServerRequest request) {
    System.out.println("Start test ");
    Mono<JwtRequest> jwtRequestMono = request.bodyToMono(JwtRequest.class);
    jwtRequestMono.subscribe(v -> System.out.println(v.getUsername() + ":" + v.getPassword()));
    return jwtRequestMono
            .flatMap(j -> ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(j.getUsername()));
}

The problem I am facing is that the response body is empty, it should be the username. I also verified that when I return the hardcoded string, it passes. It fails when I depend on jwtRequestMono.flatMap(...

Body:
This line is almost certainly your downfall:

jwtRequestMono.subscribe(v -> System.out.println(v.getUsername() + ":" + v.getPassword()));

Your request can't be subscribed to multiple times - so you subscribe to it on this line (which works and prints out the values as expected), then the framework subscribes to it, and it blows up. I'd expect to see an exception and a 500 response returned when this happens by default, so chances are you're swallowing an exception somewhere.

Never subscribe within your own application. That's the frameworks job.

Instead, if you want to have a "side-effect" where you print the values as they come in, then use doOnNext() as part of your reactive chain:

return jwtRequestMono
        .doOnNext(v -> System.out.println(v.getUsername() + ":" + v.getPassword()))
        .flatMap(j -> ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(j.getUsername()));


问:
How to store images based on a particular user in django?
I have a multi-user platform built using Django, Each user should have their own image gallery, which should be hidden to other users. How exactly can I design such a network using Django?</p>

答:
I would say that it really depends how far you wish to go to separate users. If you just wish to save pictures and be sure that it is somehow noted to which user it belongs, than the approach in the comment by iliya would work - just add field to your model where you are storing your images that will link that image to user.

If you wish to separate this on disk too (for example, you wish to prepend username to url/path) than you need to do that - prepend username to filename, but you need to be sure that you do that on time. Be aware that this does not protect other users to view images belonging to other users if they know full path to the image.

If you wish to protect pictures between users (user can only see it's own pictures) you need to do a little bit more work. This post might help:

protecting user uploaded files django

Hope this helps (or at least gives you some ideas).


问:
How to add element of a list to list of dictionary in python
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

```<code>fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]
</code>```

list

```<code>rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]
</code>```

Desired output

```<code>[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]
</code>```

I will appreciate any help in getting this done.
Thank you

答:
It can be done like this:

```<code>for i in range(len(fortunne_500)):
  fortunne_500[i]["ref per emp"]=ref_per_emp[i]
</code>```

Of course, you have to make sure, that both lists have the same size

Body:
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]

list

rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]

Desired output

[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]

I will appreciate any help in getting this done.
Thank you

Body:
It can be done like this:

for i in range(len(fortunne_500)):
  fortunne_500[i]["ref per emp"]=ref_per_emp[i]

Of course, you have to make sure, that both lists have the same size


问:
Could not load type 'WingTipToys.Global_asax'
I used to be a hobby programmer and still am. But, now I am trying to learn web application development and have been going through the first steps of Wingtiptoys project on MS site. After having done what was asked of me by the site and running the project for the first time...I get the below error on my browser.

QUOTE

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'WingTipToys.Global_asax'.

Source Error:

Line 1:  <%@ Application Codebehind="Global.asax.vb" Inherits="WingTipToys.Global_asax" Language="vb" %>

Source File: /global.asax    Line: 1

UNQUOTE

Can anyone help?

Thanks & Best Regards
Rajeev

答:
Thanks Michelle for trying to help and please accept my appology for not realizing that you were looking for the code as I assumed this was a common error for biginners. Anyways...below is the code from Global.asax.vb and at the very bottom is the code  from Global.asax

```<code>Namespace WingTipToys
Public Class [Global]
Inherits HttpApplication

Private Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
Database.SetInitializer(New ProductDatabaseInitializer)
End Sub
End Class
End Namespace
</code>```

Here is the code from Global.asax

```<code><%@ Application Codebehind="Global.asax.vb" Inherits="WingTipToys.Global.asax" language="vb" %>
</code>```

Body:
Thanks Michelle for trying to help and please accept my appology for not realizing that you were looking for the code as I assumed this was a common error for biginners. Anyways...below is the code from Global.asax.vb and at the very bottom is the code  from Global.asax

Namespace WingTipToys
Public Class [Global]
Inherits HttpApplication

Private Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
Database.SetInitializer(New ProductDatabaseInitializer)
End Sub
End Class
End Namespace

Here is the code from Global.asax

<%@ Application Codebehind="Global.asax.vb" Inherits="WingTipToys.Global.asax" language="vb" %>


问:
Confusion about `const` in compound assignment
The canonical implementation of operator+= passes the RHS as a const reference:

```<code>X& operator+=(const X& rhs)
</code>```

However, in

```<code>x += x;
</code>```

the RHS is modified. Does this invoke the UB?

答:
From dcl.type.cv:

A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but it is treated as if it does; a const-qualified access path cannot be used to modify an object even if the object referenced is a non-const object and can be modified through some other access path.

The reference rhs is const qualified, so it cannot be used to modify the object it refers to.

However, the object being referenced, i.e. x, is non-const, and so x itself can be modified through other access paths, e.g. in the definition of operator+=.

So the behavior is well defined in this code sample.

Body:
The canonical implementation of operator+= passes the RHS as a const reference:

X& operator+=(const X& rhs)

However, in

x += x;

the RHS is modified. Does this invoke the UB?


问:
Group data, rename the object property and create new dataset in NodeJs
I'm new on Stackoverflow and also new in JS.
I'm lost on how to manipulate data and need help.
I have a dataset which has some duplicated quoteDate. I need to create a new dataset by adding the prices under the its date with the option as a property Name.

Please see below original data:

```<code>const dataSet = [
      {"quoteDate":20190925,"price":39926,"option":0},
      {"quoteDate":20191118,"price":43239,"option":0},
      {"quoteDate":20190925,"price":77946,"option":1},
      {"quoteDate":20191125,"price":43178,"option":0},
      {"quoteDate":20191202,"price":46992,"option":0},
      {"quoteDate":20191210,"price":84596,"option":1},
      {"quoteDate":20191202,"price":32256,"option":1},
      {"quoteDate":20191223,"price":32285,"option":0},
      {"quoteDate":20200429,"price":68173,"option":1},
]
</code>```

Here is the desire end result:

```<code>const newDataSet = [
      {"Date": "20190925","A": 39926,"B": 77946,},
      {"Date": "20191118","A": 43239,},
      {"Date": "20191125","A": 43178,},
      {"Date": "20191202","A": 46992,"B": 32256,},
      {"Date": "20191210","B": 84596,},
      {"Date": "20191223","A": 32285,},
      {"Date": "20200429","B": 68173,},
    ]
</code>```

I"ve been trying below code but no success :(

```<code>let newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option})=>{
  if(!a[quoteDate] && a[option] === 0)
    a[quoteDate] = Object.assign({},{'A': price, Date: quoteDate });
  else if(!a[quoteDate] && a[option] === 1)
    a[quoteDate] = Object.assign({},{'B': price, Date: quoteDate });
  return a;
 },{}));
 console.log(newDataSet);
</code>```

That would be great if anyone can help me on this!

Thanks!

答:
I'd like to offer a functional approach using Map and a library I created. You may find this easier to maintain. You should use Maps over objects for heavy insertions, as they were created for that purpose. more on Maps

const { pipe, fork, map, switchCase, reduce, get, eq } = rubico

const dataSet = [
  {"quoteDate":20190925,"price":39926,"option":0},
  {"quoteDate":20191118,"price":43239,"option":0},
  {"quoteDate":20190925,"price":77946,"option":1},
  {"quoteDate":20191125,"price":43178,"option":0},
  {"quoteDate":20191202,"price":46992,"option":0},
  {"quoteDate":20191210,"price":84596,"option":1},
  {"quoteDate":20191202,"price":32256,"option":1},
  {"quoteDate":20191223,"price":32285,"option":0},
  {"quoteDate":20200429,"price":68173,"option":1},
]

const toString = x => `${x}`

const addQuotes = (q1, q2) => {
  const hasA = q1.A || q2.A
  const hasB = q1.B || q2.B
  return {
    Date: q1.Date,
    ...hasA && { A: (q1.A || 0) + (q2.A || 0) },
    ...hasB && { B: (q1.B || 0) + (q2.B || 0) },
  }
}

const incrementMap = (y, xi) => {
  if (y.has(xi.Date)) {
    y.set(xi.Date, addQuotes(y.get(xi.Date), xi))
  } else {
    y.set(xi.Date, xi)
  }
  return y
}

const xf = pipe([
  map(switchCase([
    eq(get('option'), 0),
    fork({
      Date: pipe([get('quoteDate'), toString]),
      A: get('price'),
    }),
    fork({
      Date: pipe([get('quoteDate'), toString]),
      B: get('price'),
    }),
  ])),
  reduce(incrementMap, new Map()),
  x => [...x.values()],
])

console.log(xf(dataSet))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rubico/index.js" crossorigin></script></code>```

Body:
I'm new on Stackoverflow and also new in JS.
I'm lost on how to manipulate data and need help.
I have a dataset which has some duplicated quoteDate. I need to create a new dataset by adding the prices under the its date with the option as a property Name.

Please see below original data:

const dataSet = [
      {"quoteDate":20190925,"price":39926,"option":0},
      {"quoteDate":20191118,"price":43239,"option":0},
      {"quoteDate":20190925,"price":77946,"option":1},
      {"quoteDate":20191125,"price":43178,"option":0},
      {"quoteDate":20191202,"price":46992,"option":0},
      {"quoteDate":20191210,"price":84596,"option":1},
      {"quoteDate":20191202,"price":32256,"option":1},
      {"quoteDate":20191223,"price":32285,"option":0},
      {"quoteDate":20200429,"price":68173,"option":1},
]

Here is the desire end result:

const newDataSet = [
      {"Date": "20190925","A": 39926,"B": 77946,},
      {"Date": "20191118","A": 43239,},
      {"Date": "20191125","A": 43178,},
      {"Date": "20191202","A": 46992,"B": 32256,},
      {"Date": "20191210","B": 84596,},
      {"Date": "20191223","A": 32285,},
      {"Date": "20200429","B": 68173,},
    ]

I"ve been trying below code but no success :(

let newDataSet = Object.values(dataSet.reduce((a, {price, quoteDate, option})=>{
  if(!a[quoteDate] && a[option] === 0)
    a[quoteDate] = Object.assign({},{'A': price, Date: quoteDate });
  else if(!a[quoteDate] && a[option] === 1)
    a[quoteDate] = Object.assign({},{'B': price, Date: quoteDate });
  return a;
 },{}));
 console.log(newDataSet);

That would be great if anyone can help me on this!

Thanks!

Body:
I'd like to offer a functional approach using Map and a library I created. You may find this easier to maintain. You should use Maps over objects for heavy insertions, as they were created for that purpose. more on Maps

const { pipe, fork, map, switchCase, reduce, get, eq } = rubico

const dataSet = [
  {"quoteDate":20190925,"price":39926,"option":0},
  {"quoteDate":20191118,"price":43239,"option":0},
  {"quoteDate":20190925,"price":77946,"option":1},
  {"quoteDate":20191125,"price":43178,"option":0},
  {"quoteDate":20191202,"price":46992,"option":0},
  {"quoteDate":20191210,"price":84596,"option":1},
  {"quoteDate":20191202,"price":32256,"option":1},
  {"quoteDate":20191223,"price":32285,"option":0},
  {"quoteDate":20200429,"price":68173,"option":1},
]

const toString = x => `${x}`

const addQuotes = (q1, q2) => {
  const hasA = q1.A || q2.A
  const hasB = q1.B || q2.B
  return {
    Date: q1.Date,
    ...hasA && { A: (q1.A || 0) + (q2.A || 0) },
    ...hasB && { B: (q1.B || 0) + (q2.B || 0) },
  }
}

const incrementMap = (y, xi) => {
  if (y.has(xi.Date)) {
    y.set(xi.Date, addQuotes(y.get(xi.Date), xi))
  } else {
    y.set(xi.Date, xi)
  }
  return y
}

const xf = pipe([
  map(switchCase([
    eq(get('option'), 0),
    fork({
      Date: pipe([get('quoteDate'), toString]),
      A: get('price'),
    }),
    fork({
      Date: pipe([get('quoteDate'), toString]),
      B: get('price'),
    }),
  ])),
  reduce(incrementMap, new Map()),
  x => [...x.values()],
])

console.log(xf(dataSet))

<script src="https://unpkg.com/rubico/index.js" crossorigin></script>


问:
AJAX IRC client, how?
I want to build a IRC client in Javascript, maybe using jQuery, but I am struggling a little in getting started.

I have looked a little at http://qwebirc.org/ and how they are doing things, but they have A LOT of code doing specific things only to their project.

I have searched the net for a short example, that lets me start, so I could build further. Any suggestions on where to look, or someone who can come up with an example?

答:
Here's an open source project that has made some progress to making a AJAX IRC client:
https://github.com/naneau/node-irc-client</p>

ContentLicense: CC BY-SA 3.0

Title: AJAX IRC client, how?


问:
how set ClickListener on drawable in Drawable class in android?
I have a class that extends from Drawable.
I draw some Views on it. I have drawable that I should set ClickListener on it!
I  searched a lot, and according to this link, we have not listener for this class!

anybody can help me ?! Thanks

答:
According to documentation, which you've already provided,

A Drawable is a general abstraction for "something that can be drawn."

...

Unlike a View, a Drawable does not have any facility to receive
  events or otherwise interact with the user.

Since the View provides a method to receive click events (setOnClickListener) and a method which sets its foreground to a Drawable (setForeground) why don't you use that?


问:
Generating branch instructions from an AST for a conditional expression
I am trying to write a compiler for a domain-specific language, targeting a stack-machine based VM that is NOT a JVM.

I have already generated a parser for my language, and can readily produce an AST which I can easily walk.  I also have had no problem converting many of the statements of my language into the appropriate instructions for this VM, but am facing an obstacle when it comes to the matter of handling the generation of appropriate branching instructions when complex conditionals are encountered, especially when they are combined with (possibly nested) 'and'-like or 'or' like operations which should use short-circuiting branching as applicable.

I am not asking anyone to write this for me.   I know that I have not begun to describe my problem in sufficient detail for that.  What I am asking for is pointers to useful material that can get me past this hurdle I am facing.   As I said, I am already past the point of converting about 90% of the statements in my language into applicable instructions, but it is the handling of conditionals and generating the appropriate flow control instructions that has got me stumped.  Much of the info that I have been able to find so far on generating code from an AST only seems to deal with the generation of code corresponding to simple imperative-like statements, but the handing of conditionals and flow control appears to be much more scarce.

Other than the short-circuiting/lazy-evaluation mechanism for 'and' and 'or' like constructs that I have described, I am not concerned with handling any other optimizations.

答:
Every conditional control flow can be modelled as a flow chart (or flow graph) in which the two branches of the conditional have different targets. Given that boolean operators short-circuit, they are control flow elements rather than simple expressions, and they need to be modelled as such.

One way to think about this is to rephrase boolean operators as instances of the ternary conditional operator. So, for example, A and B becomes A ? B : false and A or B becomes A ? true : B [Note 1]. Note that every control flow diagram has precisely two output points.

To combine boolean expressions, just substitute into the diagram. For example, here's A AND (B OR C)

You implement NOT by simply swapping the meaning of the two out-flows.

If the eventual use of the boolean expression is some kind of conditional, such as an if statement or a conditional loop, you can use the control flow as is. If the boolean expression is to be saved into a variable or otherwise used as a value, you need to fill in the two outflows with code to create the relevant constant, usually a true or false boolean constant, or (in C-like languages) a 1 or 0.

Notes:

Another way to write this equivalence is A and B ⇒ A ? B : A; A or B ⇒ A ? A : B, but that is less useful for a control flow view, and also clouds the fact that the intent is to only evaluate each expression once. This form (modified to reuse the initial computation of A) is commonly used in languages with multiple "falsey" values (like Python).


问:
How to return a Boolean as an expressiont to replace if, else true and false
I am trying to solve a challenge in freecodecamp and I dont want to write twice return true and false.
Instead I am looking for minimizing code and write an expression that evaluates to a boolean </p>

```<code>function confirmEnding(str, target) {

    if(str.substr(-target.length) === target){

        //Code that evaluates and returns and expression as a boolean

    }

}

console.log(confirmEnding("Connor" , "n"));
</code>```

答:
Simply return the boolean value of evaluating the expression

function confirmEnding(str, target) {
  return str.substr(-target.length) === target;
}

console.log(confirmEnding("hello", "lo"));
console.log(confirmEnding("loollo", "lo"));
console.log(confirmEnding("leo", "lo"));```
</div>
</div>
</p>

<p>Here is another way</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function confirmEnding(str, target) {
  return str.lastIndexOf(target) + target.length === str.length;
}

console.log(confirmEnding("hello", "lo"));
console.log(confirmEnding("loollo", "lo"));
console.log(confirmEnding("leo", "lo"));</code>```

Body:
I am trying to solve a challenge in freecodecamp and I dont want to write twice return true and false.
Instead I am looking for minimizing code and write an expression that evaluates to a boolean

function confirmEnding(str, target) {

    if(str.substr(-target.length) === target){

        //Code that evaluates and returns and expression as a boolean

    }

}

console.log(confirmEnding("Connor" , "n"));

Body:
Simply return the boolean value of evaluating the expression

function confirmEnding(str, target) {
  return str.substr(-target.length) === target;
}

console.log(confirmEnding("hello", "lo"));
console.log(confirmEnding("loollo", "lo"));
console.log(confirmEnding("leo", "lo"));

Here is another way

function confirmEnding(str, target) {
  return str.lastIndexOf(target) + target.length === str.length;
}

console.log(confirmEnding("hello", "lo"));
console.log(confirmEnding("loollo", "lo"));
console.log(confirmEnding("leo", "lo"));


问:
How can I set an object to a constant and display the value in react?
This is the app component :

```<code>function App() {
    const [ url, setUrl ] = useState({});
    const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            console.log(res);
            setUrl(res.config.url);
        });
    };

    return (
        <div className="App">
            <button onClick={() => fetch()}>Click</button>
            {url.length ? url : null}
        </div>
    );
}
</code>```

This actually works and it displays the url string which is https://jsonplaceholder.typicode.com/posts when I click the button
on the page but What I really want to do is to set the res whole object to the url constant and then display the config.url like this :

```<code>const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            setUrl(res);
        });
    };

</code>```

and then :

```<code><button onClick={() => fetch()}>Click</button>
            {url.length ? url.config.url : null}
</code>```

but it doesn't work and it also does not throw an error .

How can I set the whole res object to url constant and then display url.config.url when I click the button ?

答:
url.config is undefined until the axios request is made. You need to check that url.config is not undefined, if true, display url.config.url, else null.</p>

```<code><button onClick={() => fetch()}>Click</button>
        {typeof url.config !== 'undefined' ? url.config.url : null}
</code>```

Body:
This is the app component :

function App() {
    const [ url, setUrl ] = useState({});
    const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            console.log(res);
            setUrl(res.config.url);
        });
    };

    return (

            <button onClick={() => fetch()}>Click</button>
            {url.length ? url : null}

    );
}

This actually works and it displays the url string which is https://jsonplaceholder.typicode.com/posts when I click the button
on the page but What I really want to do is to set the res whole object to the url constant and then display the config.url like this :

const fetch = () => {
        axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
            setUrl(res);
        });
    };

and then :

<button onClick={() => fetch()}>Click</button>
            {url.length ? url.config.url : null}

but it doesn't work and it also does not throw an error .

How can I set the whole res object to url constant and then display url.config.url when I click the button ?

Body:
url.config is undefined until the axios request is made. You need to check that url.config is not undefined, if true, display url.config.url, else null.

<button onClick={() => fetch()}>Click</button>
        {typeof url.config !== 'undefined' ? url.config.url : null}


问:
Wait for ngInit before creating a method
I want to use this.user variables, but unfortunately I must use observable in ngOnInit method to get them, so when I try to reach this.user.username, it shows undefined, because it doesn't loaded.

@Injectable({ providedIn: 'root' })
export class SettingsService implements OnInit {
  user: User | null = null;

  userSubscription: Subscription;

  constructor(
    private http: HttpClient,
    private authService: AuthenticationService
  ) {}

  ngOnInit(): void {
    this.userSubscription = this.authService.getUser().subscribe((user) => {
      if (user !== null) {
        this.user = user;
        return;
      }
    });
  }

  changeUsername(username: string): Observable<{ message: string }> {
    console.log(username);
    console.log(this.user.username);
    return this.http.post<{ message: string }>(
      `${environment.apiUri}/users/${this.user.username}/username`,
      {
        username,
      }
    );
  }
}
```

Can I kinda merge it together?

答:
You could make this.user an RxJS BehaviorSubject observable as well. So now you can push the user to the observable and it can be listened to in the changeUsername function. Then switchMap operator could be used to map the user value to the HTTP request. Note that if the user value is still null, we return an RxJS EMPTY instead of the request. Try the following

import { BehaviorSubject, EMPTY, Observable } import 'rxjs';
import { switchMap, take } import 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class SettingsService implements OnInit {
  user = new BehaviorSubject<User | null>(null);

  userSubscription: Subscription;

  constructor(
    private http: HttpClient,
    private authService: AuthenticationService
  ) {}

  ngOnInit(): void {
    this.userSubscription = this.authService.getUser().subscribe((user) => {
      if (user !== null) {
        this.user.next(user);       // <-- push it to the observable
        // `return` isn't required here
      }
    });
  }

  changeUsername(username: string): Observable<{ message: string }> {
    console.log(username);
    return this.user.pipe(
      take(1),
      switchMap(user => {
        console.log(user.username);
        if (user) {
          return this.http.post<{ message: string }>(`${environment.apiUri}/users/${this.user.username}/username`, { username });
        } else {
          return EMPTY;
        }
      });
    );
  }
}
```

Update from comment

You could still subscribe to changeUsername function as before. Only difference is the call is made only if the this.user variable isn't null. You could also return an error (eg. using throwError) instead of EMPTY and retry the request after some time using retryWhen operator with a delay (eg. using timer).

Body:
I want to use this.user variables, but unfortunately I must use observable in ngOnInit method to get them, so when I try to reach this.user.username, it shows undefined, because it doesn't loaded.

@Injectable({ providedIn: 'root' })
export class SettingsService implements OnInit {
  user: User | null = null;

  userSubscription: Subscription;

  constructor(
    private http: HttpClient,
    private authService: AuthenticationService
  ) {}

  ngOnInit(): void {
    this.userSubscription = this.authService.getUser().subscribe((user) => {
      if (user !== null) {
        this.user = user;
        return;
      }
    });
  }

  changeUsername(username: string): Observable<{ message: string }> {
    console.log(username);
    console.log(this.user.username);
    return this.http.post<{ message: string }>(
      `${environment.apiUri}/users/${this.user.username}/username`,
      {
        username,
      }
    );
  }
}

Can I kinda merge it together?

Body:
You could make this.user an RxJS BehaviorSubject observable as well. So now you can push the user to the observable and it can be listened to in the changeUsername function. Then switchMap operator could be used to map the user value to the HTTP request. Note that if the user value is still null, we return an RxJS EMPTY instead of the request. Try the following

import { BehaviorSubject, EMPTY, Observable } import 'rxjs';
import { switchMap, take } import 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class SettingsService implements OnInit {
  user = new BehaviorSubject<User | null>(null);

  userSubscription: Subscription;

  constructor(
    private http: HttpClient,
    private authService: AuthenticationService
  ) {}

  ngOnInit(): void {
    this.userSubscription = this.authService.getUser().subscribe((user) => {
      if (user !== null) {
        this.user.next(user);       // <-- push it to the observable
        // `return` isn't required here
      }
    });
  }

  changeUsername(username: string): Observable<{ message: string }> {
    console.log(username);
    return this.user.pipe(
      take(1),
      switchMap(user => {
        console.log(user.username);
        if (user) {
          return this.http.post<{ message: string }>(`${environment.apiUri}/users/${this.user.username}/username`, { username });
        } else {
          return EMPTY;
        }
      });
    );
  }
}

Update from comment

You could still subscribe to changeUsername function as before. Only difference is the call is made only if the this.user variable isn't null. You could also return an error (eg. using throwError) instead of EMPTY and retry the request after some time using retryWhen operator with a delay (eg. using timer).


问:
Error: Client doesn't have permission to access the desired data
I've been working on this for perhaps a day but I can't get it to work at all. I set up a database with no security rules:

Then I try to access it in my angular fire app:

```<code>this.afDatabase
    .object("/test/test")
    .snapshotChanges()
    .subscribe(x => {
        console.log(x);
    });
</code>```

But I still get the following permission errors:

Error: permission_denied at /test/test: Client doesn't have permission to access the desired data.

I also ran the simulator and got successful results:

I also set up my environment.ts file:

Am I doing something wrong?

答:
This is an issue on firebase side. You need to update Real-time database rules:</p>

```<code>"rules": {
    ".read": true,
    ".write": true
  }
</code>```

Body:
I've been working on this for perhaps a day but I can't get it to work at all. I set up a database with no security rules:

Then I try to access it in my angular fire app:

this.afDatabase
    .object("/test/test")
    .snapshotChanges()
    .subscribe(x => {
        console.log(x);
    });

But I still get the following permission errors:

Error: permission_denied at /test/test: Client doesn't have permission to access the desired data.

I also ran the simulator and got successful results:

I also set up my environment.ts file:

Am I doing something wrong?

Body:
This is an issue on firebase side. You need to update Real-time database rules:

"rules": {
    ".read": true,
    ".write": true
  }


问:
rspec: failure/error: _send_(method, file). syntaxError: 104: syntax error, unexpected keyword_end, expecting end-of-input
After doing the bundle exec rspec in the terminal window.  I received two errors: [Failure/Error: send(method, file) and Syntax Error: /vagrant/src/grammable/spec/controllers/grams_controller_spec.rb:104: syntax error, unexpected keyword_end, expecting end-of-input].  I am unable to passing the test due to 1 error occurred outside of examples.

```<code>require 'rails_helper'

RSpec.describe GramsController, type: :controller
    describe "grams#update action" do
        it "should allow users to successfully update grams" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: 'Changed' } }
            expect(response).to redirect_to root_path
            gram.reload
            expect(gram.message).to eq "Changed"
        end

        it "should have http 404 error if the gram cannot be found" do
            patch :update, params: { id: "YOLOSWAG", gram: { message: 'Changed' } }
            expect(response).to have_http_status(:not_found)
        end

        it "should render the edit form with an http status of unprocessable_entity" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            gram.reload
            expect(gram.message).to eq "Initial Value"
        end
    end

    describe "grams#edit action" do
        it "should successfully show the edit form if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :edit, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error message if the gram is not found" do
            get :edit, params: { id: 'SWAG' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#show action" do
        it "should successfully show the page if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :show, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error if the gram is not found" do
            get :show, params: { id: 'TACOCAT' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#index action" do
        it "should successfully show the page" do
            get :index
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#new action" do

        it "should require users to be logged in" do
            get :new
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully show the new form" do
            user = FactoryBot.create(:user)
            sign_in user

            get :new
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#create action" do

        it "should require users to be logged in" do
            post :create, params: { gram: { message: "Hello" } }
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully create a new gram in our database" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: 'Hello!' } }
            expect(response).to redirect_to root_path

            gram = Gram.last
            expect(gram.message).to eq("Hello!")
            expect(gram.user).to eq(user)
        end

        it "should properly deal with validation errors" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            expect(Gram.count).to eq Gram.count
        end
    end
end
</code>```

答:
I think you have missed do in the first line  RSpec.describe GramsController, type: :controller. Find below the edited code. Hope this helps!

```<code>require 'rails_helper'

RSpec.describe GramsController, type: :controller do
    describe "grams#update action" do
        it "should allow users to successfully update grams" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: 'Changed' } }
            expect(response).to redirect_to root_path
            gram.reload
            expect(gram.message).to eq "Changed"
        end

        it "should have http 404 error if the gram cannot be found" do
            patch :update, params: { id: "YOLOSWAG", gram: { message: 'Changed' } }
            expect(response).to have_http_status(:not_found)
        end

        it "should render the edit form with an http status of unprocessable_entity" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            gram.reload
            expect(gram.message).to eq "Initial Value"
        end
    end

    describe "grams#edit action" do
        it "should successfully show the edit form if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :edit, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error message if the gram is not found" do
            get :edit, params: { id: 'SWAG' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#show action" do
        it "should successfully show the page if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :show, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error if the gram is not found" do
            get :show, params: { id: 'TACOCAT' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#index action" do
        it "should successfully show the page" do
            get :index
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#new action" do

        it "should require users to be logged in" do
            get :new
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully show the new form" do
            user = FactoryBot.create(:user)
            sign_in user

            get :new
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#create action" do

        it "should require users to be logged in" do
            post :create, params: { gram: { message: "Hello" } }
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully create a new gram in our database" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: 'Hello!' } }
            expect(response).to redirect_to root_path

            gram = Gram.last
            expect(gram.message).to eq("Hello!")
            expect(gram.user).to eq(user)
        end

        it "should properly deal with validation errors" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            expect(Gram.count).to eq Gram.count
        end
    end
end
</code>```

Body:
After doing the bundle exec rspec in the terminal window.  I received two errors: [Failure/Error: send(method, file) and Syntax Error: /vagrant/src/grammable/spec/controllers/grams_controller_spec.rb:104: syntax error, unexpected keyword_end, expecting end-of-input].  I am unable to passing the test due to 1 error occurred outside of examples.

require 'rails_helper'

RSpec.describe GramsController, type: :controller
    describe "grams#update action" do
        it "should allow users to successfully update grams" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: 'Changed' } }
            expect(response).to redirect_to root_path
            gram.reload
            expect(gram.message).to eq "Changed"
        end

        it "should have http 404 error if the gram cannot be found" do
            patch :update, params: { id: "YOLOSWAG", gram: { message: 'Changed' } }
            expect(response).to have_http_status(:not_found)
        end

        it "should render the edit form with an http status of unprocessable_entity" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            gram.reload
            expect(gram.message).to eq "Initial Value"
        end
    end

    describe "grams#edit action" do
        it "should successfully show the edit form if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :edit, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error message if the gram is not found" do
            get :edit, params: { id: 'SWAG' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#show action" do
        it "should successfully show the page if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :show, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error if the gram is not found" do
            get :show, params: { id: 'TACOCAT' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#index action" do
        it "should successfully show the page" do
            get :index
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#new action" do

        it "should require users to be logged in" do
            get :new
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully show the new form" do
            user = FactoryBot.create(:user)
            sign_in user

            get :new
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#create action" do

        it "should require users to be logged in" do
            post :create, params: { gram: { message: "Hello" } }
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully create a new gram in our database" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: 'Hello!' } }
            expect(response).to redirect_to root_path

            gram = Gram.last
            expect(gram.message).to eq("Hello!")
            expect(gram.user).to eq(user)
        end

        it "should properly deal with validation errors" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            expect(Gram.count).to eq Gram.count
        end
    end
end

Body:
I think you have missed do in the first line  RSpec.describe GramsController, type: :controller. Find below the edited code. Hope this helps!

require 'rails_helper'

RSpec.describe GramsController, type: :controller do
    describe "grams#update action" do
        it "should allow users to successfully update grams" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: 'Changed' } }
            expect(response).to redirect_to root_path
            gram.reload
            expect(gram.message).to eq "Changed"
        end

        it "should have http 404 error if the gram cannot be found" do
            patch :update, params: { id: "YOLOSWAG", gram: { message: 'Changed' } }
            expect(response).to have_http_status(:not_found)
        end

        it "should render the edit form with an http status of unprocessable_entity" do
            gram = FactoryBot.create(:gram, message: "Initial Value")
            patch :update, params: { id: gram.id, gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            gram.reload
            expect(gram.message).to eq "Initial Value"
        end
    end

    describe "grams#edit action" do
        it "should successfully show the edit form if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :edit, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error message if the gram is not found" do
            get :edit, params: { id: 'SWAG' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#show action" do
        it "should successfully show the page if the gram is found" do
            gram = FactoryBot.create(:gram)
            get :show, params: { id: gram.id }
            expect(response).to have_http_status(:success)
        end

        it "should return a 404 error if the gram is not found" do
            get :show, params: { id: 'TACOCAT' }
            expect(response).to have_http_status(:not_found)
        end
    end

    describe "grams#index action" do
        it "should successfully show the page" do
            get :index
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#new action" do

        it "should require users to be logged in" do
            get :new
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully show the new form" do
            user = FactoryBot.create(:user)
            sign_in user

            get :new
            expect(response).to have_http_status(:success)
        end
    end

    describe "grams#create action" do

        it "should require users to be logged in" do
            post :create, params: { gram: { message: "Hello" } }
            expect(response).to redirect_to new_user_session_path
        end

        it "should successfully create a new gram in our database" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: 'Hello!' } }
            expect(response).to redirect_to root_path

            gram = Gram.last
            expect(gram.message).to eq("Hello!")
            expect(gram.user).to eq(user)
        end

        it "should properly deal with validation errors" do
            user = FactoryBot.create(:user)
            sign_in user

            post :create, params: { gram: { message: '' } }
            expect(response).to have_http_status(:unprocessable_entity)
            expect(Gram.count).to eq Gram.count
        end
    end
end


问:
How to save Angular signaturePad blob to AWS S3 using flask
I am using the signaturePad and converting the base64 file to blob. From here i upload it onto s3 but when I download the file it's corrupted.
I don't have any issues generating and uploading the file but when I downloaded the image from s3 I can not open it on my local drive.
What I am I doing wrong?

This is my code

```<code>   drawSignature() {
        if (this.signaturePad.isEmpty()) {
          alert('Please provide a signature first')
        } else {
          const base64 = this.signaturePad.toDataURL('image/png', 0.5);
          const blob = this.base64toBlob(base64);
          const fd = new FormData();
          fd.append('image', blob);
          this.registrationService.saveSignatureRequest(fd)
            .subscribe(() => this.registrationService.successMessage(),
(error) => this.formError = error['error'][0])
        }
      }

  base64toBlob(base64: string) {
    let sliceSize = 512;
    const byteString = atob(base64.split(',')[1]);
    const contentType = base64.split(',')[0].split(';')[0].split(':')[1];
    var byteArrays = [];
    for (var offset = 0; offset < byteString.length; offset += sliceSize) {
      var slice = byteString.slice(offset, offset + sliceSize);
      const byteNumber = new Array(slice.length);
      for (let i = 0; i < byteNumber.length; i++) {
        byteNumber[i] = byteString.charAt(i);
      }
      var byteArray = new Uint8Array(byteNumber);
      byteArrays.push(byteArray);
    }
    var blob = new Blob(byteArrays, { type: contentType });
    return blob;
  }
</code>```

Function to upload file into S3

```<code>   def save_signature(self, file, object_name=None):
        filename = str(file)
        with current_app.app_context():
            from application.app import create_app
            app = create_app(current_app.config['DEV'])
            s3 = boto3.client(
                "s3",
                aws_access_key_id=app.config['AWS_ACCESS_KEY_ID'],
                aws_secret_access_key=app.config['AWS_SECRET_ACCESS_KEY']
            )
            bucket = app.config['S3_LOCATION']
            bucket_resource = s3
            try:
                file_storage_keys = [
                    file_key for file_key in object_name.keys()]
                if file_storage_keys:
                    file_storage_keys = file_storage_keys[0]
                else:
                    return
                file_storage = object_name[file_storage_keys]

                bucket_resource.put_object(Body=file_storage,
                                           Bucket=bucket,
                                           Key=filename+'.png',
                                           ContentType='image/png',
                                           ContentEncoding='utf-8')
            except ClientError as e:
                logging.error(e)
                return False
            return True
</code>```

答:
Try changing your base-64 to blob method to :- </p>

```<code>base64toBlob(b64Data) {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];
  let sliceSize = 512;
  const contentType = base64.split(',')[0].split(';')[0].split(':')[1];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
</code>```

Body:
I am using the signaturePad and converting the base64 file to blob. From here i upload it onto s3 but when I download the file it's corrupted.
I don't have any issues generating and uploading the file but when I downloaded the image from s3 I can not open it on my local drive.
What I am I doing wrong?

This is my code

   drawSignature() {
        if (this.signaturePad.isEmpty()) {
          alert('Please provide a signature first')
        } else {
          const base64 = this.signaturePad.toDataURL('image/png', 0.5);
          const blob = this.base64toBlob(base64);
          const fd = new FormData();
          fd.append('image', blob);
          this.registrationService.saveSignatureRequest(fd)
            .subscribe(() => this.registrationService.successMessage(),
(error) => this.formError = error['error'][0])
        }
      }

  base64toBlob(base64: string) {
    let sliceSize = 512;
    const byteString = atob(base64.split(',')[1]);
    const contentType = base64.split(',')[0].split(';')[0].split(':')[1];
    var byteArrays = [];
    for (var offset = 0; offset < byteString.length; offset += sliceSize) {
      var slice = byteString.slice(offset, offset + sliceSize);
      const byteNumber = new Array(slice.length);
      for (let i = 0; i < byteNumber.length; i++) {
        byteNumber[i] = byteString.charAt(i);
      }
      var byteArray = new Uint8Array(byteNumber);
      byteArrays.push(byteArray);
    }
    var blob = new Blob(byteArrays, { type: contentType });
    return blob;
  }

Function to upload file into S3

   def save_signature(self, file, object_name=None):
        filename = str(file)
        with current_app.app_context():
            from application.app import create_app
            app = create_app(current_app.config['DEV'])
            s3 = boto3.client(
                "s3",
                aws_access_key_id=app.config['AWS_ACCESS_KEY_ID'],
                aws_secret_access_key=app.config['AWS_SECRET_ACCESS_KEY']
            )
            bucket = app.config['S3_LOCATION']
            bucket_resource = s3
            try:
                file_storage_keys = [
                    file_key for file_key in object_name.keys()]
                if file_storage_keys:
                    file_storage_keys = file_storage_keys[0]
                else:
                    return
                file_storage = object_name[file_storage_keys]

                bucket_resource.put_object(Body=file_storage,
                                           Bucket=bucket,
                                           Key=filename+'.png',
                                           ContentType='image/png',
                                           ContentEncoding='utf-8')
            except ClientError as e:
                logging.error(e)
                return False
            return True

Body:
Try changing your base-64 to blob method to :-

base64toBlob(b64Data) {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];
  let sliceSize = 512;
  const contentType = base64.split(',')[0].split(';')[0].split(':')[1];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}


问:
Add COUNT in Javascript alert box
This page is where user will select the semester and program, then alert box will prompted on the selected program as per the image below.

Image

Javascript

```<code><script type="text/javascript">

$(document).ready(function(){

$("#prg").change(function(){
 var selectedcount = $('#prg option:selected').data('count');

alert ("The next intake for " +selectedcount + " will have    "    + "students");
}); </script>
</code>```

Body

```<code><div class="modal-body">
        <div class="form-group">
              <label for="title">Select Current Semester:</label>
              <select name="semester" class="form-control">
                  <option value="">--- Select Current Semester ---</option>

                  <?php
                    require('../setting/config.php');
                      $query = "SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC";
                      $do = mysqli_query($conn, $query);
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].'">'.$row['semester'].'</option>';
                      }
                  ?>
              </select>
          </div>
          <div class="form-group">
              <label for="title">Select Programme:</label>
              <select id="prg" name="prg" class="form-control">
                <option value="">--- Select Programme ---</option>

                  <?php
                      $query2 = "SELECT student_prg, COUNT(student_prg) as count FROM marketing_data GROUP BY student_prg ORDER BY student_prg DESC";
                      $do = mysqli_query($conn, $query2);
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].' data-count="'.$row['count'].'">'.$row['student_prg'].'</option>';
                      }
                ?>
              </select>
</code>```

I wants the alert box to add on the number of students as well. Eg: *The next intake for Bachelor of Multimedia Industry (Hons) will have 36 students*

Could you assist on where and how to add the count query so that it will be shown in the alert box as I mentioned.

Database

```<code>mysql> describe marketing_data;
+---------------+------------------+------+-----+---------+--------------------+
| Field         | Type                 | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+--------------------+
| student_matric| varchar(10) unsigned | NO   | PRI | NULL    | auto_increment |
| student_prg   | text unsigned        | YES  |     | NULL    |                |
| semester      | varchar(10)          | YES  |     | NULL    |                |
| intake_year   | int(10)              | YES  |     | NULL    |                |
| student_city  | text                 | YES  |     | NULL    |                |
| city_lat      | varchar(20)          | YES  |     | NULL    |                |
| city_long     | varchar(20)          | YES  |     | NULL    |                |
| student_state | text                 | YES  |     | NULL    |                |
| state_code    | varchar(100)         | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+--------------------+
</code>```

答:
You can return the counts for each record with a query like this:

```<code>SELECT student_prg, COUNT(student_prg) as count FROM marketing_data GROUP BY student_prg ORDER BY student_prg DESC
</code>```

Your results will now have a count of the number of each student_prg values.

Then I would probably add the count as a data attribute of the options that you're writing:

```<code>echo '<option value="'.$row['student_prg'].' data-count="'.$row['count'].'">'.$row['student_prg'].'</option>';
</code>```

Then you can select the value from the newly selected option.

Title: Add COUNT in Javascript alert box

Body:
This page is where user will select the semester and program, then alert box will prompted on the selected program as per the image below.

Image

Javascript

Body

              Select Current Semester:
              <select name="semester" class="form-control">
                  <option value="">--- Select Current Semester ---</option>

                  <?php
                    require('../setting/config.php');
                      $query = "SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC";
                      $do = mysqli_query($conn, $query);
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].'">'.$row['semester'].'</option>';
                      }
                  ?>
              </select>

              Select Programme:
              <select id="prg" name="prg" class="form-control">
                <option value="">--- Select Programme ---</option>

                  <?php
                      $query2 = "SELECT student_prg, COUNT(student_prg) as count FROM marketing_data GROUP BY student_prg ORDER BY student_prg DESC";
                      $do = mysqli_query($conn, $query2);
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].' data-count="'.$row['count'].'">'.$row['student_prg'].'</option>';
                      }
                ?>
              </select>

I wants the alert box to add on the number of students as well. Eg: *The next intake for Bachelor of Multimedia Industry (Hons) will have 36 students*

Could you assist on where and how to add the count query so that it will be shown in the alert box as I mentioned.

Database

mysql> describe marketing_data;
+---------------+------------------+------+-----+---------+--------------------+
| Field         | Type                 | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+--------------------+
| student_matric| varchar(10) unsigned | NO   | PRI | NULL    | auto_increment |
| student_prg   | text unsigned        | YES  |     | NULL    |                |
| semester      | varchar(10)          | YES  |     | NULL    |                |
| intake_year   | int(10)              | YES  |     | NULL    |                |
| student_city  | text                 | YES  |     | NULL    |                |
| city_lat      | varchar(20)          | YES  |     | NULL    |                |
| city_long     | varchar(20)          | YES  |     | NULL    |                |
| student_state | text                 | YES  |     | NULL    |                |
| state_code    | varchar(100)         | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+--------------------+

Body:
You can return the counts for each record with a query like this:

SELECT student_prg, COUNT(student_prg) as count FROM marketing_data GROUP BY student_prg ORDER BY student_prg DESC

Your results will now have a count of the number of each student_prg values.

Then I would probably add the count as a data attribute of the options that you're writing:

echo '<option value="'.$row['student_prg'].' data-count="'.$row['count'].'">'.$row['student_prg'].'</option>';

Then you can select the value from the newly selected option.


问:
How to flatten a nested dict and use inner values on collision
Question

For the following dictionary:

```<code>{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
</code>```

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

```<code>{k:v for (k,v) in d.items() if not k == 'remove_me'}
</code>```

yields:

```<code>{'id': 1, 'label': 'hello'}
</code>```

not exactly what I need as I'm dropping the nested dict.

Desired output:

```<code>{'id': 1, 'label': 'hello','keep_me': 52}
</code>```

答:
I think this can be done in a general case with a single recursive function with something like:</p>

```<code>def remove_keys(d, keys):
    if not isinstance(d, dict):
        return d
    ret = {}
    for k, v in d.items():
        clean = remove_keys(v, keys)
        if k not in bad_keys:
            ret[k] = clean
        else:
            if isinstance(clean, dict):
                ret.update(clean)

    return ret

bad_keys = ['remove_me', 'world']

d = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
remove_keys(d, bad_keys)
# {'id': 1, 'label': 'hello', 'keep_me': 52}

d = {'id': 1, 'label': 'hello', 'remove_me': 52}
remove_keys(d, bad_keys)
# {'id': 1, 'label': 'hello'}

d = {'id': 1, 'label': 'hello', 'dont_remove_me': {'world': {'keep_me': 52}}}
remove_keys(d, bad_keys)
# {'id': 1, 'label': 'hello', 'dont_remove_me': {'keep_me': 52}}
</code>```

Body:
Question

For the following dictionary:

{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}

I want to create a new dictionary without the remove_me or world keys.

Edit update:

To summarise, I wanted to do the following:

If the values of an item are a nested dictionary. Update the new dictionary with the inner result while removing the current key value from the main dict.

If the values of an item are not a nested dictionary, update the new dictionary with the key, value.

The accepted answer covers this.

What have I tried?

{k:v for (k,v) in d.items() if not k == 'remove_me'}

yields:

{'id': 1, 'label': 'hello'}

not exactly what I need as I'm dropping the nested dict.

Desired output:

{'id': 1, 'label': 'hello','keep_me': 52}

Body:
I think this can be done in a general case with a single recursive function with something like:

def remove_keys(d, keys):
    if not isinstance(d, dict):
        return d
    ret = {}
    for k, v in d.items():
        clean = remove_keys(v, keys)
        if k not in bad_keys:
            ret[k] = clean
        else:
            if isinstance(clean, dict):
                ret.update(clean)

    return ret

bad_keys = ['remove_me', 'world']

d = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
remove_keys(d, bad_keys)
# {'id': 1, 'label': 'hello', 'keep_me': 52}

d = {'id': 1, 'label': 'hello', 'remove_me': 52}
remove_keys(d, bad_keys)
# {'id': 1, 'label': 'hello'}

d = {'id': 1, 'label': 'hello', 'dont_remove_me': {'world': {'keep_me': 52}}}
remove_keys(d, bad_keys)
# {'id': 1, 'label': 'hello', 'dont_remove_me': {'keep_me': 52}}


问:
2 dimensional char array creation/initialization in Java
I've found my answer here multiple times both for programming problems, but thing is this time i can't, not in here, not in the web generally so here i am asking.

i'm getting this error

On the public char pinakas[][] - 4th line while i'm trying to create/initialize my 2 dimensional char array (it's going to store chars from A to Z)

```<code>public class Board {

    public char pinakas[][];
    pinakas = new char[4][3];

    // constructor - initialize
    public Board() {

        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 4; j++) {
                pinakas[i][j] = '*';
            }
        }
    }

    // Fill board with *
    public void fillBoard1() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 4; j++) {
                pinakas[i][j] = '*';
            }
        }
    }

    // Fill board with A
    public void fillBoard2() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 4; j++) {
                pinakas[i][j] = 'A';
            }
        }
    }
}
</code>```

Please help, i'm going insane
(i'm Using Eclipse and coding in Java (huehue))

答:
simply use:

```<code>char pinakas[][]=new char[5][4];
</code>```

Avoid declaration and initialisation in diiferent steps or do that outside the class.

OR use :

```<code>char pinakas[][]=new char[4][3];
</code>```

then change the limit of each iteration(decrement each of them by one).

Body:
I've found my answer here multiple times both for programming problems, but thing is this time i can't, not in here, not in the web generally so here i am asking.

i'm getting this error

On the public char pinakas[][] - 4th line while i'm trying to create/initialize my 2 dimensional char array (it's going to store chars from A to Z)

public class Board {

    public char pinakas[][];
    pinakas = new char[4][3];

    // constructor - initialize
    public Board() {

        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 4; j++) {
                pinakas[i][j] = '*';
            }
        }
    }

    // Fill board with *
    public void fillBoard1() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 4; j++) {
                pinakas[i][j] = '*';
            }
        }
    }

    // Fill board with A
    public void fillBoard2() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 4; j++) {
                pinakas[i][j] = 'A';
            }
        }
    }
}

Please help, i'm going insane
(i'm Using Eclipse and coding in Java (huehue))

Body:
simply use:

char pinakas[][]=new char[5][4];

Avoid declaration and initialisation in diiferent steps or do that outside the class.

OR use :

char pinakas[][]=new char[4][3];

then change the limit of each iteration(decrement each of them by one).


问:
Multiple users accessing the same BDE Alias, but accessing different directories
Background:
I have an application written in Delphi that uses the Borland Database Engine (BDE) that looks at its data through a BDE Alias.  I've managed to get it running via Remote Desktop Services, where each user looks at the same location for the data.  Which is great if everyone wants to look at the same data.  However I want to be able to get two groups (or more) of users looking at different data.  I'm in the process of rewriting the application so that this situation is possible, but I need a stop-gap measure.

Question:

Is there a way for two applications to be looking at the same BDE Alias, but the directory that it refers to is different for each application?

or

Is it possible to have two users logged in via RDS (Remote Desktop Services - under Server 2008 or SBS 2008/11) to get two different configurations of the BDE? (one user sees the alias DATA to be c:\users\joe\data the other to see it as c:\users\bob\data for instance).

答:
The whole point of using an alias is to be able to set in ONE place to use ONE folder. Changing the ALIAS changes the folder EVERYWHERE.

If you don't want to use an ALIAS, use the directory directly in your application instead of the ALIAS, this can be done with a TDatabase.DatabaseName (if my memory servers me well - can't start Delphi at the moment to verify this).


问:
incompatible types in assignment of 'char[10]' to 'char [50]'
I am always taking these "incompatible types in the assignment of 'const char [5]' to 'char [50]'" or like that problem.

```<code>#include <stdio.h>
#include <stdlib.h>
struct Lessons{
    char name[50];
    float note;
    int credit;
}lesson1,lesson2;

int main(){
lesson1.name = "Math";

printf("%s",lesson1.name);

return 0;
}
</code>```

The problem in lesson1.name = "Math";.But i can't solving.

答:
You cant copy strings in C by assigning them.

You need to use the string copy function (called strcpy) from the standard library

then

```<code> strcpy(lesson1.name, "Math");
</code>```

The only exception from this rule is initialization of the array by string literal or compound literal.

example:

```<code>int main()
{
     char str[] = "This is string literal";
     struct Lessons lesson3 = {.name = "This is name",};
}
</code>```

where the literal is copied by the function prologue code.

Body:
I am always taking these "incompatible types in the assignment of 'const char [5]' to 'char [50]'" or like that problem.

#include <stdio.h>
#include <stdlib.h>
struct Lessons{
    char name[50];
    float note;
    int credit;
}lesson1,lesson2;

int main(){
lesson1.name = "Math";

printf("%s",lesson1.name);

return 0;
}

The problem in lesson1.name = "Math";.But i can't solving.

Body:
You cant copy strings in C by assigning them.

You need to use the string copy function (called strcpy) from the standard library

then

 strcpy(lesson1.name, "Math");

The only exception from this rule is initialization of the array by string literal or compound literal.

example:

int main()
{
     char str[] = "This is string literal";
     struct Lessons lesson3 = {.name = "This is name",};
}

where the literal is copied by the function prologue code.


问:
Processing errorsmessages
I want to create a Javacode in processing with a simple square who can be moved by pressing A,W,S and D so i wrote a code to do so but I keep getting errormessages. I was wondering if i could get help to fix the errors.

```<code>public void setup() {

  k = new karaktar();

  background (#F5CD0C);
  size( 800, 800 );
  strokeWeight( 20 );
  frameRate( 24 );

}

int lastKey = 0;
int lastKey2 =0;
void keyPressed() {
  if (lastKey != key) {
    lastKey = key;
    k.move();

  }
}

boolean start = false;
//draw
void draw() {
      start = true;

}

</code>```

```<code>class karaktar {

  float x = 400;
  float y = 500;

  boolean alreadypressed = false;

  float xF = x;
  float yF = y-100;
  float xFF = 0;
  float yFF = 0;

  int h1 = 50;
  int w1 = 50;
  int hF = h1;
  int wF = w1;
  float wFF = 0;
  float hFF = 0;

  }

  void move() {

    if (keyPressed) {
       if (key == 'w' || key == 'W') {

        y -= 50;
        yF -=50;
      }
    }
    if (keyPressed) {
      if (key == 'a' || key == 'A') {

        x -= 50;
        xF -= 50;
      }
    }
    if (keyPressed) {
      if (key == 's' || key == 'S') {

        y += 50;
        yF += 50;
      }
    }
    if (keyPressed) {
      if (key == 'd' || key == 'D') {

        x += 50;
        xF +=50;
      }
    }

}

</code>```

The first code is meant to be the playingfield and the second is for the moving square.

答:
Seems like your variable k in method setup() is not declared.

Use karaktar k = new karaktar();, or use

```<code>karaktar k;

someMethod() {
    k = new karaktar();
}
</code>```

// note:

also, it's a convention to name classes with uppercase first letter. I'd suggest renaming class karaktar to class Karaktar.

Title: Processing errorsmessages

Body:
I want to create a Javacode in processing with a simple square who can be moved by pressing A,W,S and D so i wrote a code to do so but I keep getting errormessages. I was wondering if i could get help to fix the errors.

public void setup() {

  k = new karaktar();

  background (#F5CD0C);
  size( 800, 800 );
  strokeWeight( 20 );
  frameRate( 24 );

}

int lastKey = 0;
int lastKey2 =0;
void keyPressed() {
  if (lastKey != key) {
    lastKey = key;
    k.move();

  }
}

boolean start = false;
//draw
void draw() {
      start = true;

}

class karaktar {

  float x = 400;
  float y = 500;

  boolean alreadypressed = false;

  float xF = x;
  float yF = y-100;
  float xFF = 0;
  float yFF = 0;

  int h1 = 50;
  int w1 = 50;
  int hF = h1;
  int wF = w1;
  float wFF = 0;
  float hFF = 0;

  }

  void move() {

    if (keyPressed) {
       if (key == 'w' || key == 'W') {

        y -= 50;
        yF -=50;
      }
    }
    if (keyPressed) {
      if (key == 'a' || key == 'A') {

        x -= 50;
        xF -= 50;
      }
    }
    if (keyPressed) {
      if (key == 's' || key == 'S') {

        y += 50;
        yF += 50;
      }
    }
    if (keyPressed) {
      if (key == 'd' || key == 'D') {

        x += 50;
        xF +=50;
      }
    }

}

The first code is meant to be the playingfield and the second is for the moving square.

Body:
Seems like your variable k in method setup() is not declared.

Use karaktar k = new karaktar();, or use

karaktar k;

someMethod() {
    k = new karaktar();
}

// note:

also, it's a convention to name classes with uppercase first letter. I'd suggest renaming class karaktar to class Karaktar.