问:
How to stop the Swing EDT
The typical Swing application starts the EDT at the beginning and when the last window is closed the Application stops basically with a System.exit either implicit or explicit.

But my little application is actually a plugin for a framework which knows nothing about Swing. My plugin will when called display a dialog, in order to get some input from the user and exit afterwards but the framework will/must keep running. So I can't call System.exit.

But if I don't do that the EDT will continue to run and once the framework is finished the EDT will still run and run and run ...

So I'd like to kill the EDT without killing the application. How do I do that?

答:
There may be some hidden windows (for example, dialogs displayed using JOptionPane.showMessageDialog(…) which are already closed) preventing Swing from exiting. You can check this using

```<code>Stream.of(Window.getWindows()).forEach(System.out::println);
</code>```

If you don’t need them anymore, you can get rid of them easily:

```<code>Stream.of(Window.getWindows()).forEach(Window::dispose);
</code>```

The Event Dispatch Thread should then stop.

Title: How to stop the Swing EDT

Body:
There may be some hidden windows (for example, dialogs displayed using JOptionPane.showMessageDialog(…) which are already closed) preventing Swing from exiting. You can check this using

Stream.of(Window.getWindows()).forEach(System.out::println);

If you don’t need them anymore, you can get rid of them easily:

Stream.of(Window.getWindows()).forEach(Window::dispose);

The Event Dispatch Thread should then stop.


来源: stackexchange

问:
Mongoose, removing an object from an array and updating other objects
I'm a web development rookie and I'm trying to build a simple editable image gallery. I have a Collections schema and a Paintings schema:

```<code>var collectionSchema = new mongoose.Schema({
    name: String,
    paintings: [
        {
            type: Schema.Types.ObjectId,
            ref: "Painting"
        }
    ]
})
</code>```

&&

```<code>var paintingSchema = new mongoose.Schema({
    img: String,
    description: String,
    index: Number,
    parent: String
});
</code>```

I'm currently trying to add a destroy route which will delete one painting from one collection. I have this so far:

```<code>app.delete("paintings/:type/:index", function(req,res){
    var type = req.params.type;
    var index = req.params.index;
    Painting.findOneAndRemove({parent:type,index:index},function(err,removedPainting){
        if(err){
            console.log(err);
        } else{
            res.redirect("/paintings/"+type);
        }
    });
});
</code>```

However, I also need all of the "index" attributes of objects with higher indices than that of the deleted object to decrement by one after the object is deleted. Any idea as to what the best way to do this is?

I have tried:

changing the destroy route into an update route, and then just completely replacing the array of Paintings within the Collection to an updated version, but that doesn't seem to work--I think because the array within the Collection schema is not actually an array of objects, but an array of ObjectIds?

Redirecting (from end of the destroy route) to an update route which loops through the Paintings found by Paintings.find({parent: type}) and increments their ids, but I never actually got to test this because when I tried to redirect from the destroy route I would always get the error: "cannot GET paintings/:type/:index/delete" even though I had made the route a put request, not a get request.

Any ideas? Anything would be much appreciated, I'm clearly kind of fumbling around in the dark here. Thanks a ton!

答:
Fixed this by eliminating the index attribute of the Painting schema, and eliminating the Painting schema entirely so that all paintings only exist as an object within Collections:

```<code>var collectionSchema = new mongoose.Schema({
name: String,
paintings: [
        {
            img: String,
            description: String,
            parent: String
        }
    ]
})
</code>```

Then, I changed my delete route so that it was actually a put route which pulled the correct painting from the Collection's painting array:

```<code>//DESTROY
app.put("paintings/:type/:index/delete", middleware.isLoggedIn, function(req,res){
    var type = req.params.type;
    var index = req.params.index;
    Collection.findOne({name:type},function(err,collection){
        if(err){
            console.log(err);
        } else{
            var idOfRemove = collection.paintings[index]._id;
            Collection.findOneAndUpdate({name:type},{$pull:{ paintings:{ _id: idOfRemove}}}, function(err,removedPainting){
                if(err){
                    console.log(err);
                } else{
                    res.redirect("/paintings/"+type);
                }
            })
        }
    })
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm a web development rookie and I'm trying to build a simple editable image gallery. I have a Collections schema and a Paintings schema:

var collectionSchema = new mongoose.Schema({
    name: String,
    paintings: [
        {
            type: Schema.Types.ObjectId,
            ref: "Painting"
        }
    ]
})

&&

var paintingSchema = new mongoose.Schema({
    img: String,
    description: String,
    index: Number,
    parent: String
});

I'm currently trying to add a destroy route which will delete one painting from one collection. I have this so far:

app.delete("paintings/:type/:index", function(req,res){
    var type = req.params.type;
    var index = req.params.index;
    Painting.findOneAndRemove({parent:type,index:index},function(err,removedPainting){
        if(err){
            console.log(err);
        } else{
            res.redirect("/paintings/"+type);
        }
    });
});

However, I also need all of the "index" attributes of objects with higher indices than that of the deleted object to decrement by one after the object is deleted. Any idea as to what the best way to do this is?

I have tried:

changing the destroy route into an update route, and then just completely replacing the array of Paintings within the Collection to an updated version, but that doesn't seem to work--I think because the array within the Collection schema is not actually an array of objects, but an array of ObjectIds?

Redirecting (from end of the destroy route) to an update route which loops through the Paintings found by Paintings.find({parent: type}) and increments their ids, but I never actually got to test this because when I tried to redirect from the destroy route I would always get the error: "cannot GET paintings/:type/:index/delete" even though I had made the route a put request, not a get request.

Any ideas? Anything would be much appreciated, I'm clearly kind of fumbling around in the dark here. Thanks a ton!

Body:
Fixed this by eliminating the index attribute of the Painting schema, and eliminating the Painting schema entirely so that all paintings only exist as an object within Collections:

var collectionSchema = new mongoose.Schema({
name: String,
paintings: [
        {
            img: String,
            description: String,
            parent: String
        }
    ]
})

Then, I changed my delete route so that it was actually a put route which pulled the correct painting from the Collection's painting array:

//DESTROY
app.put("paintings/:type/:index/delete", middleware.isLoggedIn, function(req,res){
    var type = req.params.type;
    var index = req.params.index;
    Collection.findOne({name:type},function(err,collection){
        if(err){
            console.log(err);
        } else{
            var idOfRemove = collection.paintings[index]._id;
            Collection.findOneAndUpdate({name:type},{$pull:{ paintings:{ _id: idOfRemove}}}, function(err,removedPainting){
                if(err){
                    console.log(err);
                } else{
                    res.redirect("/paintings/"+type);
                }
            })
        }
    })
});


问:
How to write the contents of one CSV file to another
I have a csv file and I want to transfer the raw data without the headers to a new csv file and have the rows and columns the same as the original.

```<code>IRIS_data = "IRIS_data.csv"

with open(IRIS_data, 'wb') as data:
    wr = csv.writer(data, quoting=csv.QUOTE_ALL)
    with open(IRIS) as f:
        next(f)
        for line in f:
            wr.writerow(line)
</code>```

The code above is my most recent attempt, when I try run it I get the following error:

```<code>a bytes-like object is required, not 'str'
</code>```

答:
It's because you opened the input file with with open(IRIS_data, 'wb'), which opens it in binary mode, and the output file with just with open(IRIS) which opens it in text mode.

In Python 3, you should open both files in text mode and specify newline='' option)—see the examples in the csv module's documentation)

To fix it, change them as follows:

with open(IRIS_data, 'w', newline='') as data:

and

with open(IRIS, newline='') as f:

However there are other issues with you code. Here's how to use those statements to get what I think you want:

```<code>import csv

IRIS = "IRIS.csv"
IRIS_data = "IRIS_data.csv"

with open(IRIS, 'r', newline='') as f, open(IRIS_data, 'w', newline='') as data:
    next(f)  # Skip over header in input file.
    writer = csv.writer(data, quoting=csv.QUOTE_ALL)
    writer.writerows(line.split() for line in f)
</code>```

Contents of IRIS_data.csv file after running the script with your sample input data:

"6.4","2.8","5.6","2.2","2"
"5","2.3","3.3","1","1"
"4.9","2.5","4.5","1.7","2"
"4.9","3.1","1.5","0.1","0"
"5.7","3.8","1.7","0.3","0"
"4.4","3.2","1.3","0.2","0"
"5.4","3.4","1.5","0.4","0"
"6.9","3.1","5.1","2.3","2"
"6.7","3.1","4.4","1.4","1"
"5.1","3.7","1.5","0.4","0"
```

Body:
I have a csv file and I want to transfer the raw data without the headers to a new csv file and have the rows and columns the same as the original.

IRIS_data = "IRIS_data.csv"

with open(IRIS_data, 'wb') as data:
    wr = csv.writer(data, quoting=csv.QUOTE_ALL)
    with open(IRIS) as f:
        next(f)
        for line in f:
            wr.writerow(line)

The code above is my most recent attempt, when I try run it I get the following error:

a bytes-like object is required, not 'str'

Body:
It's because you opened the input file with with open(IRIS_data, 'wb'), which opens it in binary mode, and the output file with just with open(IRIS) which opens it in text mode.

In Python 3, you should open both files in text mode and specify newline='' option)—see the examples in the csv module's documentation)

To fix it, change them as follows:

with open(IRIS_data, 'w', newline='') as data:

and

with open(IRIS, newline='') as f:

However there are other issues with you code. Here's how to use those statements to get what I think you want:

import csv

IRIS = "IRIS.csv"
IRIS_data = "IRIS_data.csv"

with open(IRIS, 'r', newline='') as f, open(IRIS_data, 'w', newline='') as data:
    next(f)  # Skip over header in input file.
    writer = csv.writer(data, quoting=csv.QUOTE_ALL)
    writer.writerows(line.split() for line in f)

Contents of IRIS_data.csv file after running the script with your sample input data:

"6.4","2.8","5.6","2.2","2"
"5","2.3","3.3","1","1"
"4.9","2.5","4.5","1.7","2"
"4.9","3.1","1.5","0.1","0"
"5.7","3.8","1.7","0.3","0"
"4.4","3.2","1.3","0.2","0"
"5.4","3.4","1.5","0.4","0"
"6.9","3.1","5.1","2.3","2"
"6.7","3.1","4.4","1.4","1"
"5.1","3.7","1.5","0.4","0"


问:
SQL Server: Merging Two Tables Together & Sending Output to Temp Table Error
I'm trying to merge two SQL tables together on a unique column and send it to a temp table.  However, I get an error (see below).

When I do the left join below, it creates two "UNIQUE_IDENTIFIER" columns which breaks my INTO statement.

```<code>    SELECT *
    INTO #temp_table
    FROM #df_EVENT5_a as t1
    LEFT JOIN #df_ERA_Final as t2 ON t1.UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER
</code>```

Error: Column names in each table must be unique. Column name 'UNIQUE_IDENTIFIER' in table '#temp_table' is specified more than once.

答:
It's because that column name exists in both tables. You can't have two columns in a single table with the same name.

Your query is the same as saying

```<code>SELECT
    t1.UNIQUE_IDENTIFIER
    ,t2.UNIQUE_IDENTIFIER
    --list all other columns...
INTO #temp_table
FROM #df_EVENT5_a as t1
LEFT JOIN #df_ERA_Final as t2 ON t1.UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER
</code>```

This means #temp_table would have two columns named UNIQUE_IDENTIFER. So, remove the * and list the columns you want explicitly from each table... and alias any columns with the same name...

```<code>SELECT
    FIRST_UNIQUE_IDENTIFIER = t1.UNIQUE_IDENTIFIER
    ,SECOND_UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER
    --list all other columns...
INTO #temp_table
FROM #df_EVENT5_a as t1
LEFT JOIN #df_ERA_Final as t2 ON t1.UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER
</code>```

Body:
I'm trying to merge two SQL tables together on a unique column and send it to a temp table.  However, I get an error (see below).

When I do the left join below, it creates two "UNIQUE_IDENTIFIER" columns which breaks my INTO statement.

    SELECT *
    INTO #temp_table
    FROM #df_EVENT5_a as t1
    LEFT JOIN #df_ERA_Final as t2 ON t1.UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER

Error: Column names in each table must be unique. Column name 'UNIQUE_IDENTIFIER' in table '#temp_table' is specified more than once.

Body:
It's because that column name exists in both tables. You can't have two columns in a single table with the same name.

Your query is the same as saying

SELECT
    t1.UNIQUE_IDENTIFIER
    ,t2.UNIQUE_IDENTIFIER
    --list all other columns...
INTO #temp_table
FROM #df_EVENT5_a as t1
LEFT JOIN #df_ERA_Final as t2 ON t1.UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER

This means #temp_table would have two columns named UNIQUE_IDENTIFER. So, remove the * and list the columns you want explicitly from each table... and alias any columns with the same name...

SELECT
    FIRST_UNIQUE_IDENTIFIER = t1.UNIQUE_IDENTIFIER
    ,SECOND_UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER
    --list all other columns...
INTO #temp_table
FROM #df_EVENT5_a as t1
LEFT JOIN #df_ERA_Final as t2 ON t1.UNIQUE_IDENTIFIER = t2.UNIQUE_IDENTIFIER


问:
error while creating jar file
problem is occurs while creating jar file "java exception occurred" that's why i have added zip file is it sounds correct or not what i have to do can you please tell me?</p>

答:
to create jar file in java eclipse

1)write a java coding in eclipse 2)run in java platform 3)click to file->export->runnable jar file->next->launch configuration(project name)->export destination(destination folder)->finish 4)open the destination folder 5).jar extension file is nothing but your jar file

ContentLicense: CC BY-SA 2.5

Title: error while creating jar file


问:
converting ascii into object
When a user lands on our site a cookie is created. I need to access this cookie and insert it into an object. However, the cookie is coming in this way:

```<code>%7B%22tpl%22%3A%22243%22%2C%22offer%22%3A%22596%22%2C%22userid%22%3A%227035%22%2C%22mediaid%22%3A%223066%22%2C%22r%22%3A%2222784176%22%2C%22id%22%3A%22%22%2C%22region%22%3A%22LA%22%7D
</code>```

How can I convert it to something more readable like:

```<code>{"key" : "value"}
</code>```

答: Use decodeURIComponent, which understands percent notation.

Title: converting ascii into object

Body:
When a user lands on our site a cookie is created. I need to access this cookie and insert it into an object. However, the cookie is coming in this way:

%7B%22tpl%22%3A%22243%22%2C%22offer%22%3A%22596%22%2C%22userid%22%3A%227035%22%2C%22mediaid%22%3A%223066%22%2C%22r%22%3A%2222784176%22%2C%22id%22%3A%22%22%2C%22region%22%3A%22LA%22%7D

How can I convert it to something more readable like:

{"key" : "value"}


问:
How to get width of a parent div and based on do further operations in angular2
Here, I want to get width of #divToMeasure and then based on this, need to do further operations.
Please, help me to fix this code and better approach or suggestion are always welcomed.

abc-component.html

```<code><div #parentdiv class="col-xs-12 rmpm" style='width:100%;height:100%;'>
        <div #divToMeasure class="col-xs-12 rmpm"  [style.width.px]="parentdiv.offsetWidth">  <---get this 'width' in 'px'
        </div>
        </div>

        <div *ngFor ='let dta of data; let i = index' [ngStyle]="{'width':WIDTH}">
         abc
        </div>
</code>```

abc.component.ts

```<code>data = [1,2,3,4,5,6];
WIDTH: any

ngOnInit(){

// need to get the width of #divToMeasure
let divToMeasureWidth = __________; <-------how to get that

this.WIDTH = (divToMeasureWidth / this.data.length);
}
</code>```

答:
I believe this is what you are looking for.

abc.component.ts

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';

 @Component({templateUrl: './abc-component.html'})
  export class AbcComponent implements AfterViewInit {
    @ViewChild('divToMeasure') divToMeasureElement: ElementRef;

    ngAfterViewInit() {
      let divToMeasureWidth = this.divToMeasureElement.nativeElement.offsetWidth;
   }
 }
```

Body:
Here, I want to get width of #divToMeasure and then based on this, need to do further operations.
Please, help me to fix this code and better approach or suggestion are always welcomed.

abc-component.html

  <---get this 'width' in 'px'

         abc

abc.component.ts

data = [1,2,3,4,5,6];
WIDTH: any

ngOnInit(){

// need to get the width of #divToMeasure
let divToMeasureWidth = __________; <-------how to get that

this.WIDTH = (divToMeasureWidth / this.data.length);
}

ContentLicense: CC BY-SA 4.0


问:
Split string into multiple string separated
I have a string "What is Facebook?.| A. Website B. Internet C. Social Network D. Game"
How can I split and stored that string into 5 string separated in C# programming? I try to split with my code but the result I have just a mess.

What result I expect is that after split, I have 5 string variable separated like:

```<code>string A = "What is Facebook?"
string B = "A. Website"
string C = "B. Internet"
string D = "C. Social Network"
string E = "D. Game"
</code>```

That is my code:

```<code>String value = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";
Char delimiter = '|';
String[] substrings = value.Split(delimiter);
</code>```

答:
If it were me, I would create a simple class that holds a question and the possible answers. This way, you can parse your string into a class which can do other fancy things, like display itself correctly, and could contain a property that indicates the index of the correct answer (so you can compare the user's selection with the correct index).

For example, this class has a static Parse method that takes in your string and returns an instance of the class. It also overrides ToString so that it displays the Question and Answers in a nice way:

```<code>public class QuestionAndAnswers
{
    public string Question { get; set; }
    public List<string> Answers { get; set; }
    public int IndexOfCorrectAnswer { get; set; }

    public static QuestionAndAnswers Parse(string qaInput)
    {
        if (qaInput == null) throw new ArgumentNullException(nameof(qaInput));

        var result = new QuestionAndAnswers();

        var parts = Regex.Split(qaInput, @"\|?\s+(?=[A-Z]\.)");

        result.Question = parts[0].TrimEnd('.');
        result.Answers = parts.Skip(1).ToList();

        return result;
    }

    public override string ToString()
    {
        return $"{Question}\n  {string.Join("\n  ", Answers)}";
    }
}
</code>```

Then it can be use something like this:

```<code>private static void Main()
{
    var input = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";

    var qa = QuestionAndAnswers.Parse(input);

    Console.WriteLine(qa);

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Output

Body:
I have a string "What is Facebook?.| A. Website B. Internet C. Social Network D. Game"
How can I split and stored that string into 5 string separated in C# programming? I try to split with my code but the result I have just a mess.

What result I expect is that after split, I have 5 string variable separated like:

string A = "What is Facebook?"
string B = "A. Website"
string C = "B. Internet"
string D = "C. Social Network"
string E = "D. Game"

That is my code:

String value = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";
Char delimiter = '|';
String[] substrings = value.Split(delimiter);

Body:
If it were me, I would create a simple class that holds a question and the possible answers. This way, you can parse your string into a class which can do other fancy things, like display itself correctly, and could contain a property that indicates the index of the correct answer (so you can compare the user's selection with the correct index).

For example, this class has a static Parse method that takes in your string and returns an instance of the class. It also overrides ToString so that it displays the Question and Answers in a nice way:

public class QuestionAndAnswers
{
    public string Question { get; set; }
    public List<string> Answers { get; set; }
    public int IndexOfCorrectAnswer { get; set; }

    public static QuestionAndAnswers Parse(string qaInput)
    {
        if (qaInput == null) throw new ArgumentNullException(nameof(qaInput));

        var result = new QuestionAndAnswers();

        var parts = Regex.Split(qaInput, @"\|?\s+(?=[A-Z]\.)");

        result.Question = parts[0].TrimEnd('.');
        result.Answers = parts.Skip(1).ToList();

        return result;
    }

    public override string ToString()
    {
        return $"{Question}\n  {string.Join("\n  ", Answers)}";
    }
}

Then it can be use something like this:

private static void Main()
{
    var input = "What is Facebook?.| A. Website B. Internet C. Social Network D. Game";

    var qa = QuestionAndAnswers.Parse(input);

    Console.WriteLine(qa);

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output


问:
How to capture image using camera and send to firebase
I am capturing images by using camera and want to send to firebase storage. But I am getting error by 3 three days. I am stuck on it. When I fire intent it captures image, but in onActivityresult it returns request code=1 and result code=-1. Here is my code

Donation Activity:

```<code>    package com.example.manzoorhussain.kindnessapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DonationActivity extends AppCompatActivity {

    private Button mUploadBtn;
    private ImageView mImageView;
    private final static int CAMERA_REQUEST_CODE = 1;
    private StorageReference mstorage;
    ProgressDialog progressDialog;
    Uri photoURI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_donation);

        mUploadBtn = (Button) findViewById(R.id.upload);
        mImageView = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        mstorage = FirebaseStorage.getInstance().getReference();
        mUploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                dispatchTakePictureIntent();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
            Toast.makeText(this, "" + photoURI, Toast.LENGTH_SHORT).show();

            progressDialog.setMessage("Uploading...");
            progressDialog.show();
            Uri uri = data.getData();

            StorageReference filepath = mstorage.child("Photos").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(DonationActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(DonationActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
// Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

// Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File...
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                //takePictureIntent.setData(photoURI);
                // takePictureIntent.putExtra("imageUri", photoURI.toString());

                takePictureIntent.putExtra("imageUri", photoURI.toString());

                // takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            }
        }

    }

}
</code>```

I am getting error in activity resultcode that is equal to zero.

答:
I am capturing the image just as you are with saving the image to the file system before uploading, but using the mCurrentPhotoPath to load the Bitmap instead.  Then convert the Bitmap to bytes and upload to Firebase Storage from there.

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
        UploadTask uploadTask = reference.putBytes(imageBytes);
        uploadTask.addOnSuccessListener(new
        OnSuccessListener<UploadTask.TaskSnapshot>() {
             @Override
             public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
             }
        });
    } else if (resultCode == RESULT_CANCELED) {
        onCancel();
    }
}

private File createImageFile() throws IOException {
    String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String filename = String.format("JPEG_%s_", ts);
    File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(filename, ".jpg", storageDir);
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}
</code>```

To break it down further in my application I am first displaying the image within an ImageView and then when uploaded converting it to byte[] like this.

```<code>Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable().getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
</code>```

And then upload to Firebase.

```<code>StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
            }
        });
</code>```

Body:
I am capturing images by using camera and want to send to firebase storage. But I am getting error by 3 three days. I am stuck on it. When I fire intent it captures image, but in onActivityresult it returns request code=1 and result code=-1. Here is my code

Donation Activity:

    package com.example.manzoorhussain.kindnessapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DonationActivity extends AppCompatActivity {

    private Button mUploadBtn;
    private ImageView mImageView;
    private final static int CAMERA_REQUEST_CODE = 1;
    private StorageReference mstorage;
    ProgressDialog progressDialog;
    Uri photoURI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_donation);

        mUploadBtn = (Button) findViewById(R.id.upload);
        mImageView = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        mstorage = FirebaseStorage.getInstance().getReference();
        mUploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                dispatchTakePictureIntent();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
            Toast.makeText(this, "" + photoURI, Toast.LENGTH_SHORT).show();

            progressDialog.setMessage("Uploading...");
            progressDialog.show();
            Uri uri = data.getData();

            StorageReference filepath = mstorage.child("Photos").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(DonationActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(DonationActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
// Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

// Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File...
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                //takePictureIntent.setData(photoURI);
                // takePictureIntent.putExtra("imageUri", photoURI.toString());

                takePictureIntent.putExtra("imageUri", photoURI.toString());

                // takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            }
        }

    }

}

I am getting error in activity resultcode that is equal to zero.

Body:
I am capturing the image just as you are with saving the image to the file system before uploading, but using the mCurrentPhotoPath to load the Bitmap instead.  Then convert the Bitmap to bytes and upload to Firebase Storage from there.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
        UploadTask uploadTask = reference.putBytes(imageBytes);
        uploadTask.addOnSuccessListener(new
        OnSuccessListener<UploadTask.TaskSnapshot>() {
             @Override
             public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
             }
        });
    } else if (resultCode == RESULT_CANCELED) {
        onCancel();
    }
}

private File createImageFile() throws IOException {
    String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String filename = String.format("JPEG_%s_", ts);
    File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(filename, ".jpg", storageDir);
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

To break it down further in my application I am first displaying the image within an ImageView and then when uploaded converting it to byte[] like this.

Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable().getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();

And then upload to Firebase.

StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
            }
        });


问:
No result rowset is associated with the execution of this query
I am creating an Execute SQL task in SSIS 2016 which calls an insert stored procedure. I am trying to return the id of the newly created row in the output parameter but facing the following error.

No result rowset is associated with the execution of this query

I had set the SQL Server Profiler on to see what was generated and it was as follows

```<code>declare @p4 int
set @p4=NULL
exec sp_executesql N'Exec [dbo].[InsertPkgAudit] @P1,@P2',N'@P1 varchar(16),@P2 int OUTPUT','CoreReferenceETL',@p4 output
select @p4
</code>```

If I execute the following it manually it works

```<code>DECLARE @auditId INT;
EXEC [dbo].[InsertPkgAudit] @packageName = 'CoreReferenceETL', @auditId = @auditId OUTPUT;
PRINT @auditId;
</code>```

So it is clear that the stored procedure is fine but some problem with the way its called in SSIS. Could somebody help ?

The Execute SQL task contains the following statement

```<code>Exec [dbo].[InsertPkgAudit] @packageName =?, @auditId = ?
</code>```

The parameter mapping is as follows

The result pane is as follows

The stored procedure is as follows:

```<code>CREATE Procedure [dbo].[InsertPkgAudit]
    @packageName varchar(100),
    @auditId int output
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO [dbo].[PkgAudit] ([PackageName], [StartTime])
    VALUES (@packageName, GETDATE());

    SET @auditId = SCOPE_IDENTITY();
END
</code>```

The table structure is as follows

答:
You have told SSIS that your procedure returns a result set.   But it doesn't.   It populates an OUTPUT parameter instead.

You can either change your proc to return a resultset, or you can modify the Execute task and

Specify No Result Set

Change the query to this:

```<code>`Exec [dbo].[InsertPkgAudit] @packageName =?, @auditId = ? OUTPUT`
</code>```

Body:
I am creating an Execute SQL task in SSIS 2016 which calls an insert stored procedure. I am trying to return the id of the newly created row in the output parameter but facing the following error.

No result rowset is associated with the execution of this query

I had set the SQL Server Profiler on to see what was generated and it was as follows

declare @p4 int
set @p4=NULL
exec sp_executesql N'Exec [dbo].[InsertPkgAudit] @P1,@P2',N'@P1 varchar(16),@P2 int OUTPUT','CoreReferenceETL',@p4 output
select @p4

If I execute the following it manually it works

DECLARE @auditId INT;
EXEC [dbo].[InsertPkgAudit] @packageName = 'CoreReferenceETL', @auditId = @auditId OUTPUT;
PRINT @auditId;

So it is clear that the stored procedure is fine but some problem with the way its called in SSIS. Could somebody help ?

The Execute SQL task contains the following statement

Exec [dbo].[InsertPkgAudit] @packageName =?, @auditId = ?

The parameter mapping is as follows

The result pane is as follows

The stored procedure is as follows:

CREATE Procedure [dbo].[InsertPkgAudit]
    @packageName varchar(100),
    @auditId int output
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO [dbo].[PkgAudit] ([PackageName], [StartTime])
    VALUES (@packageName, GETDATE());

    SET @auditId = SCOPE_IDENTITY();
END

The table structure is as follows

Body:
You have told SSIS that your procedure returns a result set.   But it doesn't.   It populates an OUTPUT parameter instead.

You can either change your proc to return a resultset, or you can modify the Execute task and

Specify No Result Set

Change the query to this:

`Exec [dbo].[InsertPkgAudit] @packageName =?, @auditId = ? OUTPUT`


问:
possible scanf crash/ auto assigning of values
when running my main function and using scanf to get a char input, my program prints "4227467 device(s) found!" (input 1: 2, input 2:'B') and crashes after that. Wonder if its due to \n or any misunderstanding i may have towards scanf.

```<code>int main() {
    int option;
    printf("electronic devicedatabase (EDD)\n1 = Get database information\n2 = Search by port type\n3 = Search by current / power ratings\n=====\nInput: ");
    scanf("%d",&option);

    if (option ==1){
    database_info();

    }
    else if (option == 2){
        char port_type;
        printf("Specify port type: ");
        scanf("%c\n",&port_type);
        search_port_type(port_type);

    }
    else if (option ==3){
        float current_rating, power_rating;
        printf("Specify current and power: ");
        scanf("%f %f\n",&current_rating, &power_rating);
        search_current_power(current_rating, power_rating);

    }
    else{
        printf("Invalid input!\n");
    };
    return 0;
}

void search_port_type(char port_type) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].port_type == port_type ){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}
void search_current_power(float current, float power) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].current_rating == current &&  dev_database[i].power_rating == power){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}
</code>```

Attached is the hyperlink to the full code, ive check each individual function and its working as intended. https://onlinegdb.com/BkGxu3u1z

Any help is greatly appreciated, thank you!

Edit: initialised automatic/local variable in the blocks. Option 3 works now! However option 2 still does not work and always give "0 device(s) found!" when giving 'B' as an input.

Final edit: Im was wrong with giving 'B' as using scanf("%c\n",&port_type) does not require the ' '.

sample data:

```<code>struct device {
    int ports;
    char port_type;
    float cost;
    int cpu_cores;
    int chips;
    struct {
        int version;
        int year;
        char manufacturer[10];
    } make;
    float current_rating, power_rating;
};

struct device dev_database[5] = {
    {5, 'B', 73.45, 4, 7, {2, 2015, "Intel"}, 3.1, 1.2},
    {5, 'A', 70.00, 2, 5, {1, 2010, "Micron"}, 2.0, 1.5},
    {5, 'B', 65.00, 2, 5, {1, 2011, "Intel"}, 3.0, 1.5},
    {5, 'C', 80.00, 8, 7, {1, 2015, "Motorola"}, 2.5, 1.0},
    {5, 'A', 70.00, 2, 5, {3, 2012, "Intel"}, 3.0, 1.3}
};
</code>```

答:
Local/Automatic variables not initialised. Causing inaccuracy in answer.
refer to local variable initialized to zero in C

need to add space in front of scanf

updated code:

```<code>int main() {
    int option;
    printf("electronic devicedatabase (EDD)\n1 = Get database information\n2 = Search by port type\n3 = Search by current / power ratings\n=====\nInput: ");
    scanf("%d",&option);

    if (option ==1){
    database_info();

    }
    else if (option == 2){
        char port_type;
        printf("Specify port type: ");
        scanf(" %c",&port_type);
        search_port_type(port_type);

    }
    else if (option ==3){
        float current_rating, power_rating;
        printf("Specify current and power: ");
        scanf(" %f %f",&current_rating, &power_rating);
        search_current_power(current_rating, power_rating);

    }
    else{
        printf("Invalid input!\n");
    };
    return 0;
}

void search_port_type(char port_type) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].port_type == port_type ){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}
void search_current_power(float current, float power) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].current_rating == current &&  dev_database[i].power_rating == power){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}
</code>```

Body:
when running my main function and using scanf to get a char input, my program prints "4227467 device(s) found!" (input 1: 2, input 2:'B') and crashes after that. Wonder if its due to \n or any misunderstanding i may have towards scanf.

int main() {
    int option;
    printf("electronic devicedatabase (EDD)\n1 = Get database information\n2 = Search by port type\n3 = Search by current / power ratings\n=====\nInput: ");
    scanf("%d",&option);

    if (option ==1){
    database_info();

    }
    else if (option == 2){
        char port_type;
        printf("Specify port type: ");
        scanf("%c\n",&port_type);
        search_port_type(port_type);

    }
    else if (option ==3){
        float current_rating, power_rating;
        printf("Specify current and power: ");
        scanf("%f %f\n",&current_rating, &power_rating);
        search_current_power(current_rating, power_rating);

    }
    else{
        printf("Invalid input!\n");
    };
    return 0;
}

void search_port_type(char port_type) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].port_type == port_type ){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}
void search_current_power(float current, float power) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].current_rating == current &&  dev_database[i].power_rating == power){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}

Attached is the hyperlink to the full code, ive check each individual function and its working as intended. https://onlinegdb.com/BkGxu3u1z

Any help is greatly appreciated, thank you!

Edit: initialised automatic/local variable in the blocks. Option 3 works now! However option 2 still does not work and always give "0 device(s) found!" when giving 'B' as an input.

Final edit: Im was wrong with giving 'B' as using scanf("%c\n",&port_type) does not require the ' '.

sample data:

struct device {
    int ports;
    char port_type;
    float cost;
    int cpu_cores;
    int chips;
    struct {
        int version;
        int year;
        char manufacturer[10];
    } make;
    float current_rating, power_rating;
};

struct device dev_database[5] = {
    {5, 'B', 73.45, 4, 7, {2, 2015, "Intel"}, 3.1, 1.2},
    {5, 'A', 70.00, 2, 5, {1, 2010, "Micron"}, 2.0, 1.5},
    {5, 'B', 65.00, 2, 5, {1, 2011, "Intel"}, 3.0, 1.5},
    {5, 'C', 80.00, 8, 7, {1, 2015, "Motorola"}, 2.5, 1.0},
    {5, 'A', 70.00, 2, 5, {3, 2012, "Intel"}, 3.0, 1.3}
};

Body:
Local/Automatic variables not initialised. Causing inaccuracy in answer.
refer to local variable initialized to zero in C

need to add space in front of scanf

updated code:

int main() {
    int option;
    printf("electronic devicedatabase (EDD)\n1 = Get database information\n2 = Search by port type\n3 = Search by current / power ratings\n=====\nInput: ");
    scanf("%d",&option);

    if (option ==1){
    database_info();

    }
    else if (option == 2){
        char port_type;
        printf("Specify port type: ");
        scanf(" %c",&port_type);
        search_port_type(port_type);

    }
    else if (option ==3){
        float current_rating, power_rating;
        printf("Specify current and power: ");
        scanf(" %f %f",&current_rating, &power_rating);
        search_current_power(current_rating, power_rating);

    }
    else{
        printf("Invalid input!\n");
    };
    return 0;
}

void search_port_type(char port_type) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].port_type == port_type ){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}
void search_current_power(float current, float power) {
    int index[5],counter = 0,i = 0;
    for (i=0; i<5; i++){
        if (dev_database[i].current_rating == current &&  dev_database[i].power_rating == power){
                index[counter]=i;
                counter++;
        }
    }
    printf("%d device(s) found!\n",counter);
    for (i=0; i<counter; i++){
        print_device(index[i]);
    }
    return;
}


问:
ColdBox module interface support?
Is there a way to create an interface for a module that any host application can be expected to implement?

We've got a couple apps that have a lot of code that is common that we'd like to refactor into modules, but sometimes the module may need to call runEvent or setNextEvent for a handler method that lives in the host application due to unique behavior and implementation.

Can I specify in the module a contract like "host application must implement the following handlers: 'admin.foo', 'admin.bar', ..."?

I am guessing there's a module load intercept I could do this in manually, but I'm wondering if there's a convention so I can just drop the list in somewhere rather than copy-pasting boilerplate code into every module.

答:
You can specify dependencies within your ModuleConfig.cfc :  this.dependencies = [ "myOtherModule" ].  Those dependencies will load before the module.  At this time, there is no way to "interface" a module to conform to a collection of handlers.

Typically, though, passing through to other modules this is easily handled by custom routing within the module configuration, rather than by a new implementation:

```<code>addRoute(
    pattern="/this-module/foo",
    moduleRouting="that-module"
)
</code>```

or

```<code>addRoute(
    pattern="/this-module/foo",
    module="that-module",
    handler="oldFoo"
    action="bar"
)
</code>```

More on routing

Title: ColdBox module interface support?

Body:
You can specify dependencies within your ModuleConfig.cfc :  this.dependencies = [ "myOtherModule" ].  Those dependencies will load before the module.  At this time, there is no way to "interface" a module to conform to a collection of handlers.

Typically, though, passing through to other modules this is easily handled by custom routing within the module configuration, rather than by a new implementation:

addRoute(
    pattern="/this-module/foo",
    moduleRouting="that-module"
)

or

addRoute(
    pattern="/this-module/foo",
    module="that-module",
    handler="oldFoo"
    action="bar"
)

More on routing


问:
UIWindowController Assertion failure
This is the full error I'm receiving:

* Assertion failure in -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:],
  /SourceCache/UIKit_Sim/UIKit-1447.6.4/UIWindowController.m:186

And this is the line of code it's occurring on:

```<code>[self presentModalViewController:navigationController animated:YES];
</code>```

Completely stumped on this one - it just started happening, and I haven't changed anything.

答: It appears that I fixed it by cleaning all the targets...</p>

Title: UIWindowController Assertion failure

Body:
This is the full error I'm receiving:

* Assertion failure in -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:],
  /SourceCache/UIKit_Sim/UIKit-1447.6.4/UIWindowController.m:186

And this is the line of code it's occurring on:

[self presentModalViewController:navigationController animated:YES];

Completely stumped on this one - it just started happening, and I haven't changed anything.


问:
Are there md5 collisions for integers in range(1,1000000000)
I want to generate a uuid in python using the md5 hash of a preexisting unique identifier ranged between 1 and 999999999

It seems obvious that on numbers so small there couldn't be any worry... but it made me think, do we know the smallest two integers that have the same md5 hash ?

答:
I tested, and the answer is no.

counting with set() will trigger MemoryError on my 64GB memory box, so I write hexlify hash to disk:

```<code>import hashlib
from multiprocessing import Pool
import os

def f(args):
    s, e = args
    l = []
    for i in xrange(s, e):
        h = hashlib.md5(str(i)).hexdigest()
        l.append(h)
    l.sort()
    fn = '/data/tmp/%s_%s' % (s, e)
    with open(fn, 'w') as f:
        for h in l:
            f.write('%s\n' % (h,))

def main():
    def gen():
        end = 1000000000
        step = 5000000
        s = 0
        while s < end:
            yield s, s+step
            s += step

    pool = Pool(processes=16)
    res = pool.imap_unordered(f, gen())
    list(res)
</code>```

then counting with sort(1):

```<code>sort -mu /data/tmp/* | wc -l
</code>```

yields:

```<code>1000000000
</code>```

note that I encoded integer into ASCII string.

Body:
I tested, and the answer is no.

counting with set() will trigger MemoryError on my 64GB memory box, so I write hexlify hash to disk:

import hashlib
from multiprocessing import Pool
import os

def f(args):
    s, e = args
    l = []
    for i in xrange(s, e):
        h = hashlib.md5(str(i)).hexdigest()
        l.append(h)
    l.sort()
    fn = '/data/tmp/%s_%s' % (s, e)
    with open(fn, 'w') as f:
        for h in l:
            f.write('%s\n' % (h,))

def main():
    def gen():
        end = 1000000000
        step = 5000000
        s = 0
        while s < end:
            yield s, s+step
            s += step

    pool = Pool(processes=16)
    res = pool.imap_unordered(f, gen())
    list(res)

then counting with sort(1):

sort -mu /data/tmp/* | wc -l

yields:

1000000000

note that I encoded integer into ASCII string.


问:
VSTS automated Build failing for files not checked into source control (App.config)
So we are just getting into VSTS with a bunch of repos that we moved over from Github and are attempting to automate our build processes. One issue that we have run into is that our builds are failing because they can't find config files that haven't been checked into source control. This is one particular message we are getting in the logs.

App.config(0,0): Error MSB3249: Application Configuration file "App.config" is invalid. Could not find file 'd:\a\1\s\Project-Name\App.config'.

And then the build fails of course. The application we are trying to automate the build for is a simple script that has a console app with a config file containing necessary sensitive settings that we didn't want to push to Git.

I guess my question is, how do we automate a build process with VSTS when the App.Config isn't stored in Git, is there a way to push that up to the build or set it up to grab that file from somewhere? What is best practice in this instance?

答: For configuration files, you should keep a baseline version in source control and then transform it appropriately at the time of deployment. MSDeploy supports using parameters.xml / SetParameters.xml files to determine values at time of deployment. Or you could store a file with placeholders and replace the placeholders with actual values at the time of deployment.


问:
Casting Generic to int
So in school we are making a project for graphic. I have this interface:

```<code>package rasterdata;

import java.util.Optional;

public interface RasterImage<PixelType> {
    Optional<PixelType> getPixel(int c, int r);
    RasterImage<PixelType> withPixel(int c, int r, PixelType value);
    RasterImage<PixelType> cleared(PixelType pixel);
    int getWidth();
    int getHeight();
}
</code>```

And this is the class which extends the interface and its getPixel() method:

```<code>public class RasterImageBuffered<PixelType> implements RasterImage<PixelType> {
private final BufferedImage img;
private final Function<PixelType, Integer> toInteger;
private final Function<Integer, PixelType> toPixelType;
public RasterImageBuffered(final BufferedImage img,
                           final Function<PixelType, Integer> toInteger,
                           final Function<Integer, PixelType> toPixelType) {
    this.img = img;
    this.toInteger = toInteger;
    this.toPixelType = toPixelType;
}

@Override
public Optional<PixelType> getPixel(final int c, final int r) {
    if (c < 0 || c >= img.getWidth() ||
            r < 0 || r >= img.getHeight())
        return Optional.empty();
    return Optional.of(toPixelType.apply(img.getRGB(c, r)));
}
</code>```

Now, what I am trying to do is to implement a seed fill algorithm. To do that I need to compare the color of the pixel in Canvas (color) with the color which I will use to fill the polygon (fillColor).

This is the seedfill class:

```<code>public class SeedFill<PixelType> {

public RasterImage fill(final RasterImage<PixelType> img, final int x, final int y, PixelType borderColor, PixelType fillColor) {

    RasterImage<PixelType> result = img;

    PixelType color = (PixelType) img.getPixel(x,y);

        //this condition throws an error
        if((color & 0xffffff) == (fillColor & 0xffffff)){

        result = result.withPixel(x,y, fillColor);

        fill(img, x+1, y, borderColor, fillColor,bcgColor);
        fill(img, x-1, y, borderColor, fillColor,bcgColor);
        fill(img, x, y+1, borderColor, fillColor,bcgColor);
        fill(img, x, y-1, borderColor, fillColor,bcgColor);

    }

        return result;

    }

}
</code>```

The problem is that when I want to compare the colors, error saying that I cant compare PixelType with int pops out. However casting It to int throws another error saying that I cant cast PixelType to int. Is there any way of comparing those two values?

答:
I have solved the comparison by adding:

```<code>private final Function<PixelType, Integer> toInteger;
</code>```

Then the constructor:

```<code>public SeedFill(Function<PixelType, Integer> toInteger) {
    this.toInteger = toInteger;
}
</code>```

And with this function I was able to call toInteger.apply() which made an Integer out of generic PixelType:

```<code>if ((toInteger.apply(nowColor.get()) & 0xffffff) != (toInteger.apply(borderColor))) {
        if ((toInteger.apply(nowColor.get()) & 0xffffff) != (toInteger.apply(fillColor))) {
</code>```

Title: Casting Generic to int

Body:
So in school we are making a project for graphic. I have this interface:

package rasterdata;

import java.util.Optional;

public interface RasterImage<PixelType> {
    Optional<PixelType> getPixel(int c, int r);
    RasterImage<PixelType> withPixel(int c, int r, PixelType value);
    RasterImage<PixelType> cleared(PixelType pixel);
    int getWidth();
    int getHeight();
}

And this is the class which extends the interface and its getPixel() method:

public class RasterImageBuffered<PixelType> implements RasterImage<PixelType> {
private final BufferedImage img;
private final Function<PixelType, Integer> toInteger;
private final Function<Integer, PixelType> toPixelType;
public RasterImageBuffered(final BufferedImage img,
                           final Function<PixelType, Integer> toInteger,
                           final Function<Integer, PixelType> toPixelType) {
    this.img = img;
    this.toInteger = toInteger;
    this.toPixelType = toPixelType;
}

@Override
public Optional<PixelType> getPixel(final int c, final int r) {
    if (c < 0 || c >= img.getWidth() ||
            r < 0 || r >= img.getHeight())
        return Optional.empty();
    return Optional.of(toPixelType.apply(img.getRGB(c, r)));
}

Now, what I am trying to do is to implement a seed fill algorithm. To do that I need to compare the color of the pixel in Canvas (color) with the color which I will use to fill the polygon (fillColor).

This is the seedfill class:

public class SeedFill<PixelType> {

public RasterImage fill(final RasterImage<PixelType> img, final int x, final int y, PixelType borderColor, PixelType fillColor) {

    RasterImage<PixelType> result = img;

    PixelType color = (PixelType) img.getPixel(x,y);

        //this condition throws an error
        if((color & 0xffffff) == (fillColor & 0xffffff)){

        result = result.withPixel(x,y, fillColor);

        fill(img, x+1, y, borderColor, fillColor,bcgColor);
        fill(img, x-1, y, borderColor, fillColor,bcgColor);
        fill(img, x, y+1, borderColor, fillColor,bcgColor);
        fill(img, x, y-1, borderColor, fillColor,bcgColor);

    }

        return result;

    }

}

The problem is that when I want to compare the colors, error saying that I cant compare PixelType with int pops out. However casting It to int throws another error saying that I cant cast PixelType to int. Is there any way of comparing those two values?

Body:
I have solved the comparison by adding:

private final Function<PixelType, Integer> toInteger;

Then the constructor:

public SeedFill(Function<PixelType, Integer> toInteger) {
    this.toInteger = toInteger;
}

And with this function I was able to call toInteger.apply() which made an Integer out of generic PixelType:

if ((toInteger.apply(nowColor.get()) & 0xffffff) != (toInteger.apply(borderColor))) {
        if ((toInteger.apply(nowColor.get()) & 0xffffff) != (toInteger.apply(fillColor))) {


问:
Javascript Replace All words
I need to replace all the words in a DOM (web page in memory) using jquery and javascript.
I need to transform this:

```<code><html>
<head>
    Hi to all
</head>
<body>
    Hi to all
</body>
</html>
</code>```

Into this:

```<code><html>
    <head>
        Bye to all
    </head>
    <body>
        Bye to all
    </body>
</html>
</code>```

But without modifying the tags (ONLY THE VALUES IN THERE)

One try is:

```<code>jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}
</code>```

But it continue replacing the tag values and breaks the page if I put it.

Help!!!

答:
One way that would do it albeit inefficiently would be:

```<code>var element = document.getElementsByTagName('html')[0];
element.innerHTML = element.innerHTML.replace('Hi to all', 'Bye to all');
</code>```

The 'Hi to all' in quotes can also be replaced with a regex if you want.

Title: Javascript Replace All words

Body:
I need to replace all the words in a DOM (web page in memory) using jquery and javascript.
I need to transform this:

    Hi to all

    Hi to all

Into this:

        Bye to all

        Bye to all

But without modifying the tags (ONLY THE VALUES IN THERE)

One try is:

jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}

But it continue replacing the tag values and breaks the page if I put it.

Help!!!

Body:
One way that would do it albeit inefficiently would be:

var element = document.getElementsByTagName('html')[0];
element.innerHTML = element.innerHTML.replace('Hi to all', 'Bye to all');

The 'Hi to all' in quotes can also be replaced with a regex if you want.


问:
Regex infitine capture groups after a specific string
I have a bot that takes a number of different commands and I'm trying scale it's ability to take arguments for all these commands.

This is the syntax:

```<code>!action db_table mandatory_arg arg1 arg2 arg3...
</code>```

Right now I have this functional but un-scalable regex for processing commands:

```<code>^!(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)$
</code>```

It works, but it's not great and it's obviously limited to how many \S* I add in there.

So how can I match an unlimited number of arguments in the following string?

```<code>!dont match this match1 match2 match3 match4 etc...
</code>```

I've tried using a lookbehind but it only works for the first match. I've also tried making it [^ignore] the first part completely but again, this only works for the first argument since the others are also looking for that specific ignore.

Finally, I also gave \K a shot but it didn't work out.

```<code>!\w+\s\w+\s\w+\s\K(\S*)*
</code>```

答:
You seem to need to grab space separated arguments after a specific pattern from the beginning of a string. You may capture any 1+ chars after that pattern, run a re.search/re.match to grab that value, and once a match is found, just split() the match.group(1).

The regex will turn out to be

```<code>^!\w+\s+\w+\s+\w+(.+)
</code>```

Or, to shorten it a bit:

```<code>^!(?:\w+\s+){3}(.+)
</code>```

Note that ^ will be redundant in re.match where the pattern is anchored at the beginning of the string by default. See the regex demo.

See the Python demo:

```<code>import re
rx = r"!\w+\s+\w+\s+\w+(.+)"
s = "!action db_table mandatory_arg arg1 arg2 arg3"
m = re.match(rx, s)
if m:
    print(m.group(1).split())
# => ['arg1', 'arg2', 'arg3']
</code>```

Body:
I have a bot that takes a number of different commands and I'm trying scale it's ability to take arguments for all these commands.

This is the syntax:

!action db_table mandatory_arg arg1 arg2 arg3...

Right now I have this functional but un-scalable regex for processing commands:

^!(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)\s?(\S*)$

It works, but it's not great and it's obviously limited to how many \S* I add in there.

So how can I match an unlimited number of arguments in the following string?

!dont match this match1 match2 match3 match4 etc...

I've tried using a lookbehind but it only works for the first match. I've also tried making it [^ignore] the first part completely but again, this only works for the first argument since the others are also looking for that specific ignore.

Finally, I also gave \K a shot but it didn't work out.

!\w+\s\w+\s\w+\s\K(\S*)*

Body:
You seem to need to grab space separated arguments after a specific pattern from the beginning of a string. You may capture any 1+ chars after that pattern, run a re.search/re.match to grab that value, and once a match is found, just split() the match.group(1).

The regex will turn out to be

^!\w+\s+\w+\s+\w+(.+)

Or, to shorten it a bit:

^!(?:\w+\s+){3}(.+)

Note that ^ will be redundant in re.match where the pattern is anchored at the beginning of the string by default. See the regex demo.

See the Python demo:

import re
rx = r"!\w+\s+\w+\s+\w+(.+)"
s = "!action db_table mandatory_arg arg1 arg2 arg3"
m = re.match(rx, s)
if m:
    print(m.group(1).split())
# => ['arg1', 'arg2', 'arg3']


问:
NPM install -> but only add appropriate line to package.json
I have been wondering this for years, but never bothered to ask. There are many cases where I just want to add the appropriate line for the latest version of a package to package.json, without actually touching node_modules.

Say I want to add the latest version of lodash to my project w/o actually installing it to node_modules. Is there an NPM command to do that?

Let me know if there is a better way to phrase the question.

答:
Unless someone can think of something better, seems like a simple tool could be used to do this:

npm view <pkg-name> version

read package.json, add the dependency to dependencies, sort dependencies by name

save package.json


问:
How to loop through directory which have multiple subdirectories?
I'm have to get the dir path of all sub-directories which has sub-directories under that and print the output to a file which has path for all sub directories. here my question is i can do something like

```<code>find .mymountpoint/DataRoot/DATAINPUT_*/PER201448_*/IPD_*/
 -maxdepth 1 -mindepth 1 -type d
 -printf '/root/mymountpoint/DataRoot/DATAINPUT/PER201448/IPD/%f\n'
 > dirpathfile.txt
</code>```

But it will print the output of all directory paths to one location which I don't want. I want the sub directory path has to go to that particular dir path only using shell script in linux.

If i'm not clear, apologies and any help will be appreciated.

Thx

答:
As far as I understand you want to print absolute paths. You can use the realpath command for that:

```<code>find ... -exec realpath {} +
</code>```

Body:
I'm have to get the dir path of all sub-directories which has sub-directories under that and print the output to a file which has path for all sub directories. here my question is i can do something like

find .mymountpoint/DataRoot/DATAINPUT_*/PER201448_*/IPD_*/
 -maxdepth 1 -mindepth 1 -type d
 -printf '/root/mymountpoint/DataRoot/DATAINPUT/PER201448/IPD/%f\n'
 > dirpathfile.txt

But it will print the output of all directory paths to one location which I don't want. I want the sub directory path has to go to that particular dir path only using shell script in linux.

If i'm not clear, apologies and any help will be appreciated.

Thx

Body:
As far as I understand you want to print absolute paths. You can use the realpath command for that:

find ... -exec realpath {} +


问:
Aligning annotations and variables in parameters IntelliJ
For instance, I have this currently with my settings:

```<code>public foo(@Annotation1 String str,
           @Annotation2 Integer int,
           @SomeLongerAnnotation List<String> l,
           boolean b){}
</code>```

What I'm looking to do is this:

```<code>public foo(@Annotation1          String       str1,
           @Annotation2          Integer      int1,
           @SomeLongerAnnotation List<String> l1,
                                 boolean      b){}
</code>```

so that the annotations are aligned on their own, and the variables and their types are aligned on their own. Is it possible for Intellij to auto-format it in that way?

答:
I don' think its possible.   I tried.  As an alternative you could format it yourself then in Settings|Code Style panel check the box that says "Enable formatter markers in comments"

Then you can have the formatter ignore a section of code as follows (ugly and probably not what you want).  If it were me I'd just get used to the defaults and move on with whatever I was working on...

```<code>    // @formatter:off
    public Test(@NotNull String         str,
                @NotNull Integer        ints,
                @NotNull List<String>   l,
                boolean b) {
    }
    // @formatter:on
</code>```

Body:
For instance, I have this currently with my settings:

public foo(@Annotation1 String str,
           @Annotation2 Integer int,
           @SomeLongerAnnotation List<String> l,
           boolean b){}

What I'm looking to do is this:

public foo(@Annotation1          String       str1,
           @Annotation2          Integer      int1,
           @SomeLongerAnnotation List<String> l1,
                                 boolean      b){}

so that the annotations are aligned on their own, and the variables and their types are aligned on their own. Is it possible for Intellij to auto-format it in that way?

Body:
I don' think its possible.   I tried.  As an alternative you could format it yourself then in Settings|Code Style panel check the box that says "Enable formatter markers in comments"

Then you can have the formatter ignore a section of code as follows (ugly and probably not what you want).  If it were me I'd just get used to the defaults and move on with whatever I was working on...

    // @formatter:off
    public Test(@NotNull String         str,
                @NotNull Integer        ints,
                @NotNull List<String>   l,
                boolean b) {
    }
    // @formatter:on


答:
Use distinct on:

```<code>select distinct on (c.age) c.*
from cats c
order by age;
</code>```

Title: Using Postgres to take one object from each group

Body:
I am working with a table of cats and am trying to write a statement that will select one cat from each age group.

this is my table

pets=# SELECT * FROM cats;
 id |   name   | gender | age |     intake_date     |    adoption_date
----+----------+--------+-----+---------------------+---------------------
  1 | Mushi    | M      |   1 | 2016-01-09 00:00:00 | 2016-03-22 00:00:00
  2 | Seashell | F      |   7 | 2016-01-09 00:00:00 |
  3 | Azul     | M      |   3 | 2016-01-11 00:00:00 | 2016-04-17 00:00:00
  4 | Victoire | M      |   7 | 2016-01-11 00:00:00 | 2016-09-01 00:00:00
  5 | Nala     | F      |   1 | 2016-01-12 00:00:00 |
(5 rows)

Body:
Use distinct on:

select distinct on (c.age) c.*
from cats c
order by age;


问:
How to programmatically change views in TabBarViewController?
I have two instances where I want to re-direct the user to the main view of a TabBarViewController.  I've tried BringSubViewToFront(), but that does nothing... I basically want to activate the first tab (home tab?).</p>

答:
Assuming your TabViewController already has all the ViewControllers created for each tab, simply changing the SelectedIndex property in the tabbar does what you're looking for:

myTabBarController.SelectedIndex = 2;

Will send you to the third tab (array is zero-based).


问:
NPOI does not change cell´s font color
I am trying to change a cell's font color conditionally. This is my last try:

```<code>IWorkbook wb = null;

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    wb = WorkbookFactory.Create(_fileStream);
    _fileStream.Close();
}

ISheet sheet = wb.GetSheet(sheetName);
IFont font = wb.CreateFont();
...
...

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    ICellStyle redStyle = cell.CellStyle;
    font.Color = IndexedColors.Red.Index;
    redStyle.SetFont(font);
    cell.CellStyle = redStyle;
}
else
{
    ICellStyle normalStyle = cell.CellStyle;
    font.Color = XSSFFont.DEFAULT_FONT_COLOR;
    normalStyle.SetFont(font);
    cell.CellStyle = normalStyle;
}
</code>```

However, the font does not change when the condition is met. It seems like the style is applied for all cells instead of the cell I am getting within the loop. I have read some questions related to this problem but I can not make it work.

This new try is formatting all cells. No matter whether it meets the condition or not

```<code>ICellStyle redStyle = cell.CellStyle;
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

//This is how I am trying to change cells format
if (integrity < 1)
{
    cell.CellStyle.SetFont(font);
}
</code>```

Joao response would format all cells with a "normalStyle"

答:
For XSSF format use this approach to create font and then assign it to cells</p>

```<code>XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
defaultFont.FontName = "Arial";
defaultFont.Color = IndexedColors.Black.Index;
defaultFont.IsBold = false;
defaultFont.IsItalic = false;
defaultFont.Boldweight = 700;

XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
defaultStyle.SetFont(defaultFont);
</code>```

Title: NPOI does not change cell´s font color

Body:
I am trying to change a cell's font color conditionally. This is my last try:

IWorkbook wb = null;

using (FileStream _fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    wb = WorkbookFactory.Create(_fileStream);
    _fileStream.Close();
}

ISheet sheet = wb.GetSheet(sheetName);
IFont font = wb.CreateFont();
...
...

// within a loop
ICell cell = sheet.GetRow(r).GetCell(col);
if (integrity < 1)
{
    ICellStyle redStyle = cell.CellStyle;
    font.Color = IndexedColors.Red.Index;
    redStyle.SetFont(font);
    cell.CellStyle = redStyle;
}
else
{
    ICellStyle normalStyle = cell.CellStyle;
    font.Color = XSSFFont.DEFAULT_FONT_COLOR;
    normalStyle.SetFont(font);
    cell.CellStyle = normalStyle;
}

However, the font does not change when the condition is met. It seems like the style is applied for all cells instead of the cell I am getting within the loop. I have read some questions related to this problem but I can not make it work.

This new try is formatting all cells. No matter whether it meets the condition or not

ICellStyle redStyle = cell.CellStyle;
font.Color = IndexedColors.Red.Index;
redStyle.SetFont(font);

//This is how I am trying to change cells format
if (integrity < 1)
{
    cell.CellStyle.SetFont(font);
}

Joao response would format all cells with a "normalStyle"

Body:
For XSSF format use this approach to create font and then assign it to cells

XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
defaultFont.FontName = "Arial";
defaultFont.Color = IndexedColors.Black.Index;
defaultFont.IsBold = false;
defaultFont.IsItalic = false;
defaultFont.Boldweight = 700;

XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
defaultStyle.SetFont(defaultFont);


问:
Sybase - how do I return the first value that exists from a condition in SQL?
Say I'm trying to return some results where a column in a table matches a condition I set. But I only want to return the first result from a list of possible values in the condition. Is there a quick and easy way to do that? I'm thinking that I can use coalesce somehow, but not sure how I can structure it.

Something like:

```<code>select identifier,purpose from table
where identifier = 'letters'
and purpose = coalesce('A','B','C')
group by purpose
</code>```

So in the table, if A purpose isn't there, then I only want the B purpose to show up. if it isn't there, then I want the C to show up, if none of them are there, then I would ideally like a null or no results to be returned. I'd rather not make several case statements where if A is null then look to B, then if B is null to look to C. Is there a quick way syntactically to do so?

Edit: I also want this to work if I have multiple identifiers I list, such as:

```<code>select identifier,purpose from table
where identifier in ('letters1', 'letters2')
and purpose = coalesce('A','B','C')
group by purpose
</code>```

where I return two results if they exist - one purpose for each identifier, with the purpose in the order of importance for A first, then B, then C, or null if none exist.

Unforunately my reasoning for caolesce doesn't work above, as none of the variables are null so my query will just try to return all purposes of 'A' without the fallback that I intend my query to do. I want to try and avoid using temp tables if possible.

答:
Sybase ASE does not have support for the row_number() function (else this would be fairly simple), so one option would be to use a #temp table to simulate (to some extent) row_number() functionality.

Some sample data:

```<code>create table mytab
(identifier     varchar(30)
,purpose        varchar(30)
)
go

insert mytab values ('letters1','A')
insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
go
</code>```

The #temp table is created with an identity column plus a 2nd column to hold the items you wish to prioritize; priority is determined by the order in which the rows are inserted into the #temp table.

```<code>create table #priority
(id        smallint    identity
,purpose   varchar(30))
go

insert #priority (purpose)
select 'A'                  -- first  priority
union all
select 'B'                  -- second priority
union all
select 'C'                  -- last   priority
go

select * from #priority order by id
go

 id     purpose
 ------ -------
      1 A
      2 B
      3 C
</code>```

We'll use a derived table to find the highest priority purpose (ie, minimal id value).  We then join this minimal id back to #priority to generate the final result set:

```<code>select  dt.identifier,
        p.purpose

from    (-- join mytab with #priority, keeping only the minimal priority id of the rows that exist:

         select m.identifier,
                min(p.id)       as min_id

         from   mytab m

         join   #priority p
         on     p.purpose = m.purpose

         group by m.identifier) dt

-- join back to #priority to convert min(id) into the actual purpose:

join    #priority p
on      p.id = dt.min_id

order by 1
go
</code>```

Some test runs with different set of mytab data:

```<code>/* contents of mytab:

insert mytab values ('letters1','A')
insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
*/

 identifier purpose
 ---------- -------
 letters1         A
 letters2         A

/* contents of mytab:

--insert mytab values ('letters1','A')
--insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

--insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
*/

 identifier purpose
 ---------- -------
 letters1         C
 letters2         B
</code>```

Returning NULL if a row does not exist is not going to be easy since generating a NULL requires existence of a row ... somewhere ... with which to associate the NULL.

One idea would be to expand on the #temp table idea by creating another #temp table (eg, #identifiers) with the list of desired identifier values you wish to search on. You could then make use of a left (outer) join from #identifiers to mytab to ensure you always generate a result record for each identifier.

Body:
Say I'm trying to return some results where a column in a table matches a condition I set. But I only want to return the first result from a list of possible values in the condition. Is there a quick and easy way to do that? I'm thinking that I can use coalesce somehow, but not sure how I can structure it.

Something like:

select identifier,purpose from table
where identifier = 'letters'
and purpose = coalesce('A','B','C')
group by purpose

So in the table, if A purpose isn't there, then I only want the B purpose to show up. if it isn't there, then I want the C to show up, if none of them are there, then I would ideally like a null or no results to be returned. I'd rather not make several case statements where if A is null then look to B, then if B is null to look to C. Is there a quick way syntactically to do so?

Edit: I also want this to work if I have multiple identifiers I list, such as:

select identifier,purpose from table
where identifier in ('letters1', 'letters2')
and purpose = coalesce('A','B','C')
group by purpose

where I return two results if they exist - one purpose for each identifier, with the purpose in the order of importance for A first, then B, then C, or null if none exist.

Unforunately my reasoning for caolesce doesn't work above, as none of the variables are null so my query will just try to return all purposes of 'A' without the fallback that I intend my query to do. I want to try and avoid using temp tables if possible.

Body:
Sybase ASE does not have support for the row_number() function (else this would be fairly simple), so one option would be to use a #temp table to simulate (to some extent) row_number() functionality.

Some sample data:

create table mytab
(identifier     varchar(30)
,purpose        varchar(30)
)
go

insert mytab values ('letters1','A')
insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
go

The #temp table is created with an identity column plus a 2nd column to hold the items you wish to prioritize; priority is determined by the order in which the rows are inserted into the #temp table.

create table #priority
(id        smallint    identity
,purpose   varchar(30))
go

insert #priority (purpose)
select 'A'                  -- first  priority
union all
select 'B'                  -- second priority
union all
select 'C'                  -- last   priority
go

select * from #priority order by id
go

 id     purpose
 ------ -------
      1 A
      2 B
      3 C

We'll use a derived table to find the highest priority purpose (ie, minimal id value).  We then join this minimal id back to #priority to generate the final result set:

select  dt.identifier,
        p.purpose

from    (-- join mytab with #priority, keeping only the minimal priority id of the rows that exist:

         select m.identifier,
                min(p.id)       as min_id

         from   mytab m

         join   #priority p
         on     p.purpose = m.purpose

         group by m.identifier) dt

-- join back to #priority to convert min(id) into the actual purpose:

join    #priority p
on      p.id = dt.min_id

order by 1
go

Some test runs with different set of mytab data:

/* contents of mytab:

insert mytab values ('letters1','A')
insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
*/

 identifier purpose
 ---------- -------
 letters1         A
 letters2         A

/* contents of mytab:

--insert mytab values ('letters1','A')
--insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

--insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
*/

 identifier purpose
 ---------- -------
 letters1         C
 letters2         B

Returning NULL if a row does not exist is not going to be easy since generating a NULL requires existence of a row ... somewhere ... with which to associate the NULL.

One idea would be to expand on the #temp table idea by creating another #temp table (eg, #identifiers) with the list of desired identifier values you wish to search on. You could then make use of a left (outer) join from #identifiers to mytab to ensure you always generate a result record for each identifier.


问:
Playing a song using jQuery/Javascript
I'm trying to play a song when the file receives a 'playMusic' event from an Arduino, but I'm getting an Uncaught TypeError: Cannot read property 'play' of undefined at EventSource.<anonymous>. I've read that this could be because the audio is trying to play before the song file is ready, but combining the window.onload function in the event listener causes nothing to happen. I've added a delay of two seconds before I call the event to try to compensate for enough time to load the song file, but I still get the same error.

```<code><html>
    <title>Song Time</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <body>
        <audio id="song">
            <source src="song.mp3" type="audio/mpeg">
        </audio>

         <script type="text/javascript">
           var eventSource = new EventSource("https://api.particle.io/v1/devices/2d0024001047363330363431/events/?access_token=bdde583943e53ea709aa421a2e618d024700b2f1");

           eventSource.addEventListener('playMusic', function(e) {
                //window.onload=function() {
                    console.log("here");
                    $('song')[0].play();
                //}

           });
        </script>
    </body>
</html>
</code>```

```<code>Uncaught TypeError: Cannot read property 'play' of undefined
    at EventSource.<anonymous
</code>```

答:
Credit to @James

$(‘#song’) you forgot # – James

Title: Playing a song using jQuery/Javascript

Body:
I'm trying to play a song when the file receives a 'playMusic' event from an Arduino, but I'm getting an Uncaught TypeError: Cannot read property 'play' of undefined at EventSource.<anonymous>. I've read that this could be because the audio is trying to play before the song file is ready, but combining the window.onload function in the event listener causes nothing to happen. I've added a delay of two seconds before I call the event to try to compensate for enough time to load the song file, but I still get the same error.

    <title>Song Time</title>

        <audio id="song">
            <source src="song.mp3" type="audio/mpeg">
        </audio>

Uncaught TypeError: Cannot read property 'play' of undefined
    at EventSource.<anonymous


问:
How do I hide a div in angular based upon document height?
Forgive me if this is elsewhere...

I came into a project abandoned half-way through. I've not worked in angular before and need to hide/show a "back to top" button dependent upon whether the document is taller than the viewport. I've tried several different approaches and cannot get anything to work successfully. This is my latest attempt:

```<code>$(document).ready(function() {

    if ($(document).height() > $(window).height()) {
        console.log("document height is greater");
        $('#arrowUp').show();
    } else {
        console.log("window height is lesser");
        $('#arrowUp').show();
    }
});
</code>```

Thanks in advance

答:
Why don't you try something like this:

```<code><div id="arrowUp" ng-show="$(document).height() > $(window).height()" >
  /\
</div>
</code>```

I would also dismiss the usage of jQuery for a trivial task as fetching those values.

Body:
Forgive me if this is elsewhere...

I came into a project abandoned half-way through. I've not worked in angular before and need to hide/show a "back to top" button dependent upon whether the document is taller than the viewport. I've tried several different approaches and cannot get anything to work successfully. This is my latest attempt:

$(document).ready(function() {

    if ($(document).height() > $(window).height()) {
        console.log("document height is greater");
        $('#arrowUp').show();
    } else {
        console.log("window height is lesser");
        $('#arrowUp').show();
    }
});

Thanks in advance

Body:
Why don't you try something like this:

<div id="arrowUp" ng-show="$(document).height() > $(window).height()" >
  /\
</div>

I would also dismiss the usage of jQuery for a trivial task as fetching those values.


问:
How to add license file dynamically to LicenseAgreement dialog in InstallShield
I have a Basic MSI project installer. When user run a setup then I want to download a EULA file from server and then I want to display it on License Agreement dialog at the time of installation. It's possible in InstallScript installer. But how I can show EULA file dynamically in LicenseAgreement dialog in Basic MSI installer?</p>

答:
You need a custom action to dynamically download the rich text and then update the in memory msi database using temporary views.  See:

https://resources.flexera.com/web/pdf/archive/msiaccess.pdf

If you want to use C#/DTF it's more like this:

http://blog.deploymentengineering.com/2008/07/dynamic-windows-installer-ui.html


问:
Why does the Difference function give different results when switching order of strings to compare?
In SQL Server, if I do the following:

```<code>Difference ('Kennady', 'Kary') : I get 2
</code>```

If i do:

```<code>Difference ('Kary', 'Kennady') : I get 3.
</code>```

I thought the Difference function looks at the Soundex values under the hood, and gives a 0-4 number of how many characters in place are the same.

```<code>SELECT SOUNDEX('Kennady') AS [SoundEx Kennady]
    , SOUNDEX('Kary') AS [SoundEx Kary]
    , DIFFERENCE ('Kennady', 'Kary') AS [Difference Kennady vs Kary]
    , DIFFERENCE ('Kary', 'Kennady') AS [Difference Kary vs Kennady];
</code>```

答:
Reference the last post here that explains the algorithm:  https://social.msdn.microsoft.com/Forums/en-US/a6ba987d-6fde-40d3-bcd0-4c7fd3d2e8cf/tsql-difference-function-returns-different-results-for-same-query?forum=transactsql

NOTE: This is all my opinion as to what is happening.

According to that post, it uses the FIRST parameter and then steps through character by character looking for matches in the second parameters.

As an example, my name "Vogel" = V240 in SOUNDEX.  "Vasquez" = V220.

```<code>DIFFERENCE('Vogel','Vasquez') = 3
</code>```

Because it checks "V", "2", "4", and "0" and finds 3 matches.

However,

```<code>DIFFERENCE('Vasquez','Vogel') = 4
</code>```

Because it checks "V", "2", "2", and "0" and finds 4 matches.

It seems if the first parameter has a soundex with any duplicating digits it can produce unexpected results.

Body:
In SQL Server, if I do the following:

Difference ('Kennady', 'Kary') : I get 2

If i do:

Difference ('Kary', 'Kennady') : I get 3.

I thought the Difference function looks at the Soundex values under the hood, and gives a 0-4 number of how many characters in place are the same.

SELECT SOUNDEX('Kennady') AS [SoundEx Kennady]
    , SOUNDEX('Kary') AS [SoundEx Kary]
    , DIFFERENCE ('Kennady', 'Kary') AS [Difference Kennady vs Kary]
    , DIFFERENCE ('Kary', 'Kennady') AS [Difference Kary vs Kennady];

Body:
Reference the last post here that explains the algorithm:  https://social.msdn.microsoft.com/Forums/en-US/a6ba987d-6fde-40d3-bcd0-4c7fd3d2e8cf/tsql-difference-function-returns-different-results-for-same-query?forum=transactsql

NOTE: This is all my opinion as to what is happening.

According to that post, it uses the FIRST parameter and then steps through character by character looking for matches in the second parameters.

As an example, my name "Vogel" = V240 in SOUNDEX.  "Vasquez" = V220.

DIFFERENCE('Vogel','Vasquez') = 3

Because it checks "V", "2", "4", and "0" and finds 3 matches.

However,

DIFFERENCE('Vasquez','Vogel') = 4

Because it checks "V", "2", "2", and "0" and finds 4 matches.

It seems if the first parameter has a soundex with any duplicating digits it can produce unexpected results.


问:
AWS RDS PostgreSQL Tablespace
I created an AWS RDS postgres instance. When creating i was prompted to create user. There is no reason for creating tablespaces with location in AWS RDS? The reason is when creating a database i want the database to goto the tablespace i created. When i run the below command </p>

```<code>CREATE USER test;

CREATE TABLESPACE test OWNER test LOCATION '/test_data';

CREATE DATABASE test WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'C' LC_CTYPE = 'C' TABLESPACE = test;

ERROR:  permission denied for tablespace test
</code>```

<p>I logged into postgres using test_admin user to run the above commands. The test_admin is the account i created during the RDS instance provisioning. Is that the only account that i should be using above to create all of the DB objects from that point? </p>

答: Do you want the owner of the database to be test as well? If so, add that into your CREATE DATABASE.... Otherwise, you'll probably need to give the test_admin user permission on the test tablespace before trying to create it.

Title: AWS RDS PostgreSQL Tablespace

Body:
I created an AWS RDS postgres instance. When creating i was prompted to create user. There is no reason for creating tablespaces with location in AWS RDS? The reason is when creating a database i want the database to goto the tablespace i created. When i run the below command

CREATE USER test;

CREATE TABLESPACE test OWNER test LOCATION '/test_data';

CREATE DATABASE test WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'C' LC_CTYPE = 'C' TABLESPACE = test;

ERROR:  permission denied for tablespace test

I logged into postgres using test_admin user to run the above commands. The test_admin is the account i created during the RDS instance provisioning. Is that the only account that i should be using above to create all of the DB objects from that point?


问:
Can I deploy .net core application into google cloud using terminal?
I would like to deploy my dotNetCore application into google cloud (App Engine Flex) using gitlab-ci or using Unix terminal. Unfortunately, I found limited information how can I do it. Could someone help me?

Yes, there is a possibility to use docker, if I find no other options.

Thanks.

答:
Yes, you can.  This page describes how:
https://cloud.google.com/appengine/docs/flexible/dotnet/quickstart

It's a little trickier than using VS Tools, but not much.  You have to create an app.yaml file, and populate it with two lines.  Then run:

```<code>dotnet restore
dotnet publish -c Release
gcloud app deploy .\bin\Release\netcoreapp1.1\publish\app.yaml
</code>```

Again, the quickstart page and the samples it links to have the finer details.

Body:
Yes, you can.  This page describes how:
https://cloud.google.com/appengine/docs/flexible/dotnet/quickstart

It's a little trickier than using VS Tools, but not much.  You have to create an app.yaml file, and populate it with two lines.  Then run:

dotnet restore
dotnet publish -c Release
gcloud app deploy .\bin\Release\netcoreapp1.1\publish\app.yaml

Again, the quickstart page and the samples it links to have the finer details.