问:
Exporting print statements to external file
So I'm trying to teach myself , and Ive been doing online lab exercises to learn it. I wrote a program that goes into pretty good detail of arrays and structures. It uses random numbers to monitor for a spike of 100 psi, and then prints that as a 0 point, and prints the previous 10 seconds of the array and the next 10, as if I was collecting data. The next part of this exercise is to take the program's print statement, and have it write to an external file and have it print there. My thought process is to populate an array in the  printout  function  that  holds  the  values  read  from  the  file  and  then  print from the array to screen. But I'm not sure how this would look, or really how to accomplish it. If anyone could point me in the right direction or give a good explanation it would be greatly appreciated!

My code so far:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define MAX_CHANGE      100
#define ARRAY_SIZE      21

typedef struct data_slice
{
        int t;          // -> Time
        float tp;       // -> Valve pressure
    float tf;       // -> Sodium flow
    float tt;       // -> Sodium temp in Celsius
} data_slice;

// Function Declarations
void get_values(float * pressure, float * flow, float * temp);
void printIt(data_slice * data);
void initializeArray(data_slice * data);
bool spikeValueRecorded(data_slice * data, int outputIndex);

int main()
{
    srand((unsigned int)time(NULL));
    data_slice data[ARRAY_SIZE];
    int index = -1;

    while (1)
    {
        // Initialize the entire array
        initializeArray(data);

                    // If there's a spike.....
        if (spikeValueRecorded(data, index))
        {
            // Set the previous "time" in array to negatives
            int temp = index;
            for (int i = 0; i >= -10; --i)
            {
                data[temp].t = i;
                temp = temp - 1;
                if (temp < 0)
                    temp = temp + ARRAY_SIZE;
            }

                // Record for 10 more seconds
            for (int i = 0; i <= 10; ++i)
            {
                data[index].t = i;
                index = (index + 1) % ARRAY_SIZE; //         Increment the index of the circular array
                get_values(&data[index].tp, &data[index].tf,    &data[index].tt);       // "Record" the values
            }
            break;
        }
    }
    // Print the finished recording
    printIt(data);
}

// Return: void
// in - Values of the data_slice struct
//
// Description: The three values of the struct (data_slice) to be filled in
void get_values(float * pressure, float * flow, float * temp)
{
    *pressure   = (float)(rand() % (700 - 500 + 1) + 500);  //    Range: 500 - 700
    *flow       = (float)(rand() % (20 - 10 + 1) + 10);     //   Range: 10 - 20
    *temp       = (float)(rand() % (200 - 100 + 1) + 100);  //  Range: 100 - 200
}

// Return: void
// in - The array of data_slice
//
// Description: Prints the entire array being passed in
void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
     int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }

    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp,    data[indice].tf, data[indice].tt);
        indice = (indice + 1) % ARRAY_SIZE;
    }
}

// Return: void
// in - The array of data_slice
//
// Description: Initializes the entire array to random values and their   times to 0
void initializeArray(data_slice * data)
{
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        data[i].t = 0;
        get_values(&data[i].tp, &data[i].tf, &data[i].tt);
    }
}

// Return: boolean
// in - The array of data_slice
// out - Indice of the pressure spike
//
// Description: Returns true if a positive spike in pressure has been   recorded.
//      outputIndex will hold the 0-indice of the pressure spike, else -1
bool spikeValueRecorded(data_slice * data, int outputIndex)
{
    float oldValue = data[0].tp;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].tp - oldValue < MAX_CHANGE)
        {
            outputIndex = i;
            return true;
        }
    }
    outputIndex = -1;
    return false;
}
</code>```

答:
This is way you can write to file by using libc API</p>

```<code>void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
     int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }
     //write to file
    FILE *fp = fopen("output.txt", "wb"); //Binary mode since the size of array is fixed.
    fwrite(data, sizeof(char), sizeof(data), fp);
    fclose(fp);

    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp,    data[indice].tf, data[indice].tt);
        indice = (indice + 1) % ARRAY_SIZE;
    }

}
</code>```

Body:
So I'm trying to teach myself , and Ive been doing online lab exercises to learn it. I wrote a program that goes into pretty good detail of arrays and structures. It uses random numbers to monitor for a spike of 100 psi, and then prints that as a 0 point, and prints the previous 10 seconds of the array and the next 10, as if I was collecting data. The next part of this exercise is to take the program's print statement, and have it write to an external file and have it print there. My thought process is to populate an array in the  printout  function  that  holds  the  values  read  from  the  file  and  then  print from the array to screen. But I'm not sure how this would look, or really how to accomplish it. If anyone could point me in the right direction or give a good explanation it would be greatly appreciated!

My code so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define MAX_CHANGE      100
#define ARRAY_SIZE      21

typedef struct data_slice
{
        int t;          // -> Time
        float tp;       // -> Valve pressure
    float tf;       // -> Sodium flow
    float tt;       // -> Sodium temp in Celsius
} data_slice;

// Function Declarations
void get_values(float * pressure, float * flow, float * temp);
void printIt(data_slice * data);
void initializeArray(data_slice * data);
bool spikeValueRecorded(data_slice * data, int outputIndex);

int main()
{
    srand((unsigned int)time(NULL));
    data_slice data[ARRAY_SIZE];
    int index = -1;

    while (1)
    {
        // Initialize the entire array
        initializeArray(data);

                    // If there's a spike.....
        if (spikeValueRecorded(data, index))
        {
            // Set the previous "time" in array to negatives
            int temp = index;
            for (int i = 0; i >= -10; --i)
            {
                data[temp].t = i;
                temp = temp - 1;
                if (temp < 0)
                    temp = temp + ARRAY_SIZE;
            }

                // Record for 10 more seconds
            for (int i = 0; i <= 10; ++i)
            {
                data[index].t = i;
                index = (index + 1) % ARRAY_SIZE; //         Increment the index of the circular array
                get_values(&data[index].tp, &data[index].tf,    &data[index].tt);       // "Record" the values
            }
            break;
        }
    }
    // Print the finished recording
    printIt(data);
}

// Return: void
// in - Values of the data_slice struct
//
// Description: The three values of the struct (data_slice) to be filled in
void get_values(float * pressure, float * flow, float * temp)
{
    *pressure   = (float)(rand() % (700 - 500 + 1) + 500);  //    Range: 500 - 700
    *flow       = (float)(rand() % (20 - 10 + 1) + 10);     //   Range: 10 - 20
    *temp       = (float)(rand() % (200 - 100 + 1) + 100);  //  Range: 100 - 200
}

// Return: void
// in - The array of data_slice
//
// Description: Prints the entire array being passed in
void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
     int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }

    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp,    data[indice].tf, data[indice].tt);
        indice = (indice + 1) % ARRAY_SIZE;
    }
}

// Return: void
// in - The array of data_slice
//
// Description: Initializes the entire array to random values and their   times to 0
void initializeArray(data_slice * data)
{
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        data[i].t = 0;
        get_values(&data[i].tp, &data[i].tf, &data[i].tt);
    }
}

// Return: boolean
// in - The array of data_slice
// out - Indice of the pressure spike
//
// Description: Returns true if a positive spike in pressure has been   recorded.
//      outputIndex will hold the 0-indice of the pressure spike, else -1
bool spikeValueRecorded(data_slice * data, int outputIndex)
{
    float oldValue = data[0].tp;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].tp - oldValue < MAX_CHANGE)
        {
            outputIndex = i;
            return true;
        }
    }
    outputIndex = -1;
    return false;
}

Body:
This is way you can write to file by using libc API

void printIt(data_slice * data)
{
    // Find the indice holding the time value of -10
     int indice = 0;
    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        if (data[i].t == -10)
        {
            indice = i;
            break;
        }
    }
     //write to file
    FILE *fp = fopen("output.txt", "wb"); //Binary mode since the size of array is fixed.
    fwrite(data, sizeof(char), sizeof(data), fp);
    fclose(fp);

    for (int i = 0; i < ARRAY_SIZE; ++i)
    {
        printf("%i\t %f\t %f\t %f\n", data[indice].t, data[indice].tp,    data[indice].tf, data[indice].tt);
        indice = (indice + 1) % ARRAY_SIZE;
    }

}


来源: stackexchange

问:
AttributeError: 'module' object has no attribute 'xxxx'
In the current working directory:

The package foo contains the module bar.py, along with an empty __init__.py file.

For argument's sake, the module bar.py contains the following  code:

```<code>def print_message():
    print 'The function print_message() prints this message'

print 'The module \"bar\" prints \"bar\"'
</code>```

Expected behaviour upon import foo:

foo.bar to print The module "bar" prints "bar"

foo.bar.print_message() to print The function print_message() prints this message

Instead, I struggle with the import of the bar.py module:

On one hand, using from foo import bar then allows to call
bar.print_message()

On the other hand, if I import foo, then foo.bar yields the
error in the title: AttributeError: 'module' object has no attribute 'bar'(and so does foo.bar.print_message())

All the best rated questions on SO I've skimmed through so far, with regards to AttributeError, feature an answer related to something within the module, not the import itself. Also, Kernel is restarted between each attempt.

Question: Not a blocking point as such but it bugs me down not to understand that behaviour. I'm rather inexperienced, so what fondamental concept am I missing here?
Thank you,

答:
When you import foo, you just imported the package, not any of the modules, so when you called bar, it looked in the init.py file for bar, and that file doesn't have bar in it. If you don't import bar into the modules global namespace, it has no idea what bar is, which is why you got an error.

```<code>import foo
print(dir(foo)) # ['__builtins__', ...,'__spec__', 'print_message']
from foo import bar
print(dir(foo)) # ['__builtins__',..., 'bar', 'print_message']
</code>```

You could add from . import bar to the init.py file. This would make foo aware of bar when it runs the init.py file on import.
https://docs.python.org/3/tutorial/modules.html has some information about modules and packages, and there's some really good info in this post here Importing packages in Python

ContentLicense: CC BY-SA 3.0

Body:
In the current working directory:

The package foo contains the module bar.py, along with an empty __init__.py file.

For argument's sake, the module bar.py contains the following  code:

def print_message():
    print 'The function print_message() prints this message'

print 'The module \"bar\" prints \"bar\"'

Expected behaviour upon import foo:

foo.bar to print The module "bar" prints "bar"

foo.bar.print_message() to print The function print_message() prints this message

Instead, I struggle with the import of the bar.py module:

On one hand, using from foo import bar then allows to call
bar.print_message()

On the other hand, if I import foo, then foo.bar yields the
error in the title: AttributeError: 'module' object has no attribute 'bar'(and so does foo.bar.print_message())

All the best rated questions on SO I've skimmed through so far, with regards to AttributeError, feature an answer related to something within the module, not the import itself. Also, Kernel is restarted between each attempt.

Question: Not a blocking point as such but it bugs me down not to understand that behaviour. I'm rather inexperienced, so what fondamental concept am I missing here?
Thank you,

Body:
When you import foo, you just imported the package, not any of the modules, so when you called bar, it looked in the init.py file for bar, and that file doesn't have bar in it. If you don't import bar into the modules global namespace, it has no idea what bar is, which is why you got an error.

import foo
print(dir(foo)) # ['__builtins__', ...,'__spec__', 'print_message']
from foo import bar
print(dir(foo)) # ['__builtins__',..., 'bar', 'print_message']

You could add from . import bar to the init.py file. This would make foo aware of bar when it runs the init.py file on import.
https://docs.python.org/3/tutorial/modules.html has some information about modules and packages, and there's some really good info in this post here Importing packages in Python


问:
R dplyr filter requires stored filter condition
When I filter a dataframe where the condition is made up of other filters, it doesn't seem to work. However, if I store the condition as a variable (f in the example), the filtering works fine. Can someone explain why this happens, and how to make something like Example 2 work? I would prefer to not store the filter condition as a variable.

```<code>library(dplyr)

# Dummy data set
df <- data.frame(Country = factor(c("Argentina", "Brazil", "Brazil", "Brazil")),
                 Type = factor(c("A", "A", "B", "C")))

# Only returns Brazil. No problem here.
f <- df %>%
  group_by(Country) %>%
  summarise(nTypes = n_distinct(Type)) %>%
  filter(nTypes==3) %>%
  select(Country) %>%
  droplevels() %>%
  unlist()
# > f
#   Country
# Brazil
# Levels: Brazil

# Example 1 - Only returns rows of df where Country=="Brazil". No problem here.
df %>% filter(
  Country %in% (f
                )
  )
#   Country Type
# 1  Brazil    A
# 2  Brazil    B
# 3  Brazil    C

# Example 2 - Filter is equivalent to `f` but returns all rows of df, not just Brazil. No idea why!
df %>% filter(
  Country %in% (df %>%
                  group_by(Country) %>%
                  summarise(nTypes = n_distinct(Type)) %>%
                  filter(nTypes==3) %>%
                  select(Country) %>%
                  droplevels() %>%
                  unlist()
                )
  )
#     Country Type
# 1 Argentina    A
# 2    Brazil    A
# 3    Brazil    B
# 4    Brazil    C
</code>```

答:
While I'm not sure why you are getting unexpected results, based on this answer: Using filter inside filter in dplyr gives unexpected results a way to get desired result after filtering is to use inner_join

```<code>df %>%
  group_by(Country) %>%
  summarise(nTypes = n_distinct(Type)) %>%
  filter(nTypes==3) %>%
  select(Country) %>% inner_join(.,df)
</code>```

Output:

```<code>Joining, by = "Country"
# A tibble: 3 x 2
  Country   Type
   <fctr> <fctr>
1  Brazil      A
2  Brazil      B
3  Brazil      C
</code>```

Body:
When I filter a dataframe where the condition is made up of other filters, it doesn't seem to work. However, if I store the condition as a variable (f in the example), the filtering works fine. Can someone explain why this happens, and how to make something like Example 2 work? I would prefer to not store the filter condition as a variable.

library(dplyr)

# Dummy data set
df <- data.frame(Country = factor(c("Argentina", "Brazil", "Brazil", "Brazil")),
                 Type = factor(c("A", "A", "B", "C")))

# Only returns Brazil. No problem here.
f <- df %>%
  group_by(Country) %>%
  summarise(nTypes = n_distinct(Type)) %>%
  filter(nTypes==3) %>%
  select(Country) %>%
  droplevels() %>%
  unlist()
# > f
#   Country
# Brazil
# Levels: Brazil

# Example 1 - Only returns rows of df where Country=="Brazil". No problem here.
df %>% filter(
  Country %in% (f
                )
  )
#   Country Type
# 1  Brazil    A
# 2  Brazil    B
# 3  Brazil    C

# Example 2 - Filter is equivalent to `f` but returns all rows of df, not just Brazil. No idea why!
df %>% filter(
  Country %in% (df %>%
                  group_by(Country) %>%
                  summarise(nTypes = n_distinct(Type)) %>%
                  filter(nTypes==3) %>%
                  select(Country) %>%
                  droplevels() %>%
                  unlist()
                )
  )
#     Country Type
# 1 Argentina    A
# 2    Brazil    A
# 3    Brazil    B
# 4    Brazil    C

Body:
While I'm not sure why you are getting unexpected results, based on this answer: Using filter inside filter in dplyr gives unexpected results a way to get desired result after filtering is to use inner_join

df %>%
  group_by(Country) %>%
  summarise(nTypes = n_distinct(Type)) %>%
  filter(nTypes==3) %>%
  select(Country) %>% inner_join(.,df)

Output:

Joining, by = "Country"
# A tibble: 3 x 2
  Country   Type
   <fctr> <fctr>
1  Brazil      A
2  Brazil      B
3  Brazil      C


问:
Set table view cell height by identifier - Swift
I am trying to set the height of each cell in the table view depending on the identifier. I do not want to use indexPath.row, because the i am filling the cell from an array containing a flag for each type of cell and the order is random. Exactly 3 types of cells.

I used this code but it causing an error:

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}
</code>```

The error is at this line:

```<code>let cell = tableV.cellForRow(at: indexPath)
</code>```

Thank you.

答:
talking about UITableView lifecycle

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
</code>```

it's called before

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
</code>```

hence I guess your

```<code>func cellForRow(at indexPath: IndexPath) -> UITableViewCell?
</code>```

returns nil

Body:
I am trying to set the height of each cell in the table view depending on the identifier. I do not want to use indexPath.row, because the i am filling the cell from an array containing a flag for each type of cell and the order is random. Exactly 3 types of cells.

I used this code but it causing an error:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}

The error is at this line:

let cell = tableV.cellForRow(at: indexPath)

Thank you.

Body:
talking about UITableView lifecycle

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

it's called before

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

hence I guess your

func cellForRow(at indexPath: IndexPath) -> UITableViewCell?

returns nil


问:
How to extract parts of nested multi-level JSON objects / array and flatten it with JavaScript
I'm working with the following data structure:

```<code>"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}
</code>```

I'd like extract parts of it to flatten so the results is as follows:

```<code>[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]
</code>```

How can I accomplish this?

I have tried this:

```<code>for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}
</code>```

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.

答:
You could use a recursive approach by checking the items property or return the result of reduced properties. This approach works for any depth with an expected items property at the end.

function flat(object) {
    return object.items || Object.keys(object).reduce(function (r, k) {
        return r.concat(flat(object[k]));
    }, []);
}

var object = { data: { products: [[{ category: "A", items: [{ name: "Aloe", price: 10 }, { name: "Apples", price: 5 }] }, { category: "B", items: [{ name: "Bread", price: 5 }] }], [{ category: "C", items: [{ name: "Candy", price: 5 }, { name: "Crayon", price: 5 }] }, { category: "D", items: [{ name: "Dice", price: 5 }, { name: "Doll", price: 10 }] }]] } }

console.log(flat(object));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm working with the following data structure:

"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}

I'd like extract parts of it to flatten so the results is as follows:

[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]

How can I accomplish this?

I have tried this:

for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) {
        // assemble new array
      }
    }
  }
}

... but had problems looping through the children objects. I've found a couple other similar questions, but they seem to address simpler data structures, and flatten the entire object rather than parts of it.

Any pointers would be appreciated.

Body:
You could use a recursive approach by checking the items property or return the result of reduced properties. This approach works for any depth with an expected items property at the end.

function flat(object) {
    return object.items || Object.keys(object).reduce(function (r, k) {
        return r.concat(flat(object[k]));
    }, []);
}

var object = { data: { products: [[{ category: "A", items: [{ name: "Aloe", price: 10 }, { name: "Apples", price: 5 }] }, { category: "B", items: [{ name: "Bread", price: 5 }] }], [{ category: "C", items: [{ name: "Candy", price: 5 }, { name: "Crayon", price: 5 }] }, { category: "D", items: [{ name: "Dice", price: 5 }, { name: "Doll", price: 10 }] }]] } }

console.log(flat(object));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Value undefined onChange multiselect dropdown
I am using multiselect drop down, I want to get value onChange event. I have two functions main function and function b, function b I am using for onChange event.

I have created object of function b to get it's value in main function.

I want to get it's value in main function.

Now problem is function b is getting value on change but not showing it if I create object.

If I assign string to this.selected_cats = 'some string'; it shows perfectly in main function. But if I assign selected category to this.selected_cats = elem; it says undefined in console. If I say  onChange="alert(this.value)"; this shows me value fine.

```<code>function b (elem){
 this.selected_cats = elem;
};

var obj_b = new b();

function main(){
   console.log(obj_b.selected_cats);
}

<select name='category[]' id="select_cats" onchange="b(this.value);" multiple="multiple">
</code>```

This way it shows me value fine also 🠟🠟🠟
I mean without using object

```<code>  function b (elem){
  var show_value = elem;
  console.log(show_value);
  };
</code>```

答:
You need to be calling a function on your instance of b in order to changes its values.  EG:

```<code>function b (elem){
 this.selected_cats = elem;
};

var obj_b = new b();
obj_b.onChange = function (elem){
 this.selected_cats = elem;
};

function main(){
   console.log(obj_b.selected_cats);
}

<select name='category[]' id="select_cats" onchange="obj_b.onChange(this.value);" multiple="multiple">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using multiselect drop down, I want to get value onChange event. I have two functions main function and function b, function b I am using for onChange event.

I have created object of function b to get it's value in main function.

I want to get it's value in main function.

Now problem is function b is getting value on change but not showing it if I create object.

If I assign string to this.selected_cats = 'some string'; it shows perfectly in main function. But if I assign selected category to this.selected_cats = elem; it says undefined in console. If I say  onChange="alert(this.value)"; this shows me value fine.

function b (elem){
 this.selected_cats = elem;
};

var obj_b = new b();

function main(){
   console.log(obj_b.selected_cats);
}

<select name='category[]' id="select_cats" onchange="b(this.value);" multiple="multiple">

This way it shows me value fine also 🠟🠟🠟
I mean without using object

  function b (elem){
  var show_value = elem;
  console.log(show_value);
  };

Body:
You need to be calling a function on your instance of b in order to changes its values.  EG:

function b (elem){
 this.selected_cats = elem;
};

var obj_b = new b();
obj_b.onChange = function (elem){
 this.selected_cats = elem;
};

function main(){
   console.log(obj_b.selected_cats);
}

<select name='category[]' id="select_cats" onchange="obj_b.onChange(this.value);" multiple="multiple">


问:
CSS Tranistion Button Background Color
Trying to create a slide right transition on a button. If I remove the .container background color the transition works. But I want the button to start black and change to yellow while keeping the container color as default. But the output seems different. It will only transition to yellow if the button background is transparent. Any help is appreciated, been racking my brain way too long on this.

.container {
 background: #F0F0F0;
 margin: 20px 20%
}
a.animated-button:link, a.animated-button:visited {
 position: relative;
 display: block;
 margin: 30px auto 0;
 padding: 14px 15px;
 color: #fff;
 font-size: 14px;
 text-align: center;
 text-decoration: none;
 text-transform: uppercase;
 overflow: hidden;
 -webkit-transition: all 1s ease;
 -moz-transition: all 1s ease;
 -o-transition: all 1s ease;
 transition: all 1s ease;
}
a.animated-button:link:after, a.animated-button:visited:after {
 content: "";
 position: absolute;
 height: 0%;
 left: 50%;
 top: 50%;
 width: 150%;
 z-index: -1;
 -webkit-transition: all 0.75s ease 0s;
 -moz-transition: all 0.75s ease 0s;
 -o-transition: all 0.75s ease 0s;
 transition: all 0.75s ease 0s;
}
a.animated-button:link:hover, a.animated-button:visited:hover {
 color: #FFF;
}
a.animated-button:link:hover:after, a.animated-button:visited:hover:after {
 height: 450%;
}
a.animated-button:link, a.animated-button:visited {
 position: relative;
 display: block;
 margin: 30px auto 0;
 padding: 14px 15px;
 color: #fff;
 font-size: 14px;
 border-radius: 0;
 font-weight: bold;
 text-align: center;
 text-decoration: none;
 text-transform: uppercase;
 overflow: hidden;
 letter-spacing: .08em;
 text-shadow: 0 0 1px rgba(0, 0, 0, 0.2), 0 1px 0 rgba(0, 0, 0, 0.2);
 -webkit-transition: all 1s ease;
 -moz-transition: all 1s ease;
 -o-transition: all 1s ease;
 transition: all 1s ease;
}
a.animated-button.thar-three {
 color: #fff;
 cursor: pointer;
 display: block;
 position: relative;
 border: 2px solid #F7CA18;
 transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
}
a.animated-button.thar-three:hover {
 color: #000 !important;
}
a.animated-button.thar-three:hover:before {
 left: 0%;
 right: auto;
 width: 100%;
}
a.animated-button.thar-three:before {
 display: block;
 position: absolute;
 top: 0px;
 right: 0px;
 height: 100%;
 width: 0px;
 z-index: -1;
 content: '';
 color: #000 !important;
 background: #F7CA18;
 transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div class="container">
          <p>Register</p>
        </div></code>```

答:
As you've written it, your ::before pseudo-element is below the .container element, because both the .container and the anchor (a) are on the same z-index.

To place it in-between the anchor and the container, you need to make your anchor being above the container on the z-axis, i.e, set its z-index.

a.animated-button.thar-three {
  color: #fff;
  cursor: pointer;
  display: block;
  position: relative;
  border: 2px solid #F7CA18;
  transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
  /* place it at a higher z-index than its parent ... */
  z-index: 1;
}

a.animated-button.thar-three:before {
  display: block;
  position: absolute;
  top: 0px;
  right: 0px;
  height: 100%;
  width: 0px;
  /* ... to make this be in-between .container and the a */
  z-index: -1;
  content: '';
  color: #000 !important;
  background: #F7CA18;
  transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
}

.container {
  background: #F0F0F0;
  margin: 20px 20%
}

a.animated-button:link,
a.animated-button:visited {
  position: relative;
  display: block;
  margin: 30px auto 0;
  padding: 14px 15px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  overflow: hidden;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
}

a.animated-button:link:after,
a.animated-button:visited:after {
  content: "";
  position: absolute;
  height: 0%;
  left: 50%;
  top: 50%;
  width: 150%;
  z-index: -1;
  -webkit-transition: all 0.75s ease 0s;
  -moz-transition: all 0.75s ease 0s;
  -o-transition: all 0.75s ease 0s;
  transition: all 0.75s ease 0s;
}

a.animated-button:link:hover,
a.animated-button:visited:hover {
  color: #FFF;
}

a.animated-button:link:hover:after,
a.animated-button:visited:hover:after {
  height: 450%;
}

a.animated-button:link,
a.animated-button:visited {
  position: relative;
  display: block;
  margin: 30px auto 0;
  padding: 14px 15px;
  color: #fff;
  font-size: 14px;
  border-radius: 0;
  font-weight: bold;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  overflow: hidden;
  letter-spacing: .08em;
  text-shadow: 0 0 1px rgba(0, 0, 0, 0.2), 0 1px 0 rgba(0, 0, 0, 0.2);
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
}

a.animated-button.thar-three:hover {
  color: #000 !important;
}

a.animated-button.thar-three:hover:before {
  left: 0%;
  right: auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <p>Register</p>
</div></code>```

Title: CSS Tranistion Button Background Color

Body:
Trying to create a slide right transition on a button. If I remove the .container background color the transition works. But I want the button to start black and change to yellow while keeping the container color as default. But the output seems different. It will only transition to yellow if the button background is transparent. Any help is appreciated, been racking my brain way too long on this.

.container {
 background: #F0F0F0;
 margin: 20px 20%
}
a.animated-button:link, a.animated-button:visited {
 position: relative;
 display: block;
 margin: 30px auto 0;
 padding: 14px 15px;
 color: #fff;
 font-size: 14px;
 text-align: center;
 text-decoration: none;
 text-transform: uppercase;
 overflow: hidden;
 -webkit-transition: all 1s ease;
 -moz-transition: all 1s ease;
 -o-transition: all 1s ease;
 transition: all 1s ease;
}
a.animated-button:link:after, a.animated-button:visited:after {
 content: "";
 position: absolute;
 height: 0%;
 left: 50%;
 top: 50%;
 width: 150%;
 z-index: -1;
 -webkit-transition: all 0.75s ease 0s;
 -moz-transition: all 0.75s ease 0s;
 -o-transition: all 0.75s ease 0s;
 transition: all 0.75s ease 0s;
}
a.animated-button:link:hover, a.animated-button:visited:hover {
 color: #FFF;
}
a.animated-button:link:hover:after, a.animated-button:visited:hover:after {
 height: 450%;
}
a.animated-button:link, a.animated-button:visited {
 position: relative;
 display: block;
 margin: 30px auto 0;
 padding: 14px 15px;
 color: #fff;
 font-size: 14px;
 border-radius: 0;
 font-weight: bold;
 text-align: center;
 text-decoration: none;
 text-transform: uppercase;
 overflow: hidden;
 letter-spacing: .08em;
 text-shadow: 0 0 1px rgba(0, 0, 0, 0.2), 0 1px 0 rgba(0, 0, 0, 0.2);
 -webkit-transition: all 1s ease;
 -moz-transition: all 1s ease;
 -o-transition: all 1s ease;
 transition: all 1s ease;
}
a.animated-button.thar-three {
 color: #fff;
 cursor: pointer;
 display: block;
 position: relative;
 border: 2px solid #F7CA18;
 transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
}
a.animated-button.thar-three:hover {
 color: #000 !important;
}
a.animated-button.thar-three:hover:before {
 left: 0%;
 right: auto;
 width: 100%;
}
a.animated-button.thar-three:before {
 display: block;
 position: absolute;
 top: 0px;
 right: 0px;
 height: 100%;
 width: 0px;
 z-index: -1;
 content: '';
 color: #000 !important;
 background: #F7CA18;
 transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
}

Register

Body:
As you've written it, your ::before pseudo-element is below the .container element, because both the .container and the anchor (a) are on the same z-index.

To place it in-between the anchor and the container, you need to make your anchor being above the container on the z-axis, i.e, set its z-index.

a.animated-button.thar-three {
  color: #fff;
  cursor: pointer;
  display: block;
  position: relative;
  border: 2px solid #F7CA18;
  transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
  /* place it at a higher z-index than its parent ... */
  z-index: 1;
}

a.animated-button.thar-three:before {
  display: block;
  position: absolute;
  top: 0px;
  right: 0px;
  height: 100%;
  width: 0px;
  /* ... to make this be in-between .container and the a */
  z-index: -1;
  content: '';
  color: #000 !important;
  background: #F7CA18;
  transition: all 0.4s cubic-bezier(0.42, 0, 0.58, 1) 0s;
}

.container {
  background: #F0F0F0;
  margin: 20px 20%
}

a.animated-button:link,
a.animated-button:visited {
  position: relative;
  display: block;
  margin: 30px auto 0;
  padding: 14px 15px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  overflow: hidden;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
}

a.animated-button:link:after,
a.animated-button:visited:after {
  content: "";
  position: absolute;
  height: 0%;
  left: 50%;
  top: 50%;
  width: 150%;
  z-index: -1;
  -webkit-transition: all 0.75s ease 0s;
  -moz-transition: all 0.75s ease 0s;
  -o-transition: all 0.75s ease 0s;
  transition: all 0.75s ease 0s;
}

a.animated-button:link:hover,
a.animated-button:visited:hover {
  color: #FFF;
}

a.animated-button:link:hover:after,
a.animated-button:visited:hover:after {
  height: 450%;
}

a.animated-button:link,
a.animated-button:visited {
  position: relative;
  display: block;
  margin: 30px auto 0;
  padding: 14px 15px;
  color: #fff;
  font-size: 14px;
  border-radius: 0;
  font-weight: bold;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  overflow: hidden;
  letter-spacing: .08em;
  text-shadow: 0 0 1px rgba(0, 0, 0, 0.2), 0 1px 0 rgba(0, 0, 0, 0.2);
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
}

a.animated-button.thar-three:hover {
  color: #000 !important;
}

a.animated-button.thar-three:hover:before {
  left: 0%;
  right: auto;
  width: 100%;
}

<div class="container">
  <p><a href="#" class="animated-button thar-three">Register</a></p>
</div>


问:
Android Studio 2.1 does not generate signed Apk after updating
Recently, I've updated my android studio from 1.3 to 2.1. After that, when I trying to create a signed apk from "Generate Signed APK" in build menu. Android studio seems to works fine and prompting for successful generating release file, but always there is not such apk file in selected output folder. Also, open directory from successful pop up message does not work.
I try creating new keystore for signing and reinstalling android studio as suggested in some posts, but there is no change on issue..

This is build.gradle file I am using:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.vcc4.homeui"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile files('libs/gson-2.6.2.jar')
    compile 'com.android.support:design:23.4.0'
}
</code>```

答:
it seems that the apk generated will be in</p>

```<code>{project-folder}/app/release/app-release.apk
</code>```

Body:
Recently, I've updated my android studio from 1.3 to 2.1. After that, when I trying to create a signed apk from "Generate Signed APK" in build menu. Android studio seems to works fine and prompting for successful generating release file, but always there is not such apk file in selected output folder. Also, open directory from successful pop up message does not work.
I try creating new keystore for signing and reinstalling android studio as suggested in some posts, but there is no change on issue..

This is build.gradle file I am using:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.vcc4.homeui"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile files('libs/gson-2.6.2.jar')
    compile 'com.android.support:design:23.4.0'
}

Body:
it seems that the apk generated will be in

{project-folder}/app/release/app-release.apk


问:
Is the SQL Server IsShutdown property useful to determine whether a database is in a good state?
My company has a tool that monitors statuses on servers, services, databases, etc. We monitor a number of on-site servers for our customers. One particular simple check performed is to determine whether a SQL Server database is in a 'good' state by querying for the value of certain database properties. The four database properties we monitor are:

IsSuspect

IsOffline

IsEmergencyMode

IsShutdown

This is the query we use:

```<code>SELECT name AS [SuspectDB],
  DATABASEPROPERTY(name, N'IsSuspect') AS [Suspect],
  DATABASEPROPERTY(name, N'IsOffline') AS [Offline],
  ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) AS [Shutdown],
  DATABASEPROPERTY(name, N'IsEmergencyMode') AS [Emergency]
FROM sysdatabases
WHERE (DATABASEPROPERTY(name, N'IsSuspect') = 1)
   OR (DATABASEPROPERTY(name, N'IsOffline') = 1)
   OR (ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) = 1)
   OR (DATABASEPROPERTY(name, N'IsEmergencyMode') = 1)
</code>```

In testing an upgrade to SQL Server 2008, it seems that quite a few of our databases are returning a 1 (true) value for the IsShutdown property. This was never the case previously with SQL Server 2005. The MSDN documentation for the property simply states "Database encountered a problem at startup".

As far as I can tell, the databases are perfectly fine. They are up, can be queried, etc. No issues.

Does the IsShutdown property really matter for my monitoring purposes, i.e., does it indicate that the database is in a bad state? Or should I just remove it from my query?

NOTE: In talking to one of our resident DBAs, they found that on some of our new SQL Server 2008 databases, the fact that the IsAutoClose property is enabled might have something to do with the reason for these databases having an IsShutdown of true. Disabling IsAutoClose seems to "fix" the IsShutdown being true.

答:
I would say that ONLINE and MULTI_USER is the only good state you'd want your database to be in.</p>

```<code>select state_desc,user_access_desc from sys.databases
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My company has a tool that monitors statuses on servers, services, databases, etc. We monitor a number of on-site servers for our customers. One particular simple check performed is to determine whether a SQL Server database is in a 'good' state by querying for the value of certain database properties. The four database properties we monitor are:

IsSuspect

IsOffline

IsEmergencyMode

IsShutdown

This is the query we use:

SELECT name AS [SuspectDB],
  DATABASEPROPERTY(name, N'IsSuspect') AS [Suspect],
  DATABASEPROPERTY(name, N'IsOffline') AS [Offline],
  ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) AS [Shutdown],
  DATABASEPROPERTY(name, N'IsEmergencyMode') AS [Emergency]
FROM sysdatabases
WHERE (DATABASEPROPERTY(name, N'IsSuspect') = 1)
   OR (DATABASEPROPERTY(name, N'IsOffline') = 1)
   OR (ISNULL(DATABASEPROPERTY(name, N'IsShutdown'), 1) = 1)
   OR (DATABASEPROPERTY(name, N'IsEmergencyMode') = 1)

In testing an upgrade to SQL Server 2008, it seems that quite a few of our databases are returning a 1 (true) value for the IsShutdown property. This was never the case previously with SQL Server 2005. The MSDN documentation for the property simply states "Database encountered a problem at startup".

As far as I can tell, the databases are perfectly fine. They are up, can be queried, etc. No issues.

Does the IsShutdown property really matter for my monitoring purposes, i.e., does it indicate that the database is in a bad state? Or should I just remove it from my query?

NOTE: In talking to one of our resident DBAs, they found that on some of our new SQL Server 2008 databases, the fact that the IsAutoClose property is enabled might have something to do with the reason for these databases having an IsShutdown of true. Disabling IsAutoClose seems to "fix" the IsShutdown being true.

Body:
I would say that ONLINE and MULTI_USER is the only good state you'd want your database to be in.

select state_desc,user_access_desc from sys.databases


问:
Why does google visit my url every time I start chrome?
I've noticed that Google keeps visiting some of my url:s each time i boot up Google Chrome, does anyone know why this might be?

This wouldn't be much of a problem, except that it keeps hitting an login-url for a system I've built. And each time there's an unknown login-call I receive a text message... so, it's kind of annoying.

The IP range i keep receiving this visits from is  66.102.9.*.

Sure, I could block this ip-range. But first I'd like to know why I keep receiving this visits. Does anyone have any ideas?

答:
When you use Google Chrome, it sends GET requests to Google's servers for the bowser's update checks and for the Chrome apps updates.

Chrome sends requests to multiple URLs when it’s checking for and downloading updates. The order of requests is determined dynamically at runtime. Both HTTP and HTTPS protocols might be tried. The following URL list of hostnames and paths can change at any time without notice:

www.google.com/dl/*

*.gvt1.com

tools.google.com/service/update2

dl.google.com/*

google.com/dl/*

clients2.google.com

update.googleapis.com/service/update2


问:
Getting this warning " Control may reach end of non-void function "
I keep getting this error "Control may reach end of non-void function". Can anyone help me get through?  I am stuck here. Thank you. </p>

```<code>bool Vector_double::erase(int ind1, int ind2){
    if(ind1 >= count || ind2 >= count || ind1 >= ind2){
       if(ind1 == ind2){
          erase(ind1);
          return true;
       }
       return false;
    }
    else{
       double *narr = new double[count - ind2 - 1];
       for(int i = ind2 + 1; i < count; ++i){
          narr[i - ind2 - 1] = arr[i];
       }
       for(int i = ind1; i < ind1 + count - ind2 - 1;++i){
          arr[i] = narr[i - ind1];
       }
       count = count - (ind2 - ind1) - 1;
    }
}
</code>```

答: Your function promises to return something (bool). However, the code contains paths that don't return anything. In order to fix this bug, start by documenting (in plain English) what the returned value is supposed to express. Then, adjust your code.

Body:
I keep getting this error "Control may reach end of non-void function". Can anyone help me get through?  I am stuck here. Thank you.

bool Vector_double::erase(int ind1, int ind2){
    if(ind1 >= count || ind2 >= count || ind1 >= ind2){
       if(ind1 == ind2){
          erase(ind1);
          return true;
       }
       return false;
    }
    else{
       double *narr = new double[count - ind2 - 1];
       for(int i = ind2 + 1; i < count; ++i){
          narr[i - ind2 - 1] = arr[i];
       }
       for(int i = ind1; i < ind1 + count - ind2 - 1;++i){
          arr[i] = narr[i - ind1];
       }
       count = count - (ind2 - ind1) - 1;
    }
}


问:
linking a website to an image
So I am using this to display images on a site

```<code>var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');

images();
function images() {
image1 = new Image();

image1.src = 'https://lh3.googleusercontent.com/7PP1DeqGfPdu-12ULf1baVkQ7B-
lZvbjef7uPg5ZWOs5OX_4psOdKJO8RpgaXKhN9OlC=w200-h300';

image1.onload = function () {
    context.drawImage(image1, 10, 10, 220, 300);
}
</code>```

But now I've decided I want to link a site to each of those images when they are clicked.

Initially, I thought I could just use the normal href way, but that cant be done in this case. Is there another way I can set this up?

答: catch the click event and redirect to the page/site you want by window.location='https://yourwebpage.com'</p>

Title: linking a website to an image

Body:
So I am using this to display images on a site

var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');

images();
function images() {
image1 = new Image();

image1.src = 'https://lh3.googleusercontent.com/7PP1DeqGfPdu-12ULf1baVkQ7B-
lZvbjef7uPg5ZWOs5OX_4psOdKJO8RpgaXKhN9OlC=w200-h300';

image1.onload = function () {
    context.drawImage(image1, 10, 10, 220, 300);
}

But now I've decided I want to link a site to each of those images when they are clicked.

Initially, I thought I could just use the normal href way, but that cant be done in this case. Is there another way I can set this up?


问:
How to define click event on click and href event when user opens a new tab
This is very specific requirement but was wondering if this is possible.

I have a header menu, "Create Report". I had defined "click" event for this. On clicking this menu, it opens a new modal, without changing the route.. and once user feeds some data there and clicks submit, it changes the route to "/reports" and shows the data.

But problem with this approach is, when user want to open this link (header menu Create report) in new tab (right click and open in new tab), it doesn't open anything.. may be new tab could not understand this.

One solution is to replace click with href, so instead I can do, href="/report". But this way, as soon as user clicks this link, it changes the route, to "/report", which I do not want. I want to change the route when user submits the report.

I can not use ng-click/ ng-href due to some techinal limitation with my current project.

I hope my question is clear, please let me know if you know of a solution or you want any more information.

答:
While submitting the report from modal, send user submitted data via ajax and save data in session as well. Then create report from that data.
Once data is in session, you can create reports in new tab as well.</p>


问:
cannot display PDF file from assets folder as MODE_WORLD_READABLE no longer supported
The following code is working absolutely fine in devices with API 22 but in devices with API 24 it gives the following error:

```<code>java.lang.SecurityException: MODE_WORLD_READABLE no longer supported
</code>```

Here is my code:

```<code>private void CopyReadAssets(String filename) {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), filename);

    try {
        in = assetManager.open(filename);
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/pdf");

        startActivity(intent);
    } catch (Exception e)
    {
        Log.e("cra",e.toString());
        Toast.makeText(PdfFilesList.this, "cra: "+e.toString(), Toast.LENGTH_SHORT).show();
    }
}
</code>```

If I change MODE_WORLD_READABLE  to MODE_PRIVATE then it stops working in all devices.
devices with API 22 give the following error

```<code>11-16 12:00:53.133 16531-31103/? E/DisplayData: openFd: java.io.FileNotFoundException: Permission denied
11-16 12:00:53.134 16531-31103/? E/PdfLoader: Can't load file (doesn't open)  Display Data [PDF : 818 New Jeevan Nidhi.pdf] +FileOpenable, uri: file:///data/data/com.user.plansmart/files/818%20New%20Jeevan%20Nidhi.pdf
</code>```

Device with API 24 throw the following exception

```<code>11-16 12:05:00.100 2682-2682/com.user.plansmart E/cra: android.os.FileUriExposedException: file:///data/user/0/com.user.plansmart/files/827%20Jeevan%20Rakshak.pdf exposed beyond app through Intent.getData()
</code>```

Can someone help me in resolving the issue.

Thanks.

答:
Found a workaround instead of using MODE_WORLD_READABLE since looking here

int MODE_WORLD_READABLE
  This constant was deprecated in API level 17.
  Creating world-readable files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as ContentProvider, BroadcastReceiver, and Service. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore.

```<code>private void CopyReadAssets(String filename) {
    AssetManager assetManager = getAssets();
    InputStream in;
    OutputStream out;

    try {
        in = assetManager.open(filename);
        String outDir = Environment.getExternalStorageDirectory().getAbsolutePath();

        File outFile = new File(outDir, filename);
        if(outFile.createNewFile()){
            return;
        }

        out = new FileOutputStream(outFile);

        copyFile(in, out);
        in.close();
        out.flush();
        out.close();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(outFile), "application/pdf");

        startActivity(intent);
    } catch (Exception e) {
        Log.e("cra", e.toString());
        Toast.makeText(this, "cra: " + e.toString(), Toast.LENGTH_SHORT).show();
    }
}
</code>```

For devices, after M you need to ask permission separately.

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission
                        .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                102);
    }
} else {
    CopyReadAssets("yourpdf.pdf");
}
</code>```

Then in onRequestPermissionsResult implement, your code.

```<code>@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 102:
            CopyReadAssets("yourpdf.pdf");
            break;
    }
}
</code>```

Hope this helps

Body:
The following code is working absolutely fine in devices with API 22 but in devices with API 24 it gives the following error:

java.lang.SecurityException: MODE_WORLD_READABLE no longer supported

Here is my code:

private void CopyReadAssets(String filename) {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), filename);

    try {
        in = assetManager.open(filename);
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/pdf");

        startActivity(intent);
    } catch (Exception e)
    {
        Log.e("cra",e.toString());
        Toast.makeText(PdfFilesList.this, "cra: "+e.toString(), Toast.LENGTH_SHORT).show();
    }
}

If I change MODE_WORLD_READABLE  to MODE_PRIVATE then it stops working in all devices.
devices with API 22 give the following error

11-16 12:00:53.133 16531-31103/? E/DisplayData: openFd: java.io.FileNotFoundException: Permission denied
11-16 12:00:53.134 16531-31103/? E/PdfLoader: Can't load file (doesn't open)  Display Data [PDF : 818 New Jeevan Nidhi.pdf] +FileOpenable, uri: file:///data/data/com.user.plansmart/files/818%20New%20Jeevan%20Nidhi.pdf

Device with API 24 throw the following exception

11-16 12:05:00.100 2682-2682/com.user.plansmart E/cra: android.os.FileUriExposedException: file:///data/user/0/com.user.plansmart/files/827%20Jeevan%20Rakshak.pdf exposed beyond app through Intent.getData()

Can someone help me in resolving the issue.

Thanks.

Body:
Found a workaround instead of using MODE_WORLD_READABLE since looking here

int MODE_WORLD_READABLE
  This constant was deprecated in API level 17.
  Creating world-readable files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as ContentProvider, BroadcastReceiver, and Service. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore.

private void CopyReadAssets(String filename) {
    AssetManager assetManager = getAssets();
    InputStream in;
    OutputStream out;

    try {
        in = assetManager.open(filename);
        String outDir = Environment.getExternalStorageDirectory().getAbsolutePath();

        File outFile = new File(outDir, filename);
        if(outFile.createNewFile()){
            return;
        }

        out = new FileOutputStream(outFile);

        copyFile(in, out);
        in.close();
        out.flush();
        out.close();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(outFile), "application/pdf");

        startActivity(intent);
    } catch (Exception e) {
        Log.e("cra", e.toString());
        Toast.makeText(this, "cra: " + e.toString(), Toast.LENGTH_SHORT).show();
    }
}

For devices, after M you need to ask permission separately.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission
                        .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                102);
    }
} else {
    CopyReadAssets("yourpdf.pdf");
}

Then in onRequestPermissionsResult implement, your code.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 102:
            CopyReadAssets("yourpdf.pdf");
            break;
    }
}

Hope this helps


答:
Perhaps it is your Chrome's starting page and you could change it in the settings.

That's where I'd start, unless you have already checked that.

If that's not it, try the Google Chrome forums

Title: Why does google visit my url every time I start chrome?

Body:
I've noticed that Google keeps visiting some of my url:s each time i boot up Google Chrome, does anyone know why this might be?

This wouldn't be much of a problem, except that it keeps hitting an login-url for a system I've built. And each time there's an unknown login-call I receive a text message... so, it's kind of annoying.

The IP range i keep receiving this visits from is  66.102.9.*.

Sure, I could block this ip-range. But first I'd like to know why I keep receiving this visits. Does anyone have any ideas?


问:
finding if substring exists in file in python
I have 2 files. One is my "keyfile" and other is "lookupfile". I'am trying to check if line in keyfile is present in lookup.Here's my code snippet

```<code>lookupfile = open("riskeng_recon_e_mso_transact_db_msoinputapplication_t2.txt","r")

with open("1.txt","r") as my_file:
    for line in my_file:
        print "-------------checking for "+line+"-----------"
        for x in lookupfile:
            #print x
            if str(line) in str(x):
                print "Line present"+line
</code>```

My 2 files have records in this format.

```<code>Lookupfile:

1234asfd
32453sdfvs
sfgagss234

keyfile:

123
3245
124
</code>```

My issue here is that after taking first record from key file and comparing it with lookupfile, it is not moving forward with the next record in lookupfile.

答:
The way you do it now, you exhaust the lookup iterator in the first outer loop iteration. The time complexity of the nested loops is O(M*N*L) where L is the average length of the lookup lines which for two long files can be too much. You can create a sorted suffix array of your lookup strings and use binary search for each key:

```<code>from bisect import bisect_left

with open("1.txt") as myfile, open('...') as lookup:
    # sorted lookup suffix array
    l_u = sorted(l[i:] for l in lookup for i in range(1, len(l)))
    for line in myfile:
        if l_u[bisect_left(l_u, line)].startswith(line):
            print('Line "{}" exists'.format(line))
</code>```

The time complexity is now O(N*L*log(N*L) + M*log(N*L)). For large files with relatively short lines (such that L*log(N*L) and log(N*L) are much smaller than M,N) this should be significantly better than O(M*N).

Body:
I have 2 files. One is my "keyfile" and other is "lookupfile". I'am trying to check if line in keyfile is present in lookup.Here's my code snippet

lookupfile = open("riskeng_recon_e_mso_transact_db_msoinputapplication_t2.txt","r")

with open("1.txt","r") as my_file:
    for line in my_file:
        print "-------------checking for "+line+"-----------"
        for x in lookupfile:
            #print x
            if str(line) in str(x):
                print "Line present"+line

My 2 files have records in this format.

Lookupfile:

1234asfd
32453sdfvs
sfgagss234

keyfile:

123
3245
124

My issue here is that after taking first record from key file and comparing it with lookupfile, it is not moving forward with the next record in lookupfile.

Body:
The way you do it now, you exhaust the lookup iterator in the first outer loop iteration. The time complexity of the nested loops is O(M*N*L) where L is the average length of the lookup lines which for two long files can be too much. You can create a sorted suffix array of your lookup strings and use binary search for each key:

from bisect import bisect_left

with open("1.txt") as myfile, open('...') as lookup:
    # sorted lookup suffix array
    l_u = sorted(l[i:] for l in lookup for i in range(1, len(l)))
    for line in myfile:
        if l_u[bisect_left(l_u, line)].startswith(line):
            print('Line "{}" exists'.format(line))

The time complexity is now O(N*L*log(N*L) + M*log(N*L)). For large files with relatively short lines (such that L*log(N*L) and log(N*L) are much smaller than M,N) this should be significantly better than O(M*N).


问:
Convert varchar data to time format in postgresql
I currently have a range of transaction data, and I am trying to query the data for the sum of transactions within a certain time frame. One field, transaction_time is a varchar. An example of one of these times is "13:42", which corresponds to 1:42pm. I was experimenting around with to_timestamp, but I have been unable to figure it out. Would anyone have any idea as to how to alter this varchar to represent time data.

Kind regards

答:
Casting can be done two ways:

```<code>select cast('12:47' as time)
</code>```

and

```<code>select '12:47'::time
</code>```

Body:
Casting can be done two ways:

select cast('12:47' as time)

and

select '12:47'::time


问:
Custom CIColorKernel in Xamarin IOS
I'm trying to create a functionnality in Xamarin Forms that allow the application to change [1..N] colors to [1..N] of an images.

Example:

Change all blue & purple pixels to yellow & orange pixels

After some investigation, It seems that I need to create a custom CIColorKernel to achieve it.

The problem is that is very difficult to find examples and the documentation is light.

If someone have a tutorial or a basic example to start...

Thanks

EDIT :

I implemented the soutioion of @SushiHangover and I Call it in the second method of the code sample :

```<code> private IImageSourceHandler GetHandler(ImageSource source)
        {
            IImageSourceHandler returnValue = null;
            if (source is UriImageSource)
            {
                returnValue = new ImageLoaderSourceHandler();
            }
            else if (source is FileImageSource)
            {
                returnValue = new FileImageSourceHandler();
            }
            else if (source is StreamImageSource)
            {
                returnValue = new StreamImagesourceHandler();
            }
            return returnValue;
        }

        public async Task<ImageSource> ChangeImageColor(ImageSource source, string oldColor, string newColor)
        {
            var handler = GetHandler(source);
            var uiImage = (UIImage)null;

            uiImage = await handler.LoadImageAsync(source);
            UIImage uiImageOutput = null;

            using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromRgb(200, 200, 200),
                ReplaceWithColor = CIColor.RedColor,
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
            {
                uiImageOutput = UIImage.FromImage(filter.OutputImage);
            }

            return Xamarin.Forms.ImageSource.FromStream(() => uiImageOutput.AsPNG().AsStream()); ;
        }
</code>```

This two methods are in a class named BitmapHelper that is called in Xamarin Forms project with Dependecy Injection.

```<code>var bitmap = DependencyService.Get<IBitmapHelper>().ChangeImageColor(AmbiancePicture.Source, oldColor, newColor);
            AmbiancePicture.Source = bitmap.Result;
</code>```

The result contains as expected the new Image but AmbiancePicture.Source but is not updated.

Here the image I try to change :

EDIT 2 :

If I set the AmbiancePicture.Source to null before the update, The image stay empty.
The image seems to not be empty ( I see some correct properties in the stream ).

WORKING EDIT :

So after the error comes from the UIImage creation and convertion.

This is the working code :

```<code>  using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromString(oldColor),
                ReplaceWithColor = CIColor.FromString(newColor),
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
           {
            var output = context.CreateCGImage(filter.OutputImage, filter.OutputImage.Extent); // This line is slow...
            var img = UIImage.FromImage(output);
            jpegData = img.AsJPEG(1.0f);

        }
        return Xamarin.Forms.ImageSource.FromStream(() => jpegData.AsStream());
</code>```

答:
I used filter in Xamarin.iOS and this this a small sample code:

```<code>CIContext ci = CIContext.Create();
CGImage img = <YourUIImageInstanceClass>.CGImage;
CIImage inputImage = CIImage.FromCGImage(img);

CLFGaussianBlur blurFilter = new CLFGaussianBlur();

NSMutableDictionary  inputParameters = new NSMutableDictionary ();
NSNumber num = new NSNumber(<radius>);
inputParameters.SetValueForKey(num, new NSString("inputRadius"));

outputImage = inputImage.CreateByFiltering("CIGaussianBlur",     inputParameters);
</code>```

This is made for blurring a image but i think is the same procedure for other filters

Title: Custom CIColorKernel in Xamarin IOS

Body:
I'm trying to create a functionnality in Xamarin Forms that allow the application to change [1..N] colors to [1..N] of an images.

Example:

Change all blue & purple pixels to yellow & orange pixels

After some investigation, It seems that I need to create a custom CIColorKernel to achieve it.

The problem is that is very difficult to find examples and the documentation is light.

If someone have a tutorial or a basic example to start...

Thanks

EDIT :

I implemented the soutioion of @SushiHangover and I Call it in the second method of the code sample :

 private IImageSourceHandler GetHandler(ImageSource source)
        {
            IImageSourceHandler returnValue = null;
            if (source is UriImageSource)
            {
                returnValue = new ImageLoaderSourceHandler();
            }
            else if (source is FileImageSource)
            {
                returnValue = new FileImageSourceHandler();
            }
            else if (source is StreamImageSource)
            {
                returnValue = new StreamImagesourceHandler();
            }
            return returnValue;
        }

        public async Task<ImageSource> ChangeImageColor(ImageSource source, string oldColor, string newColor)
        {
            var handler = GetHandler(source);
            var uiImage = (UIImage)null;

            uiImage = await handler.LoadImageAsync(source);
            UIImage uiImageOutput = null;

            using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromRgb(200, 200, 200),
                ReplaceWithColor = CIColor.RedColor,
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
            {
                uiImageOutput = UIImage.FromImage(filter.OutputImage);
            }

            return Xamarin.Forms.ImageSource.FromStream(() => uiImageOutput.AsPNG().AsStream()); ;
        }

This two methods are in a class named BitmapHelper that is called in Xamarin Forms project with Dependecy Injection.

var bitmap = DependencyService.Get<IBitmapHelper>().ChangeImageColor(AmbiancePicture.Source, oldColor, newColor);
            AmbiancePicture.Source = bitmap.Result;

The result contains as expected the new Image but AmbiancePicture.Source but is not updated.

Here the image I try to change :

EDIT 2 :

If I set the AmbiancePicture.Source to null before the update, The image stay empty.
The image seems to not be empty ( I see some correct properties in the stream ).

WORKING EDIT :

So after the error comes from the UIImage creation and convertion.

This is the working code :

  using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromString(oldColor),
                ReplaceWithColor = CIColor.FromString(newColor),
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
           {
            var output = context.CreateCGImage(filter.OutputImage, filter.OutputImage.Extent); // This line is slow...
            var img = UIImage.FromImage(output);
            jpegData = img.AsJPEG(1.0f);

        }
        return Xamarin.Forms.ImageSource.FromStream(() => jpegData.AsStream());

Body:
I used filter in Xamarin.iOS and this this a small sample code:

CIContext ci = CIContext.Create();
CGImage img = <YourUIImageInstanceClass>.CGImage;
CIImage inputImage = CIImage.FromCGImage(img);

CLFGaussianBlur blurFilter = new CLFGaussianBlur();

NSMutableDictionary  inputParameters = new NSMutableDictionary ();
NSNumber num = new NSNumber(<radius>);
inputParameters.SetValueForKey(num, new NSString("inputRadius"));

outputImage = inputImage.CreateByFiltering("CIGaussianBlur",     inputParameters);

This is made for blurring a image but i think is the same procedure for other filters


问:
How to get all HTML elements 500px below viewport using Javascript
I am trying to get all the HTML elements(div with particular id) which are there 500px below viewport on the page. I want to have this on scroll event.

```<code>    var windowHeight = window.outerHeight;
    var gridTop = windowHeight + 500;
    var elements = document.getElementsByClassName('test');
    window.addEventListener('scroll', function () {
        for (let i = 0; i < elements.length; i++) {
            var thisTop = elements[i].offsetTop - document.body.scrollTop;
            if (thisTop >= gridTop) {
                console.log('hi');
            }
        }
    });
</code>```

I need help on finding elements 500px below viewport.

EDIT:
I want to do it with pure JavaScript and I am using above code. But every time I am getting thisTop as 0. Please let me know the approach to do this.

答:
You should not set multiple elements to have the same ID.
It will have a conflict in your js.
If you want to identify a set of DIVs, you should use CLASS instead.

Here, what I did was to find all elements classed as some-class-name iterated through the list,
Then get their width, both style.width and offsetWidth

```<code>    <div id="the_900px_div" class="some-class-name" style="width:900px;border:1px solid blue;"></div>
    <div id="the_200px_div" class="some-class-name" style="width:200px;border:1px solid blue;"></div>
    <div id="the_100px_div" class="some-class-name" style="width:100px;border:1px solid red;"></div>
    <script type="text/javascript">
    function autorun()
    {
        var elements = document.getElementsByClassName('some-class-name');
        var elementsLength = elements.length;
        console.log(elements);
        for (var i = 0; i < elementsLength; i++){
            var sw = elements[i].style.width.replace('px','');
            var ow = elements[i].offsetWidth;
            var id = elements[i].id;
            console.log(sw > 500)
            console.log(id + ' style.width is ' + sw + 'px')
            console.log(ow > 500)
            console.log(id + ' offsetWidth is ' + ow + 'px')
        }
    }
    if (document.addEventListener) document.addEventListener("DOMContentLoaded", autorun, false);
    else if (document.attachEvent) document.attachEvent("onreadystatechange", autorun);
    else window.onload = autorun;
    </script>
</code>```

Body:
I am trying to get all the HTML elements(div with particular id) which are there 500px below viewport on the page. I want to have this on scroll event.

    var windowHeight = window.outerHeight;
    var gridTop = windowHeight + 500;
    var elements = document.getElementsByClassName('test');
    window.addEventListener('scroll', function () {
        for (let i = 0; i < elements.length; i++) {
            var thisTop = elements[i].offsetTop - document.body.scrollTop;
            if (thisTop >= gridTop) {
                console.log('hi');
            }
        }
    });

I need help on finding elements 500px below viewport.

EDIT:
I want to do it with pure JavaScript and I am using above code. But every time I am getting thisTop as 0. Please let me know the approach to do this.

Body:
You should not set multiple elements to have the same ID.
It will have a conflict in your js.
If you want to identify a set of DIVs, you should use CLASS instead.

Here, what I did was to find all elements classed as some-class-name iterated through the list,
Then get their width, both style.width and offsetWidth

    <div id="the_900px_div" class="some-class-name" style="width:900px;border:1px solid blue;"></div>
    <div id="the_200px_div" class="some-class-name" style="width:200px;border:1px solid blue;"></div>
    <div id="the_100px_div" class="some-class-name" style="width:100px;border:1px solid red;"></div>
    <script type="text/javascript">
    function autorun()
    {
        var elements = document.getElementsByClassName('some-class-name');
        var elementsLength = elements.length;
        console.log(elements);
        for (var i = 0; i < elementsLength; i++){
            var sw = elements[i].style.width.replace('px','');
            var ow = elements[i].offsetWidth;
            var id = elements[i].id;
            console.log(sw > 500)
            console.log(id + ' style.width is ' + sw + 'px')
            console.log(ow > 500)
            console.log(id + ' offsetWidth is ' + ow + 'px')
        }
    }
    if (document.addEventListener) document.addEventListener("DOMContentLoaded", autorun, false);
    else if (document.attachEvent) document.attachEvent("onreadystatechange", autorun);
    else window.onload = autorun;
    </script>


问:
How can I implement search Objective-c?
I have a record like this.

FirstName - LastName -    PhoneNo -  Address  -      Designation

A         -    Mick     -   789367789 -    New york -    Professor

B       -     Jossef   -    534647458     -     USA     -        Doctor

C       -     Sha      -    342576765    -      USA     -        Doctor

D      -      Gee     -     535346457 -     USA     -        Business Man

......Like this

I am displaying one FirstName in UITableView with UISearchBar. Search is working fine it filters data according the keyword your typing in the SearchBar but suppose you are typing M it list all the items of M and after then when i click on the first item of M, it displays the Details of A rather then M on the next View.

I think you can understand my problem.

How can i resolve this how to pass multiple values in the Next view corresponding to record.?

Thanks,

This function i took from the same code of TableView(apple sample code with searchbar ).
and i modified this according to my logic.

```<code> - (void) searchTableView
{

    NSString *searchText = searchBar.text;
    NSMutableArray *searchArray = [[NSMutableArray alloc] init];

    NSInteger TotalNoOfRecords=[self.SearchtableDataSource count];
    for (int i=0;i<TotalNoOfRecords;i++)
    {   NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:i];
        NSArray *array = [dictionary objectForKey:@"Title"];
        NSString *arrayID=  [dictionary objectForKey:@"ID"];
        NSLog(@"Testing - Id-%d",arrayID);
        [searchArrayID addObject:arrayID];
        [searchArray addObject:array];
    }

    for (NSString *sTemp in searchArray)
    {

        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (titleResultsRange.length > 0)
        {
                [copyListOfItems addObject:sTemp];
        }
    }

    [searchArray release];
    searchArray = nil;
 }
</code>```

This is my didSelectRowAtIndexPath code i know this need modification but i don't know how?

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:indexPath.row];
    FirstName=  [dictionary objectForKey:@"FirstName"];
    LastName=[dictionary objectForKey:@"LastName"];
    DetailViewController *ivc = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
    ivc.FirstName = FirstName;
    ivc.LastName=LastName;
    ivc.Title=[dictionary objectForKey:@"Details of Person"];
    [self.navigationController pushViewController:ivc animated:YES];
    [ivc release];
}
</code>```

Please help me out...

Thanks

答: Change your init method in didSelectrowatIndexPath method and pass the dictionary object and set the DetailViewController attributes there, i hope that will work as it worked for me.</p>

Title: How can I implement search Objective-c?

Body:
I have a record like this.

FirstName - LastName -    PhoneNo -  Address  -      Designation

A         -    Mick     -   789367789 -    New york -    Professor

B       -     Jossef   -    534647458     -     USA     -        Doctor

C       -     Sha      -    342576765    -      USA     -        Doctor

D      -      Gee     -     535346457 -     USA     -        Business Man

......Like this

I am displaying one FirstName in UITableView with UISearchBar. Search is working fine it filters data according the keyword your typing in the SearchBar but suppose you are typing M it list all the items of M and after then when i click on the first item of M, it displays the Details of A rather then M on the next View.

I think you can understand my problem.

How can i resolve this how to pass multiple values in the Next view corresponding to record.?

Thanks,

This function i took from the same code of TableView(apple sample code with searchbar ).
and i modified this according to my logic.

 - (void) searchTableView
{

    NSString *searchText = searchBar.text;
    NSMutableArray *searchArray = [[NSMutableArray alloc] init];

    NSInteger TotalNoOfRecords=[self.SearchtableDataSource count];
    for (int i=0;i<TotalNoOfRecords;i++)
    {   NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:i];
        NSArray *array = [dictionary objectForKey:@"Title"];
        NSString *arrayID=  [dictionary objectForKey:@"ID"];
        NSLog(@"Testing - Id-%d",arrayID);
        [searchArrayID addObject:arrayID];
        [searchArray addObject:array];
    }

    for (NSString *sTemp in searchArray)
    {

        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (titleResultsRange.length > 0)
        {
                [copyListOfItems addObject:sTemp];
        }
    }

    [searchArray release];
    searchArray = nil;
 }

This is my didSelectRowAtIndexPath code i know this need modification but i don't know how?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dictionary = [self.SearchtableDataSource objectAtIndex:indexPath.row];
    FirstName=  [dictionary objectForKey:@"FirstName"];
    LastName=[dictionary objectForKey:@"LastName"];
    DetailViewController *ivc = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
    ivc.FirstName = FirstName;
    ivc.LastName=LastName;
    ivc.Title=[dictionary objectForKey:@"Details of Person"];
    [self.navigationController pushViewController:ivc animated:YES];
    [ivc release];
}

Please help me out...

Thanks


问:
Angular CLI - why does <ng serve> bundle better than <ng build>?
Performing a number of Angular CLI commands in order to build the minified basic project:

```<code>ng new project
cd project
ng build --prod
</code>```

... as a result, I get the generated dist folder with a number of bundles. The largest one is called vendor.[hash].js and it's size about 855kB.

However, if I perform ng serve --prod instead:

```<code>ng new project
cd project
ng serve --prod
</code>```

... I can see the loaded by localhost:4200 vendor's bundle weight is about 300kB using Chrome console.

Why is that happens? Is there a way to achieve the second result without ng serve but rather with ng build?

答:
It's not about which one is better.

It's all about when to use build or serve.

build is used for deployment purpose and serve is used for development purpose.

build generates compiled output to /dist directory and serve build artifacts from memory for a faster development experience.

Ref : build vs. serve

Body:
Performing a number of Angular CLI commands in order to build the minified basic project:

ng new project
cd project
ng build --prod

... as a result, I get the generated dist folder with a number of bundles. The largest one is called vendor.[hash].js and it's size about 855kB.

However, if I perform ng serve --prod instead:

ng new project
cd project
ng serve --prod

... I can see the loaded by localhost:4200 vendor's bundle weight is about 300kB using Chrome console.

Why is that happens? Is there a way to achieve the second result without ng serve but rather with ng build?


问:
How does tools/bazel.rc work with external Workspace dependencies?
If I pull in an external Bazel project as a WORKSPACE dependency, and this project has a tools/bazel.rc that adds some default build options and defines some build --config options, how does this work exactly?

Are these default options used when building these external build targets? Can I pass the --config options defined in the external bazel.rc file when building targets in my project? Are there any best-practices for configuring the build of Bazel external WORKSPACE dependencies.

Also, is a .bazelrc written to the root of the external project picked up when building.

Just looking for clarification on how this works.

答: For better or worse, Bazel's rc file finding logic is completely unaware of external repositories. So, Bazel will only look for a tools/bazel.rc in your main workspace. If you need options from somewhere Bazel isn't looking, you'll need to copy them into your main workspace's rc file or explicitly specify the desired configuration file with --bazelrc.


问:
Fix NSS version not match when update Chrome in Ubuntu
After installing Chrome in Ubuntu, I start Chrome, then encounter the error below:

[4694:4729:0909/113001.627523:FATAL:nss_util.cc(632)] NSS_VersionCheck("3.26") failed. NSS >= 3.26 is required. Please upgrade to the latest NSS, and if you still get this error, contact your distribution maintainer.
  Aborted (core dumped)

How do I fix it?

答:
If you are running 15.10 and below, the proper way is to upgrade the distro. However if you need to stick to your current version for whatever reason, here is what I have done.

I have force install the libnss3 from the upgraded version .deb file along with a dependency requirements.

Here is the dependency

```<code>sudo dpkg -i libnspr4_4.13.1-0ubuntu0.16.10.1_amd64.deb
</code>```

from http://launchpadlibrarian.net/317146464/libnspr4_4.13.1-0ubuntu0.16.10.1_amd64.deb

Then, install the libnss3

```<code>sudo dpkg -i libnss3_3.26.2-1ubuntu1_amd64.deb
</code>```

from http://launchpadlibrarian.net/295856174/libnss3_3.26.2-1ubuntu1_amd64.deb

You still need to install one more, libnss3-nssdb, which is required for the Chrome as well

```<code>sudo dpkg --force-all -i libnss3-nssdb_3.26.2-0ubuntu0.16.04.2_all.deb
</code>```

from http://launchpadlibrarian.net/296542005/libnss3-nssdb_3.26.2-0ubuntu0.16.04.2_all.deb

=====

I have taken the precaution by backing up these packages from system before installing the upgraded version in case something break and I cannot find the original .deb. In my case, I cannot find the deb for libnss3-nssdb

```<code>sudo apt-get install dpkg-repack
sudo dpkg-repack libnss3-nssdb
</code>```

Body:
If you are running 15.10 and below, the proper way is to upgrade the distro. However if you need to stick to your current version for whatever reason, here is what I have done.

I have force install the libnss3 from the upgraded version .deb file along with a dependency requirements.

Here is the dependency

sudo dpkg -i libnspr4_4.13.1-0ubuntu0.16.10.1_amd64.deb

from http://launchpadlibrarian.net/317146464/libnspr4_4.13.1-0ubuntu0.16.10.1_amd64.deb

Then, install the libnss3

sudo dpkg -i libnss3_3.26.2-1ubuntu1_amd64.deb

from http://launchpadlibrarian.net/295856174/libnss3_3.26.2-1ubuntu1_amd64.deb

You still need to install one more, libnss3-nssdb, which is required for the Chrome as well

sudo dpkg --force-all -i libnss3-nssdb_3.26.2-0ubuntu0.16.04.2_all.deb

from http://launchpadlibrarian.net/296542005/libnss3-nssdb_3.26.2-0ubuntu0.16.04.2_all.deb

=====

I have taken the precaution by backing up these packages from system before installing the upgraded version in case something break and I cannot find the original .deb. In my case, I cannot find the deb for libnss3-nssdb

sudo apt-get install dpkg-repack
sudo dpkg-repack libnss3-nssdb


问:
Textbox blank out valid value after erroneous input - WPF
So, I have a simple view containing a Textbox and a Label.

```<code><TextBox x:Name="MyIntTextBox" Text="{Binding MyInt, UpdateSourceTrigger=LostFocus, Mode=TwoWay, StringFormat={}{D2}}"/>
<Label Content="{Binding MyStr2}"/>
</code>```

And in the ViewModel, I have:

```<code>private decimal myInt;

public decimal MyInt
{
    get { return myInt; }
    set
    {
        if (value == myInt) { return; }
        myInt = value;
        OnPropertyChange();
        OnPropertyChange("MyStr2");
    }
}

public string MyStr2
{
    get
    {
        return myInt.ToString("N2", CultureInfo.CreateSpecificCulture("en-IN"));
    }

}
</code>```

Simply speaking, the TextBox Text is bound to a decimal value, and the Label is supposed display the value in the textbox with proper formatting.

Since I have LostFocus as my UpdateSourceTriggerin TextBox, I press TAB in order for the validation and binding to work.

So when I enter a decimal value, everything works properly. The Label properly displays the formatted number.

And when I enter some garbage non-decimal value, the TextBox Border turns red indicating validation error.

But, when I put some valid value after that, like this...

...and then focus out of the TextBox, bam! The TextBox goes blank.

The Label however indicates the correct value. I set up breakpoints in the ViewModel, and I can see that MyInt does have the correct value, in this case, 600, but the TextBox does not display it.

I also get the following error in my Output Window:

```<code>System.Windows.Data Error: 6 : 'StringFormat' converter failed to convert value '600' (type 'Decimal'); fallback value will be used, if available. BindingExpression:Path=MyInt; DataItem='ViewModel' (HashCode=37975124); target element is 'TextBox' (Name='MyIntTextBox'); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.Format(IFormatProvider provider, String format, Object[] args)
   at System.Windows.Data.BindingExpression.ConvertHelper(IValueConverter converter, Object value, Type targetType, Object parameter, CultureInfo culture)'
</code>```

Is there any simple workaround for this? Or is it something I am doing wrong?

答:
The solution of mm8 is good but fails with nullable decimals.
Here is a fixed ConvertBack function:</p>

```<code>public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (decimal.TryParse(value.ToString(), out var d))
         return d;

    if (Nullable.GetUnderlyingType(targetType) != null)
        return null;
    else
        return 0m;
}
</code>```

Body:
So, I have a simple view containing a Textbox and a Label.

<TextBox x:Name="MyIntTextBox" Text="{Binding MyInt, UpdateSourceTrigger=LostFocus, Mode=TwoWay, StringFormat={}{D2}}"/>

And in the ViewModel, I have:

private decimal myInt;

public decimal MyInt
{
    get { return myInt; }
    set
    {
        if (value == myInt) { return; }
        myInt = value;
        OnPropertyChange();
        OnPropertyChange("MyStr2");
    }
}

public string MyStr2
{
    get
    {
        return myInt.ToString("N2", CultureInfo.CreateSpecificCulture("en-IN"));
    }

}

Simply speaking, the TextBox Text is bound to a decimal value, and the Label is supposed display the value in the textbox with proper formatting.

Since I have LostFocus as my UpdateSourceTriggerin TextBox, I press TAB in order for the validation and binding to work.

So when I enter a decimal value, everything works properly. The Label properly displays the formatted number.

And when I enter some garbage non-decimal value, the TextBox Border turns red indicating validation error.

But, when I put some valid value after that, like this...

...and then focus out of the TextBox, bam! The TextBox goes blank.

The Label however indicates the correct value. I set up breakpoints in the ViewModel, and I can see that MyInt does have the correct value, in this case, 600, but the TextBox does not display it.

I also get the following error in my Output Window:

System.Windows.Data Error: 6 : 'StringFormat' converter failed to convert value '600' (type 'Decimal'); fallback value will be used, if available. BindingExpression:Path=MyInt; DataItem='ViewModel' (HashCode=37975124); target element is 'TextBox' (Name='MyIntTextBox'); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.Format(IFormatProvider provider, String format, Object[] args)
   at System.Windows.Data.BindingExpression.ConvertHelper(IValueConverter converter, Object value, Type targetType, Object parameter, CultureInfo culture)'

Is there any simple workaround for this? Or is it something I am doing wrong?

Body:
The solution of mm8 is good but fails with nullable decimals.
Here is a fixed ConvertBack function:

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (decimal.TryParse(value.ToString(), out var d))
         return d;

    if (Nullable.GetUnderlyingType(targetType) != null)
        return null;
    else
        return 0m;
}


问:
WebDriver Drag n Drop Selected text from Google Search
What I want is When I type "username" in Email Box and with the help of actions  i am selecting the text by double clicking it and I want to drag the "username" from email box to Firstname Box .

Can somebody Help me

答:
You can Use Actions Keyword for Drag and Drop Feature. Below is the example for it

```<code>WebElement From = driver.findElement(By.xpath("Xpath of Email Box");
WebElement To = driver.findElement(By.xpath("Xpath of FirstName Box"));
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(From)
.moveToElement(To)
.release(To)
.build();
.dragAndDrop.perform();
</code>```

Body:
You can Use Actions Keyword for Drag and Drop Feature. Below is the example for it

WebElement From = driver.findElement(By.xpath("Xpath of Email Box");
WebElement To = driver.findElement(By.xpath("Xpath of FirstName Box"));
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(From)
.moveToElement(To)
.release(To)
.build();
.dragAndDrop.perform();


问:
Why is there no padding in the structure for only "char" type members?
I have declared only char type members in the structure.

```<code>#include <stdio.h>

struct st
{
    char c1;
    char c2;
    char c3;
    char c4;
    char c5;
};

int main() {
    struct st s;
    printf("%zu\n", sizeof(s));
    return 0;
}
</code>```

Output: [Live Demo]

```<code>5
</code>```

So, why is there no padding in the structure for only char type members?

答:
Padding is to enforce alignment requeriments. A member is said to be aligned (to its size) if it is located at an address that is divisible by its size.

There is no need for padding in your example, since all members of the st structure are already aligned to their size, i.e.: the address of each member of st is already divisible by its size. All members are of type char and the size of a char is 1. If a member's size is 1, that member is always aligned to its size, since any address is divisible by 1.

Body:
I have declared only char type members in the structure.

#include <stdio.h>

struct st
{
    char c1;
    char c2;
    char c3;
    char c4;
    char c5;
};

int main() {
    struct st s;
    printf("%zu\n", sizeof(s));
    return 0;
}

Output: [Live Demo]

5

So, why is there no padding in the structure for only char type members?