问:
ASP.Net Core saving base64 string
I have a Image model:

```<code>public class Image
{
    [Key]
    public long ImagelId { get; set; }
    public string base64 { get; set; }
}
</code>```

Which I use like following:

```<code>public class CoreGoal
{
    [Key]
    public long CoreGoalId { get; set; }
    [Required]
    public string Title { get; set; }

    public virtual ICollection<Image> Images { get; set; }

    public CoreGoal()
    {

    }
}
</code>```

I am using MySql database. I intend to store possibly multiple images as base64 strings against each CoreGoal.

Whenever I make a POST request with base64 strings, it is successful, however a large portion of the the string is chopped while saving to the database.

Am I using a wrong data structure for storing base64 i.e. string? Is it a problem in my ASP.Net code or is it a MySql limitation?

How can I fix this?

UPDATE:

My Repository class:

```<code>public class CoreGoalRepository : ICoreGoalRepository
{
    private readonly WebAPIDataContext _db;

    public CoreGoalRepository(WebAPIDataContext db)
    {
        _db = db;
    }

    //Add new
    public void CreateCoreGoal(CoreGoal coreGoal)
    {
        _db.CoreGoals.Add(coreGoal);
        _db.SaveChanges();
    }

    //Get all
    public IEnumerable<CoreGoal> GetAllCoreGoals()
    {
        return _db.CoreGoals
            .Include(coreGoal => coreGoal.Benefits)
            .Include(coreGoal => coreGoal.Images)
            .ToList();
    }
}

public interface ICoreGoalRepository
{
    void CreateCoreGoal(CoreGoal coreGoal);
    IEnumerable<CoreGoal> GetAllCoreGoals();
}
</code>```

My controller:

```<code> [Route("api/[controller]")]
    public class CoreGoalController : Controller
    {
        private readonly ICoreGoalRepository _coreGoalRepository;

        //Controller
        public CoreGoalController(ICoreGoalRepository coreGoalRepository) {
            _coreGoalRepository = coreGoalRepository;
        }

        //Get methods
        [HttpGet]
        public IEnumerable<CoreGoal> GetAll()
        {
            return _coreGoalRepository.GetAllCoreGoals();
        }

        //Create
        [HttpPost]
        public IActionResult Create([FromBody] CoreGoal item)
        {
            if (item == null)
            {
                return BadRequest();
            }

            _coreGoalRepository.CreateCoreGoal(item);

            return CreatedAtRoute("GetCoreGoal", new { id = item.CoreGoalId }, item);
        }
     }
</code>```

答:
When you make the post request return also the object created as a JSON, so you can see the URL, or put a break point in your post and see the value of base64 string.

If the URL is ok then its the Db, so you need to manually set the max size of the URL with the attribute [StringLength(length)]

Title: ASP.Net Core saving base64 string

Body:
I have a Image model:

public class Image
{
    [Key]
    public long ImagelId { get; set; }
    public string base64 { get; set; }
}

Which I use like following:

public class CoreGoal
{
    [Key]
    public long CoreGoalId { get; set; }
    [Required]
    public string Title { get; set; }

    public virtual ICollection<Image> Images { get; set; }

    public CoreGoal()
    {

    }
}

I am using MySql database. I intend to store possibly multiple images as base64 strings against each CoreGoal.

Whenever I make a POST request with base64 strings, it is successful, however a large portion of the the string is chopped while saving to the database.

Am I using a wrong data structure for storing base64 i.e. string? Is it a problem in my ASP.Net code or is it a MySql limitation?

How can I fix this?

UPDATE:

My Repository class:

public class CoreGoalRepository : ICoreGoalRepository
{
    private readonly WebAPIDataContext _db;

    public CoreGoalRepository(WebAPIDataContext db)
    {
        _db = db;
    }

    //Add new
    public void CreateCoreGoal(CoreGoal coreGoal)
    {
        _db.CoreGoals.Add(coreGoal);
        _db.SaveChanges();
    }

    //Get all
    public IEnumerable<CoreGoal> GetAllCoreGoals()
    {
        return _db.CoreGoals
            .Include(coreGoal => coreGoal.Benefits)
            .Include(coreGoal => coreGoal.Images)
            .ToList();
    }
}

public interface ICoreGoalRepository
{
    void CreateCoreGoal(CoreGoal coreGoal);
    IEnumerable<CoreGoal> GetAllCoreGoals();
}

My controller:

 [Route("api/[controller]")]
    public class CoreGoalController : Controller
    {
        private readonly ICoreGoalRepository _coreGoalRepository;

        //Controller
        public CoreGoalController(ICoreGoalRepository coreGoalRepository) {
            _coreGoalRepository = coreGoalRepository;
        }

        //Get methods
        [HttpGet]
        public IEnumerable<CoreGoal> GetAll()
        {
            return _coreGoalRepository.GetAllCoreGoals();
        }

        //Create
        [HttpPost]
        public IActionResult Create([FromBody] CoreGoal item)
        {
            if (item == null)
            {
                return BadRequest();
            }

            _coreGoalRepository.CreateCoreGoal(item);

            return CreatedAtRoute("GetCoreGoal", new { id = item.CoreGoalId }, item);
        }
     }


来源: stackexchange

问:
Getting a count of an outcome which match a date
I know that this will be a really simple answer but I cannot ask the right question on Google to get the answer I want.

What I want to know is how to get Excel to look in column B to look for a particular date, then every time it finds a match to that date count what is in column H. There are only 2 responses in column H "Dealt With" and "Passed Back" I've tried the following but of course it hasn't worked

=IF(B<>O3,COUNTIF(H2:H2000,"Dealt With"),"")

I think I am close so if anyone could just tell me how to correct this that would be great.

答:
After further soul searching I found what it was. In-case anyone new like me wants to know, what I wanted was to use countifs.

=COUNTIFS($H$2:$H$404,$L$3,$B$2:$B$404,O3)

Countifs added both the matching date and the response. I then just made two separate columns to count them.

ContentLicense: CC BY-SA 3.0


问:
Hom press second button with id:inf?
I use Testdroid, it based on junit3.
Command:

```<code>solo.clickOnView(solo.findViewById("cc.app.R.id.inf"));
</code>```

open first button with id:inf

what command need use to press on second(third and more) button
with id:inf.

how select area/layout, where junit try found element with
 id:inf, something like that:

Here use command to chose LinearLayout by index and then

```<code>solo.clickOnView(solo.findViewById("cc.app.R.id.inf"));
</code>```

答:
You can get/find LinearLayout view by index with methods:

```<code>getView(int id,int index)
getView(Class<T> viewClass, int index)
...
</code>```

Then you can use method(s):

```<code>getViews(android.view.View parent)
getCurrentViews(Class<T> classToFilterBy, android.view.View parent)
</code>```

which returns list of views, so filtering must be done by your code/helper method.

Title: Hom press second button with id:inf?

Body:
I use Testdroid, it based on junit3.
Command:

solo.clickOnView(solo.findViewById("cc.app.R.id.inf"));

open first button with id:inf

what command need use to press on second(third and more) button
with id:inf.

how select area/layout, where junit try found element with
 id:inf, something like that:

Here use command to chose LinearLayout by index and then

solo.clickOnView(solo.findViewById("cc.app.R.id.inf"));

Body:
You can get/find LinearLayout view by index with methods:

getView(int id,int index)
getView(Class<T> viewClass, int index)
...

Then you can use method(s):

getViews(android.view.View parent)
getCurrentViews(Class<T> classToFilterBy, android.view.View parent)

which returns list of views, so filtering must be done by your code/helper method.


问:
Replacing an empty cell in one column based on corresponding value from another column?
I have this data frame:

```<code>df <- data.frame(number = c(1,2,3,1,3,4,5,2),
             name = c('dany', 'rand', 'tanya',
                      ' ', ' ', 'bruce', 'tony', ' '),
             grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))
</code>```

which looks like this:

```<code> > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1
    3           c
    4 bruce     d
    5  tony     e
    2
</code>```

what I want is this:

```<code> > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1  dany     a
    3 tanya     c
    4 bruce     d
    5  tony     e
    2  rand     b
</code>```

How do I accomplish this ?
how do I replace the empty spaces with the values corresponding to number column?

If possible, please explain how can I achieve this with dplyr(tidyverse).

答:
I would do this in base R using merge:

```<code>x <- df$name==" "
A <- df[x,]
B <- df[!x,]
rbind(B, setNames(merge(A, B, by = "number")[,c(1,4,5)], colnames(a)))

   # number  name grade
# 1       1  dany     a
# 2       2  rand     b
# 3       3 tanya     c
# 6       4 bruce     d
# 7       5  tony     e
# 11      1  dany     a
# 21      2  rand     b
# 31      3 tanya     c
</code>```

Body:
I have this data frame:

df <- data.frame(number = c(1,2,3,1,3,4,5,2),
             name = c('dany', 'rand', 'tanya',
                      ' ', ' ', 'bruce', 'tony', ' '),
             grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))

which looks like this:

 > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1
    3           c
    4 bruce     d
    5  tony     e
    2

what I want is this:

 > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1  dany     a
    3 tanya     c
    4 bruce     d
    5  tony     e
    2  rand     b

How do I accomplish this ?
how do I replace the empty spaces with the values corresponding to number column?

If possible, please explain how can I achieve this with dplyr(tidyverse).

Body:
I would do this in base R using merge:

x <- df$name==" "
A <- df[x,]
B <- df[!x,]
rbind(B, setNames(merge(A, B, by = "number")[,c(1,4,5)], colnames(a)))

   # number  name grade
# 1       1  dany     a
# 2       2  rand     b
# 3       3 tanya     c
# 6       4 bruce     d
# 7       5  tony     e
# 11      1  dany     a
# 21      2  rand     b
# 31      3 tanya     c


问:
How to execute setTimeout in order regardless of the timing using Promise?
I'm currently having this piece of code:

```<code>var timeOne = new Promise(function(resolve,reject) {
    setTimeout(function(){
        console.log('This is one');
    }, Math.random() * 1000);
});

var timeTwo = new Promise(function(resolve,reject) {
    setTimeout(function(){
        console.log('This is two');
    }, Math.random() * 1000);
});

    timeOne.then(timeTwo);
</code>```

My desired out come is to display timeOne result before timeTwo regardless of what Math.random() provides. I'm currently struggling with this promise "thingy". Can anyone clarify why the code above isnt working as intended? (it still can display "This is two" before "This is one").

答:
var timeOne = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('This is one');
  }, Math.random() * 1000);
});

var timeTwo = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('This is two');
  }, Math.random() * 1000);
});

timeOne.then(function(m) {
  console.log(m);
  return timeTwo;
}).then(function(m) {
  console.log(m);
  return 'done';
}).then(function(m){
  console.log(m);
});```

Body:
I'm currently having this piece of code:

var timeOne = new Promise(function(resolve,reject) {
    setTimeout(function(){
        console.log('This is one');
    }, Math.random() * 1000);
});

var timeTwo = new Promise(function(resolve,reject) {
    setTimeout(function(){
        console.log('This is two');
    }, Math.random() * 1000);
});

    timeOne.then(timeTwo);

My desired out come is to display timeOne result before timeTwo regardless of what Math.random() provides. I'm currently struggling with this promise "thingy". Can anyone clarify why the code above isnt working as intended? (it still can display "This is two" before "This is one").


答:
Basically what everyone said in the comments. Here's how you could do it:

var timeOne = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve(console.log('This is one'));
    }, Math.random() * 1000);
  });
}

var timeTwo = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve(console.log('This is two'));
    }, Math.random() * 1000);
  });
}

timeOne().then(timeTwo);```

Title: How to execute setTimeout in order regardless of the timing using Promise?


问:
Class vs Struct for data only?
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

```<code>class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};
</code>```

Versus:

```<code>struct Foo {
   struct Pos { int x, y, z } Pos;
};
</code>```

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

答:
There is no real advantage of using one over the other, in c++, the only difference between a struct and a class is the default visibility of it's members (structs default to public, classes default to private).

Personally, I tend to prefer structs for POD types and use classes for everything else.

EDIT: litb made a good point in the comment so I'm going to quote him here:

one important other difference is that
  structs derive from other
  classes/struct public by default,
  while classes derive privately by
  default.

OwnerDisplayName: Daniel

ContentLicense: CC BY-SA 2.5

Title: Class vs Struct for data only?

Body:
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};

Versus:

struct Foo {
   struct Pos { int x, y, z } Pos;
};

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

LastEditorDisplayName: dmckee

OwnerDisplayName: Evan Teran

LastEditorDisplayName: Evan Teran


问:
How do you view session cookies in Internet Explorer?
I am able to see session cookies in Firefox 3.6 by going to

Tools->Options->Privacy->Remove Individual Cookies

How do I see those same session cookies in IE (6/7/8)?

Tools->Internet Options->Browsing
  history Settings->View files

only contains persistent cookies

Also how do I access them programmatically? In Firefox I use the nsICookieManager interface to read the session cookies, does IE contain an equivalent interface?

答: F12-> Network Tab -> Enable Network Capture Traffic Capturing - > Details Tab -> Request Header Tab.


问:
Backend Server fetching data vs UI fetching data
I have an architecture question.

I am currently working on a system architecture for an Employee information system which will show all the employee information. But the information what needs to be shown to user is currently stored in two systems. But on UI for user we need to show the data in consolidated view. We have two option to approach this.

Option#1:

One backend server which fetches both the data from the two systems and then send it UI to display.

Option#2:

One backend server sends the data from one system and links to get the data from other system.UI then fetches the data from other system to display it on UI.

According to me the Option#2 is better since the data is fetched by UI as and when needed. But the concern with this approach is UI needs to make repeated calls to system2 which makes lot of HTTP requests.

Can I get suggestions on which option is better and why?

答:
1. Use one Back-end server as a point of contact for UI. It fetches data from both services.

Pros:

One Back-end server can cache the data for multiple users

Less potential race conditions in UI

One Back-end service to validate requests and secure connection

In case data sets have some relations, system can implement GraphQL

Packed big data can be faster transferred than two separate requests

Cons:

If one service is down, users won't see any information till Back-end times out on the request and send the partial response

In general if those two sets are big, it takes longer for a UI to show something valuable to an user

Another server/service to maintain

2. Use two Back-end services and merge data sets from both in UI.

Pros:

Valuable feedback quicker visible in UI, when for instance one service is down

Two transportation layers (HTTP for the first one and WebSockets for the other one)

Cons:

Opposite statement to Pros from Option 1 :)


问:
Trying to call a PHP CLI script from a web script causes Apache to spawn multiple child processes
Having read loads of threads about calling a long-running PHP CLI script from a web script, and the best way to daemonize the CLI script, I have hit an insoluble problem with the way Apache handles the CLI script.
According to this blog post, the best option is to do something like :

```<code>print `echo /usr/bin/php -q longThing.php | at now`;
</code>```

When I do this on my local CentOS 7/PHP 7/Apache 2.4.6 VM, it works like a charm, however, the identical code on my production server Centos 6.8/PHP 7/Apache 2.4.25 (cPanel) causes Apache to spawn 100s of child processes, rapidly exhausting the CPU and memory resources, requiring a reboot to fix. Even if I quickly kill the PHP CLI process, Apache has already got itself into some kind of loop. My understanding was that by using the suggested code above, you disassociated Apache from the CLI process, but clearly not.
Can anyone point me toward what is going wrong ? I can post the actual code and more details of my production server if needed.
Thanks

答:
Test this:

php file called xyz.php

```<code><?php
shell_exec('php -r "sleep(20);" >> /dev/null 2>&1 &');
</code>```

then run under command line

```<code>php xyz.php
</code>```

And it is equal behavior if you call it from an browser.

xyz.php will finish and not wait 20 seconds.

Body:
Having read loads of threads about calling a long-running PHP CLI script from a web script, and the best way to daemonize the CLI script, I have hit an insoluble problem with the way Apache handles the CLI script.
According to this blog post, the best option is to do something like :

print `echo /usr/bin/php -q longThing.php | at now`;

When I do this on my local CentOS 7/PHP 7/Apache 2.4.6 VM, it works like a charm, however, the identical code on my production server Centos 6.8/PHP 7/Apache 2.4.25 (cPanel) causes Apache to spawn 100s of child processes, rapidly exhausting the CPU and memory resources, requiring a reboot to fix. Even if I quickly kill the PHP CLI process, Apache has already got itself into some kind of loop. My understanding was that by using the suggested code above, you disassociated Apache from the CLI process, but clearly not.
Can anyone point me toward what is going wrong ? I can post the actual code and more details of my production server if needed.
Thanks

Body:
Test this:

php file called xyz.php

<?php
shell_exec('php -r "sleep(20);" >> /dev/null 2>&1 &');

then run under command line

php xyz.php

And it is equal behavior if you call it from an browser.

xyz.php will finish and not wait 20 seconds.


问:
For Loop Filter on Pandas DataFrame not Working
I have a very simple for loop :

```<code>## Keep or Drop Rows from Ad Servers

dataframes = [atlas_df, flashtalking_df, innovid_df, ias_viewability_df, ias_fraud_df]

for df in dataframes:
    df = df[df['Placement Name'].str.contains("»")]
</code>```

when I run the for loop though, nothing filters.

However, if I write it down manually as:

```<code>ias_fraud_df = ias_fraud_df[ias_fraud_df['Placement Name'].str.contains("»")]
</code>```

The filter works.

Any ideas on what I am missing?

答:
You can use list comprehension - output is list of filtered Dataframes:

```<code>dataframes = [df[df['Placement Name'].str.contains(u"»")] for df in dataframes]
</code>```

Sample:

```<code>atlas_df = pd.DataFrame({'Placement Name':['deu_gathf»', 'deu_gahf', 'fra_gagg'],
                         'another_col':[1,2,3]})
flashtalking_df = pd.DataFrame({'Placement Name':['deu_gahf»','fra_ga', 'deu_gatt'],
                         'another_col':[4,5,6]})

dataframes = [atlas_df, flashtalking_df]
print (dataframes)
[  Placement Name  another_col
0     deu_gathf»            1
1       deu_gahf            2
2       fra_gagg            3,   Placement Name  another_col
0      deu_gahf»            4
1         fra_ga            5
2       deu_gatt            6]

dataframes = [df[df['Placement Name'].str.contains(u"»")] for df in dataframes]
print (dataframes)
[  Placement Name  another_col
0     deu_gathf»            1,   Placement Name  another_col
0      deu_gahf»            4]
</code>```

Body:
I have a very simple for loop :

## Keep or Drop Rows from Ad Servers

dataframes = [atlas_df, flashtalking_df, innovid_df, ias_viewability_df, ias_fraud_df]

for df in dataframes:
    df = df[df['Placement Name'].str.contains("»")]

when I run the for loop though, nothing filters.

However, if I write it down manually as:

ias_fraud_df = ias_fraud_df[ias_fraud_df['Placement Name'].str.contains("»")]

The filter works.

Any ideas on what I am missing?

Body:
You can use list comprehension - output is list of filtered Dataframes:

dataframes = [df[df['Placement Name'].str.contains(u"»")] for df in dataframes]

Sample:

atlas_df = pd.DataFrame({'Placement Name':['deu_gathf»', 'deu_gahf', 'fra_gagg'],
                         'another_col':[1,2,3]})
flashtalking_df = pd.DataFrame({'Placement Name':['deu_gahf»','fra_ga', 'deu_gatt'],
                         'another_col':[4,5,6]})

dataframes = [atlas_df, flashtalking_df]
print (dataframes)
[  Placement Name  another_col
0     deu_gathf»            1
1       deu_gahf            2
2       fra_gagg            3,   Placement Name  another_col
0      deu_gahf»            4
1         fra_ga            5
2       deu_gatt            6]

dataframes = [df[df['Placement Name'].str.contains(u"»")] for df in dataframes]
print (dataframes)
[  Placement Name  another_col
0     deu_gathf»            1,   Placement Name  another_col
0      deu_gahf»            4]


问:
Generate a random number in MS WORD VBA
In MS EXCEL VBA I have for many years used

```<code>lowerbound=some figure
upperbound=some other figure
m=Int((upperbound-lowerbound+1)*Rnd +lowerbound)
</code>```

I put this in a WORD macro and it did not work; it gave the same number for m every time I ran it.

答: I don't quite understand it, but if I split the expression for m into smaller expressions and combined the expressions later, then it worked.</p>

Title: Generate a random number in MS WORD VBA

Body:
In MS EXCEL VBA I have for many years used

lowerbound=some figure
upperbound=some other figure
m=Int((upperbound-lowerbound+1)*Rnd +lowerbound)

I put this in a WORD macro and it did not work; it gave the same number for m every time I ran it.


问:
BlackBerry InputStream to String conversion
How do I convert an InputStream to a String on a BlackBerry?</p>

答:
I would store the data from the inputStream in a StringBuffer. The code would look like this:</p>

```<code>byte[] buffer = new byte[1024];
StringBuffer sb = new StringBuffer();
int readIn = 0;
while((readIn = inputStream.read(buffer)) > 0)
{
     String temp = new String(buffer, 0, readIn);
     sb.append(temp);
}
String result = sb.toString();
</code>```

Body:
I would store the data from the inputStream in a StringBuffer. The code would look like this:

byte[] buffer = new byte[1024];
StringBuffer sb = new StringBuffer();
int readIn = 0;
while((readIn = inputStream.read(buffer)) > 0)
{
     String temp = new String(buffer, 0, readIn);
     sb.append(temp);
}
String result = sb.toString();


问:
SQLite don't order by date
I need a selection of all the elements of the table, sorted according to the column where there are dates

this is the table create code:

```<code>String query = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +" ( "+
            " id INTEGER PRIMARY KEY,"+
            " "+ COLUMN_LIST +" TEXT,"+
            " "+ COLUMN_PRICE + " TEXT,"+
            " "+ COLUMN_EXPIRY + " NUMERIC,"+
            " "+ COLUMN_DATE +" NUMERIC,"+
            " f_k INTEGER,"+
            " FOREIGN KEY(f_k) REFERENCES user(id)"+
            " ON DELETE CASCADE"+
            ")";
</code>```

This is the code to insert elements in the column that I need to be ordered:

```<code>try{
    VAL.put( COLUMN_EXPIRY, String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );
}catch( ParseException e ){
    e.printStackTrace();
}
</code>```

the items.get( 2 ).toString() is stringDate variable:

```<code>int day = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();

stringDate = Integer.toString( day ) +"-"+ Integer.toString( month ) +"-"+ Integer.toString( year );
</code>```

the code of select element:

```<code>final String QUERY = SELECT_ALL + t;
final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";
final Cursor RESULT = DB.rawQuery( QUERY + ORDER, null );
</code>```

the result does not satisfy me. the dates are not in order.
Also some elements of the column are null and I would put down the list using a different order taken by another column.

thank you

答:
```<code>" "+ COLUMN_EXPIRY +" NUMERIC,"
</code>```

And u store

```<code>String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );
</code>```

It is completely wrong because you are getting String.valueOf(date)

You can use instead

```<code>" "+ COLUMN_DATE +" INTEGER,"
</code>```

And get long value in milliseconds of your date which is casted to string

```<code>String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 )).getTime()) ) );
</code>```

Then it should work

UPDATE

Dont forget to change

```<code>final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";
</code>```

to

```<code>final String ORDER = " ORDER BY "+ COLUMN_EXPIRY +" DESC";
</code>```

Title: SQLite don't order by date

Body:
I need a selection of all the elements of the table, sorted according to the column where there are dates

this is the table create code:

String query = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME +" ( "+
            " id INTEGER PRIMARY KEY,"+
            " "+ COLUMN_LIST +" TEXT,"+
            " "+ COLUMN_PRICE + " TEXT,"+
            " "+ COLUMN_EXPIRY + " NUMERIC,"+
            " "+ COLUMN_DATE +" NUMERIC,"+
            " f_k INTEGER,"+
            " FOREIGN KEY(f_k) REFERENCES user(id)"+
            " ON DELETE CASCADE"+
            ")";

This is the code to insert elements in the column that I need to be ordered:

try{
    VAL.put( COLUMN_EXPIRY, String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );
}catch( ParseException e ){
    e.printStackTrace();
}

the items.get( 2 ).toString() is stringDate variable:

int day = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();

stringDate = Integer.toString( day ) +"-"+ Integer.toString( month ) +"-"+ Integer.toString( year );

the code of select element:

final String QUERY = SELECT_ALL + t;
final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";
final Cursor RESULT = DB.rawQuery( QUERY + ORDER, null );

the result does not satisfy me. the dates are not in order.
Also some elements of the column are null and I would put down the list using a different order taken by another column.

thank you

Body:
" "+ COLUMN_EXPIRY +" NUMERIC,"

And u store

String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 ).toString() ) ) );

It is completely wrong because you are getting String.valueOf(date)

You can use instead

" "+ COLUMN_DATE +" INTEGER,"

And get long value in milliseconds of your date which is casted to string

String.valueOf( new SimpleDateFormat( "dd-MM-yyyy" ).parse( items.get( 2 )).getTime()) ) );

Then it should work

UPDATE

Dont forget to change

final String ORDER = " ORDER BY DATE("+ COLUMN_EXPIRY +") DESC";

to

final String ORDER = " ORDER BY "+ COLUMN_EXPIRY +" DESC";


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
Well we can do this efficiently in two phases. In the analysis phase, we filter out positive numbers, sort them and group them by index, like:

```<code><b>from itertools import groupby</b>

subresult = dict(map(lambda x:(x[0],iter(tuple(x[1]))),
                     groupby(sorted(filter(lambda x:x[1] < 0,enumerate(results)),
                             key=lambda x:x[::-1]),lambda x:x[1])
            ))</code>```

Or we can generate it step-by-step, like:

```<code>subresult = filter(lambda x:x[1] < 0,enumerate(results)) # filter negative values
subresult = sorted(subresult,key=lambda x:x[::-1]) # sort them on value and then on index
subresult = groupby(subresult,lambda x:x[1]) # group them on the value
subresult = map(lambda x:(x[0],iter(tuple(x[1]))),subresult) # construct a sequence of tuples (value,list of indices)
subresult = dict(subresult) # make it a dictionary
</code>```

This generates a dictionary:

```<code>{-100: <itertools._grouper object at 0x7fedfb523ef0>}
</code>```

Next in construction phase, we iterate over all positive integers, and always take the next opposite one from the subresult dictionary. Like:

```<code>end_result = [[i,next(subresult[-v])[0]] for i,v in enumerate(results) if v > 0]</code>```

This generates:

```<code>>>> subresult = dict(map(lambda x:(x[0],iter(tuple(x[1]))),groupby(sorted(filter(lambda x:x[1] < 0,enumerate(results)),key=lambda x:x[::-1]),lambda x:x[1])))
>>> [[i,next(subresult[-v])[0]] for i,v in enumerate(results) if v > 0]
[[0, 2], [1, 4], [3, 5]]
</code>```

Usually because of the dictionary lookup and because we use an iterator (that thus does bookkeeping on at which index we are), this will work quite efficiently.

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

Body:
Well we can do this efficiently in two phases. In the analysis phase, we filter out positive numbers, sort them and group them by index, like:

from itertools import groupby

subresult = dict(map(lambda x:(x[0],iter(tuple(x[1]))),
                     groupby(sorted(filter(lambda x:x[1] < 0,enumerate(results)),
                             key=lambda x:x[::-1]),lambda x:x[1])
            ))

Or we can generate it step-by-step, like:

subresult = filter(lambda x:x[1] < 0,enumerate(results)) # filter negative values
subresult = sorted(subresult,key=lambda x:x[::-1]) # sort them on value and then on index
subresult = groupby(subresult,lambda x:x[1]) # group them on the value
subresult = map(lambda x:(x[0],iter(tuple(x[1]))),subresult) # construct a sequence of tuples (value,list of indices)
subresult = dict(subresult) # make it a dictionary

This generates a dictionary:

{-100: <itertools._grouper object at 0x7fedfb523ef0>}

Next in construction phase, we iterate over all positive integers, and always take the next opposite one from the subresult dictionary. Like:

end_result = [[i,next(subresult[-v])[0]] for i,v in enumerate(results) if v > 0]

This generates:

>>> subresult = dict(map(lambda x:(x[0],iter(tuple(x[1]))),groupby(sorted(filter(lambda x:x[1] < 0,enumerate(results)),key=lambda x:x[::-1]),lambda x:x[1])))
>>> [[i,next(subresult[-v])[0]] for i,v in enumerate(results) if v > 0]
[[0, 2], [1, 4], [3, 5]]

Usually because of the dictionary lookup and because we use an iterator (that thus does bookkeeping on at which index we are), this will work quite efficiently.


问:
Java: Method that returns either String or int
A part of a small program I am coding:

```<code>String maxs = "";
int maxi = 0;
</code>```

At this part I defined two variables as int and String.

```<code>public Class(String max){
   try {
           this.maxi = Integer.parseInt(max);
       }catch (Exception e){
           this.maxs = max;
       }
}
</code>```

I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.

Now I need to check what I need to return:

```<code>private TypeOfReturn getMax(){
    if(this.maxi == 0){
        // return maxs (return String)
    } else if (this.maxs.equals("")) {
        // return maxi (return int)
    } else return null;
}
</code>```

The quastion is, how do I fill the missing parts of the method getMax()?

Is it even possiable in Java?

答:
Use Object instead of TypeOfReturn
You can change the TypeoOfReturn to Object and then return the respective types.

Body:
A part of a small program I am coding:

String maxs = "";
int maxi = 0;

At this part I defined two variables as int and String.

public Class(String max){
   try {
           this.maxi = Integer.parseInt(max);
       }catch (Exception e){
           this.maxs = max;
       }
}

I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.

Now I need to check what I need to return:

private TypeOfReturn getMax(){
    if(this.maxi == 0){
        // return maxs (return String)
    } else if (this.maxs.equals("")) {
        // return maxi (return int)
    } else return null;
}

The quastion is, how do I fill the missing parts of the method getMax()?

Is it even possiable in Java?


问:
How to execute a sql file
I have .sql file which has lots of database creation, deletion, population stuff. Is it possible to have a go function which can excute a sql file. I am using postgres as my database and using lib/pq driver for all database transactions. But I am open to any library for executing this sql file in my Go project.</p>

答:
I found dotsql in search of similar demand. You can load named sql statements/prepare statements from a specific file and execute.

```<code>// Get a database handle
db, err := sql.Open("sqlite3", ":memory:")

// Loads queries from file
dot, err := dotsql.LoadFromFile("queries.sql")

// Run queries
res, err := dot.Exec(db, "create-users-table")
res, err := dot.Exec(db, "create-user", "User Name", "main@example.com")
rows, err := dot.Query(db, "find-users-by-email", "main@example.com")
row, err := dot.QueryRow(db, "find-one-user-by-email", "user@example.com")

stmt, err := dot.Prepare(db, "drop-users-table")
result, err := stmt.Exec()
</code>```

see: https://github.com/gchaincl/dotsql

ContentLicense: CC BY-SA 4.0

Title: How to execute a sql file

Body:
I found dotsql in search of similar demand. You can load named sql statements/prepare statements from a specific file and execute.

// Get a database handle
db, err := sql.Open("sqlite3", ":memory:")

// Loads queries from file
dot, err := dotsql.LoadFromFile("queries.sql")

// Run queries
res, err := dot.Exec(db, "create-users-table")
res, err := dot.Exec(db, "create-user", "User Name", "main@example.com")
rows, err := dot.Query(db, "find-users-by-email", "main@example.com")
row, err := dot.QueryRow(db, "find-one-user-by-email", "user@example.com")

stmt, err := dot.Prepare(db, "drop-users-table")
result, err := stmt.Exec()

see: https://github.com/gchaincl/dotsql


问:
Aggregate array occourances
I have a set of documents (posts) which have an array of users mentioned in each post.

```<code>{
    "title": "Some post title",
    [ ... ]
    "mentions": ["johnsmith", "johndoe", "paul"]
}
</code>```

I want to aggregate a list of unique mentions, and the number of times they've been mentioned across all posts. For example:

```<code>[{ user: "johnsmith", count: 5 }, { user: "benlewis", count: 9 }, { user: "johndoe", count: 1 }]
</code>```

With Mongo, I'd do something like:

```<code>"mentions": [{
    "$unwind": "$mentions"
}, {
    "$group": {
        "_id": "$mentions",
        "count": { "$sum": 1 }
   }
}]
</code>```

What's the equivalent in Elasticsearch?

答:
You can use a Terms aggregation for that. A small (5.x) example:

```<code>PUT test
{
  "mappings": {
    "test" : {
      "properties": {
        "title": {
          "type": "text"
        },
        "mentions": {
          "type": "keyword"
        }
      }
    }
  }
}

POST test/test/1
{
  "title": "Some post title",
  "mentions": [
    "johnsmith",
    "johndoe",
    "paul"
  ]
}

POST test/test/2
{
  "title": "Some post title 2",
  "mentions": [
    "johnsmith"
  ]
}

GET test/_search
{
  "size": 0,
  "aggs": {
    "test": {
      "terms": {
        "field": "mentions",
        "size": 10
      }
    }
  }
}
</code>```

Gives the following response:

```<code>"aggregations": {
    "test": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "johnsmith",
          "doc_count": 2
        },
        {
          "key": "johndoe",
          "doc_count": 1
        },
        {
          "key": "paul",
          "doc_count": 1
        }
      ]
    }
  }
}
</code>```

Hope this helps :)

Title: Aggregate array occourances

Body:
I have a set of documents (posts) which have an array of users mentioned in each post.

{
    "title": "Some post title",
    [ ... ]
    "mentions": ["johnsmith", "johndoe", "paul"]
}

I want to aggregate a list of unique mentions, and the number of times they've been mentioned across all posts. For example:

[{ user: "johnsmith", count: 5 }, { user: "benlewis", count: 9 }, { user: "johndoe", count: 1 }]

With Mongo, I'd do something like:

"mentions": [{
    "$unwind": "$mentions"
}, {
    "$group": {
        "_id": "$mentions",
        "count": { "$sum": 1 }
   }
}]

What's the equivalent in Elasticsearch?

Body:
You can use a Terms aggregation for that. A small (5.x) example:

PUT test
{
  "mappings": {
    "test" : {
      "properties": {
        "title": {
          "type": "text"
        },
        "mentions": {
          "type": "keyword"
        }
      }
    }
  }
}

POST test/test/1
{
  "title": "Some post title",
  "mentions": [
    "johnsmith",
    "johndoe",
    "paul"
  ]
}

POST test/test/2
{
  "title": "Some post title 2",
  "mentions": [
    "johnsmith"
  ]
}

GET test/_search
{
  "size": 0,
  "aggs": {
    "test": {
      "terms": {
        "field": "mentions",
        "size": 10
      }
    }
  }
}

Gives the following response:

"aggregations": {
    "test": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "johnsmith",
          "doc_count": 2
        },
        {
          "key": "johndoe",
          "doc_count": 1
        },
        {
          "key": "paul",
          "doc_count": 1
        }
      ]
    }
  }
}

Hope this helps :)


问:
Loop for variable value,
I have a variable generated by $_POST called $quantity,

What would be the correct way to run a loop based on the value of this variable?

答:
You can do a for loop (I'm assuming you want to run some code $quantity number of times)

```<code>for ($i = 0; $i < $quantity; $i++) {
    //
}
</code>```

Just make sure to sanitize your POST data

Title: Loop for variable value,

Body:
You can do a for loop (I'm assuming you want to run some code $quantity number of times)

for ($i = 0; $i < $quantity; $i++) {
    //
}

Just make sure to sanitize your POST data


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答:
You can't just write pointers to a stream and expect it to be magically done.  You need to implement save/load methods in your objects.  E.g:</p>

```<code>class Serializable
{
    virtual void save(std::ofstream& _out) const = 0;
    virtual void load(std::ifstream& _in) = 0;
}; // eo class Serializable

// some game object
class MyObject : public Serializable
{
    int myInt;
    std::string myString;

    virtual void save(std::ofstream& _out) const
    {
        _out << myInt << myString;
    }; // eo save

    virtual void load(std::ifstream& _in)
    {
        _in >> myInt >> myString;
    }; // eo load
}; // eo class SomeObject

class MyGame : public Serializable
{
    MyObject a;
    MyObject b;

    virtual void save(std::ofstream& _out) const
    {
        a.save(_out);
        b.save(_out);
    };  // eo save

    virtual void load(std::ifstream& _in)
    {
        a.load(_in);
        b.load(_in);
    };  // eo load
}; // eo class MyGame
</code>```

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

Body:
You can't just write pointers to a stream and expect it to be magically done.  You need to implement save/load methods in your objects.  E.g:

class Serializable
{
    virtual void save(std::ofstream& _out) const = 0;
    virtual void load(std::ifstream& _in) = 0;
}; // eo class Serializable

// some game object
class MyObject : public Serializable
{
    int myInt;
    std::string myString;

    virtual void save(std::ofstream& _out) const
    {
        _out << myInt << myString;
    }; // eo save

    virtual void load(std::ifstream& _in)
    {
        _in >> myInt >> myString;
    }; // eo load
}; // eo class SomeObject

class MyGame : public Serializable
{
    MyObject a;
    MyObject b;

    virtual void save(std::ofstream& _out) const
    {
        a.save(_out);
        b.save(_out);
    };  // eo save

    virtual void load(std::ifstream& _in)
    {
        a.load(_in);
        b.load(_in);
    };  // eo load
}; // eo class MyGame


答:
Another way to find out fast if a string is a number or not, which is the main part of your program, is to use the lambda expressions in java 8 like this:

```<code>String max = "123";
boolean isNumber = max.chars().allMatch(Character::isDigit);
System.out.println(isNumber);
</code>```

Which will give you the output

```<code>true
</code>```

Title: Java: Method that returns either String or int

Body:
Another way to find out fast if a string is a number or not, which is the main part of your program, is to use the lambda expressions in java 8 like this:

String max = "123";
boolean isNumber = max.chars().allMatch(Character::isDigit);
System.out.println(isNumber);

Which will give you the output

true


问:
Get a round dollar amounts in SQL
I am trying to find transactions with round dollar amounts (e.g 200.0000, 5.0000, 1350.0000).

SQL sever Amount column is NUMERIC(38.4) type.

How do I convert it and what function do I need to apply after?

答:
You can just check the column against it's truncation.</p>

```<code>Select *
From Table
Where Amount = Cast(Amount as Int)
</code>```

Title: Get a round dollar amounts in SQL

Body:
You can just check the column against it's truncation.

Select *
From Table
Where Amount = Cast(Amount as Int)


问:
c# chart.object from excel as .png low resolution
I have created an excel file and want to export its contents as a png or jpeg file.

Unfortunately the quality of the image is really low.

Is there a solution to this? I wish a really high resolution picture.

Thank you

My current code (from internet):

```<code>     Excel.Range xlRange = xlWorksheet5.get_Range("A1", "K30");
        xlRange.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture);
        Excel.ChartObject chartObj;
        chartObj = xlWorksheet5.ChartObjects().Add(xlRange.Left, xlRange.Top, xlRange.Width, xlRange.Height);
        chartObj.Activate();
        string path_image = path + "\\image.png";
        Excel.Chart chart = chartObj.Chart;
        chart.Paste();
        chart.Export(path_image);
</code>```

答:
Try this.  You'll need to put a [STAThread] attribute over the entry point of whatever thread you run this on.

```<code>    //This first copy/paste is to convert from chart to image
    chartObj.CopyPicture();
    xlWorksheet5.Paste();

    //This image has decent resolution
    xlWorksheet5.Shapes.Item(xlWorksheet5.Shapes.Count).Copy();

    //Save the image
    System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
    enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(System.Windows.Clipboard.GetImage()));
    using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
    {
        enc.Save(outStream);
        System.Drawing.Image pic = new System.Drawing.Bitmap(outStream);
        pic.Save("image.png");
    }
</code>```

Body:
I have created an excel file and want to export its contents as a png or jpeg file.

Unfortunately the quality of the image is really low.

Is there a solution to this? I wish a really high resolution picture.

Thank you

My current code (from internet):

     Excel.Range xlRange = xlWorksheet5.get_Range("A1", "K30");
        xlRange.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture);
        Excel.ChartObject chartObj;
        chartObj = xlWorksheet5.ChartObjects().Add(xlRange.Left, xlRange.Top, xlRange.Width, xlRange.Height);
        chartObj.Activate();
        string path_image = path + "\\image.png";
        Excel.Chart chart = chartObj.Chart;
        chart.Paste();
        chart.Export(path_image);

Body:
Try this.  You'll need to put a [STAThread] attribute over the entry point of whatever thread you run this on.

    //This first copy/paste is to convert from chart to image
    chartObj.CopyPicture();
    xlWorksheet5.Paste();

    //This image has decent resolution
    xlWorksheet5.Shapes.Item(xlWorksheet5.Shapes.Count).Copy();

    //Save the image
    System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
    enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(System.Windows.Clipboard.GetImage()));
    using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
    {
        enc.Save(outStream);
        System.Drawing.Image pic = new System.Drawing.Bitmap(outStream);
        pic.Save("image.png");
    }


问:
How to provide values for only certain views inside a cell while leaving some nil and not crash?
I have a coursework with some confusing specifications. I need to write an app to store details about the food that the user consumes. I have done all of it, I store the entries in a Core Data entities and I display them inside a table. The problem is that out of the 6 different pieces of information that the user can provide only 3 are mandatory (the name of the meal, the date and time and the food group). the other 3 (photo, meal type , and user id) he can skip. All my attributes inside core data are optional. It works just fine when I complete all the fields. As soon as I set the unnecessary 3 as nil I get a fatal error (found nil while unwrapping optional). Could someone please help with this one? Thank you. Code listing below.

```<code> @IBAction func saveUserInput(_ sender: UIButton) {
    let userMeals = UserMeals(context: managedObjectContext!)
    if (mealName.text?.isEmpty)! || (foodGroup.text?.isEmpty)! || (dateAndTimeOfMeal.text?.isEmpty)!{
        let screenAlert = UIAlertController(title: "Warning!", message: "You must enter at least the name of the meal, the date and time, and the group!", preferredStyle: .alert)
        screenAlert.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil))
        self.present(screenAlert, animated: true, completion: nil)
    } else if photoView?.image == nil || (mealType.text?.isEmpty)! || (userName.text?.isEmpty)!{
        userMeals.mealPhoto = nil
        userMeals.mealType = nil
        userMeals.userID = nil
        let screenNotification = UIAlertController(title: "Done!", message: "Your meal has been saved without a photo, meal type and user name!", preferredStyle: .alert)
        screenNotification.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil))
        self.present(screenNotification, animated: true, completion: nil)
    } else {
        userMeals.mealPhoto = NSData(data: UIImageJPEGRepresentation((photoView?.image)!, 0.5)!)
        userMeals.mealName = mealName?.text
        userMeals.foodGroup = foodGroup?.text
        userMeals.dateAndTime = dateAndTimeOfMeal?.text
        userMeals.mealType = mealType?.text
        userMeals.userID = userName?.text
        let screenNotification = UIAlertController(title: "Done!", message: "Your meal has been saved!", preferredStyle: .alert)
        screenNotification.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil))
        self.present(screenNotification, animated: true, completion: nil)
    }
}
</code>```

Code from the table view class:

```<code>private func loadData() {
    let mealRequest: NSFetchRequest<UserMeals> = UserMeals.fetchRequest() // get all information from core, of type guardian.
    do {
        storedMeals = try managedObjectContext.fetch(mealRequest)
    } catch {
        print("could not load data from core \(error.localizedDescription)") // get more details from the error.
    }
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return storedMeals.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellForMeal", for: indexPath) as! ViewMealsCell
    let mealItem = storedMeals[indexPath.row]
    if let mealImage = UIImage(data: mealItem.mealPhoto as! Data) {
        cell.mealPhoto.image = mealImage
    }
    cell.mealName.text = mealItem.mealName
    cell.foodGroup.text = mealItem.foodGroup
    cell.dateAndTime.text = mealItem.dateAndTime
    cell.mealType.text = mealItem.mealType
    cell.userName.text = mealItem.userID
    return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete { // delete the row from the data source
        tableView.deleteRows(at: [indexPath], with: .fade)
        self.tableView.reloadData()
    }
}
</code>```

The definition of user meals:

```<code>extension UserMeals {

@nonobjc public class func fetchRequest() -> NSFetchRequest<UserMeals> {
    return NSFetchRequest<UserMeals>(entityName: "UserMeals");
}

@NSManaged public var dateAndTime: String?
@NSManaged public var foodGroup: String?
@NSManaged public var mealName: String?
@NSManaged public var mealPhoto: NSData?
@NSManaged public var mealType: String?
@NSManaged public var userID: String?
</code>```

}

答:
The problem is this line:

```<code>if let mealImage = UIImage(data: mealItem.mealPhoto as! Data) {
    cell.mealPhoto.image = mealImage
}
</code>```

Any time you have an exclamation mark, you are saying "crash me, please." You cannot complain if the runtime does exactly what you asked it to do.

You want to use as? here. This will unwrap safely.

There may be additional safe unwrapping to do, but this, in general, is the approach you want to take. For example, you might write something like this:

```<code>if let data = mailItem.mealPhoto as? Data {
    cell.mealPhoto.image = UIImage(data:data)
}
</code>```

In this way we first safe-unwrap mealPhoto into a Data and then safely create the image from that Data. You need to do it in two steps like this because you cannot call UIImage(data:) with a Data? parameter; you have to unwrap to a Data first.

EDIT As rightly pointed out in the comments, we need to set the image for every row, not just those for which we have data. So expand the above to the following:

```<code>if let data = mailItem.mealPhoto as? Data {
    cell.mealPhoto.image = UIImage(data:data)
} else {
    cell.mealPhoto.image = nil
}
</code>```

In this way, we remove the image for reused table rows for which we have no image data.

Body:
I have a coursework with some confusing specifications. I need to write an app to store details about the food that the user consumes. I have done all of it, I store the entries in a Core Data entities and I display them inside a table. The problem is that out of the 6 different pieces of information that the user can provide only 3 are mandatory (the name of the meal, the date and time and the food group). the other 3 (photo, meal type , and user id) he can skip. All my attributes inside core data are optional. It works just fine when I complete all the fields. As soon as I set the unnecessary 3 as nil I get a fatal error (found nil while unwrapping optional). Could someone please help with this one? Thank you. Code listing below.

 @IBAction func saveUserInput(_ sender: UIButton) {
    let userMeals = UserMeals(context: managedObjectContext!)
    if (mealName.text?.isEmpty)! || (foodGroup.text?.isEmpty)! || (dateAndTimeOfMeal.text?.isEmpty)!{
        let screenAlert = UIAlertController(title: "Warning!", message: "You must enter at least the name of the meal, the date and time, and the group!", preferredStyle: .alert)
        screenAlert.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil))
        self.present(screenAlert, animated: true, completion: nil)
    } else if photoView?.image == nil || (mealType.text?.isEmpty)! || (userName.text?.isEmpty)!{
        userMeals.mealPhoto = nil
        userMeals.mealType = nil
        userMeals.userID = nil
        let screenNotification = UIAlertController(title: "Done!", message: "Your meal has been saved without a photo, meal type and user name!", preferredStyle: .alert)
        screenNotification.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil))
        self.present(screenNotification, animated: true, completion: nil)
    } else {
        userMeals.mealPhoto = NSData(data: UIImageJPEGRepresentation((photoView?.image)!, 0.5)!)
        userMeals.mealName = mealName?.text
        userMeals.foodGroup = foodGroup?.text
        userMeals.dateAndTime = dateAndTimeOfMeal?.text
        userMeals.mealType = mealType?.text
        userMeals.userID = userName?.text
        let screenNotification = UIAlertController(title: "Done!", message: "Your meal has been saved!", preferredStyle: .alert)
        screenNotification.addAction(UIAlertAction(title: "Got it!", style: .default, handler: nil))
        self.present(screenNotification, animated: true, completion: nil)
    }
}

Code from the table view class:

private func loadData() {
    let mealRequest: NSFetchRequest<UserMeals> = UserMeals.fetchRequest() // get all information from core, of type guardian.
    do {
        storedMeals = try managedObjectContext.fetch(mealRequest)
    } catch {
        print("could not load data from core \(error.localizedDescription)") // get more details from the error.
    }
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return storedMeals.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellForMeal", for: indexPath) as! ViewMealsCell
    let mealItem = storedMeals[indexPath.row]
    if let mealImage = UIImage(data: mealItem.mealPhoto as! Data) {
        cell.mealPhoto.image = mealImage
    }
    cell.mealName.text = mealItem.mealName
    cell.foodGroup.text = mealItem.foodGroup
    cell.dateAndTime.text = mealItem.dateAndTime
    cell.mealType.text = mealItem.mealType
    cell.userName.text = mealItem.userID
    return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete { // delete the row from the data source
        tableView.deleteRows(at: [indexPath], with: .fade)
        self.tableView.reloadData()
    }
}

The definition of user meals:

extension UserMeals {

@nonobjc public class func fetchRequest() -> NSFetchRequest<UserMeals> {
    return NSFetchRequest<UserMeals>(entityName: "UserMeals");
}

@NSManaged public var dateAndTime: String?
@NSManaged public var foodGroup: String?
@NSManaged public var mealName: String?
@NSManaged public var mealPhoto: NSData?
@NSManaged public var mealType: String?
@NSManaged public var userID: String?

}

Body:
The problem is this line:

if let mealImage = UIImage(data: mealItem.mealPhoto as! Data) {
    cell.mealPhoto.image = mealImage
}

Any time you have an exclamation mark, you are saying "crash me, please." You cannot complain if the runtime does exactly what you asked it to do.

You want to use as? here. This will unwrap safely.

There may be additional safe unwrapping to do, but this, in general, is the approach you want to take. For example, you might write something like this:

if let data = mailItem.mealPhoto as? Data {
    cell.mealPhoto.image = UIImage(data:data)
}

In this way we first safe-unwrap mealPhoto into a Data and then safely create the image from that Data. You need to do it in two steps like this because you cannot call UIImage(data:) with a Data? parameter; you have to unwrap to a Data first.

EDIT As rightly pointed out in the comments, we need to set the image for every row, not just those for which we have data. So expand the above to the following:

if let data = mailItem.mealPhoto as? Data {
    cell.mealPhoto.image = UIImage(data:data)
} else {
    cell.mealPhoto.image = nil
}

In this way, we remove the image for reused table rows for which we have no image data.


问:
Programmatically customize styles
I'm using the "new" Material Charts from google charts. It currently lacks a lot of options from the classic charts, including legend position.

Without being able to set legend position, I'm forced to hide the built-in legend and render my own in html below the canvas. I also need to manually implement interactivity, which is where my problem lies:

The material charts have styles for hover and select states, so when the user hovers or selects a given column in the legend, the graph responds to his action. I can easily control select state through the API, but it looks like there's no way to control hover state.

So, is there any way to programmatically customize styles, so that I can mimic the hover state when the user hovers my custom legend?

答:
the columns in a BarChart or ColumnChart will represented by <rect> elements

however, there will be other <rect> elements, such as the chart itself, gridlines, etc

so finding the correct <rect> elements to modify is usually the hardest part

once the elements are found, use a MutationObserver to override the style every time activity occurs

see following working snippet,

the colors of the columns are switched out for rgba, which support transparency...

google.charts.load('current', {
  callback: function () {
    window.addEventListener('resize', drawChart, false);
    drawChart();
  },
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Y1', 'Y2'],
    ['2010', 10, 14],
    ['2020', 14, 22],
    ['2030', 16, 24],
    ['2040', 22, 30],
    ['2050', 28, 36]
  ]);

  var seriesColors = ['#00ffff', '#ff00ff'];
  var rgbaMap = {
    '#00ffff': 'rgba(0,255,0,0.5)',
    '#ff00ff': 'rgba(255,0,0,0.5)'
  };

  var options = {
    colors: seriesColors,
  };

  var chartDiv = document.getElementById('chart_div');
  var chart = new google.visualization.ColumnChart(chartDiv);

  // modify svg
  var observer = new MutationObserver(function () {
    Array.prototype.forEach.call(chartDiv.getElementsByTagName('rect'), function(rect) {
      if (seriesColors.indexOf(rect.getAttribute('fill')) > -1) {
        rect.setAttribute('fill', rgbaMap[rect.getAttribute('fill')]);
      }
    });
  });
  observer.observe(chartDiv, {
    childList: true,
    subtree: true
  });

  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div></code>```

EDIT

following is an example of a typical <rect> element that represents a column

<rect x="283" y="113" width="27" height="48" stroke="none" stroke-width="0" fill="rgba(0,255,0,0.5)"></rect>

you'll notice there isn't an attribute for 'id'

you can access by index, but since there are more <rect> elements than columns, you'll need to use something like width or fill in addition

to access by index...

chartDiv.getElementsByTagName('rect')[0]

chartDiv.getElementsByTagName('rect')[1]

setting a specific color is an easy way to identify, similar to above snippet...

Title: Programmatically customize styles

Body:
the columns in a BarChart or ColumnChart will represented by <rect> elements

however, there will be other <rect> elements, such as the chart itself, gridlines, etc

so finding the correct <rect> elements to modify is usually the hardest part

once the elements are found, use a MutationObserver to override the style every time activity occurs

see following working snippet,

the colors of the columns are switched out for rgba, which support transparency...

google.charts.load('current', {
  callback: function () {
    window.addEventListener('resize', drawChart, false);
    drawChart();
  },
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Y1', 'Y2'],
    ['2010', 10, 14],
    ['2020', 14, 22],
    ['2030', 16, 24],
    ['2040', 22, 30],
    ['2050', 28, 36]
  ]);

  var seriesColors = ['#00ffff', '#ff00ff'];
  var rgbaMap = {
    '#00ffff': 'rgba(0,255,0,0.5)',
    '#ff00ff': 'rgba(255,0,0,0.5)'
  };

  var options = {
    colors: seriesColors,
  };

  var chartDiv = document.getElementById('chart_div');
  var chart = new google.visualization.ColumnChart(chartDiv);

  // modify svg
  var observer = new MutationObserver(function () {
    Array.prototype.forEach.call(chartDiv.getElementsByTagName('rect'), function(rect) {
      if (seriesColors.indexOf(rect.getAttribute('fill')) > -1) {
        rect.setAttribute('fill', rgbaMap[rect.getAttribute('fill')]);
      }
    });
  });
  observer.observe(chartDiv, {
    childList: true,
    subtree: true
  });

  chart.draw(data, options);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

EDIT

following is an example of a typical <rect> element that represents a column

<rect x="283" y="113" width="27" height="48" stroke="none" stroke-width="0" fill="rgba(0,255,0,0.5)"></rect>

you'll notice there isn't an attribute for 'id'

you can access by index, but since there are more <rect> elements than columns, you'll need to use something like width or fill in addition

to access by index...

chartDiv.getElementsByTagName('rect')[0]

chartDiv.getElementsByTagName('rect')[1]

setting a specific color is an easy way to identify, similar to above snippet...


答:
Not 100% sure what you want but if you don't want any fraction then just cast to an integer like this:</p>

```<code>SELECT CAST(COLUMN_NAME_YOU_DID_NOT_SAY AS INTEGER) AS Result
FROM TABLE_NAME_YOU_DID_NOT_SAY
</code>```

Title: Get a round dollar amounts in SQL

Body:
I am trying to find transactions with round dollar amounts (e.g 200.0000, 5.0000, 1350.0000).

SQL sever Amount column is NUMERIC(38.4) type.

How do I convert it and what function do I need to apply after?

Body:
Not 100% sure what you want but if you don't want any fraction then just cast to an integer like this:

SELECT CAST(COLUMN_NAME_YOU_DID_NOT_SAY AS INTEGER) AS Result
FROM TABLE_NAME_YOU_DID_NOT_SAY


问:
Django mysql too many connections
I use Django with mysql, and having this problem of too many connections.

I run python script from command line, but integrated with Django model to check the data from database. The script runs every 30 seconds, and I use thread to control that. My_function is the function that will check db status.

```<code>while True:
    now = time.time()
    if now < next:
        time.sleep(next - now)
        t = Thread(target=my_function,)
        t.start()# start a thread

    next += interval
</code>```

The problem is when I monitor mysql server. There are about 10 connections all the time, and all of them are sleeping. I just don't understand why. There are 2 active python threads running constantly, and all the other threads are terminated when they finish. How come the mysql connection are like 10?
Anyone can help me? Much appreciate!

Update 1:
Now put the screenshot of mysql processlist. The connections are all in sleep mode and does nothing, and the thread that creates the connection already terminates. That's really strange.

```<code>+------+------+-----------------+----------+---------+-------+-------+------------------+
| Id   | User | Host            | db       | Command | Time  | State | Info             |
+------+------+-----------------+----------+---------+-------+-------+------------------+
|  411 | root | localhost:47347 | NULL     | Sleep   |     2 |       | NULL             |
|  412 | root | localhost:47350 | NULL     | Sleep   |     3 |       | NULL             |
|  479 | root | localhost       | NULL     | Sleep   | 27164 |       | NULL             |
|  918 | root | localhost       | EZ_Green | Sleep   | 14006 |       | NULL             |
|  953 | root | localhost       | EZ_Green | Sleep   | 12956 |       | NULL             |
|  989 | root | localhost       | EZ_Green | Sleep   | 11874 |       | NULL             |
| 1025 | root | localhost       | EZ_Green | Sleep   | 10796 |       | NULL             |
| 1061 | root | localhost       | EZ_Green | Sleep   |  9716 |       | NULL             |
| 1097 | root | localhost       | EZ_Green | Sleep   |  8636 |       | NULL             |
| 1132 | root | localhost       | EZ_Green | Sleep   |  7586 |       | NULL             |
| 1168 | root | localhost       | EZ_Green | Sleep   |  6506 |       | NULL             |
| 1204 | root | localhost       | EZ_Green | Sleep   |  5426 |       | NULL             |
| 1240 | root | localhost       | EZ_Green | Sleep   |  4346 |       | NULL             |
| 1276 | root | localhost       | EZ_Green | Sleep   |  3266 |       | NULL             |
| 1312 | root | localhost       | EZ_Green | Sleep   |  2186 |       | NULL             |
| 1348 | root | localhost       | EZ_Green | Sleep   |  1106 |       | NULL             |
| 1384 | root | localhost       | EZ_Green | Sleep   |    26 |       | NULL             |
| 1385 | root | localhost       | NULL     | Query   |     0 | NULL  | show processlist |
+------+------+-----------------+----------+---------+-------+-------+------------------+
</code>```

答:
Although this is not specific to your question but rather to the title and might help someone else, In my company we got this message and couldn't figure out where it was originating.
After backtracking we found out that using django built-in Site model with debug mode caused a lot of connections to stay open.

We ended up setting a timeout on DB connections that are open more then 20 minutes.

Title: Django mysql too many connections

Body:
I use Django with mysql, and having this problem of too many connections.

I run python script from command line, but integrated with Django model to check the data from database. The script runs every 30 seconds, and I use thread to control that. My_function is the function that will check db status.

while True:
    now = time.time()
    if now < next:
        time.sleep(next - now)
        t = Thread(target=my_function,)
        t.start()# start a thread

    next += interval

The problem is when I monitor mysql server. There are about 10 connections all the time, and all of them are sleeping. I just don't understand why. There are 2 active python threads running constantly, and all the other threads are terminated when they finish. How come the mysql connection are like 10?
Anyone can help me? Much appreciate!

Update 1:
Now put the screenshot of mysql processlist. The connections are all in sleep mode and does nothing, and the thread that creates the connection already terminates. That's really strange.

+------+------+-----------------+----------+---------+-------+-------+------------------+
| Id   | User | Host            | db       | Command | Time  | State | Info             |
+------+------+-----------------+----------+---------+-------+-------+------------------+
|  411 | root | localhost:47347 | NULL     | Sleep   |     2 |       | NULL             |
|  412 | root | localhost:47350 | NULL     | Sleep   |     3 |       | NULL             |
|  479 | root | localhost       | NULL     | Sleep   | 27164 |       | NULL             |
|  918 | root | localhost       | EZ_Green | Sleep   | 14006 |       | NULL             |
|  953 | root | localhost       | EZ_Green | Sleep   | 12956 |       | NULL             |
|  989 | root | localhost       | EZ_Green | Sleep   | 11874 |       | NULL             |
| 1025 | root | localhost       | EZ_Green | Sleep   | 10796 |       | NULL             |
| 1061 | root | localhost       | EZ_Green | Sleep   |  9716 |       | NULL             |
| 1097 | root | localhost       | EZ_Green | Sleep   |  8636 |       | NULL             |
| 1132 | root | localhost       | EZ_Green | Sleep   |  7586 |       | NULL             |
| 1168 | root | localhost       | EZ_Green | Sleep   |  6506 |       | NULL             |
| 1204 | root | localhost       | EZ_Green | Sleep   |  5426 |       | NULL             |
| 1240 | root | localhost       | EZ_Green | Sleep   |  4346 |       | NULL             |
| 1276 | root | localhost       | EZ_Green | Sleep   |  3266 |       | NULL             |
| 1312 | root | localhost       | EZ_Green | Sleep   |  2186 |       | NULL             |
| 1348 | root | localhost       | EZ_Green | Sleep   |  1106 |       | NULL             |
| 1384 | root | localhost       | EZ_Green | Sleep   |    26 |       | NULL             |
| 1385 | root | localhost       | NULL     | Query   |     0 | NULL  | show processlist |
+------+------+-----------------+----------+---------+-------+-------+------------------+


问:
Jenkins pipeline from scm with base clearcase
I try to set up a Jenkins Pipeline from SCM (base clearcase / existing dynamic view). When i try to apply the changes to the Pipeline an exception is thrown.

Does anyone use base clearcase and Pipeline from SCM with dynamic views?
Perhaps i only have misconfigured the settings for base clearcase and dynamic views.

These are my Settings:

```<code>View tag: view_name
View path: view_name
config Spec: element * CHECKEDOUT
include some_file
element * -None
Get load rules from config spec: checked
Use dynamic view: checked
View root: x:\
Do not reset Config Spec: checked
Script path: \Path\to\script_in_view
</code>```

答:
We are using ClearCase at the company and are facing the same problem. I created an incident at Jenkins JIRA, but I don´t think that this will be fixed soon. See

https://issues.jenkins-ci.org/browse/JENKINS-32551

What we did to finally get the pipleline code in ClearCase:

Start a job (using "build job" functionality in the pipeline code)
which puts the code into artifactory

Use the artifactory functionality of the Pipeline plugin to get the code back again

Before we did this, I tried to set up a perl script which updates the ClearCase view, but it was not stable enough, one of ten times failed. So we use the normal Jenkins ClearCase Plugin by calling a Jenkins job.

In your case, I would recommend following:

Set up a job which updates your ClearCase view

In this job, copy the pipeline code to a file server

Then, after the job is finished, you can load the pipeline code from the file server

The only disadvantage is that you need a real machine which executes the job, but normally, this does not take a lot of time.

Body:
I try to set up a Jenkins Pipeline from SCM (base clearcase / existing dynamic view). When i try to apply the changes to the Pipeline an exception is thrown.

Does anyone use base clearcase and Pipeline from SCM with dynamic views?
Perhaps i only have misconfigured the settings for base clearcase and dynamic views.

These are my Settings:

View tag: view_name
View path: view_name
config Spec: element * CHECKEDOUT
include some_file
element * -None
Get load rules from config spec: checked
Use dynamic view: checked
View root: x:\
Do not reset Config Spec: checked
Script path: \Path\to\script_in_view


问:
Classic ASP Random Letter
I would like to know if there is a way to get a random letter (from A-Z)

Thanks for any help.

答:
Roger Baretto's answer fixed with Cem's hint ))</p>
```<code>Function RandomString(iSize)
    Const VALID_TEXT = "abcdefghijklmnopqrstuvwxyz1234567890"
    Dim Length, sNewSearchTag, I

    Length = Len(VALID_TEXT)

    Randomize()

    For I = 1 To iSize
        sNewSearchTag = sNewSearchTag & Mid(VALID_TEXT, Int(Rnd()*Length + 1), 1)
    Next

    RandomString = sNewSearchTag
End Function
</code>```

Title: Classic ASP Random Letter

Body:
Roger Baretto's answer fixed with Cem's hint ))

Function RandomString(iSize)
    Const VALID_TEXT = "abcdefghijklmnopqrstuvwxyz1234567890"
    Dim Length, sNewSearchTag, I

    Length = Len(VALID_TEXT)

    Randomize()

    For I = 1 To iSize
        sNewSearchTag = sNewSearchTag & Mid(VALID_TEXT, Int(Rnd()*Length + 1), 1)
    Next

    RandomString = sNewSearchTag
End Function


问:
MongoDB: updateOne query , set unset values if exists
I am looking to create a mongodb query to update once document such a way that it will set a few fields with values and if there are already fields available (other fields which are not is set) unset them.

I did it like this:

```<code>db.collection('collectionName").find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    }
                },
                { "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })
</code>```

Now the problem is if the field1,2 or 3 are not there in the document then the query fails to set the field 4 and 5.

Is there any flag which i am missing in the mongo query?
Please help.

EDIT: Solution

```<code>db.collection('collectionName').find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    },
                  "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })
</code>```

答:
Please read docs for updateOne.

First parameter is a filter. What you are trying to achieve should be:

```<code>db.d.updateOne(
    {"itemId": itemsDataArray[i].itemId},
    {
        "$unset":
            {
                "field1": 1,
                "field2": 1,
                "field3": 1
            },

        "$set":
        {
           "field4" : "value",
           "field5" : "value"

        }
    }
)
</code>```

Body:
I am looking to create a mongodb query to update once document such a way that it will set a few fields with values and if there are already fields available (other fields which are not is set) unset them.

I did it like this:

db.collection('collectionName").find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    }
                },
                { "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })

Now the problem is if the field1,2 or 3 are not there in the document then the query fails to set the field 4 and 5.

Is there any flag which i am missing in the mongo query?
Please help.

EDIT: Solution

db.collection('collectionName').find({"itemId": itemsDataArray[i].itemId }).updateOne(
                { "$unset" :
                    {
                        "field1": 1,
                        "field2": 1,
                        "field3": 1
                    },
                  "$set":
                    {
                       "field4" : "value",
                       "field5" : "value"

                    }
                })

Body:
Please read docs for updateOne.

First parameter is a filter. What you are trying to achieve should be:

db.d.updateOne(
    {"itemId": itemsDataArray[i].itemId},
    {
        "$unset":
            {
                "field1": 1,
                "field2": 1,
                "field3": 1
            },

        "$set":
        {
           "field4" : "value",
           "field5" : "value"

        }
    }
)


问:
How to get fields from ExecuteAsync() method
I'm familiar with creating folder in my Google Drive, but I'm looking into doing this using the asynchronous method. However, in doing so, I'm not sure how to obtain a field that I explicitly added to the fields I'd like returned.

My code below:

```<code>private Task<Google.Apis.Drive.v3.Data.File> CreateGoogleDriveFolderAsync(DriveService service, string foldername, string parent_id = null)
{
    IList<string> parent_ids = new List<string>();

    Google.Apis.Drive.v3.Data.File folder = new Google.Apis.Drive.v3.Data.File
    {
        Name = foldername
        , MimeType = "application/vnd.google-apps.folder"
        , Description = "Client Name: blah\nUser: Rudy\n"
    };

    var insert = service.Files.Create(folder);

    // The field I'd like to get somewhere.
    insert.Fields = "id";

    var task = insert.ExecuteAsync();

    task.ContinueWith(t =>
    {
        // NotOnRanToCompletion - this code will be called if the upload fails
        Console.WriteLine("Failed to create folder \"{0}\": " + t.Exception, foldername);
    }, TaskContinuationOptions.NotOnRanToCompletion);
    task.ContinueWith(t =>
    {
        // I'd like a way to access "id" from my insert execution.
        log.insertLogging(foldername, "Directory Created");
    });

    return task;
}
</code>```

答:
Using an example from the documentation, await the task and get the file back from there you should have access to its properties

```<code>private async Task<File> CreateGoogleDriveFolderAsync(DriveService driveService, string foldername) {
    var metadata = new File()
    {
        Name = foldername,
        MimeType = "application/vnd.google-apps.folder"
    };
    var request = driveService.Files.Create(metadata);
    request.Fields = "id";
    var folder = await request.ExecuteAsync();
    Console.WriteLine("Folder ID: " + folder.Id);

    return folder;
}
</code>```

Body:
I'm familiar with creating folder in my Google Drive, but I'm looking into doing this using the asynchronous method. However, in doing so, I'm not sure how to obtain a field that I explicitly added to the fields I'd like returned.

My code below:

private Task<Google.Apis.Drive.v3.Data.File> CreateGoogleDriveFolderAsync(DriveService service, string foldername, string parent_id = null)
{
    IList<string> parent_ids = new List<string>();

    Google.Apis.Drive.v3.Data.File folder = new Google.Apis.Drive.v3.Data.File
    {
        Name = foldername
        , MimeType = "application/vnd.google-apps.folder"
        , Description = "Client Name: blah\nUser: Rudy\n"
    };

    var insert = service.Files.Create(folder);

    // The field I'd like to get somewhere.
    insert.Fields = "id";

    var task = insert.ExecuteAsync();

    task.ContinueWith(t =>
    {
        // NotOnRanToCompletion - this code will be called if the upload fails
        Console.WriteLine("Failed to create folder \"{0}\": " + t.Exception, foldername);
    }, TaskContinuationOptions.NotOnRanToCompletion);
    task.ContinueWith(t =>
    {
        // I'd like a way to access "id" from my insert execution.
        log.insertLogging(foldername, "Directory Created");
    });

    return task;
}

Body:
Using an example from the documentation, await the task and get the file back from there you should have access to its properties

private async Task<File> CreateGoogleDriveFolderAsync(DriveService driveService, string foldername) {
    var metadata = new File()
    {
        Name = foldername,
        MimeType = "application/vnd.google-apps.folder"
    };
    var request = driveService.Files.Create(metadata);
    request.Fields = "id";
    var folder = await request.ExecuteAsync();
    Console.WriteLine("Folder ID: " + folder.Id);

    return folder;
}


答:
Find values with no decimals

```<code>Select *
 From  YourTable
 where Val = floor(Val)
</code>```

EDIT - Example

```<code>Declare @YourTable table (Val decimal(10,4))
Insert Into @YourTable values
(100.25),
(5.00),
(100.00)

Select *
 From  @YourTable
 where Val/100 = floor(Val/100)
</code>```

Returns

```<code>100.0000
</code>```

Title: Get a round dollar amounts in SQL

Body:
Find values with no decimals

Select *
 From  YourTable
 where Val = floor(Val)

EDIT - Example

Declare @YourTable table (Val decimal(10,4))
Insert Into @YourTable values
(100.25),
(5.00),
(100.00)

Select *
 From  @YourTable
 where Val/100 = floor(Val/100)

Returns

100.0000


问:
Is there a way to load a mtl using the path in the obj file?
Examples of using the three.js ObjLoader also use the MTLLoader which is given a separate path to the mtl file.

https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_obj_mtl.html#L91

However, obj files include the mtl file path like this:

```<code>mtllib mymaterial.mtl
</code>```

I am part of the IIIF community, and it is a requirement that resources included in a IIIF manifest have a single path that describes everything you need. Are there any examples of using an obj file to load the mesh and materials?

答:
I think the primary issue is that the objloader as it's currently written needs to have materials in hand to know what materials to apply when the obj file is loaded.

Applying an mtl file to an existing mesh is non-trivial.

The other caveat is that I can't seem to find anywhere where objloader supports more than one mtl file.

Conclusion is that objloader as is is not ready or supported for what you would like to do. But since it's open source and accepting pull reqs, you could potentially write an objloader of your own. If you google you will find there was an attempt called objmtlloader.js. But apparently it was problematic and removed.

If you're ok with one mtllib per obj, and you don't want to write code however, you could use the following pattern:

```<code>            var loader = new THREE.OBJLoader( manager );
            var objpath = 'path/to/your/object.obj';

            loader.load( objpath, function ( object ) {
                loadMats(object, objpath);
            },
            function(eve){console.log("obj progress", eve)},
            function(xhr){console.log("obj error", e)}
            );
            var loadMats = function(obj, objpath){
                imgloader = new THREE.MTLLoader(manager);
                imgloader.setPath(objpath.substring(0, objpath.lastIndexOf("/")+1));
                imgloader.load( obj.materialLibraries[0],
                    function(materials){
                        var objLoader = new THREE.OBJLoader(manager);
                        objLoader.setMaterials(materials);
                        objLoader.load(objpath, function(object) {
                                scene.add(object);
                            },
                            function(eve){console.log("obj progress", eve)},
                            function(xhr){console.log("obj error", e)}
                        );
                    },
                    function(eve){console.log("mtl progress", eve)},
                    function(xhr){console.log("mtl error", e)}
                );
            }
</code>```

This pattern loads the obj, allows it to discover the material file names, and then loads them. This pattern is problematic in that it must load the obj twice, but we can assume the second load it's cached in browser ram and should take just a few milliseconds.

This is a crap answer, and maybe someone can correct me, but since no one has answered, I am going to say this is how I would handle grabbing mtl files from the mtllib lines, and work on better support going forward.

All that said, knowing the mtl spec, it seems rather silly that an obj file would use multiple MTL files unless the MTL were shared among many obj files.

Body:
Examples of using the three.js ObjLoader also use the MTLLoader which is given a separate path to the mtl file.

https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_obj_mtl.html#L91

However, obj files include the mtl file path like this:

mtllib mymaterial.mtl

I am part of the IIIF community, and it is a requirement that resources included in a IIIF manifest have a single path that describes everything you need. Are there any examples of using an obj file to load the mesh and materials?

Body:
I think the primary issue is that the objloader as it's currently written needs to have materials in hand to know what materials to apply when the obj file is loaded.

Applying an mtl file to an existing mesh is non-trivial.

The other caveat is that I can't seem to find anywhere where objloader supports more than one mtl file.

Conclusion is that objloader as is is not ready or supported for what you would like to do. But since it's open source and accepting pull reqs, you could potentially write an objloader of your own. If you google you will find there was an attempt called objmtlloader.js. But apparently it was problematic and removed.

If you're ok with one mtllib per obj, and you don't want to write code however, you could use the following pattern:

            var loader = new THREE.OBJLoader( manager );
            var objpath = 'path/to/your/object.obj';

            loader.load( objpath, function ( object ) {
                loadMats(object, objpath);
            },
            function(eve){console.log("obj progress", eve)},
            function(xhr){console.log("obj error", e)}
            );
            var loadMats = function(obj, objpath){
                imgloader = new THREE.MTLLoader(manager);
                imgloader.setPath(objpath.substring(0, objpath.lastIndexOf("/")+1));
                imgloader.load( obj.materialLibraries[0],
                    function(materials){
                        var objLoader = new THREE.OBJLoader(manager);
                        objLoader.setMaterials(materials);
                        objLoader.load(objpath, function(object) {
                                scene.add(object);
                            },
                            function(eve){console.log("obj progress", eve)},
                            function(xhr){console.log("obj error", e)}
                        );
                    },
                    function(eve){console.log("mtl progress", eve)},
                    function(xhr){console.log("mtl error", e)}
                );
            }

This pattern loads the obj, allows it to discover the material file names, and then loads them. This pattern is problematic in that it must load the obj twice, but we can assume the second load it's cached in browser ram and should take just a few milliseconds.

This is a crap answer, and maybe someone can correct me, but since no one has answered, I am going to say this is how I would handle grabbing mtl files from the mtllib lines, and work on better support going forward.

All that said, knowing the mtl spec, it seems rather silly that an obj file would use multiple MTL files unless the MTL were shared among many obj files.


问:
How to allow optional trailing commas in macros?
Here's a synthetic example of what I want:

```<code>macro_rules! define_enum {
    ($Name:ident { $($Variant:ident),* }) => {
        pub enum $Name {
            None,
            $($Variant),*,
        }
    }
}

define_enum!(Foo { A, B });
</code>```

This code compiles, but if add a comma to it:

```<code>define_enum!(Foo { A, B, });
//                     ^
</code>```

The compilation fails. I can fix it with:

```<code>($Name:ident { $($Variant:ident,)* })
//                             ^
</code>```

but then define_enum!(Foo { A, B }); fails,

How should I write a macro to handle both cases:

```<code>define_enum!(Foo { A, B });
define_enum!(Foo { A, B, });
</code>```

答:
Make the comma optional

As DK. points out, the trailing comma can be made optional.

Rust 1.32

You can use the ? macro repeater to write this and disallow multiple trailing commas:

($Name:ident { $($Variant:ident),* $(,)? }) => {
//                                 ^^^^^
```
<h2>Previous versions</h2>
<p>This allows multiple trailing commas:</p>
<pre class="lang-rust prettyprint-override"><code>($Name:ident { $($Variant:ident),* $(,)* }) => {
//                                 ^^^^^
</code>```

Handle both cases

Or you can handle both cases by... handling both cases:

```<code>macro_rules! define_enum {
    ($Name:ident { $($Variant:ident,)* }) => {
        pub enum $Name {
            None,
            $($Variant),*,
        }
    };
    ($Name:ident { $($Variant:ident),* }) => {
        define_enum!($Name { $($Variant,)* });
    };
}

define_enum!(Foo1 { A, B });
define_enum!(Foo2 { A, B, });

fn main() {}
</code>```

We've moved the main implementation to the version that expects the trailing comma. We then added a second clause that matches the case with the missing comma and rewrites it to the version with a comma.

Body:
Here's a synthetic example of what I want:

macro_rules! define_enum {
    ($Name:ident { $($Variant:ident),* }) => {
        pub enum $Name {
            None,
            $($Variant),*,
        }
    }
}

define_enum!(Foo { A, B });

This code compiles, but if add a comma to it:

define_enum!(Foo { A, B, });
//                     ^

The compilation fails. I can fix it with:

($Name:ident { $($Variant:ident,)* })
//                             ^

but then define_enum!(Foo { A, B }); fails,

How should I write a macro to handle both cases:

define_enum!(Foo { A, B });
define_enum!(Foo { A, B, });

Body:
Make the comma optional

As DK. points out, the trailing comma can be made optional.

Rust 1.32

You can use the ? macro repeater to write this and disallow multiple trailing commas:

($Name:ident { $($Variant:ident),* $(,)? }) => {
//                                 ^^^^^

Previous versions

This allows multiple trailing commas:

($Name:ident { $($Variant:ident),* $(,)* }) => {
//                                 ^^^^^

Handle both cases

Or you can handle both cases by... handling both cases:

macro_rules! define_enum {
    ($Name:ident { $($Variant:ident,)* }) => {
        pub enum $Name {
            None,
            $($Variant),*,
        }
    };
    ($Name:ident { $($Variant:ident),* }) => {
        define_enum!($Name { $($Variant,)* });
    };
}

define_enum!(Foo1 { A, B });
define_enum!(Foo2 { A, B, });

fn main() {}

We've moved the main implementation to the version that expects the trailing comma. We then added a second clause that matches the case with the missing comma and rewrites it to the version with a comma.


问:
want to add to buttons on top of every view in iPhone
I want to add two buttons of width 133 px and 150 px each and 28 px in height on top of every view in my iPhone app. Only the view below this button bar will change, but when navigation occurs (push pop operation), I want this bar also to slide with the remaining view.
basically, i want a bar containing 2 buttons to be present in ever screen of the app. Please help me. Thanks</p>

答:
You'd be best off writing a subclass of UIViewController (for instance call it CustomUIViewController).

in the viewDidLoad method of this class you can add the view as appropriate eg:

```<code>- (void)viewDidLoad {
    UIView *bar = [[[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,28)] autorelease];
    UIButton *buttonOne = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // etc...
    [bar addSubview:buttonOne];
    UIButton *buttonTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // etc...
    [bar addSubview:buttonTwo];

    [self.view insertSubview:bar atIndex:0];
}
</code>```

That should work (as long as you remember to call [super viewDidLoad] in all your classes.

Now you just have to make sure you're subclassing CustomUIViewController instead of UIViewController in your view controllers.

Edit

To get the navigation bar option to work do this:

```<code>    UIBarButtonItem *cancel = [[[UIBarButtonItem alloc] initWithTitle:@"Cancelsdkjfnsdjfhksdjfhks" style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)] autorelease];
    [self.navigationItem setLeftBarButtonItem:cancel];
    UIBarButtonItem *send = [[[UIBarButtonItem alloc] initWithTitle:@"Senddsfsdfsdfsdfsdfsdf" style:UIBarButtonItemStylePlain target:self action:@selector(send:)] autorelease];
    [self.navigationItem setRightBarButtonItem:send];

    self.navigationItem.titleView = [[[UIView alloc] init] autorelease];
</code>```

Body:
You'd be best off writing a subclass of UIViewController (for instance call it CustomUIViewController).

in the viewDidLoad method of this class you can add the view as appropriate eg:

- (void)viewDidLoad {
    UIView *bar = [[[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,28)] autorelease];
    UIButton *buttonOne = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // etc...
    [bar addSubview:buttonOne];
    UIButton *buttonTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // etc...
    [bar addSubview:buttonTwo];

    [self.view insertSubview:bar atIndex:0];
}

That should work (as long as you remember to call [super viewDidLoad] in all your classes.

Now you just have to make sure you're subclassing CustomUIViewController instead of UIViewController in your view controllers.

Edit

To get the navigation bar option to work do this:

    UIBarButtonItem *cancel = [[[UIBarButtonItem alloc] initWithTitle:@"Cancelsdkjfnsdjfhksdjfhks" style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)] autorelease];
    [self.navigationItem setLeftBarButtonItem:cancel];
    UIBarButtonItem *send = [[[UIBarButtonItem alloc] initWithTitle:@"Senddsfsdfsdfsdfsdfsdf" style:UIBarButtonItemStylePlain target:self action:@selector(send:)] autorelease];
    [self.navigationItem setRightBarButtonItem:send];

    self.navigationItem.titleView = [[[UIView alloc] init] autorelease];


问:
Exception on creating a DotNetFactory object on UFT
I am trying to create a DotNetFactory.CreateInstance Object using UFT 12.02.

Below is the code:

```<code>Set obj = DotNetFactory.CreateInstance(namespace.Class, C:\namespace.dll)
</code>```

while running this I am getting an error:

Exception has been thrown by the target of an invocation.

Can anyone please help me on getting this resolved?

NOTE:

1. I am trying to create an object of a dll object of a application which is already installed. I do not have access to the code.

2. Microsoft .Net framework 4.5.1 is installed in my system.

答:
Correct syntax should be

DotNetFactory.CreateInstance("Namespace.ClassName","<complete path of the dll>")

If the constructor of the class requires any arguments,

DotNetFactory.CreateInstance("Namespace.ClassName","<complete path of the dll>", arg1,arg2,arg3)

Body:
I am trying to create a DotNetFactory.CreateInstance Object using UFT 12.02.

Below is the code:

Set obj = DotNetFactory.CreateInstance(namespace.Class, C:\namespace.dll)

while running this I am getting an error:

Exception has been thrown by the target of an invocation.

Can anyone please help me on getting this resolved?

NOTE:

1. I am trying to create an object of a dll object of a application which is already installed. I do not have access to the code.

2. Microsoft .Net framework 4.5.1 is installed in my system.