问:
"multiple definition of..." error for a full specialisation of a template function

 I have a project with configuration:

```<code>./main.cpp
./type_traints/TypeTraints.cpp
./type_traints/TypeTraints.hpp
./type_traints/chapter_20.hpp
</code>```

The ./type_traints/CMakeLists.txt file is:

```<code> cmake_minimum_required (VERSION 2.8)
 add_library(chapter_20 TypeTraints.cpp)
</code>```

and the ./CMakeLists.txt follows:

```<code>cmake_minimum_required (VERSION 2.8)
project (mpl)

add_subdirectory(type_traints)
include_directories(type_traints)
link_directories(type_traints)

add_executable (mpl main.cpp)
target_link_libraries(mpl chapter_20)
</code>```

Relevant parts of files (most includes omitted) include:

./type_traints/chapter_20.hpp

```<code>#ifndef CHAPTER_20_GUARD
#define CHAPTER_20_GUARD
#include <TypeTraints.hpp>

void chapter_20() {
  test_23();
}
#endif //CHAPTER_20_GUARD
</code>```

./type_traints/TypeTraints.hpp

```<code>#ifndef TYPE_TRAINTS_GUARD
#define TYPE_TRAINTS_GUARD
namespace details {

  template<class T> const char* class2name() {
    return "unknown";
  };

  template<> const char* class2name<int>() {
    return "int";
  };
}

template<class T>
class type_descriptor {
  friend std::ostream& operator << (std::ostream& stream,
                                    const type_descriptor<T>& desc) {
    stream << desc.getName();
    return stream;
  }

public:
  std::string getName() const;
};

template<class T>
std::string type_descriptor<T>::getName() const {
  return details::class2name<T>();
}

void test_23();
#endif // TYPE_TRAINTS_GUARD
</code>```

./type_traints/TypeTraints.cpp

```<code>#include<TypeTraints.hpp>

void test_23() {
  cout << type_descriptor<int>() << endl;
}
</code>```

and ./main.cpp

```<code>#include <chapter_20.hpp>

int main(int argc, char* argv[]) {
chapter_20();
  return 0;
}
</code>```

The project compiles but fails to link:

```<code>[ 50%] Building CXX object type_traints/CMakeFiles/chapter_20.dir/TypeTraints.cpp.o
Linking CXX static library libchapter_20.a
[ 50%] Built target chapter_20
[100%] Building CXX object CMakeFiles/mpl.dir/main.cpp.o
Linking CXX executable mpl
type_traints/libchapter_20.a(TypeTraints.cpp.o): In function `char const* details::cl
ass2name<int>()':
/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:312: multiple definition of `c
har const* details::class2name<int>()'
CMakeFiles/mpl.dir/main.cpp.o:/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:
312: first defined here
collect2: ld returned 1 exit status
make[2]: *** [mpl] Błąd 1
make[1]: *** [CMakeFiles/mpl.dir/all] Error 2
make: *** [all] Error 2
23:56:20@marcin-laptop ~/P
</code>```

The project links fine if I remove the class2name specialization (class2name<int>()) from TypeTraints.hpp and use only the generic implementation.

Does anybody have an idea Why is that? Did I miss-configure cmake files?

答:
In short: an explicitly (i.e. fully) specialized template function is no longer a template. It is an ordinary function and it obeys One Definition Rule for ordinary functions.

In other words you can't define explicitly specialized function templates in header file. Doing so will result in ODR violations.

A template is a template only as long as it depends on at least one parameter. I.e. partial specializations can be defined in header files (since they are still templates). Explicit (i.e. full) specializations can only be declared in header files, but have to be defined in implementation files, just like ordinary functions.

Body:
 I have a project with configuration:

./main.cpp
./type_traints/TypeTraints.cpp
./type_traints/TypeTraints.hpp
./type_traints/chapter_20.hpp

The ./type_traints/CMakeLists.txt file is:

 cmake_minimum_required (VERSION 2.8)
 add_library(chapter_20 TypeTraints.cpp)

and the ./CMakeLists.txt follows:

cmake_minimum_required (VERSION 2.8)
project (mpl)

add_subdirectory(type_traints)
include_directories(type_traints)
link_directories(type_traints)

add_executable (mpl main.cpp)
target_link_libraries(mpl chapter_20)

Relevant parts of files (most includes omitted) include:

./type_traints/chapter_20.hpp

#ifndef CHAPTER_20_GUARD
#define CHAPTER_20_GUARD
#include <TypeTraints.hpp>

void chapter_20() {
  test_23();
}
#endif //CHAPTER_20_GUARD

./type_traints/TypeTraints.hpp

#ifndef TYPE_TRAINTS_GUARD
#define TYPE_TRAINTS_GUARD
namespace details {

  template<class T> const char* class2name() {
    return "unknown";
  };

  template<> const char* class2name<int>() {
    return "int";
  };
}

template<class T>
class type_descriptor {
  friend std::ostream& operator << (std::ostream& stream,
                                    const type_descriptor<T>& desc) {
    stream << desc.getName();
    return stream;
  }

public:
  std::string getName() const;
};

template<class T>
std::string type_descriptor<T>::getName() const {
  return details::class2name<T>();
}

void test_23();
#endif // TYPE_TRAINTS_GUARD

./type_traints/TypeTraints.cpp

#include<TypeTraints.hpp>

void test_23() {
  cout << type_descriptor<int>() << endl;
}

and ./main.cpp

#include <chapter_20.hpp>

int main(int argc, char* argv[]) {
chapter_20();
  return 0;
}

The project compiles but fails to link:

[ 50%] Building CXX object type_traints/CMakeFiles/chapter_20.dir/TypeTraints.cpp.o
Linking CXX static library libchapter_20.a
[ 50%] Built target chapter_20
[100%] Building CXX object CMakeFiles/mpl.dir/main.cpp.o
Linking CXX executable mpl
type_traints/libchapter_20.a(TypeTraints.cpp.o): In function `char const* details::cl
ass2name<int>()':
/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:312: multiple definition of `c
har const* details::class2name<int>()'
CMakeFiles/mpl.dir/main.cpp.o:/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:
312: first defined here
collect2: ld returned 1 exit status
make[2]: *** [mpl] Błąd 1
make[1]: *** [CMakeFiles/mpl.dir/all] Error 2
make: *** [all] Error 2
23:56:20@marcin-laptop ~/P

The project links fine if I remove the class2name specialization (class2name<int>()) from TypeTraints.hpp and use only the generic implementation.

Does anybody have an idea Why is that? Did I miss-configure cmake files?


来源: stackexchange

问:
How to convert List to Map in Kotlin?
For example I have a list of strings like:

```<code>val list = listOf("a", "b", "c", "d")
</code>```

and I want to convert it to a map, where the strings are the keys.

I know I should use the .toMap() function, but I don't know how, and I haven't seen any examples of it.

答:
From List to Map with associate function

With Kotlin 1.3, List has a function called associate. associate has the following declaration:

```<code>fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>
</code>```

Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

Usage:

```<code>class Person(val name: String, val id: Int)

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associate({ Pair(it.id, it.name) })
    //val map = friends.associate({ it.id to it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}
</code>```

From List to Map with associateBy function

With Kotlin, List has a function called associateBy. associateBy has the following declaration:

```<code>fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V>
</code>```

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.

Usage:

```<code>class Person(val name: String, val id: Int)

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associateBy(keySelector = { person -> person.id }, valueTransform = { person -> person.name })
    //val map = friends.associateBy({ it.id }, { it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to convert List to Map in Kotlin?

Body:
For example I have a list of strings like:

val list = listOf("a", "b", "c", "d")

and I want to convert it to a map, where the strings are the keys.

I know I should use the .toMap() function, but I don't know how, and I haven't seen any examples of it.

Body:
From List to Map with associate function

With Kotlin 1.3, List has a function called associate. associate has the following declaration:

fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>

Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

Usage:

class Person(val name: String, val id: Int)

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associate({ Pair(it.id, it.name) })
    //val map = friends.associate({ it.id to it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}

From List to Map with associateBy function

With Kotlin, List has a function called associateBy. associateBy has the following declaration:

fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V>

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.

Usage:

class Person(val name: String, val id: Int)

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associateBy(keySelector = { person -> person.id }, valueTransform = { person -> person.name })
    //val map = friends.associateBy({ it.id }, { it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}


问:
Azure functions with complex c# code
I have complex code in c# with multiple classes(and classes have different functions) and i want to implement it as azure function. The problem is that the architecture is as follows: stream data is coming to function as input and after complex calculation within the class functions, I need to return calculated values as stream again. To be returned values are inside class functions and I am having trouble to find a way to return these to "run" function. Is there any easy way to do it?
Structure is like this

```<code>public static void Run(string myQueueItem, TraceWriter log)
{
 // gets data from service bus per second
 call function 1
}

public class Class1
{
function1(){
 call function2
 }
}

public class Class2
{
function2()
output interested is in here and program creates an output after 30 31 seconds and continues to creates about every 20 second
)}
</code>```

Many thanks

答:
Your question is not very clear, but based on your comments I understood that your processing logic and calculation results depend on multiple incoming messages.

Azure Function (Run method) will be called once per each Service Bus message in your queue. That means that you need to persist some state, e.g. the previous messages, across Function calls.

Azure Functions themselves don't provide any reliable in-process state storage, so you need to make use of external storage (e.g. SQL Database, Cosmos DB, Table Storage etc).

Your function flow would look something like this:

Run is called for an incoming Service Bus message.

You load the previous state of the function from external storage.

You instantiate Class1/Class2/etc hierachy.

You pass the incoming message AND your state to Class1/Class2.

Your logic produces an output message, new state, or both.

You persist the state back to the storage.

You return the output message to the output binding.

In case you don't want any external state, Azure Functions might not be the right service for you. E.g. you may have a Web Job, which constantly runs and keeps a series of messages in memory.

Edit: As @Gaurav suggested, you should take a look at
Durable Functions, but they are still at early preview stage.

ContentLicense: CC BY-SA 3.0

Title: Azure functions with complex c# code

Body:
I have complex code in c# with multiple classes(and classes have different functions) and i want to implement it as azure function. The problem is that the architecture is as follows: stream data is coming to function as input and after complex calculation within the class functions, I need to return calculated values as stream again. To be returned values are inside class functions and I am having trouble to find a way to return these to "run" function. Is there any easy way to do it?
Structure is like this

public static void Run(string myQueueItem, TraceWriter log)
{
 // gets data from service bus per second
 call function 1
}

public class Class1
{
function1(){
 call function2
 }
}

public class Class2
{
function2()
output interested is in here and program creates an output after 30 31 seconds and continues to creates about every 20 second
)}

Many thanks


问:
awk to add specific fields to file based on match in field
I am trying to use awk to add the $4,$5,$6 fields and the header in the tab-delimeted file2 to the lines that in file2 $2 there is a matching $3 value in file1. I added comments to each line as well as to my understanding of whats going on. Thank you :).

file1  tab-delimeted

```<code>ID  Name    Number
0-0 A,A 123456
2-2 B,B 789123
4-4 C,C 456789
</code>```

file2  tab-delimeted

```<code>ID  Number  Name    Info1   Info2   Info3   Info4
0-0 123456  A,A aaaaa   bbbbb   ccccc   eeeee
1-1 111111  Z,Z aaa bbb ccc eee
2-2 789123  B,B aaaaa   bb,bbb  ccccc   eeeee
3-3 222222  Y,Y aaa bb,bb   cc  e
4-4 456789  C,C aaa bb  ccc eeee
</code>```

desired output  tab-delimeted

```<code>ID  Name    Number  Info1   Info2   Info3
0-0 A,A 123456  aaaaa   bbbbb   ccccc
2-2 B,B 789123  aaaaa   bb,bbb  ccccc
4-4 C,C 456789  aaa bb  ccc
</code>```

awk

```<code>awk -F"\t" '$3 in a{  # read $3 value of file1 into array a
 a[$3]=a[$2];   # match $3 array a from file1 with $2 value in file2
  next   # process next line
 }  # close block
  { print $1,$2,a[$2],$4,$5,$6  # print desired output
 }  # close block
    END {  # start block
 for ( i in a) {   # create for loop i to print
     print a[i]  # print for each matching line in i
  }  # close block
}' file1 file2
</code>```

答:
try: one more approach reading file2 first and then reading file1.

```<code>awk -F"\t" 'FNR==NR{a[$1,$3,$2]=$4 OFS $5 OFS $6;next} (($1,$2,$3) in a){print $1,$2,$3,a[$1,$2,$3]}' OFS="\t" file2 file1
</code>```

Will add explanation in few mins.

EDIT: Adding non-one liner form of solution along with the explanation too.

```<code>awk -F"\t" 'FNR==NR{                              ####Checking condition FNR==NR which will be only true when first file named file2 is being read. Because FNR and NR both represent the number of lines for a Input_file, only difference is FNR value will be RESET whenever it is starting to read next Input_file and NR value will be keep on increasing till all the Input_files are being read.
                a[$1,$3,$2]=$4 OFS $5 OFS $6;     ####Creating an array named a whose index is $1,$3 and $2 and value is $4,$5 and $6. Where OFS is output field separator, whose default value is space.
                next                              ####next is awk built-in keyword which will NOT allow cursor to go further and will skip all next statements.
            }
     (($1,$2,$3) in a){                           ####Checking a condition which will be only checked when 2nd Input_file is being read. So checking here if $1, $2 and $3 is present in array a, then do following.
                        print $1,$2,$3,a[$1,$2,$3]####print the value of $1, $2,$3 and array a value whose index is $1,$2 and $3.
                      }
    ' OFS="\t" file2 file1                        ####Mentioning the Input_files here.
</code>```

Body:
I am trying to use awk to add the $4,$5,$6 fields and the header in the tab-delimeted file2 to the lines that in file2 $2 there is a matching $3 value in file1. I added comments to each line as well as to my understanding of whats going on. Thank you :).

file1  tab-delimeted

ID  Name    Number
0-0 A,A 123456
2-2 B,B 789123
4-4 C,C 456789

file2  tab-delimeted

ID  Number  Name    Info1   Info2   Info3   Info4
0-0 123456  A,A aaaaa   bbbbb   ccccc   eeeee
1-1 111111  Z,Z aaa bbb ccc eee
2-2 789123  B,B aaaaa   bb,bbb  ccccc   eeeee
3-3 222222  Y,Y aaa bb,bb   cc  e
4-4 456789  C,C aaa bb  ccc eeee

desired output  tab-delimeted

ID  Name    Number  Info1   Info2   Info3
0-0 A,A 123456  aaaaa   bbbbb   ccccc
2-2 B,B 789123  aaaaa   bb,bbb  ccccc
4-4 C,C 456789  aaa bb  ccc

awk

awk -F"\t" '$3 in a{  # read $3 value of file1 into array a
 a[$3]=a[$2];   # match $3 array a from file1 with $2 value in file2
  next   # process next line
 }  # close block
  { print $1,$2,a[$2],$4,$5,$6  # print desired output
 }  # close block
    END {  # start block
 for ( i in a) {   # create for loop i to print
     print a[i]  # print for each matching line in i
  }  # close block
}' file1 file2

Body:
try: one more approach reading file2 first and then reading file1.

awk -F"\t" 'FNR==NR{a[$1,$3,$2]=$4 OFS $5 OFS $6;next} (($1,$2,$3) in a){print $1,$2,$3,a[$1,$2,$3]}' OFS="\t" file2 file1

Will add explanation in few mins.

EDIT: Adding non-one liner form of solution along with the explanation too.

awk -F"\t" 'FNR==NR{                              ####Checking condition FNR==NR which will be only true when first file named file2 is being read. Because FNR and NR both represent the number of lines for a Input_file, only difference is FNR value will be RESET whenever it is starting to read next Input_file and NR value will be keep on increasing till all the Input_files are being read.
                a[$1,$3,$2]=$4 OFS $5 OFS $6;     ####Creating an array named a whose index is $1,$3 and $2 and value is $4,$5 and $6. Where OFS is output field separator, whose default value is space.
                next                              ####next is awk built-in keyword which will NOT allow cursor to go further and will skip all next statements.
            }
     (($1,$2,$3) in a){                           ####Checking a condition which will be only checked when 2nd Input_file is being read. So checking here if $1, $2 and $3 is present in array a, then do following.
                        print $1,$2,$3,a[$1,$2,$3]####print the value of $1, $2,$3 and array a value whose index is $1,$2 and $3.
                      }
    ' OFS="\t" file2 file1                        ####Mentioning the Input_files here.


问:
Set switch to On, reload table then insert a new row
I've got an UITableViewController that I use to create settings of my application.

There is a section with only one row where I put an UISwitch.

How can I insert a new row inside the same section of row with the switch only if the switch in set to YES? And how can I delete this row if the switch is set to NO?

Can anyone help me? Thanks!

I tried to use insertRowsAtIndexPaths:withRowAnimation: method but doesn't work...

This is my settings table code:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = NSLocalizedString(@"Impostazioni", @"");
}

- (void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
}

-(void)addCellToSetCode:(id)sender {

    if ([codeSwitch isOn]) {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"stateOfSwitch"];
    }
    else {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"stateOfSwitch"];
    }
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return NSLocalizedString(@"ListaDesideri", @"");
    }
    if (section == 1) {
        return NSLocalizedString(@"CondivisioneMail", @"");
    }
    if (section == 2) {
        return @"Sicurezza";
    }
    else {
        return nil;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) || (section == 2) || (section == 3) {
        return 2;
    }
    else if (section == 1) {
        return 1;
    }
    else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"Ordine", @"");

        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Nome"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Nome", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Costo"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Costo", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Categoria"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Categoria", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Nome Discendente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"NomeDiscendente", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Costo Discendente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"CostoDiscendente", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Categoria Discndente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"CategoriaDiscendente", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"DettagliDesiderio", @"");

        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"costoView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Costo", @"");
        }
        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"descrizioneView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Descrizione", @"");
        }
        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"urlView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"URL", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"Shortener", @"");

        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"Nessuno"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Nessuno", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"is.gd"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"is.gd", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"bit.ly"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"bit.ly", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"TinyURL"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"TinyURL", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"Linkyy"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Linkyy", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 2 && indexPath.row == 0) {
        cell.textLabel.text = @"Access Code";

        codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
        cell.accessoryView = codeSwitch;
        [codeSwitch addTarget:self action:@selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
        codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"codeSwitchState"];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section == 3 && indexPath.row == 0) {
        cell.textLabel.text = NSLocalizedString(@"Supporto", @"");
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 3 && indexPath.row == 1) {
        cell.textLabel.text = NSLocalizedString(@"Informazioni", @"");
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    return cell;
}</code>```

EDIT: Updates below...

I solved part of this problem!

I tried to use [self.tableView reloadData] but doesn't work and casually I solved using [self.tableView setNeedsDisplay]...

Now the switch works but if I set to On it and then I go out from app, completely closing it, the switch doesn't work... How can I solve this?

If this can help other, these are pieces of code updated:

```<code>-(void)addCellToSetCode:(id)sender {

    if ([codeSwitch isOn]) {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [self.tableView setNeedsDisplay];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"codeSwitchState"];
    }
    else {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [self.tableView setNeedsDisplay];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"codeSwitchState"];
    }
}

// tableView:numberOfRowsInSection:
else if (section == 2) {
    return codeSwitch.on ? 2 : 1;
}

// tableView:cellForRowAtIndexPath:
if (indexPath.section == 2 && indexPath.row == 0) {
    cell.textLabel.text = @"Access Code";

    codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
    cell.accessoryView = codeSwitch;
    [codeSwitch addTarget:self action:@selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
    codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"codeSwitchState"];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (indexPath.section == 2 && indexPath.row == 1) {
    if ([codeSwitch isOn]) {
        cell.textLabel.text = @"Set Access Code";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
}</code>```

答:
At least part of your problem (in the updated code) is that you don't create the UISwitch until you create the cell.  Your codeSwitch ivar may end up pointing to a different switch as that table row comes in and out of view.

Here's how I'd do this: in tableView:numberOfRowsInSection:, use the NSUserDefaults to see which state the table should be in, instead of using the state of the switch (which may not exist yet).  Then, in the switch's action method, call setBool:forKey: for the user defaults before you insert or delete the table row.

In essence, this makes the code follow the MVC model better, because it separates your view (the UISwitch) from the model (the BOOL in user defaults), with the controller (the view controller) in the middle.  By confounding the view and the model (the switch and the boolean state), you end up with problems when trying to deal with the state when the view isn't available yet.

BTW, you shouldn't need to call setNeedsDisplay on the table view at all.

Body:
I've got an UITableViewController that I use to create settings of my application.

There is a section with only one row where I put an UISwitch.

How can I insert a new row inside the same section of row with the switch only if the switch in set to YES? And how can I delete this row if the switch is set to NO?

Can anyone help me? Thanks!

I tried to use insertRowsAtIndexPaths:withRowAnimation: method but doesn't work...

This is my settings table code:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = NSLocalizedString(@"Impostazioni", @"");
}

- (void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
}

-(void)addCellToSetCode:(id)sender {

    if ([codeSwitch isOn]) {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"stateOfSwitch"];
    }
    else {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"stateOfSwitch"];
    }
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return NSLocalizedString(@"ListaDesideri", @"");
    }
    if (section == 1) {
        return NSLocalizedString(@"CondivisioneMail", @"");
    }
    if (section == 2) {
        return @"Sicurezza";
    }
    else {
        return nil;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) || (section == 2) || (section == 3) {
        return 2;
    }
    else if (section == 1) {
        return 1;
    }
    else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"Ordine", @"");

        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Nome"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Nome", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Costo"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Costo", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Categoria"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Categoria", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Nome Discendente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"NomeDiscendente", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Costo Discendente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"CostoDiscendente", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Categoria Discndente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"CategoriaDiscendente", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"DettagliDesiderio", @"");

        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"costoView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Costo", @"");
        }
        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"descrizioneView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Descrizione", @"");
        }
        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"urlView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"URL", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"Shortener", @"");

        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"Nessuno"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Nessuno", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"is.gd"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"is.gd", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"bit.ly"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"bit.ly", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"TinyURL"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"TinyURL", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"Linkyy"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Linkyy", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 2 && indexPath.row == 0) {
        cell.textLabel.text = @"Access Code";

        codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
        cell.accessoryView = codeSwitch;
        [codeSwitch addTarget:self action:@selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
        codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"codeSwitchState"];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section == 3 && indexPath.row == 0) {
        cell.textLabel.text = NSLocalizedString(@"Supporto", @"");
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 3 && indexPath.row == 1) {
        cell.textLabel.text = NSLocalizedString(@"Informazioni", @"");
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    return cell;
}

EDIT: Updates below...

I solved part of this problem!

I tried to use [self.tableView reloadData] but doesn't work and casually I solved using [self.tableView setNeedsDisplay]...

Now the switch works but if I set to On it and then I go out from app, completely closing it, the switch doesn't work... How can I solve this?

If this can help other, these are pieces of code updated:

-(void)addCellToSetCode:(id)sender {

    if ([codeSwitch isOn]) {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [self.tableView setNeedsDisplay];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"codeSwitchState"];
    }
    else {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [self.tableView setNeedsDisplay];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"codeSwitchState"];
    }
}

// tableView:numberOfRowsInSection:
else if (section == 2) {
    return codeSwitch.on ? 2 : 1;
}

// tableView:cellForRowAtIndexPath:
if (indexPath.section == 2 && indexPath.row == 0) {
    cell.textLabel.text = @"Access Code";

    codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
    cell.accessoryView = codeSwitch;
    [codeSwitch addTarget:self action:@selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
    codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"codeSwitchState"];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (indexPath.section == 2 && indexPath.row == 1) {
    if ([codeSwitch isOn]) {
        cell.textLabel.text = @"Set Access Code";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
}

ContentLicense: CC BY-SA 2.5


问:
Form Select with AspnetBoilerplate BSB Theme
Can't get a styled select form element to display correctly with the AspnetBoilerplate BSB Theme and there is no examples of one being used in the code.

I do see in the stylesheet the .bootstrap-select styles. Does someone have an example of how to use this?

答:
Create your html  with the .selectpicker class.

```<code><select class="selectpicker">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Relish</option>
</select>
</code>```

Options can be passed via data attributes or JavaScript.

```<code>$('.selectpicker').selectpicker({
  style: 'btn-info',
  size: 4
});
</code>```

If you have not included libraries then include them all.

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/i18n/defaults-*.min.js"></script>
</code>```

Body:
Create your html  with the .selectpicker class.

<select class="selectpicker">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Relish</option>
</select>

Options can be passed via data attributes or JavaScript.

$('.selectpicker').selectpicker({
  style: 'btn-info',
  size: 4
});

If you have not included libraries then include them all.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/i18n/defaults-*.min.js"></script>


问:
How to get current loggedin username in vtiger tpl file
How i can get the current loggedin username in the header.tpl file of vtiger CRM. It should be for use inside {php} {/php} tags.

Header.tpl

```<code>{php} if($CURRENT_USER == 'admin') { echo "yes"; } else { echo "no"; } {/php}
</code>```

答:
$current_user_model isn't a variable that the .tpl has in it's scope by default.

What you should do is go to the .php file for the view that you're using and add something like this:

```<code>$username = Users_Record_Model::getCurrentUserModel() ->get('user_name');
$viewer->assign('USERNAME', $username);
</code>```

This passes the php variable $username to your tpl with the name $USERNAME, so now anywhere you need it in the .tpl simply use {$USERNAME}

Body:
How i can get the current loggedin username in the header.tpl file of vtiger CRM. It should be for use inside {php} {/php} tags.

Header.tpl

{php} if($CURRENT_USER == 'admin') { echo "yes"; } else { echo "no"; } {/php}

Body:
$current_user_model isn't a variable that the .tpl has in it's scope by default.

What you should do is go to the .php file for the view that you're using and add something like this:

$username = Users_Record_Model::getCurrentUserModel() ->get('user_name');
$viewer->assign('USERNAME', $username);

This passes the php variable $username to your tpl with the name $USERNAME, so now anywhere you need it in the .tpl simply use {$USERNAME}


问:
Undertow servlet handler looses already authenticated and valid SecurityContext managed by keycloak
I'm trying to enable role based access control on a rest end point that I've setup using undertow, jersey and CDI. I initialize the servlet deployment as follows:

```<code>DeploymentInfo servletBuilder = Servlets.deployment()
    .setClassLoader(Main.class.getClassLoader())
    .setContextPath("/rest")
    .setDeploymentName("sv.war")
    .addListeners(listener(Listener.class))
    .setLoginConfig(new LoginConfig("KEYCLOAK", "some-realm"))
    .setAuthorizationManager(auth) // my dummy for testing
    .addServlets(servlet("jerseyServlet", ServletContainer.class)
        .setLoadOnStartup(1)
        .addInitParam("javax.ws.rs.Application", SystemViewApplication.class.getName())
        .addMapping("/api/*"));
</code>```

I enabled kecloak authentication based on this example code.

So, my server is started as:

```<code>DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();

PathHandler path = Handlers.path(Handlers.resource(staticResources).setDirectoryListingEnabled(false).setWelcomeFiles("index.html"))
    .addPrefixPath("/rest", manager.start());
Undertow server = Undertow.builder()
    .addHttpListener(8087, "localhost")
    .setHandler(sessionHandling(addSecurity(exchange -> {
      final SecurityContext context = exchange.getSecurityContext();
      if (!context.isAuthenticated()) {
        exchange.endExchange();
        return;
      }
      log.info("Authenticated: {} {} {}", context.getMechanismName(), context.getAuthenticatedAccount().getPrincipal().getName(), context.getAuthenticatedAccount().getRoles());
      // propagate the request
      path.handleRequest(exchange);
    })))
    .build();
server.start();
</code>```

Where the two methods sessionHandling() and addSecurity() are lifted from the example I've linked above.

The authentication works, I am forced to log in, and the Authenticated: .. logging line is printed out with the correct details. But, once it hits the servlet handling, the security context (and account) is lost. I've traced this call and I can see that at some point along the path, it's replaced by brand new SecurityContext which has a null account.

Now my question - is there some authentication mechanism that I am missing that would propagate the state after the keycloak authentication or can I just fix the undertow code and in the SecurityContext, if the passed in context is already correctly authenticated, accept that state and move on? (the latter doesn't seem right, I'm guessing it's because the could be different authentication for the servlet deployment?) If so, is there any way to connect the servlet deployment to see the keycloak authentication has already happened?

答:
Incase anyone comes looking here on how to authenticate servlets properly with keycloak and use role based authentication, this worked for me (note, this worked for me without the requirement of any xml files, purely with annotations.

First in the servlet application (wherever you extended ResourceConfig) register() the RolesAllowedDynamicFeature.class.

Also enable "use-resource-role-mappings": true in keycloak.json.

Next, instantiate the servlet deployment with an initial security wrapper:

```<code>DeploymentInfo servletBuilder = Servlets.deployment()
    .setClassLoader(Main.class.getClassLoader())
    .setContextPath("/")
    .setDeploymentName("sv.war")
    .addListeners(listener(Listener.class))
    .setIdentityManager(idm)
    .setSessionManagerFactory(new InMemorySessionManagerFactory())
    .setInitialSecurityWrapper(handler -> sessionHandling(addSecurity(handler)))
    .setResourceManager(staticResources)
    .addWelcomePage("index.html")
    .addServlets(servlet("jerseyServlet", ServletContainer.class)
        .setLoadOnStartup(1)
        .addInitParam("javax.ws.rs.Application", SystemViewApplication.class.getName())
        .addMapping("/api/*"));

DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();

Undertow server = Undertow.builder()
    .addHttpListener(8087, "localhost")
    .setHandler(Handlers.path(manager.start()))
    .build();
server.start();
</code>```

Where sessionHandling(addSecurity(handler)) is basically the code from the linked github repo.

Now authentication via keycloak will work, and also role based authentication will work, so for example, if you have a CDI injected rest end point, such as:

```<code>@RolesAllowed({"admin", "guest"})
@GET
@Path("/{id}")
public Response findById(@PathParam("id") @NotNull Integer id){
  // some method
}
</code>```

As long as the roles are configured in keycloak, it should work.

Body:
I'm trying to enable role based access control on a rest end point that I've setup using undertow, jersey and CDI. I initialize the servlet deployment as follows:

DeploymentInfo servletBuilder = Servlets.deployment()
    .setClassLoader(Main.class.getClassLoader())
    .setContextPath("/rest")
    .setDeploymentName("sv.war")
    .addListeners(listener(Listener.class))
    .setLoginConfig(new LoginConfig("KEYCLOAK", "some-realm"))
    .setAuthorizationManager(auth) // my dummy for testing
    .addServlets(servlet("jerseyServlet", ServletContainer.class)
        .setLoadOnStartup(1)
        .addInitParam("javax.ws.rs.Application", SystemViewApplication.class.getName())
        .addMapping("/api/*"));

I enabled kecloak authentication based on this example code.

So, my server is started as:

DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();

PathHandler path = Handlers.path(Handlers.resource(staticResources).setDirectoryListingEnabled(false).setWelcomeFiles("index.html"))
    .addPrefixPath("/rest", manager.start());
Undertow server = Undertow.builder()
    .addHttpListener(8087, "localhost")
    .setHandler(sessionHandling(addSecurity(exchange -> {
      final SecurityContext context = exchange.getSecurityContext();
      if (!context.isAuthenticated()) {
        exchange.endExchange();
        return;
      }
      log.info("Authenticated: {} {} {}", context.getMechanismName(), context.getAuthenticatedAccount().getPrincipal().getName(), context.getAuthenticatedAccount().getRoles());
      // propagate the request
      path.handleRequest(exchange);
    })))
    .build();
server.start();

Where the two methods sessionHandling() and addSecurity() are lifted from the example I've linked above.

The authentication works, I am forced to log in, and the Authenticated: .. logging line is printed out with the correct details. But, once it hits the servlet handling, the security context (and account) is lost. I've traced this call and I can see that at some point along the path, it's replaced by brand new SecurityContext which has a null account.

Now my question - is there some authentication mechanism that I am missing that would propagate the state after the keycloak authentication or can I just fix the undertow code and in the SecurityContext, if the passed in context is already correctly authenticated, accept that state and move on? (the latter doesn't seem right, I'm guessing it's because the could be different authentication for the servlet deployment?) If so, is there any way to connect the servlet deployment to see the keycloak authentication has already happened?

Body:
Incase anyone comes looking here on how to authenticate servlets properly with keycloak and use role based authentication, this worked for me (note, this worked for me without the requirement of any xml files, purely with annotations.

First in the servlet application (wherever you extended ResourceConfig) register() the RolesAllowedDynamicFeature.class.

Also enable "use-resource-role-mappings": true in keycloak.json.

Next, instantiate the servlet deployment with an initial security wrapper:

DeploymentInfo servletBuilder = Servlets.deployment()
    .setClassLoader(Main.class.getClassLoader())
    .setContextPath("/")
    .setDeploymentName("sv.war")
    .addListeners(listener(Listener.class))
    .setIdentityManager(idm)
    .setSessionManagerFactory(new InMemorySessionManagerFactory())
    .setInitialSecurityWrapper(handler -> sessionHandling(addSecurity(handler)))
    .setResourceManager(staticResources)
    .addWelcomePage("index.html")
    .addServlets(servlet("jerseyServlet", ServletContainer.class)
        .setLoadOnStartup(1)
        .addInitParam("javax.ws.rs.Application", SystemViewApplication.class.getName())
        .addMapping("/api/*"));

DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();

Undertow server = Undertow.builder()
    .addHttpListener(8087, "localhost")
    .setHandler(Handlers.path(manager.start()))
    .build();
server.start();

Where sessionHandling(addSecurity(handler)) is basically the code from the linked github repo.

Now authentication via keycloak will work, and also role based authentication will work, so for example, if you have a CDI injected rest end point, such as:

@RolesAllowed({"admin", "guest"})
@GET
@Path("/{id}")
public Response findById(@PathParam("id") @NotNull Integer id){
  // some method
}

As long as the roles are configured in keycloak, it should work.


问:
Is there a better way to run a command N times in bash?
I occasionally run a bash command line like this:

```<code>n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done
</code>```

To run some_command a number of times in a row -- 10 times in this case.

Often some_command is really a chain of commands or a pipeline.

Is there a more concise way to do this?

答:
A little bit naive but this is what I usually remember off the top of my head:

```<code>for i in 1 2 3; do
  some commands
done
</code>```

Very similar to @joe-koberg's answer. His is better especially if you need many repetitions, just harder for me to remember other syntax because in last years I'm not using bash a lot. I mean not for scripting at least.

Body:
I occasionally run a bash command line like this:

n=0; while [[ $n -lt 10 ]]; do some_command; n=$((n+1)); done

To run some_command a number of times in a row -- 10 times in this case.

Often some_command is really a chain of commands or a pipeline.

Is there a more concise way to do this?

Body:
A little bit naive but this is what I usually remember off the top of my head:

for i in 1 2 3; do
  some commands
done

Very similar to @joe-koberg's answer. His is better especially if you need many repetitions, just harder for me to remember other syntax because in last years I'm not using bash a lot. I mean not for scripting at least.


问:
My Android Studio may have some issue
I am using Android Studio 2.3.3 . but it appears a little different from others. It look like:

But I want that it look like this:

Please suggest what to do?

答:
Look for the red circle. It has a settings icon, click on that and select the option, "Include Device Frame (If Available)" and you will have the black overlay around the device, which you want.

However for the Palette to look the way you want, you have to downgrade your Android Studio to at least '2.1.2'. Because for your version that is the way the palette will look.

Title: My Android Studio may have some issue


问:
Optimizing apply function output
I have the following function:

```<code>library (reshape)
phenotype <- rnorm (100)
data <- matrix(rnorm(1000), nrow = 10, ncol=100)

spearman.p <-
             reshape(
                     melt(
                          apply(data, 1, function(y){
                                        cor.test(y,phenotype,method="spearman")
                                                    }[c("p.value", "estimate")]
                               )
                          ), timevar="L2", idvar="L1", direction="wide"
                       )
</code>```

that I would like to know if there is a more efficent way of getting out the p.value and estimate from a "apply"ed cor.test

Can anyone provide some suggestions?

答:
This would be more compact and delivers the p.values from the duplicated data. Is that what you wanted?:

```<code> dtt <- do.call(rbind, apply(data, 1, function(y){
                            cor.test(y,phenotype,method="spearman")
                                  }[c("p.value", "estimate")]
                                 ) )
  dtt
 ###      p.value   estimate
     [1,] 0.2305644 0.1208641
     [2,] 0.2305644 0.1208641
     [3,] 0.2305644 0.1208641
     [4,] 0.2305644 0.1208641
     [5,] 0.2305644 0.1208641
     [6,] 0.2305644 0.1208641
     [7,] 0.2305644 0.1208641
     [8,] 0.2305644 0.1208641
     [9,] 0.2305644 0.1208641
    [10,] 0.2305644 0.1208641
</code>```

Edit: If you are looking for speed and/or the possibility of easily transporting to parallel-oriented platforms then add this to the list of candidates:

```<code> pmtx <- matrix(NA, nrow=nrow(data), ncol=2)
 for( i in 1:nrow(data) ) {
  pmtx[i, 1:2 ] <- unlist(cor.test(data[i, ],
                                   phenotype,
                                   method="spearman")[c("p.value", "estimate")] ) }
 pmtx
</code>```

OwnerDisplayName: please delete me

LastEditorDisplayName: please delete me

Title: Optimizing apply function output

Body:
I have the following function:

library (reshape)
phenotype <- rnorm (100)
data <- matrix(rnorm(1000), nrow = 10, ncol=100)

spearman.p <-
             reshape(
                     melt(
                          apply(data, 1, function(y){
                                        cor.test(y,phenotype,method="spearman")
                                                    }[c("p.value", "estimate")]
                               )
                          ), timevar="L2", idvar="L1", direction="wide"
                       )

that I would like to know if there is a more efficent way of getting out the p.value and estimate from a "apply"ed cor.test

Can anyone provide some suggestions?

Body:
This would be more compact and delivers the p.values from the duplicated data. Is that what you wanted?:

 dtt <- do.call(rbind, apply(data, 1, function(y){
                            cor.test(y,phenotype,method="spearman")
                                  }[c("p.value", "estimate")]
                                 ) )
  dtt
 ###      p.value   estimate
     [1,] 0.2305644 0.1208641
     [2,] 0.2305644 0.1208641
     [3,] 0.2305644 0.1208641
     [4,] 0.2305644 0.1208641
     [5,] 0.2305644 0.1208641
     [6,] 0.2305644 0.1208641
     [7,] 0.2305644 0.1208641
     [8,] 0.2305644 0.1208641
     [9,] 0.2305644 0.1208641
    [10,] 0.2305644 0.1208641

Edit: If you are looking for speed and/or the possibility of easily transporting to parallel-oriented platforms then add this to the list of candidates:

 pmtx <- matrix(NA, nrow=nrow(data), ncol=2)
 for( i in 1:nrow(data) ) {
  pmtx[i, 1:2 ] <- unlist(cor.test(data[i, ],
                                   phenotype,
                                   method="spearman")[c("p.value", "estimate")] ) }
 pmtx


问:
Angular 2: is styleUrls relative to the current component?
I'm encounter some troubles to add style to my angular 2 component using styleUrls.

Here is how I use it :

path/main.component.ts

```<code>@Component({
    selector: 'app-view',
    styleUrls: ['./styles/style.css'],
    template: //...
})
</code>```

path/styles/style.css

```<code>.main-wrapper {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background: red; }
</code>```

And nothing happens in my browser.
I've tried with :

an absolute path

a path relative to the root component.

I've also tried :

to write this with different syntaxes like './styles/style.css', 'styles/style.css'

to move my style.css next to my component.

But I can't get it works.

答:
Don't use styleUrls. Simply rename the style file with scss extension. The stylesheet will be used automatically!

Therefore, my component's files will be like this, and will work with the style:

mycomponent.ts

mycomponent.html

mycomponent.scss

Body:
I'm encounter some troubles to add style to my angular 2 component using styleUrls.

Here is how I use it :

path/main.component.ts

@Component({
    selector: 'app-view',
    styleUrls: ['./styles/style.css'],
    template: //...
})

path/styles/style.css

.main-wrapper {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background: red; }

And nothing happens in my browser.
I've tried with :

an absolute path

a path relative to the root component.

I've also tried :

to write this with different syntaxes like './styles/style.css', 'styles/style.css'

to move my style.css next to my component.

But I can't get it works.


问:
How to bottom-align an element inside a flex item?
I have a flex container with three flex items and inside each item a link that should be aligned on the bottom (all links bottom middle aligned).

Flex-items are stretched and do not have a fix height, same as flex container. Thanks!

.flex-container {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-align-content: flex-start;
  -ms-flex-line-pack: start;
  align-content: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: start;
  align-items: flex-start;
}

.flex-item {
  -webkit-order: 0;
  -ms-flex-order: 0;
  order: 0;
  -webkit-flex: 1 0 0;
  -ms-flex: 1 0 0;
  flex: 1 0 0;
  -webkit-align-self: stretch;
  -ms-flex-item-align: stretch;
  align-self: stretch;
  padding: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="main-section">
  <div class="container">
    <div class="flex-container">
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
          consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et
          porttitor lacus.</p>
        Link
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.</p>
        Link
      </div>
      <div class="flex-item">
        <p class="subTitle">Titel</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.</p>
        Link
      </div>
    </div>
  </div>
</section></code>```

https://jsfiddle.net/ABoooo/dns5zr1p/

答:
Put position: absolute; on your a tag and position: relative; to your flex-item:

.flex-container {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-align-content: flex-start;
  -ms-flex-line-pack: start;
  align-content: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: start;
  align-items: flex-start;
}

.flex-item {
  -webkit-order: 0;
  -ms-flex-order: 0;
  order: 0;
  -webkit-flex: 1 0 0;
  -ms-flex: 1 0 0;
  flex: 1 0 0;
  -webkit-align-self: stretch;
  -ms-flex-item-align: stretch;
  align-self: stretch;
  padding: 15px;
  position: relative;
}

.flex-item a {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="main-section">
        <div class="container">
            <div class="flex-container">
                <div class="flex-item">
                    <p class="subTitle">Titel</p>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et porttitor lacus.</p>
                    Link
                </div>
                <div class="flex-item">
                    <p class="subTitle">Titel</p>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.</p>
                    Link
                </div>
                <div class="flex-item">
                    <p class="subTitle">Titel</p>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.</p>
                    Link
                </div>
            </div>
        </div>
    </section></code>```

Body:
I have a flex container with three flex items and inside each item a link that should be aligned on the bottom (all links bottom middle aligned).

Flex-items are stretched and do not have a fix height, same as flex container. Thanks!

.flex-container {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-align-content: flex-start;
  -ms-flex-line-pack: start;
  align-content: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: start;
  align-items: flex-start;
}

.flex-item {
  -webkit-order: 0;
  -ms-flex-order: 0;
  order: 0;
  -webkit-flex: 1 0 0;
  -ms-flex: 1 0 0;
  flex: 1 0 0;
  -webkit-align-self: stretch;
  -ms-flex-item-align: stretch;
  align-self: stretch;
  padding: 15px;
}

Titel

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
          consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et
          porttitor lacus.

        Link

Titel

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.

        Link

Titel

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt
          arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.

        Link

https://jsfiddle.net/ABoooo/dns5zr1p/

Body:
Put position: absolute; on your a tag and position: relative; to your flex-item:

.flex-container {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-align-content: flex-start;
  -ms-flex-line-pack: start;
  align-content: flex-start;
  -webkit-align-items: flex-start;
  -ms-flex-align: start;
  align-items: flex-start;
}

.flex-item {
  -webkit-order: 0;
  -ms-flex-order: 0;
  order: 0;
  -webkit-flex: 1 0 0;
  -ms-flex: 1 0 0;
  flex: 1 0 0;
  -webkit-align-self: stretch;
  -ms-flex-item-align: stretch;
  align-self: stretch;
  padding: 15px;
  position: relative;
}

.flex-item a {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
}

<section class="main-section">
        <div class="container">
            <div class="flex-container">
                <div class="flex-item">
                    <p class="subTitle">Titel</p>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent consequat urna quis commodo varius. Praesent hendrerit at augue in fermentum. Ut sed dolor blandit, lacinia orci eget, ultrices elit. Nulla luctus, risus eu viverra eleifend, leo orci posuere nulla, ut vestibulum orci metus in nisi. Aenean et porttitor lacus.</p>
                    <a href="#">Link</a>
                </div>
                <div class="flex-item">
                    <p class="subTitle">Titel</p>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus.</p>
                    <a href="#">Link</a>
                </div>
                <div class="flex-item">
                    <p class="subTitle">Titel</p>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dignissim ante turpis, sit amet suscipit velit consequat id. Donec a est tellus. Sed pellentesque non arcu et interdum. Aenean venenatis, ipsum a viverra interdum, neque nisl tincidunt arcu, non vulputate justo metus nec quam. Nullam blandit, purus id pretium congue, turpis diam semper sapien, vel suscipit est velit eget leo.</p>
                    <a href="#">Link</a>
                </div>
            </div>
        </div>
    </section>


问:
Get underlying entity object from entity framework proxy
I have an entity by getting it from DbEntityEntry.Entity. This returns the Entity Framework proxy for the entity.

How do I access the underlying object as its original type instead of the proxy?

Alternatively I need to dynamically try to cast the proxy to the entity type. Here's a start.

```<code>var theEntityType = entityEntry.Entity;

if (
    theEntityType.BaseType != null
    && entityType.Namespace == "System.Data.Entity.DynamicProxies"
)
   theEntityType = entityType.BaseType;

// Now I need to cast to the correct type
// THIS WON'T WORK BECAUSE `theEntityType` is dynamic.
var entityObject = (theEntityType)entityEntry.Entity;
// My entites also don't implement IConvertible
</code>```

答:
Use AutoMapper 4.2.1 It is having DynamicMap which can remove the Proxy from the object.</p>

```<code>     var parents = parentsRepo.GetAll().ToList();
     Mapper.CreateMap<Parent,ParentDto>();
     var parentsDto = Mapper.DynamicMap<List<ParentDto>>(parents);
</code>```

Body:
I have an entity by getting it from DbEntityEntry.Entity. This returns the Entity Framework proxy for the entity.

How do I access the underlying object as its original type instead of the proxy?

Alternatively I need to dynamically try to cast the proxy to the entity type. Here's a start.

var theEntityType = entityEntry.Entity;

if (
    theEntityType.BaseType != null
    && entityType.Namespace == "System.Data.Entity.DynamicProxies"
)
   theEntityType = entityType.BaseType;

// Now I need to cast to the correct type
// THIS WON'T WORK BECAUSE `theEntityType` is dynamic.
var entityObject = (theEntityType)entityEntry.Entity;
// My entites also don't implement IConvertible

Body:
Use AutoMapper 4.2.1 It is having DynamicMap which can remove the Proxy from the object.

     var parents = parentsRepo.GetAll().ToList();
     Mapper.CreateMap<Parent,ParentDto>();
     var parentsDto = Mapper.DynamicMap<List<ParentDto>>(parents);


问:
asp.net trigger button click on server side from postback manually
I have an asp.net page. & I am using jquery confirm plug in from here.
  https://craftpip.github.io/jquery-confirm/

I want that when user clicks a button, they are prompted for a confirm dialog & when they say confirm,only then my button click on server should get fired. I do not want to use the window.confirm dialog.

I was able to use jquery confirm & called postback manually via Button's ClientClick property.

The __doPostBack event is firing. However, the click event on server side for the button is not getting fired.

What am i missing ?

ASPX Code :

```<code> <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tester.aspx.cs" Inherits="BLF_Gauri.Tester" %>

<html>
<head>
    <script src="Scripts/jquery-2.1.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.3/jquery-confirm.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.3/jquery-confirm.min.js"></script>

</head>
<body>
    <form runat="server">
        <asp:Button ID="Button2" runat="server" Text="YEs" OnClick="Button2_Click"
OnClientClick="return TestClick(this);" />
    </form>

    <script type="text/javascript">

        function TestClick(x)
        {
            jQuery.confirm({
                title: 'Confirm!',
                content: 'Simple confirm!',
                buttons: {
                    confirm: function () {
                        __doPostBack("'" + x.id + "'", 'OnClick');
                    },
                    cancel: function () {
          //              Do Nothing
                    }
                }
            });
            return false;
        }
    </script>

</body>
</html>
</code>```

The Code Behind  : (Simplified)

```<code>protected void Page_Load(object sender, EventArgs e)
        {
           //IT COMES HERE.
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //IT DOES NOT COME HERE.
        }
</code>```

答:
So I solved this!! Instead of using __dopostback I used this.

```<code>WebForm_DoPostBackWithOptions(
      new WebForm_PostBackOptions("" + x.name + "", "", true, "", "", false, true));
</code>```

x.name coz inside a master page. id changes.

Body:
I have an asp.net page. & I am using jquery confirm plug in from here.
  https://craftpip.github.io/jquery-confirm/

I want that when user clicks a button, they are prompted for a confirm dialog & when they say confirm,only then my button click on server should get fired. I do not want to use the window.confirm dialog.

I was able to use jquery confirm & called postback manually via Button's ClientClick property.

The __doPostBack event is firing. However, the click event on server side for the button is not getting fired.

What am i missing ?

ASPX Code :

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tester.aspx.cs" Inherits="BLF_Gauri.Tester" %>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.3/jquery-confirm.min.css">

    <form runat="server">
        <asp:Button ID="Button2" runat="server" Text="YEs" OnClick="Button2_Click"
OnClientClick="return TestClick(this);" />
    </form>

The Code Behind  : (Simplified)

protected void Page_Load(object sender, EventArgs e)
        {
           //IT COMES HERE.
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //IT DOES NOT COME HERE.
        }

Body:
So I solved this!! Instead of using __dopostback I used this.

WebForm_DoPostBackWithOptions(
      new WebForm_PostBackOptions("" + x.name + "", "", true, "", "", false, true));

x.name coz inside a master page. id changes.


问:
Are there any secure alternatives to XDMCP?
Are there any secure alternatives to XDMCP (A Linux remote desktop protocol)?

I'd like to set up some thin clients -- UI heads (old computer + mouse + keyboard) connected to VMs on a fast server. ssh -Y doesn't quite cut it, since this would be for non-savvy computer users. I'd like it integrated with kdm/gdm if possible (this seems to rule out Nomachine NX, and I don't like closed source).

I am on a private network, so I guess I'll probably end up going with XDMCP, but it would seem kinda sorry if there aren't any secure open-source alternatives.

答: Check out Nomachine NX, which is a secure version of X. They reduced the chattyness of the X protocol in a neat way and tunnel it through ssh. It works really well (but disclaimer - my company does resell the software). Available in free-as-in-beer single user version, or paid for enterprise version. There's also freenx, which is a GPL implementation of the server (the protocol, at least in version 3.x, is GPL).</p>


问:
DataGridView and MessageBox
I have a problem with a MessageBox in DGV. So, when I click cell opening context menu, next I click in this menu and should show the MessageBox, but not showing up. Why?

This is my code:

```<code>private void DGV1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
       ContextMenuStrip1.Show(Cursor.Position);
    }

private void optionToolStripMenuItem_Click(object sender, EventArgs e)
    {
       DialogResult res = MessageBox.Show("Are You Sure?",
              "Are You Sure", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
       if (res == DialogResult.Yes)
         {
           ......
         }
     }
</code>```

This MessageBox not showing up, but in application nothing can be done, as if the MessageBox was hidden.
I'm trying this:

```<code>MessageBox.Show(new Form { TopMost = true }, "Message");
</code>```

But still not working :(

答:
This is frustrating problem. I had this same issue and Google was not a lot of help. Eventually I discovered that if you have implemented the CellFormatting event of the DataGridView (and perhaps other events that override the display logic) MessageBoxes will NOT be displayed over the DataGridView until the window is redrawn. To work around this behavior there are a few options, here are two.

1) Cheese method (hide and show Grid)

```<code>MyGrid.Visible = false;
MessageBox.Show("my message text");
MyGrid.Visible = true;
</code>```

2) Better method (Detach event before Message, and reattach after)

```<code>MyGrid.CellFormatting -= MyGrid_CellFormatting;
MessageBox.Show("my message text");
MyGrid.CellFormatting += MyGrid_CellFormatting;
</code>```

3) And wrap it up on your Form as a helper

```<code>private DialogResult ShowMessageBox(string p_text, string p_caption, MessageBoxButtons p_buttons, MessageBoxIcon p_icon) {
    bool detached = false;
    try {
        // detach events
        MyGrid.CellFormatting -= MyGrid_CellFormatting;
        detached = true;
        // show the message box
        return MessageBox.Show(p_text, p_caption, p_buttons, p_icon);
    }
    catch(Exception ex) {
        throw ex;
    }
    finally {
        if(detached) {
            // reattach
            MyGrid.CellFormatting += MyGrid_CellFormatting;
        }
        MyGrid.Invalidate();
    }
}
</code>```

Title: DataGridView and MessageBox

Body:
I have a problem with a MessageBox in DGV. So, when I click cell opening context menu, next I click in this menu and should show the MessageBox, but not showing up. Why?

This is my code:

private void DGV1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
       ContextMenuStrip1.Show(Cursor.Position);
    }

private void optionToolStripMenuItem_Click(object sender, EventArgs e)
    {
       DialogResult res = MessageBox.Show("Are You Sure?",
              "Are You Sure", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
       if (res == DialogResult.Yes)
         {
           ......
         }
     }

This MessageBox not showing up, but in application nothing can be done, as if the MessageBox was hidden.
I'm trying this:

MessageBox.Show(new Form { TopMost = true }, "Message");

But still not working :(

Body:
This is frustrating problem. I had this same issue and Google was not a lot of help. Eventually I discovered that if you have implemented the CellFormatting event of the DataGridView (and perhaps other events that override the display logic) MessageBoxes will NOT be displayed over the DataGridView until the window is redrawn. To work around this behavior there are a few options, here are two.

1) Cheese method (hide and show Grid)

MyGrid.Visible = false;
MessageBox.Show("my message text");
MyGrid.Visible = true;

2) Better method (Detach event before Message, and reattach after)

MyGrid.CellFormatting -= MyGrid_CellFormatting;
MessageBox.Show("my message text");
MyGrid.CellFormatting += MyGrid_CellFormatting;

3) And wrap it up on your Form as a helper

private DialogResult ShowMessageBox(string p_text, string p_caption, MessageBoxButtons p_buttons, MessageBoxIcon p_icon) {
    bool detached = false;
    try {
        // detach events
        MyGrid.CellFormatting -= MyGrid_CellFormatting;
        detached = true;
        // show the message box
        return MessageBox.Show(p_text, p_caption, p_buttons, p_icon);
    }
    catch(Exception ex) {
        throw ex;
    }
    finally {
        if(detached) {
            // reattach
            MyGrid.CellFormatting += MyGrid_CellFormatting;
        }
        MyGrid.Invalidate();
    }
}


问:
Wix Toolset confirmation dialog before exit
I am developing an installation msi file using Wix toolset (in VS 2012) and faced with the problem that I can't add a confirmation dialog when user press button 'Cancel'. I tried to add also custom action dll with the message box, but if the function returns ActionResult.Failure, then my setup shows error dialog.

Original control:

```<code><Control Type="PushButton" Id="progressCancelBtn" Width="56" Height="17" X="296" Y="244">
   <Text>Cancel</Text>
   <Publish Event="EndDialog" Value="Exit" />
</Control>
</code>```

Try number 1:

```<code>public class CustomActions
    {
        [CustomAction]
        public static ActionResult ShowExitMessageBox(Session session)
        {
            DialogResult result = MessageBox.Show("Exit installation?", "Exit", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                return ActionResult.Failure;
            }
            else
            {
                return ActionResult.Success;
            }
        }
    }
</code>```

Custom action:

```<code> <CustomAction Id='ShowExitMsgBox' BinaryKey='CustomActions' DllEntry='ShowExitMessageBox' Execute='immediate'               Return='ignore'/>

    <Binary Id='CustomActions' SourceFile='$(var.CASourcesPath)\CustomActions.CA.dll'/>
</code>```

And tried to use:

```<code><Control Type="PushButton" Id="cancelBtn" Width="56" Height="17" X="300" Y="244" Cancel="yes">
    <Text>Cancel</Text>
    <Publish Event="DoAction" Value="ShowExitMsgBox">1</Publish>
    <!--Publish Event="EndDialog" Value="Exit" /-->
</Control>
</code>```

But it shows like failure, instead of cancellation.

Thank you for help in advance.

Update:

I changed my custom action C# code to the next:

```<code>public class CustomActions
    {
        [CustomAction]
        public static ActionResult ShowExitMessageBox(Session session)
        {
            DialogResult result = MessageBox.Show("Exit installation?", "Exit", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                session["CANCELEDPROP"] = "1";
            }
            else
            {
                session["CANCELEDPROP"] = "0";
            }

            return ActionResult.Success;
        }
    }
</code>```

and WIX part:

```<code>// in Product.wxs
<Property Id="CANCELEDPROP" Secure="yes">0</Property>
// in UIFile.wxs
<Control Type="PushButton" Id="cancelBtn" Width="56" Height="17" X="300" Y="244" Cancel="yes">
    <Text>Cancel</Text>
    <Publish Event="DoAction" Value="ShowExitMsgBox">1</Publish>
    <Publish Event="EndDialog" Value="Exit">CANCELEDPROP=1</Publish>
</Control>
</code>```

It works on the first page, but I get an error on progress page: "Windows installer has stopped working" after I pressed some button on my message box. :(
I have found out if I don't use message box, then everything works. It is strange.

Update 2:

I tried to use session.Message instead of Windows.Forms, but message box just doesn't appear. Strange.

```<code>[CustomAction]
public static ActionResult ShowExitMessageBox(Session session)
{
    Record record = new Record();
    record.FormatString = "Exit installation?";

    MessageResult result = session.Message(InstallMessage.Warning
                                                    | (InstallMessage)System.Windows.Forms.MessageBoxIcon.Warning
                                                    | (InstallMessage)System.Windows.Forms.MessageBoxButtons.YesNo,
                                                    record);

    if (result == MessageResult.Yes)
    {
        session["CANCELEDPROP"] = "1";
    }
    else
    {
        session["CANCELEDPROP"] = "0";
    }

    return ActionResult.Success;
}
</code>```

答:
Finally I have found a solution by using CancelDlg from WixUIExtension.dll
(http://wixtoolset.org/documentation/manual/v3/wixui/dialog_reference/wixui_dialogs.html)

Add reference to WixUIExtension.dll (path on my computer is the next C:\Program Files (x86)\WiX Toolset v3.11\bin)

Add reference to icon that would be on the message box (Product.wxs):

< Binary Id="WixUI_Ico_Info" SourceFile="Images/MyIcon.ico" />

Control itself:

< Control Type="PushButton" Id="cancelBtn" Width="56" Height="17" X="300" Y="244" Cancel="yes">
    < Text>Cancel
    < Publish Event="SpawnDialog" Value="CancelDlg">1
< /Control>

Body:
I am developing an installation msi file using Wix toolset (in VS 2012) and faced with the problem that I can't add a confirmation dialog when user press button 'Cancel'. I tried to add also custom action dll with the message box, but if the function returns ActionResult.Failure, then my setup shows error dialog.

Original control:

<Control Type="PushButton" Id="progressCancelBtn" Width="56" Height="17" X="296" Y="244">
   <Text>Cancel</Text>
   <Publish Event="EndDialog" Value="Exit" />
</Control>

Try number 1:

public class CustomActions
    {
        [CustomAction]
        public static ActionResult ShowExitMessageBox(Session session)
        {
            DialogResult result = MessageBox.Show("Exit installation?", "Exit", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                return ActionResult.Failure;
            }
            else
            {
                return ActionResult.Success;
            }
        }
    }

Custom action:

 <CustomAction Id='ShowExitMsgBox' BinaryKey='CustomActions' DllEntry='ShowExitMessageBox' Execute='immediate'               Return='ignore'/>

    <Binary Id='CustomActions' SourceFile='$(var.CASourcesPath)\CustomActions.CA.dll'/>

And tried to use:

<Control Type="PushButton" Id="cancelBtn" Width="56" Height="17" X="300" Y="244" Cancel="yes">
    <Text>Cancel</Text>
    <Publish Event="DoAction" Value="ShowExitMsgBox">1</Publish>

</Control>

But it shows like failure, instead of cancellation.

Thank you for help in advance.

Update:

I changed my custom action C# code to the next:

public class CustomActions
    {
        [CustomAction]
        public static ActionResult ShowExitMessageBox(Session session)
        {
            DialogResult result = MessageBox.Show("Exit installation?", "Exit", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
            {
                session["CANCELEDPROP"] = "1";
            }
            else
            {
                session["CANCELEDPROP"] = "0";
            }

            return ActionResult.Success;
        }
    }

and WIX part:

// in Product.wxs
<Property Id="CANCELEDPROP" Secure="yes">0</Property>
// in UIFile.wxs
<Control Type="PushButton" Id="cancelBtn" Width="56" Height="17" X="300" Y="244" Cancel="yes">
    <Text>Cancel</Text>
    <Publish Event="DoAction" Value="ShowExitMsgBox">1</Publish>
    <Publish Event="EndDialog" Value="Exit">CANCELEDPROP=1</Publish>
</Control>

It works on the first page, but I get an error on progress page: "Windows installer has stopped working" after I pressed some button on my message box. :(
I have found out if I don't use message box, then everything works. It is strange.

Update 2:

I tried to use session.Message instead of Windows.Forms, but message box just doesn't appear. Strange.

[CustomAction]
public static ActionResult ShowExitMessageBox(Session session)
{
    Record record = new Record();
    record.FormatString = "Exit installation?";

    MessageResult result = session.Message(InstallMessage.Warning
                                                    | (InstallMessage)System.Windows.Forms.MessageBoxIcon.Warning
                                                    | (InstallMessage)System.Windows.Forms.MessageBoxButtons.YesNo,
                                                    record);

    if (result == MessageResult.Yes)
    {
        session["CANCELEDPROP"] = "1";
    }
    else
    {
        session["CANCELEDPROP"] = "0";
    }

    return ActionResult.Success;
}


问:
Dynamically change data adapters connection
I am using C#, .NET 4.5, VS2015.

I want to be able to change connection property of data adapter dynamically. (during run time).

Looking at connection property of data adapter, connection is a private setting:

```<code>private global::System.Data.SqlClient.SqlConnection _connection;

private void InitConnection() {
            this._connection = new global::System.Data.SqlClient.SqlConnection();
            this._connection.ConnectionString = global::Audit.Properties.Settings.Default.LoggingConnectionString;
        }
</code>```

Is it possible to change connection of table adapter during run time?

EDIT:

Interesting thing is that for table adapters with select commands, connection property is public, so it's not a problem changing it. For adapters with insert commands, connection is private and I don't know how to change it. Of course, I am speaking about components dragged directly from server explorer to design view of the dataset.

Example for select command (generated as internal global):

```<code> internal global::System.Data.SqlClient.SqlConnection Connection {
            get {
                if ((this._connection == null)) {
                    this.InitConnection();
                }
                return this._connection;
            }
</code>```

Example for insert command (generated as private):

```<code> private void InitCommandCollection() {
            this._commandCollection = new global::System.Data.IDbCommand[1];
            this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand();
            ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).Connection = new global::System.Data.SqlClient.SqlConnection(global::Audit.Properties.Settings.Default.LoggingConnectionString1);
</code>```

答:
I was able to overcome this limitation by creating my own ConnectionString property in the TableAdapter. You just need to make sure that it's part of the TableAdapter's namespace.</p>

```<code>public partial class MyTableAdapter
{
    public string ConnectionString
    {
        set
        {
            if ((this._commandCollection == null))
            {
                this.InitCommandCollection();
            }

            for (int index = 0; index < this._commandCollection.Length; index++)
            {
                this._commandCollection[index].Connection.ConnectionString = value;
            }
        }
    }
}
</code>```

Body:
I am using C#, .NET 4.5, VS2015.

I want to be able to change connection property of data adapter dynamically. (during run time).

Looking at connection property of data adapter, connection is a private setting:

private global::System.Data.SqlClient.SqlConnection _connection;

private void InitConnection() {
            this._connection = new global::System.Data.SqlClient.SqlConnection();
            this._connection.ConnectionString = global::Audit.Properties.Settings.Default.LoggingConnectionString;
        }

Is it possible to change connection of table adapter during run time?

EDIT:

Interesting thing is that for table adapters with select commands, connection property is public, so it's not a problem changing it. For adapters with insert commands, connection is private and I don't know how to change it. Of course, I am speaking about components dragged directly from server explorer to design view of the dataset.

Example for select command (generated as internal global):

 internal global::System.Data.SqlClient.SqlConnection Connection {
            get {
                if ((this._connection == null)) {
                    this.InitConnection();
                }
                return this._connection;
            }

Example for insert command (generated as private):

 private void InitCommandCollection() {
            this._commandCollection = new global::System.Data.IDbCommand[1];
            this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand();
            ((global::System.Data.SqlClient.SqlCommand)(this._commandCollection[0])).Connection = new global::System.Data.SqlClient.SqlConnection(global::Audit.Properties.Settings.Default.LoggingConnectionString1);

Body:
I was able to overcome this limitation by creating my own ConnectionString property in the TableAdapter. You just need to make sure that it's part of the TableAdapter's namespace.

public partial class MyTableAdapter
{
    public string ConnectionString
    {
        set
        {
            if ((this._commandCollection == null))
            {
                this.InitCommandCollection();
            }

            for (int index = 0; index < this._commandCollection.Length; index++)
            {
                this._commandCollection[index].Connection.ConnectionString = value;
            }
        }
    }
}


问:
Animating a UIView's alpha in sequence with UIViewPropertyAnimator
I have a UIView that I want to reveal after 0.5 seconds, and hide again after 0.5 seconds, creating a simple animation. My code is as follows:

```<code>    let animation = UIViewPropertyAnimator.init(duration: 0.5, curve: .linear) {
        self.timerBackground.alpha = 1
        let transition = UIViewPropertyAnimator.init(duration: 0.5, curve: .linear) {
            self.timerBackground.alpha = 0
        }
        transition.startAnimation(afterDelay: 0.5)
    }
    animation.startAnimation()
</code>```

When I test it out, nothing happens. I assume it's because they're both running at the same time, which would mean they cancel each other out, but isn't that what the "afterDelay" part should prevent?

If I run them separately, i.e. either fading from hidden to visible, or visible to hidden, it works, but when I try to run them in a sequence, it doesn't work.

My UIView is not opaque or hidden.

答:
You can use Timer, and add appearing / hiding animations blocks on every timer tick to your UIViewPropertyAnimatorobject.

Here's a codebase:

```<code>@IBOutlet weak var timerBackground: UIImageView!

private var timer: Timer?
private var isShown = false
private var viewAnimator = UIViewPropertyAnimator.init(duration: 0.5, curve: .linear)

override func viewDidLoad() {
    super.viewDidLoad()
    viewAnimator.addAnimations {
        self.timerBackground.alpha = 1
    }
    viewAnimator.startAnimation()
    isShown = true

    self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.startReversedAction), userInfo: nil, repeats: true)
}

func startReversedAction() {
    // stop the previous animations block if it did not have time to finish its movement
    viewAnimator.stopAnimation(true)
    viewAnimator.addAnimations ({
        self.timerBackground.alpha = self.isShown ? 0 : 1
    })
    viewAnimator.startAnimation()
    isShown  =  !isShown
}
</code>```

I've implemented the very similar behavior for dots jumping of iOS 10 Animations demo project.

Please, feel free to look at it to get more details.

Body:
I have a UIView that I want to reveal after 0.5 seconds, and hide again after 0.5 seconds, creating a simple animation. My code is as follows:

    let animation = UIViewPropertyAnimator.init(duration: 0.5, curve: .linear) {
        self.timerBackground.alpha = 1
        let transition = UIViewPropertyAnimator.init(duration: 0.5, curve: .linear) {
            self.timerBackground.alpha = 0
        }
        transition.startAnimation(afterDelay: 0.5)
    }
    animation.startAnimation()

When I test it out, nothing happens. I assume it's because they're both running at the same time, which would mean they cancel each other out, but isn't that what the "afterDelay" part should prevent?

If I run them separately, i.e. either fading from hidden to visible, or visible to hidden, it works, but when I try to run them in a sequence, it doesn't work.

My UIView is not opaque or hidden.

Body:
You can use Timer, and add appearing / hiding animations blocks on every timer tick to your UIViewPropertyAnimatorobject.

Here's a codebase:

@IBOutlet weak var timerBackground: UIImageView!

private var timer: Timer?
private var isShown = false
private var viewAnimator = UIViewPropertyAnimator.init(duration: 0.5, curve: .linear)

override func viewDidLoad() {
    super.viewDidLoad()
    viewAnimator.addAnimations {
        self.timerBackground.alpha = 1
    }
    viewAnimator.startAnimation()
    isShown = true

    self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.startReversedAction), userInfo: nil, repeats: true)
}

func startReversedAction() {
    // stop the previous animations block if it did not have time to finish its movement
    viewAnimator.stopAnimation(true)
    viewAnimator.addAnimations ({
        self.timerBackground.alpha = self.isShown ? 0 : 1
    })
    viewAnimator.startAnimation()
    isShown  =  !isShown
}

I've implemented the very similar behavior for dots jumping of iOS 10 Animations demo project.

Please, feel free to look at it to get more details.


问:
Horizontal Line In Login Page
Good day, I'm trying to design a login page similar to this one. The problem is whenever I add the View tag to create a horizontal line, and aligned it to the word "or". It doesn't achieved the same effect as shown in this picture. Instead it aligned itself - alignBottomLine.

答:
Here is how i would do it,

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E73A4A">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_margin="16dp">

    <View
        android:layout_width="200dp"
        android:layout_height="2dp"
        android:layout_centerInParent="true"
        android:background="#F6828F" />

    <TextView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="#E73A4A"
        android:text="or"
        android:textAlignment="center"
        android:textColor="#F6828F" />
</RelativeLayout>
</code>```

Title: Horizontal Line In Login Page

Body:
Here is how i would do it,

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E73A4A">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_margin="16dp">

    <View
        android:layout_width="200dp"
        android:layout_height="2dp"
        android:layout_centerInParent="true"
        android:background="#F6828F" />

    <TextView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="#E73A4A"
        android:text="or"
        android:textAlignment="center"
        android:textColor="#F6828F" />
</RelativeLayout>