问:
How to run linphone in android studio
I want to integrate android video chat in my app.I am trying out linphone but they just have provided source code with no documentation and no sample modules.I imported project in android studio just to get lot of errors.I did not find any tutorial on how to run it in android studio all the tutorials are outdated using eclipse.
So,is there any link on to run linphone in android studio so that i can start to explore it.Please help

答:
Did work for me on mac on this

Note :- the build script tries to read a file RELEASE.txt in the root of /ndk-bundle/. It has been removed since >= ndk 15.

You need add a RELEASE.TXT in the root with text containing following

r15c (64-bit).

Rest is all the same.

Title: How to run linphone in android studio


来源: stackexchange

问:
Cannot find terminal in android studio
I am using macOS X. I was using android studio in it. It was doing great before,but from today, when I open my android studio project, this is not showing any terminal on it. I can't find it from view> Tool Windows.</p>

答: Go to file->settings->keymap-> search terminal on top and it will show the shortcut assigned . Here is a pic for your understanding . You can also change the shortcut if you want .

ContentLicense: CC BY-SA 4.0

Title: Cannot find terminal in android studio

ContentLicense: CC BY-SA 3.0


问:
iPhone: starting an NSThread from a C++ object
I'm writing a game for the iPhone. Almost all the code is written in C++. Now I'd like to create a new thread using NSThread (I want to use the runLoop).

It's possible to mix objective-C and C++ if the code is written in a .mm file, which I did.

The problem is, that for creating a NSThread

```<code>NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(workerThreadFunction:) object:nil];
[myThread start];
</code>```

I need to pass "self" which (as far as I understand it) an Objective-C "id" - and a c++ object is not an objective-c object.

So - is there a way to use NSThread in a c++ aplication or am I forced to use pthreads?

Thanks!

答:
can I somehow create an objective-C object which - in it's constructor - takes a c++ function pointer as an argument which it calls later?

Sure. Like this:

```<code>//The C++ base
class ThreadBase
{
    virtual void Run() = 0;
};

typedef ThreadBase * (*ThreadCreator)();

//The ObjC wrapper

@interface ThreadStarter:NSObject
{
    ThreadCreator TheCreator;
}

-(void)Run;
-(id)init:(ThreadCreator)tc;
@end

@implementation ThreadStarter
-(id)init:(ThreadCreator)tc
{
    TheCreator = tc;
    return [super init];
}

-(void)Run
{
    (*TheCreator)()->Run();
}
@end

//
class MyThread: public ThreadBase
{
//...
};

ThreadBase *MyThreadCreator()
{
    return new MyThread();
}

//And finally usage

ThreadStarter *tc = [[ThreadStarter alloc]init:MyThreadCreator];
NSThread* myThread = [[NSThread alloc] initWithTarget:tc selector:@selector(Run) object:nil]; [myThread start];
</code>```

It's parametrized by a creator function because you wanted it so. But you can parametrize by class as well.

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a game for the iPhone. Almost all the code is written in C++. Now I'd like to create a new thread using NSThread (I want to use the runLoop).

It's possible to mix objective-C and C++ if the code is written in a .mm file, which I did.

The problem is, that for creating a NSThread

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(workerThreadFunction:) object:nil];
[myThread start];

I need to pass "self" which (as far as I understand it) an Objective-C "id" - and a c++ object is not an objective-c object.

So - is there a way to use NSThread in a c++ aplication or am I forced to use pthreads?

Thanks!

Body:
can I somehow create an objective-C object which - in it's constructor - takes a c++ function pointer as an argument which it calls later?

Sure. Like this:

//The C++ base
class ThreadBase
{
    virtual void Run() = 0;
};

typedef ThreadBase * (*ThreadCreator)();

//The ObjC wrapper

@interface ThreadStarter:NSObject
{
    ThreadCreator TheCreator;
}

-(void)Run;
-(id)init:(ThreadCreator)tc;
@end

@implementation ThreadStarter
-(id)init:(ThreadCreator)tc
{
    TheCreator = tc;
    return [super init];
}

-(void)Run
{
    (*TheCreator)()->Run();
}
@end

//
class MyThread: public ThreadBase
{
//...
};

ThreadBase *MyThreadCreator()
{
    return new MyThread();
}

//And finally usage

ThreadStarter *tc = [[ThreadStarter alloc]init:MyThreadCreator];
NSThread* myThread = [[NSThread alloc] initWithTarget:tc selector:@selector(Run) object:nil]; [myThread start];

It's parametrized by a creator function because you wanted it so. But you can parametrize by class as well.


问:
Javascript returns only one timestamp inside for loop
I want to generate a timestamp for each item inside the for loop but i am getting only one timestamp inside the loop.How can i make new timestamp for each item in the for loop in javascript.

```<code>for (var i = 0 ; i < 5; i++ ) { vm.workers[i].id = (new Date()).getTime(); }
</code>```

This one provides only one timestamp instead of 5 different timestamp can anyone tell me how to generate multiple timestamps inside the loop.

答:
A simple loop iteration can certainly take less than a millisecond to complete, hence you're getting the same timestamp.

Find a more reliable way to create id's such as a GUID.

Here's a function, taken from this S.O answer that creates GUID's:

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

console.log(guid())```

Body:
I want to generate a timestamp for each item inside the for loop but i am getting only one timestamp inside the loop.How can i make new timestamp for each item in the for loop in javascript.

for (var i = 0 ; i < 5; i++ ) { vm.workers[i].id = (new Date()).getTime(); }

This one provides only one timestamp instead of 5 different timestamp can anyone tell me how to generate multiple timestamps inside the loop.


问:
Match string in XText regardless of upper/lower case
I want to create a rule in XText that matches to a string, but does not care in what case the string is. For example, I want it to match against both "DUCK", "DucK" and "duck". Is there a more simple way of doing it than covering all cases, like:</p>

```<code>Rule:
     'Duck'|'DucK'|'DuCK'|... and so on
;
</code>```

答:
FYI.</p>

```<code>    language = StandardLanguage {
        ...
        parserGenerator = {
            options = {
                ignoreCase = true //Case Insensitive Keywords
            }
        }
        scopeProvider = {
            ignoreCase = true //Case Insensitive "name=ID"
        }
        ...
    }
</code>```

Body:
I want to create a rule in XText that matches to a string, but does not care in what case the string is. For example, I want it to match against both "DUCK", "DucK" and "duck". Is there a more simple way of doing it than covering all cases, like:

Rule:
     'Duck'|'DucK'|'DuCK'|... and so on
;

Body:
FYI.

    language = StandardLanguage {
        ...
        parserGenerator = {
            options = {
                ignoreCase = true //Case Insensitive Keywords
            }
        }
        scopeProvider = {
            ignoreCase = true //Case Insensitive "name=ID"
        }
        ...
    }


问:
Laravel Intervention/image memory_limit
In my floder I have 120MB of images. One image - near 3 MB. I try to use this code to resize them:

```<code>public function images_zip(Request $request){
    if($request->width < 1 || $request->hight < 1 || $request->width > 2000 || $request->hight >2000){
        return Redirect::back()->withErrors(['Некорректные входные данные']);
    }
    $files = Storage::disk('images')->files('/'.$request->name.'/image');
    $mime_types = array('image/gif','image/jpeg','image/png','image/svg+xml');
    ini_set('memory_limit','128M');
    foreach ($files as $file){
        if(in_array(File::mimeType($file),$mime_types)) {
            $img = Image::make(public_path() . '/' . $file);
                $img->resize($request->width, $request->hight);
                $img->save(public_path() . '/' . $file);
                $img->destroy();
        }
    }
    return \redirect()->back();
}
</code>```

But I take this error -

```<code>Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
</code>```

I tried to use ->destroy() and ini_set('memory_limit','128M') ,like people say, but it didnt help. My server have 128MB memory. Help me,please!

答:
This error is probably thrown by PHP. Try to change these lines in php.ini file and restart the server:

```<code>memory_limit = 128M
</code>```

You should also check this line:

```<code>max_execution_time = 30
</code>```

This is the max execution time of a script, which can cause you problems too.

But be aware that 134217728 bytes are exactly 128mb. So, this should not be effective at all. If you keep the same code, you will probably need more memory.

Title: Laravel Intervention/image memory_limit

Body:
In my floder I have 120MB of images. One image - near 3 MB. I try to use this code to resize them:

public function images_zip(Request $request){
    if($request->width < 1 || $request->hight < 1 || $request->width > 2000 || $request->hight >2000){
        return Redirect::back()->withErrors(['Некорректные входные данные']);
    }
    $files = Storage::disk('images')->files('/'.$request->name.'/image');
    $mime_types = array('image/gif','image/jpeg','image/png','image/svg+xml');
    ini_set('memory_limit','128M');
    foreach ($files as $file){
        if(in_array(File::mimeType($file),$mime_types)) {
            $img = Image::make(public_path() . '/' . $file);
                $img->resize($request->width, $request->hight);
                $img->save(public_path() . '/' . $file);
                $img->destroy();
        }
    }
    return \redirect()->back();
}

But I take this error -

Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)

I tried to use ->destroy() and ini_set('memory_limit','128M') ,like people say, but it didnt help. My server have 128MB memory. Help me,please!

Body:
This error is probably thrown by PHP. Try to change these lines in php.ini file and restart the server:

memory_limit = 128M

You should also check this line:

max_execution_time = 30

This is the max execution time of a script, which can cause you problems too.

But be aware that 134217728 bytes are exactly 128mb. So, this should not be effective at all. If you keep the same code, you will probably need more memory.


问:
Counting values from td's in jQuery

 I have a problem with jQuery script. I'm trying to make a simple counting loop, for each tr. I got a table like below, and I want to select the second td, multiply it by two and add to the third td and display the result in the fourth td.

https://codepen.io/adeowsky/pen/YEgVKG

I'm trying to make it with the for each loop like below ->

```<code><script>
(function($) {
    $('.sp-league-table tbody tr').each( function() {
        var pct = this.find('.data-pct').text();
        console.log(pct);
        //var pct = $('').hasClass('data-pct').text();
        //console.log(pct);
        var winy = $('.data-w').text();
        var losy = $('.data-l').text();

        /*var pkt = (winy*2) + (losy*2);
        $('.data-pct').text(pkt);*/
    });
})( jQuery );
</script>
</code>```

But it doesn't work for me, where is the reason?

答:
There are a couple of problems

Your table does not have the required class

you're not targeting the specific row's cells

You should explicitly parse the string values to integers

you've commented out the bit that does the calculation:

```<code>$(function(){

 $('.sp-league-table tbody tr').each( function() {
   var pct = $('.data-pct',this).text();

   var winy = parseInt($('.data-w',this).text(),10);
   var losy =parseInt($('.data-l',this).text(),10);

   var pkt = (winy*2) + (losy*2);
   $('.data-pct',this).text(pkt);
 });
})
</code>```

Updated: https://codepen.io/anon/pen/NwJjaO

Live example:

$(function(){

 $('.sp-league-table tbody tr').each( function() {
   var pct = $('.data-pct',this).text();

   var winy = parseInt($('.data-w',this).text(),10);
   var losy =parseInt($('.data-l',this).text(),10);

   var pkt = (winy*2) + (losy*2);
   $('.data-pct',this).text(pkt);
 });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, tr, td, th {
  border: 1px solid #000;
  border-collapse: collapse;
  padding: 10px;
}</code>```

      Name
      W
      L
      PCT

    Name 1
    12
    0
    x

    Name 2
    9
    3
    x

      Name
      W
      L
      PCT

    Name 1
    12
    0
    24

    Name 2
    6
    5
    17

```

Title: Counting values from td's in jQuery

Body:
 I have a problem with jQuery script. I'm trying to make a simple counting loop, for each tr. I got a table like below, and I want to select the second td, multiply it by two and add to the third td and display the result in the fourth td.

https://codepen.io/adeowsky/pen/YEgVKG

I'm trying to make it with the for each loop like below ->

But it doesn't work for me, where is the reason?

Body:
There are a couple of problems

Your table does not have the required class

you're not targeting the specific row's cells

You should explicitly parse the string values to integers

you've commented out the bit that does the calculation:

$(function(){

 $('.sp-league-table tbody tr').each( function() {
   var pct = $('.data-pct',this).text();

   var winy = parseInt($('.data-w',this).text(),10);
   var losy =parseInt($('.data-l',this).text(),10);

   var pkt = (winy*2) + (losy*2);
   $('.data-pct',this).text(pkt);
 });
})

Updated: https://codepen.io/anon/pen/NwJjaO

Live example:

$(function(){

 $('.sp-league-table tbody tr').each( function() {
   var pct = $('.data-pct',this).text();

   var winy = parseInt($('.data-w',this).text(),10);
   var losy =parseInt($('.data-l',this).text(),10);

   var pkt = (winy*2) + (losy*2);
   $('.data-pct',this).text(pkt);
 });
})

table, tr, td, th {
  border: 1px solid #000;
  border-collapse: collapse;
  padding: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="sp-league-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>W</th>
      <th>L</th>
      <th>PCT</th>
  </thead>
  <tr>
    <td>Name 1</td>
    <td class="data-w">12</td>
    <td class="data-l">0</td>
    <td class="data-pct">x</td>
  </tr>
  <tr>
    <td>Name 2</td>
    <td class="data-w">9</td>
    <td class="data-l">3</td>
    <td class="data-pct">x</td>
  </tr>
</table>

<table class="sp-league-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>W</th>
      <th>L</th>
      <th>PCT</th>
  </thead>
  <tr>
    <td>Name 1</td>
    <td class="data-w">12</td>
    <td class="data-l">0</td>
    <td class="data-pct">24</td>
  </tr>
  <tr>
    <td>Name 2</td>
    <td class="data-w">6</td>
    <td class="data-l">5</td>
    <td class="data-pct">17</td>
  </tr>
</table>


问:
Simple question from a very no experienced programmer
Simple question: This is a method I created

```<code>public void move()
{
    double radians = direction * Math.PI / 180;
    //change the x location by the x vector of the speed
    X_Coordinate += (int)(speed * Math.Cos(radians));

    //change the y location by the y vectior of the speed
    Y_Coordinate -= (int)(speed * Math.Sin(radians));
}
</code>```

How do I take a value enter into a text box, use a button called move, to call this method and display the result?

答:
Hook up the Click event of the button, and in the event handler you can access the entered value by TextBoxName.Text. You will probably need to parse the string value using int.Parse in order to use it in a calculation.

Your button will look something like this.

```<code><asp:Button ID="MoveBtn" runat="server" onclick="Move" Text="Move" />
</code>```

And then in your code behind

```<code>protected void Move(object sender, EventArgs e)
{
   // Call your move method here.
   // If it is in the same class, it's just move();
   // Otherwise you need a reference to your class so you can call it.
}
</code>```

Body:
Simple question: This is a method I created

public void move()
{
    double radians = direction * Math.PI / 180;
    //change the x location by the x vector of the speed
    X_Coordinate += (int)(speed * Math.Cos(radians));

    //change the y location by the y vectior of the speed
    Y_Coordinate -= (int)(speed * Math.Sin(radians));
}

How do I take a value enter into a text box, use a button called move, to call this method and display the result?

Body:
Hook up the Click event of the button, and in the event handler you can access the entered value by TextBoxName.Text. You will probably need to parse the string value using int.Parse in order to use it in a calculation.

Your button will look something like this.

<asp:Button ID="MoveBtn" runat="server" onclick="Move" Text="Move" />

And then in your code behind

protected void Move(object sender, EventArgs e)
{
   // Call your move method here.
   // If it is in the same class, it's just move();
   // Otherwise you need a reference to your class so you can call it.
}


问:
Embedding password in and Internal Console App
I'm about to release a console application onto one of our servers to be run by the task scheduler on a daily basis. Based on certain conditions, the application will email selected users through Office 365. In order to email users, of course, I'll need to use the credentials for an email account.

Given that this is an internal application on one of our servers, is embedding the username and password in the code safe? If not, what is the best practice to securely get around this?

If it helps, this is my code for the email function (written in C#):

```<code>String userName = "my.email@organization.ca";
String password = "myPassword";

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(user.getEmail()));
msg.From = new MailAddress(userName);
msg.Subject = "My Subject";
msg.Body = "My message";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "mail.office365.com";
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Port = 587;
client.EnableSsl = true;
client.Send(msg);
</code>```

Edit: I should add that only administrators have access to this specific server.

答:
is embedding the username and password in the code safe

Of course not. Storing credentials without decent protection is never safe. Every user having access to the code or the executable can extract the credentials.

If I were you, I would store those credentials in an encrypted file on the machine it runs in a place where only the service user can access it. Encrypt the file with a device-specific key, so even if other users can obtain the file, it is useless to them since they can't decrypt it.

Body:
I'm about to release a console application onto one of our servers to be run by the task scheduler on a daily basis. Based on certain conditions, the application will email selected users through Office 365. In order to email users, of course, I'll need to use the credentials for an email account.

Given that this is an internal application on one of our servers, is embedding the username and password in the code safe? If not, what is the best practice to securely get around this?

If it helps, this is my code for the email function (written in C#):

String userName = "my.email@organization.ca";
String password = "myPassword";

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(user.getEmail()));
msg.From = new MailAddress(userName);
msg.Subject = "My Subject";
msg.Body = "My message";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "mail.office365.com";
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Port = 587;
client.EnableSsl = true;
client.Send(msg);

Edit: I should add that only administrators have access to this specific server.


问:
SMTP Error: Could not connect to SMTP host. PHPMailer. PHP
PHPMailer is not working and throwing following error.

```<code>2017-12-04 13:34:14 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP y19sm20173980pgv.19 - gsmtp
2017-12-04 13:34:14 CLIENT -> SERVER: EHLO solutions.proprompt.com
2017-12-04 13:34:14 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [103.58.144.11]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-12-04 13:34:14 CLIENT -> SERVER: STARTTLS
2017-12-04 13:34:14 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
SMTP Error: Could not connect to SMTP host.
2017-12-04 13:34:14 CLIENT -> SERVER: QUIT
2017-12-04 13:34:15
2017-12-04 13:34:15
SMTP Error: Could not connect to SMTP host.
Message could not be sent.Mailer Error: SMTP Error: Could not connect to SMTP host.
</code>```

It was working properly before. I have used following lines of code:

```<code>$mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'some@email.com';                 // SMTP username
    $mail->Password = 'somepassword';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;
</code>```

Can anyone tell me where it went wrong?

答:
Following lines of code solved this issue.</p>

```<code>$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
</code>```

Body:
PHPMailer is not working and throwing following error.

2017-12-04 13:34:14 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP y19sm20173980pgv.19 - gsmtp
2017-12-04 13:34:14 CLIENT -> SERVER: EHLO solutions.proprompt.com
2017-12-04 13:34:14 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [103.58.144.11]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-12-04 13:34:14 CLIENT -> SERVER: STARTTLS
2017-12-04 13:34:14 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
SMTP Error: Could not connect to SMTP host.
2017-12-04 13:34:14 CLIENT -> SERVER: QUIT
2017-12-04 13:34:15
2017-12-04 13:34:15
SMTP Error: Could not connect to SMTP host.
Message could not be sent.Mailer Error: SMTP Error: Could not connect to SMTP host.

It was working properly before. I have used following lines of code:

$mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'some@email.com';                 // SMTP username
    $mail->Password = 'somepassword';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;

Can anyone tell me where it went wrong?

Body:
Following lines of code solved this issue.

$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);


问:
Python3.x Prime Number List with while loop
```<code>def prime(upper):
    while upper >=2:
        for num in range(2, upper + 1):
            prime = True
            for i in range(2, num):
                if (num % i == 0):
                    prime = False
            if prime:
                print(num, end=",")
                if num == upper:   #I think there is a problem here
                   break
prime(7)
</code>```

How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...

答:
EDIT:

I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)

```<code>def is_prime(n):
    """"pre-condition: n is a nonnegative integer
    post-condition: return True if n is prime and False otherwise."""
    if n < 2:
         return False;
    if n % 2 == 0:
         return n == 2  # return False
    k = 3
    while k*k <= n:
         if n % k == 0:
             return False
         k += 2
    return True
</code>```

You should use this function.

BEFORE EDIT:

I would use the is_prime function from here. You can use another way.

And, I would suggest this code for you:

```<code>def is_prime(Number):
    return 2 in [Number, 2**Number%Number]

def prime(upper):
    print([num for num in range(2, upper + 1) if is_prime(num)])

prime(7)
</code>```

Output:

```<code>[2, 3, 5, 7]
</code>```

But if you insist on using only while loop, you can modify your prime function as:

```<code>def prime(upper):
    num = 2
    while num <= upper:
        if is_prime(num):
            print(num, end = ",")
        num += 1
</code>```

Then, output will be:

```<code>2,3,5,7,
</code>```

Body:
def prime(upper):
    while upper >=2:
        for num in range(2, upper + 1):
            prime = True
            for i in range(2, num):
                if (num % i == 0):
                    prime = False
            if prime:
                print(num, end=",")
                if num == upper:   #I think there is a problem here
                   break
prime(7)

How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...

Body:
EDIT:

I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)

def is_prime(n):
    """"pre-condition: n is a nonnegative integer
    post-condition: return True if n is prime and False otherwise."""
    if n < 2:
         return False;
    if n % 2 == 0:
         return n == 2  # return False
    k = 3
    while k*k <= n:
         if n % k == 0:
             return False
         k += 2
    return True

You should use this function.

BEFORE EDIT:

I would use the is_prime function from here. You can use another way.

And, I would suggest this code for you:

def is_prime(Number):
    return 2 in [Number, 2**Number%Number]

def prime(upper):
    print([num for num in range(2, upper + 1) if is_prime(num)])

prime(7)

Output:

[2, 3, 5, 7]

But if you insist on using only while loop, you can modify your prime function as:

def prime(upper):
    num = 2
    while num <= upper:
        if is_prime(num):
            print(num, end = ",")
        num += 1

Then, output will be:

2,3,5,7,


问:
"Given parent is not an ancestor of this virtual file" error when adding Spring library
I'm implementing some web app that uses numerous libraries (Spring, Log4j, Jackson,...). Until now, everything worked ok, but if I try to add another Spring library (webmvc - I'm implementing REST API that needs DispatcherServlet class), I'm getting the following error when deploying on JBoss AS 7.1.1:

```<code>    2017-11-28 08:31:26,678 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) JBAS015876: Starting deployment of "Office.war"
2017-11-28 08:31:27,973 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-5) MSC00001: Failed to start service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: Failed to process phase PARSE of subdeployment "Office.war" of deployment "Office.ear"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) [rt.jar:1.6.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) [rt.jar:1.6.0_45]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_45]
Caused by: java.lang.IllegalArgumentException: Given parent is not an ancestor of this virtual file
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:116) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:110) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.as.web.deployment.TldParsingDeploymentProcessor.processTlds(TldParsingDeploymentProcessor.java:107)
    at org.jboss.as.web.deployment.TldParsingDeploymentProcessor.deploy(TldParsingDeploymentProcessor.java:83)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    ... 5 more

2017-11-28 08:31:28,224 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS015870: Deploy of deployment "Office.ear" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE" => "org.jboss.msc.service.StartException in service jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE: Failed to process phase PARSE of subdeployment \"Office.war\" of deployment \"Office.ear\""}}
2017-11-28 08:31:28,336 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-8) JBAS015877: Stopped deployment Office.war in 113ms
2017-11-28 08:31:28,339 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment Office.ear in 116ms
2017-11-28 08:31:28,341 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 1) JBAS014774: Service status report
JBAS014777:   Services which failed to start:      service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: Failed to process phase PARSE of subdeployment "Office.war" of deployment "Office.ear"

2017-11-28 08:31:28,347 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE" => "org.jboss.msc.service.StartException in service jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE: Failed to process phase PARSE of subdeployment \"Office.war\" of deployment \"Office.ear\""}}}}
</code>```

Here's my EAR deployment assembly

and my web module assembly.

I have no idea why that error appears, other libraries cause no trouble. Any suggestions?

EDIT 1:

I noticed another strange thing. In Eclipse "Add and remove" dialog, there are three entries of Spring webmvc jars at available resources section.

Where do those entries come from? Could it be Eclipse issue?

EDIT 2:

I've moved all jars directly into lib folder (instead of subfolders like lib/spring/spring-webmvc-4.0.6.jar) and I deployed my app successfully. Can anyone explain why that error disappeared after moving jars?

答: I have put all jars directly into lib folder (and NOT into subfolders like lib/spring/spring-webmvc.4.0.6.jar) and I succeeded with deployment. Not sure why - It would be great if someone can explain what is the reason.

Body:
I'm implementing some web app that uses numerous libraries (Spring, Log4j, Jackson,...). Until now, everything worked ok, but if I try to add another Spring library (webmvc - I'm implementing REST API that needs DispatcherServlet class), I'm getting the following error when deploying on JBoss AS 7.1.1:

    2017-11-28 08:31:26,678 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) JBAS015876: Starting deployment of "Office.war"
2017-11-28 08:31:27,973 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-5) MSC00001: Failed to start service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: Failed to process phase PARSE of subdeployment "Office.war" of deployment "Office.ear"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) [rt.jar:1.6.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) [rt.jar:1.6.0_45]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_45]
Caused by: java.lang.IllegalArgumentException: Given parent is not an ancestor of this virtual file
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:116) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:110) [jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
    at org.jboss.as.web.deployment.TldParsingDeploymentProcessor.processTlds(TldParsingDeploymentProcessor.java:107)
    at org.jboss.as.web.deployment.TldParsingDeploymentProcessor.deploy(TldParsingDeploymentProcessor.java:83)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    ... 5 more

2017-11-28 08:31:28,224 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS015870: Deploy of deployment "Office.ear" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE" => "org.jboss.msc.service.StartException in service jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE: Failed to process phase PARSE of subdeployment \"Office.war\" of deployment \"Office.ear\""}}
2017-11-28 08:31:28,336 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-8) JBAS015877: Stopped deployment Office.war in 113ms
2017-11-28 08:31:28,339 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment Office.ear in 116ms
2017-11-28 08:31:28,341 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 1) JBAS014774: Service status report
JBAS014777:   Services which failed to start:      service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.subunit."Office.ear"."Office.war".PARSE: Failed to process phase PARSE of subdeployment "Office.war" of deployment "Office.ear"

2017-11-28 08:31:28,347 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE" => "org.jboss.msc.service.StartException in service jboss.deployment.subunit.\"Office.ear\".\"Office.war\".PARSE: Failed to process phase PARSE of subdeployment \"Office.war\" of deployment \"Office.ear\""}}}}

Here's my EAR deployment assembly

and my web module assembly.

I have no idea why that error appears, other libraries cause no trouble. Any suggestions?

EDIT 1:

I noticed another strange thing. In Eclipse "Add and remove" dialog, there are three entries of Spring webmvc jars at available resources section.

Where do those entries come from? Could it be Eclipse issue?

EDIT 2:

I've moved all jars directly into lib folder (instead of subfolders like lib/spring/spring-webmvc-4.0.6.jar) and I deployed my app successfully. Can anyone explain why that error disappeared after moving jars?


问:
SQLAlchemy, clear database content but don't drop the schema
I'm developing a Pylons app which is based on exisitng database, so I'm using reflection. I have an SQL file with the schema that I used to create my test database. That's why I can't simply use drop_all and create_all.

I would like to write some unit tests and I faced the problem of clearing the database content after each test. I just want to erase all the data but leave the tables intact. Is this possible?

The application uses Postgres and this is what has to be used also for the tests.

答:
How about using truncate:

TRUNCATE [ TABLE ] name [, ...]

(http://www.postgresql.org/docs/8.4/static/sql-truncate.html)

This will delete all the records in the table, but leave the schema in tact.


问:
Override value from ui-iconpicker Library - Angular
I'm using the following library to be able to select an icon in an input field for angular.

https://github.com/justin-lau/ui-iconpicker

What I've tried

```<code><!-- Generates iconpicker button -->
<ui-iconpicker ng-model="icon"
               groups="font-awesome">
</ui-iconpicker>

<!-- input field with icon string that will be stored in DB -->
<input ng-model="icon"
       type="text"
       class="form-control"
       placeholder="Select Icon"
       name="icon"
       disabled>
</code>```

I have this JSON string stored in my database

```<code>"icon":"fa fa-lg fa-heart"
</code>```

But somehow I can't or don't know how to override the default value from this ui-iconpicker library.

My ng-model icon will be set to fa fa-lg fa-glass by loading my page again and overrides my "fa fa-lg fa-heart"

To get the data I have an initialise function that will get the object with the icon by the way. But that gets ignored or overrided by the library functionality. What I would like is to override this value in the controller again.

Any help is appreciated.

答:
Figured it out, didn't know this would work but it's a simple solution. I thought the library would work without the brackets but guess I was just wrong.</p>

```<code><ui-iconpicker ng-model="icon"
               value="<% icon %>" <!-- or use default angular brackets {{ icon }} -->
               groups="font-awesome">
</ui-iconpicker>
</code>```

Body:
I'm using the following library to be able to select an icon in an input field for angular.

https://github.com/justin-lau/ui-iconpicker

What I've tried

<ui-iconpicker ng-model="icon"
               groups="font-awesome">
</ui-iconpicker>

<input ng-model="icon"
       type="text"
       class="form-control"
       placeholder="Select Icon"
       name="icon"
       disabled>

I have this JSON string stored in my database

"icon":"fa fa-lg fa-heart"

But somehow I can't or don't know how to override the default value from this ui-iconpicker library.

My ng-model icon will be set to fa fa-lg fa-glass by loading my page again and overrides my "fa fa-lg fa-heart"

To get the data I have an initialise function that will get the object with the icon by the way. But that gets ignored or overrided by the library functionality. What I would like is to override this value in the controller again.

Any help is appreciated.

Body:
Figured it out, didn't know this would work but it's a simple solution. I thought the library would work without the brackets but guess I was just wrong.

<ui-iconpicker ng-model="icon"
               value="<% icon %>" <!-- or use default angular brackets {{ icon }} -->
               groups="font-awesome">
</ui-iconpicker>


问:
Rotating an SKShapeNode along its center
I have an SKShapeNode (rectangle in this case) which I am trying to rotate along its center. However it is rotating along the screen's bottom left point. Since I cannot set an anchor point for SKShapeNode, how can I achieve my requirement (to rotate the shape along its centre). This is the code I'm trying.

```<code>    let rectangle = SKShapeNode()
    rectangle.path = UIBezierPath(rect: CGRectMake(view.frame.width/4, view.frame.height/2, view.frame.width/2, view.frame.width/2)).CGPath
    rectangle.fillColor = UIColor.yellowColor()
    rectangle.strokeColor = UIColor.yellowColor()

    let oneRevolution = SKAction.rotateByAngle(360, duration: 100.0)
    let repeat = SKAction.repeatActionForever(oneRevolution)
    rectangle.runAction(repeat)
</code>```

答:
We have to explicitly center the SKShapeNode before applying rotation.

```<code>    import SpriteKit
    import PlaygroundSupport

    let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
    let skview = SKView(frame: bounds)

    PlaygroundPage.current.liveView = skview
</code>```

In the first and second examples below, this is done by setting x and y parameters while initializing the rectangle, and then setting the position property.

```<code>    let first = SKShapeNode(rect: CGRect(x:-20, y:-20, width: 40, height: 40))
    first.position = CGPoint(x: 70, y: 30)

    let second = SKShapeNode(rect: CGRect(x:-20, y:-20, width: 40, height: 40))
    second.position = CGPoint(x: 70, y: 30)
    second.zRotation = CGFloat.pi * 0.15
    second.strokeColor = .red
</code>```

In the third example below, this is done by setting centered to true while initializing the shape, and then setting the position property.

```<code>    let path = CGMutablePath();
    path.move(to: CGPoint(x: 50,y: 10))
    path.addLine(to: CGPoint(x: 90, y: 10))
    path.addLine(to: CGPoint(x: 90, y: 50))
    path.addLine(to: CGPoint(x: 50, y: 50))
    path.addLine(to: CGPoint(x: 50, y: 10))

    let third = SKShapeNode(path: path, centered: true);
    third.position = CGPoint(x: 70,y: 30);
    third.zRotation = CGFloat.pi * 0.35
    third.strokeColor = .yellow

    let scene = SKScene(size: CGSize(width: 400, height: 200))
    scene.scaleMode = SKSceneScaleMode.aspectFill
    scene.size = skview.bounds.size
    scene.addChild(first);
    scene.addChild(second);
    scene.addChild(third);
    skview.presentScene(scene);
</code>```

Body:
I have an SKShapeNode (rectangle in this case) which I am trying to rotate along its center. However it is rotating along the screen's bottom left point. Since I cannot set an anchor point for SKShapeNode, how can I achieve my requirement (to rotate the shape along its centre). This is the code I'm trying.

    let rectangle = SKShapeNode()
    rectangle.path = UIBezierPath(rect: CGRectMake(view.frame.width/4, view.frame.height/2, view.frame.width/2, view.frame.width/2)).CGPath
    rectangle.fillColor = UIColor.yellowColor()
    rectangle.strokeColor = UIColor.yellowColor()

    let oneRevolution = SKAction.rotateByAngle(360, duration: 100.0)
    let repeat = SKAction.repeatActionForever(oneRevolution)
    rectangle.runAction(repeat)

Body:
We have to explicitly center the SKShapeNode before applying rotation.

    import SpriteKit
    import PlaygroundSupport

    let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
    let skview = SKView(frame: bounds)

    PlaygroundPage.current.liveView = skview

In the first and second examples below, this is done by setting x and y parameters while initializing the rectangle, and then setting the position property.

    let first = SKShapeNode(rect: CGRect(x:-20, y:-20, width: 40, height: 40))
    first.position = CGPoint(x: 70, y: 30)

    let second = SKShapeNode(rect: CGRect(x:-20, y:-20, width: 40, height: 40))
    second.position = CGPoint(x: 70, y: 30)
    second.zRotation = CGFloat.pi * 0.15
    second.strokeColor = .red

In the third example below, this is done by setting centered to true while initializing the shape, and then setting the position property.

    let path = CGMutablePath();
    path.move(to: CGPoint(x: 50,y: 10))
    path.addLine(to: CGPoint(x: 90, y: 10))
    path.addLine(to: CGPoint(x: 90, y: 50))
    path.addLine(to: CGPoint(x: 50, y: 50))
    path.addLine(to: CGPoint(x: 50, y: 10))

    let third = SKShapeNode(path: path, centered: true);
    third.position = CGPoint(x: 70,y: 30);
    third.zRotation = CGFloat.pi * 0.35
    third.strokeColor = .yellow

    let scene = SKScene(size: CGSize(width: 400, height: 200))
    scene.scaleMode = SKSceneScaleMode.aspectFill
    scene.size = skview.bounds.size
    scene.addChild(first);
    scene.addChild(second);
    scene.addChild(third);
    skview.presentScene(scene);


问:
How to place the last
 on the right side of my page?
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>Home</li>
                <li>About</li>
                <li>Contact</li>
                <li>
                    <div class="flagChangeCountry">
                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div></code>```

i want to move this image to right side which is in div. here it is.

```<code><li>
    <div class="flagChangeCountry">
        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
    </div>
</li>
</code>```

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.

答:
You need to set a width to the ul, like this:

```<code>  ul{
    float:left;
    width: 100%;
  }
</code>```

and here's a working example in jsfiddle:

https://jsfiddle.net/d7dtm4we/

Edit: I copied the jsfiddle, to the code snippet, and added the width 100% vs no set width

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}

ul.nav{
  margin: 0;
  padding: 0;
  float:left;
  width: 100%;
}

ul.nav2{
  margin: 0;
  padding: 0;
  float:left;
}

ul li {
    list-style: none;
    float:left;
    padding: 5px
}

ul li:last-child {
     float: right;
}

.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>            <ul class="nav navbar-nav">
                <li>Home</li>
                <li>About</li>
                <li>Contact</li>
                <li>
                    <div class="flagChangeCountry">
                      <img src="http://satyr.io/32x20?flag=gbr" />
                    </div>
                </li>
            </ul>
            <ul class="nav2 navbar-nav">
                <li>Home</li>
                <li>About</li>
                <li>Contact</li>
                <li>
                    <div class="flagChangeCountry">
                      <img src="http://satyr.io/32x20?flag=gbr" />
                    </div>
                </li>
            </ul></code>```

Title: How to place the last <li> on the right side of my page?

Body:
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>

Home

About

Contact

                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

i want to move this image to right side which is in div. here it is.

        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.

Body:
You need to set a width to the ul, like this:

  ul{
    float:left;
    width: 100%;
  }

and here's a working example in jsfiddle:

https://jsfiddle.net/d7dtm4we/

Edit: I copied the jsfiddle, to the code snippet, and added the width 100% vs no set width

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}

ul.nav{
  margin: 0;
  padding: 0;
  float:left;
  width: 100%;
}

ul.nav2{
  margin: 0;
  padding: 0;
  float:left;
}

ul li {
    list-style: none;
    float:left;
    padding: 5px
}

ul li:last-child {
     float: right;
}

.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}

            <ul class="nav navbar-nav">
                <li><a runat="server" href="/">Home</a></li>
                <li><a runat="server" href="/About.aspx">About</a></li>
                <li><a runat="server" href="/Contact.aspx">Contact</a></li>
                <li>
                    <div class="flagChangeCountry">
                      <img src="http://satyr.io/32x20?flag=gbr" />
                    </div>
                </li>
            </ul>
            <ul class="nav2 navbar-nav">
                <li><a runat="server" href="/">Home</a></li>
                <li><a runat="server" href="/About.aspx">About</a></li>
                <li><a runat="server" href="/Contact.aspx">Contact</a></li>
                <li>
                    <div class="flagChangeCountry">
                      <img src="http://satyr.io/32x20?flag=gbr" />
                    </div>
                </li>
            </ul>


问:
Protocol Buffers: How to parse a .proto file in Java
I am trying to dynamically parse a given .proto file in Java to decode a Protobuf-encoded binary.

I have the following parsing method, in which the "proto" string contains the content of the .proto file:

```<code>public static Descriptors.FileDescriptor parseProto (String proto) throws InvalidProtocolBufferException, Descriptors.DescriptorValidationException {
        DescriptorProtos.FileDescriptorProto descriptorProto = DescriptorProtos.FileDescriptorProto.parseFrom(proto.getBytes());
        return Descriptors.FileDescriptor.buildFrom(descriptorProto, null);
}
</code>```

Though, on execution the previous method throws an exception with the message "Protocol message tag had invalid wire type.". I use the example .proto file from Google so I guess it is valid: https://github.com/google/protobuf/blob/master/examples/addressbook.proto

Here is the stack trace:

```<code>15:43:24.707 [pool-1-thread-1] ERROR com.github.whiver.nifi.processor.ProtobufDecoderProcessor - ProtobufDecoderProcessor[id=42c8ab94-2d8a-491b-bd99-b4451d127ae0] Protocol message tag had invalid wire type.
com.google.protobuf.InvalidProtocolBufferException$InvalidWireTypeException: Protocol message tag had invalid wire type.
    at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:115)
    at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:551)
    at com.google.protobuf.GeneratedMessageV3.parseUnknownField(GeneratedMessageV3.java:293)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:88)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:53)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:773)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:768)
    at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:163)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:197)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:209)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:214)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.parseFrom(DescriptorProtos.java:260)
    at com.github.whiver.nifi.parser.SchemaParser.parseProto(SchemaParser.java:9)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.lambda$onTrigger$0(ProtobufDecoderProcessor.java:103)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:895)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:62)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.onTrigger(ProtobufDecoderProcessor.java:100)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:251)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:245)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Any idea?
Thank you!

答:
Don't use java String to hold the protobuf payload. The issue is that String does translations behind the scenes, and makes assumptions about character sets.

Protobuf works on byte arrays, and the exact representation in the array has to be unchanged. Going to and from String does not work.

Body:
I am trying to dynamically parse a given .proto file in Java to decode a Protobuf-encoded binary.

I have the following parsing method, in which the "proto" string contains the content of the .proto file:

public static Descriptors.FileDescriptor parseProto (String proto) throws InvalidProtocolBufferException, Descriptors.DescriptorValidationException {
        DescriptorProtos.FileDescriptorProto descriptorProto = DescriptorProtos.FileDescriptorProto.parseFrom(proto.getBytes());
        return Descriptors.FileDescriptor.buildFrom(descriptorProto, null);
}

Though, on execution the previous method throws an exception with the message "Protocol message tag had invalid wire type.". I use the example .proto file from Google so I guess it is valid: https://github.com/google/protobuf/blob/master/examples/addressbook.proto

Here is the stack trace:

15:43:24.707 [pool-1-thread-1] ERROR com.github.whiver.nifi.processor.ProtobufDecoderProcessor - ProtobufDecoderProcessor[id=42c8ab94-2d8a-491b-bd99-b4451d127ae0] Protocol message tag had invalid wire type.
com.google.protobuf.InvalidProtocolBufferException$InvalidWireTypeException: Protocol message tag had invalid wire type.
    at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:115)
    at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:551)
    at com.google.protobuf.GeneratedMessageV3.parseUnknownField(GeneratedMessageV3.java:293)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:88)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.<init>(DescriptorProtos.java:53)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:773)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet$1.parsePartialFrom(DescriptorProtos.java:768)
    at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:163)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:197)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:209)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:214)
    at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
    at com.google.protobuf.DescriptorProtos$FileDescriptorSet.parseFrom(DescriptorProtos.java:260)
    at com.github.whiver.nifi.parser.SchemaParser.parseProto(SchemaParser.java:9)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.lambda$onTrigger$0(ProtobufDecoderProcessor.java:103)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:895)
    at org.apache.nifi.util.MockProcessSession.write(MockProcessSession.java:62)
    at com.github.whiver.nifi.processor.ProtobufDecoderProcessor.onTrigger(ProtobufDecoderProcessor.java:100)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:251)
    at org.apache.nifi.util.StandardProcessorTestRunner$RunProcessor.call(StandardProcessorTestRunner.java:245)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Any idea?
Thank you!


问:
want to remove legend in mpAndroidchart graph
want to remove legend in mpAndroidchart graph

答:
Recently i found it add line</p>

```<code>               mChart.getLegend().setEnabled(false);
</code>```

Body:
Recently i found it add line

               mChart.getLegend().setEnabled(false);


问:
Scratch-Based Movement in Java
I am trying to write a program where an object moves in a direction at a certain speed. Java does not have any built in function to determine direction. How would I write the Scratch Code below in Java? Also is there a way to make an object point at another object?

Screenshot of Scratch code to make object move in a direction or point toward mouse

I want the code to look like this:

```<code>public void move(int direction, int distance) {
    // 0 degrees is up, 90 is right, 180 is down, 270 is left.
}
</code>```

Also if you feel there is a better way to ask this question, please give me tips, this is my first question on this site.

答:
Well, I figured it out with a friend who's very good at geometry.
These are the functions we came up with:

```<code>// Movement
public void move(int speed) {
    x += speed * Math.cos(direction * Math.PI / 180);
    y += speed * Math.sin(direction * Math.PI / 180);
}
// Pointing toward an object
public void pointToward(SObject target) {
    direction = Math.atan2(target.y - y, target.x - x) * (180 / Math.PI);
}
// Pointing toward the mouse
public void pointTowardMouse() {
    direction = Math.atan2(Main.mouse.getY() - y, Main.mouse.getX() - x) * (180 / Math.PI);
}
// Ensure that the degrees of rotation stay between 0 and 359
public void turn(int degrees) {
    double newDir = direction;
    newDir += degrees;
    if (degrees > 0) {
        if (newDir > 359) {
            newDir -= 360;
        }
    } else if (degrees < 0) {
        if (newDir < 0) {
            newDir += 360;
        }
    }
    direction = newDir;
}
</code>```

I guess this can help someone else who needs rotational movement in their game.

Title: Scratch-Based Movement in Java

Body:
I am trying to write a program where an object moves in a direction at a certain speed. Java does not have any built in function to determine direction. How would I write the Scratch Code below in Java? Also is there a way to make an object point at another object?

Screenshot of Scratch code to make object move in a direction or point toward mouse

I want the code to look like this:

public void move(int direction, int distance) {
    // 0 degrees is up, 90 is right, 180 is down, 270 is left.
}

Also if you feel there is a better way to ask this question, please give me tips, this is my first question on this site.

Body:
Well, I figured it out with a friend who's very good at geometry.
These are the functions we came up with:

// Movement
public void move(int speed) {
    x += speed * Math.cos(direction * Math.PI / 180);
    y += speed * Math.sin(direction * Math.PI / 180);
}
// Pointing toward an object
public void pointToward(SObject target) {
    direction = Math.atan2(target.y - y, target.x - x) * (180 / Math.PI);
}
// Pointing toward the mouse
public void pointTowardMouse() {
    direction = Math.atan2(Main.mouse.getY() - y, Main.mouse.getX() - x) * (180 / Math.PI);
}
// Ensure that the degrees of rotation stay between 0 and 359
public void turn(int degrees) {
    double newDir = direction;
    newDir += degrees;
    if (degrees > 0) {
        if (newDir > 359) {
            newDir -= 360;
        }
    } else if (degrees < 0) {
        if (newDir < 0) {
            newDir += 360;
        }
    }
    direction = newDir;
}

I guess this can help someone else who needs rotational movement in their game.


问:
Django: jQuery autocomplete with multiple queryset
I am trying to code an autocomplete for django which would display multiple queryset instead of a single list, an example of another site that have this implementation can be found here: https://www.uala.it/

Now i was able to send in a queryset the objects of two model:

```<code>def multi_autocomplete(request):
    if request.is_ajax():
        # In base a cosa sta scrivendo l'utente mostro un set di aziende.
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query)
        treatments = Treatment.objects.filter(name__icontains=query)
        results = []
        for company in companies:
            place_json = company.name
            results.append(place_json)
        for treatment in treatments:
            place_json = treatment.name
            results.append(place_json)
        data = json.dumps(results)
    return HttpResponse(data, "application/json")
</code>```

As you can see i'm returning the json.dumps with the data from the two models, how can I change the ui to show the values in different columns like in the link i provided?

答:
Try to send the result in dictionary format and handle the same in autocomplete ajax response handler,

```<code>clist = []
tlist = []

for company in companies:
    clist.append(company.name)
for treatment in treatments:
    tlist.append(treatment)
data = json.dumps({"companies":clist, "treatments":tlist})
return HttpResponse(data, "application/json")
</code>```

Autocomplete AJAX handling

```<code>$("#input_autocomplete").autocomplete({
        source: function(request, response) {

            $.ajax({
                type:"GET",
                cache:false,
                data:{
                    'term': request.term,
                },
                url: "{% url 'treatment-autocomplete' %}",
                success:function(data) {
                    $("#input_autocomplete").removeClass('ui-autocomplete-loading');
                    $('#companyList').empty();
                    $('#treatmentList').empty();
                    $.each(data['companies'], function(i, item) {
                       $('#companyList').append(item);
                    });
                    $.each(data['treatments'], function(i, item) {
                       $('#treatmentList').append(item);
                    });
                }
           });

        },
        error: function(data) {
            $('#input_autocomplete').removeClass('ui-autocomplete-loading');
        }
         minLength: 1,
        open: function() {},
        close: function() {},
        focus: function(event,ui) {},
        select: function(event, ui) {}
</code>```

});

Body:
I am trying to code an autocomplete for django which would display multiple queryset instead of a single list, an example of another site that have this implementation can be found here: https://www.uala.it/

Now i was able to send in a queryset the objects of two model:

def multi_autocomplete(request):
    if request.is_ajax():
        # In base a cosa sta scrivendo l'utente mostro un set di aziende.
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query)
        treatments = Treatment.objects.filter(name__icontains=query)
        results = []
        for company in companies:
            place_json = company.name
            results.append(place_json)
        for treatment in treatments:
            place_json = treatment.name
            results.append(place_json)
        data = json.dumps(results)
    return HttpResponse(data, "application/json")

As you can see i'm returning the json.dumps with the data from the two models, how can I change the ui to show the values in different columns like in the link i provided?

Body:
Try to send the result in dictionary format and handle the same in autocomplete ajax response handler,

clist = []
tlist = []

for company in companies:
    clist.append(company.name)
for treatment in treatments:
    tlist.append(treatment)
data = json.dumps({"companies":clist, "treatments":tlist})
return HttpResponse(data, "application/json")

Autocomplete AJAX handling

$("#input_autocomplete").autocomplete({
        source: function(request, response) {

            $.ajax({
                type:"GET",
                cache:false,
                data:{
                    'term': request.term,
                },
                url: "{% url 'treatment-autocomplete' %}",
                success:function(data) {
                    $("#input_autocomplete").removeClass('ui-autocomplete-loading');
                    $('#companyList').empty();
                    $('#treatmentList').empty();
                    $.each(data['companies'], function(i, item) {
                       $('#companyList').append(item);
                    });
                    $.each(data['treatments'], function(i, item) {
                       $('#treatmentList').append(item);
                    });
                }
           });

        },
        error: function(data) {
            $('#input_autocomplete').removeClass('ui-autocomplete-loading');
        }
         minLength: 1,
        open: function() {},
        close: function() {},
        focus: function(event,ui) {},
        select: function(event, ui) {}

});


问:
HTTP Host Field with empty value, by response 400
when executed this command:

```<code>curl -H "Host:" http://127.0.0.1
</code>```

it response 400 Bad request.

from http rfc:

If the requested URI does not include an Internet host name for the service being requested, then the Host header field MUST be given with an empty value.

why?

答:
Because -H "Host:" removes the header altogether. See the docs for -H, --header :

[...] Remove an internal header by giving a replacement without content on the right side of the colon, as in: -H "Host:". If you send the custom header with no-value then its header must be terminated with a semicolon, such as -H "X-Custom-Header;" to send "X-Custom-Header:".

You need -H "Host;" to send an empty host header.

Body:
when executed this command:

curl -H "Host:" http://127.0.0.1

it response 400 Bad request.

from http rfc:

If the requested URI does not include an Internet host name for the service being requested, then the Host header field MUST be given with an empty value.

why?

Body:
Because -H "Host:" removes the header altogether. See the docs for -H, --header <header/@file>:

[...] Remove an internal header by giving a replacement without content on the right side of the colon, as in: -H "Host:". If you send the custom header with no-value then its header must be terminated with a semicolon, such as -H "X-Custom-Header;" to send "X-Custom-Header:".

You need -H "Host;" to send an empty host header.


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
First Step for me: Understanding FOR loops in Turbo Pascal 5. That forever changed my life.

Second Step: Understand, that every object is kind-of like a button (or any other ui control), just usually invisible.

You might be interested in reading this:

Coding Horror: Separating Programming Sheep from Non-Programming Goats

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Lemmy

LastEditorDisplayName: Lemmy


问:
Possible JQuery functions to use
I am currently working on a website which has a fixed header and body and within the body is a main DIV.

For the page to change, the contents of the main DIV is changed. (Not my development)

I would like to display a notice to the user (Please wait loading) for any DB requests to the server or if the page changes. (The contents of the main DIV is changed for this to occur). Once the results from the DB has been returned or the main DIV has completed loading, I would like for the notice to be removed.

I am considering using JQuery to achieve this, by having a loader DIV within the body and for this to be visible when required and hidden when not.

What would be the best JQuery function to use to achieve my requirements?

There is no AJAX used on the site.

Many thanks

答: You're probably looking for .show() and .hide()  Or, if you want to get fancy, .fadeIn() and .fadeOut()

Title: Possible JQuery functions to use


问:
Fetching data from a CSV file and storing it into a 2D array - Java
I have a csv file saved with the name - "public/csvFiles/pushup.csv", where I have converted a 2D matrix into csv format.
Now I want to make a static method in a manager class, where in I will make a 2D array by fetching data from that csv file.
So I want to know how to do that. How to make a 2D array from the data present in the csv file?

I have made my csv file in the following format :

comma separated values, after every comma, means new column

every new line means new row

答:
If I get you right - the first dimension of an array is structure reflecting lines.
Second dimension - rows of CSV file.

So I propose to create a structure reflecting row.
Names must be meaningful.
But the idea is:

```<code>RowClss {
    String row;
    String row 2;
    // etc
}
</code>```

Then in the loop, you can read the file and fill the array:

```<code>String[x][y] rows = new String[x][y];

for(ont i = 0; i < file.size; i++) {
    // read line from file and parse it here
    for(j = 0; j < numOfColumns;j++) {
        rows[j][i] = new String(valueOfCurrentCollumn);
    }
}
</code>```

Body:
If I get you right - the first dimension of an array is structure reflecting lines.
Second dimension - rows of CSV file.

So I propose to create a structure reflecting row.
Names must be meaningful.
But the idea is:

RowClss {
    String row;
    String row 2;
    // etc
}

Then in the loop, you can read the file and fill the array:

String[x][y] rows = new String[x][y];

for(ont i = 0; i < file.size; i++) {
    // read line from file and parse it here
    for(j = 0; j < numOfColumns;j++) {
        rows[j][i] = new String(valueOfCurrentCollumn);
    }
}


问:
Setting up git server with web interface?
As our company would never let a third party like github anywhere near our source code, is anyone aware of any software or setup guides or blogs on how to setup a scm server like github, ie it would support

Creation of repostories using a web interface

Limiting/managing user access to individual repositories

Browsing repositories online

If I can get this going I can see a potential mass migration from svn/cvs to git. (The only stumbling block I can see will be the windows Tortise SVN users having difficulty with the Git windows alternatives)

答: Use Gogs. It's a lightweight git server with web interface written in Go language. It looks like a github clone, but not at all. There is an internal bugtracker and wiki, but they can be replaced by external in settings. Take a look at it.</p>


问:
How to allow user to register with duplicate UserName using Identity Framework 1.0
I want to develop an application in MVC using Identity Framework 1.0 which allow users to register with same username used by some other user.

When deleting a user I want to set its IsDeleted custom property to true rather than deleting the user from database. In this case another user can use the UserName of the user whose IsDeleted is set to true.

But the default UserManager.CreateAsync(user, password); method is preventing doing this.

I had overridden the ValidateEntity method of IdentityDbContext like this

```<code>protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
    if ((entityEntry != null) && (entityEntry.State == EntityState.Added))
    {
        ApplicationUser user = entityEntry.Entity as ApplicationUser;
        if ((user != null) && this.Users.Any<ApplicationUser>(u => string.Equals(u.UserName, user.UserName) && u.IsDeleted==false))
        {
            return new DbEntityValidationResult(entityEntry, new List<DbValidationError>()) {
                ValidationErrors = {
                    new DbValidationError("User", string.Format(CultureInfo.CurrentCulture,
                       "", new object[] { user.UserName }))
                }
            };
        }
        IdentityRole role = entityEntry.Entity as IdentityRole;
        if ((role != null) && this.Roles.Any<IdentityRole>(r => string.Equals(r.Name, role.Name)))
        {
            return new DbEntityValidationResult(entityEntry, new List<DbValidationError>()) {
                ValidationErrors = {
                    new DbValidationError("Role", string.Format(CultureInfo.CurrentCulture,
                        "", new object[] { role.Name })) } };
        }
    }
    return base.ValidateEntity(entityEntry, items);
}
</code>```

Here is my register method where user is created

```<code>public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email.ToLower(), CreatedBy = model.UserName, CreatedDate = DateTime.UtcNow, };

        user.ConfirmedEmail = false;
        var result = await _accountService.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {

            TempData["MessageConfirm"] = user.Email;
            return RedirectToAction("Confirm", "Account");
        }
        else
        {
            AddErrors(result);
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}
</code>```

ValidateEntity method should be executed when await _accountService.CreateAsync(user, model.Password); executes. But it is executing after the register method completes it's execution. So the result throws error.

Any suggestions how I can achieve this?

答:
My pet peeve is when people decide to give advice in lieu of answering the question asked.  usernames don't have to be unique.  The db key is userid not user name.  If you have application that services several companies there is a chance that employees of different companies will have the same username.  In order to do this you have to extent aspnet identity.

https://www.scottbrady91.com/ASPNET-Identity/Quick-and-Easy-ASPNET-Identity-Multitenancy

IdentityUser
To start with we’ll need to add the claim of TenantId (you can rename this as fits your business requirements) by extending the IdentityUser class. Whilst this is conceptually a claim, we will take advantage of the AspNetUser table and add TenantId as a property, as we will be querying by this property a fair bit. For simplicity I have added the TenantId as an int however a non-iterative alternative would be to use a string.

```<code>    public class ApplicationUser : IdentityUser {
    public int TenantId { get; set; }
}
</code>```

UserStore
Next we’ll implement the UserStore for our new user that is aware of our new property. Here we are using a property within our UserStore class to set our TenantId, allowing us to override the base implementation with our multi-tenanted implementation.

```<code>    public class ApplicationUserStore<TUser> : UserStore<TUser>
  where TUser : ApplicationUser {
    public ApplicationUserStore(DbContext context)
      : base(context) {
    }

    public int TenantId { get; set; }
}
</code>```

CreateUserAsync

```<code>public override Task CreateAsync(TUser user) {
if (user == null) {
    throw new ArgumentNullException("user");
}

user.TenantId = this.TenantId;
return base.CreateAsync(user);

}
</code>```

FindByEmailAsync

```<code>public override Task<TUser> FindByEmailAsync(string email) {
return this.GetUserAggregateAsync(u => u.Email.ToUpper() == email.ToUpper()
    && u.TenantId == this.TenantId);

}
</code>```

FindByNameAsync

```<code>public override Task<TUser> FindByNameAsync(string userName) {
return this.GetUserAggregateAsync(u => u.UserName.ToUpper() == userName.ToUpper()
    && u.TenantId == this.TenantId);

}
</code>```

UserValidator
Whilst the default UserValidator has hardcoded checks for duplicate user names, our new implementation of the UserStore methods FindByNameAsync and FindByEmailAsync will allow for the correct multi-tenanted behaviour (assuming you have set a TenantId within the UserStore). This means we can take full advantage of the default UserValidator and extend it if necessary.

IdentityDbContext
Now here’s an awkward bit. The ASP.NET Identity team have again hardcoded a check for duplicate usernames within the IdentityDbContext class, however this time it is both within the ValidateEntity method and in the EF database schema itself using an index.

The index can be solved by extending the OnModelCreating method to change the unique index based on username to also look for our TenantId (a composite index). This saves us losing this useful index and optimises our database for multitenancy. You can do this with the following override method:

```<code>        public class ApplicationUserDbContext<TUser> : IdentityDbContext<TUser>
      where TUser : ApplicationUser {
        public ApplicationUserDbContext(string nameOrConnectionString)
          : base(nameOrConnectionString) {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);

            var user = modelBuilder.Entity<TUser>();

            user.Property(u => u.UserName)
                .IsRequired()
                .HasMaxLength(256)
                .HasColumnAnnotation("Index", new IndexAnnotation(
                    new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 1}));

            user.Property(u => u.TenantId)
                .IsRequired()
                .HasColumnAnnotation("Index", new IndexAnnotation(
                    new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 2 }));
        }
    }
</code>```

The ValidateEntity method is a bit more tricky however, as we will have to reimplement the entire method in order to remove the hardcoded username checks:

```<code>        protected override DbEntityValidationResult ValidateEntity(
          DbEntityEntry entityEntry, IDictionary<object, object> items) {
            if (entityEntry != null && entityEntry.State == EntityState.Added) {
                var errors = new List<DbValidationError>();
                var user = entityEntry.Entity as TUser;

                if (user != null) {
                    if (this.Users.Any(u => string.Equals(u.UserName, user.UserName)
                      && u.TenantId == user.TenantId)) {
                        errors.Add(new DbValidationError("User",
                          string.Format("Username {0} is already taken for AppId {1}",
                            user.UserName, user.TenantId)));
                    }

                    if (this.RequireUniqueEmail
                      && this.Users.Any(u => string.Equals(u.Email, user.Email)
                      && u.TenantId == user.TenantId)) {
                        errors.Add(new DbValidationError("User",
                          string.Format("Email Address {0} is already taken for AppId {1}",
                            user.UserName, user.TenantId)));
                    }
                }
                else {
                    var role = entityEntry.Entity as IdentityRole;

                    if (role != null && this.Roles.Any(r => string.Equals(r.Name, role.Name))) {
                        errors.Add(new DbValidationError("Role",
                          string.Format("Role {0} already exists", role.Name)));
                    }
                }
                if (errors.Any()) {
                    return new DbEntityValidationResult(entityEntry, errors);
                }
            }

            return new DbEntityValidationResult(entityEntry, new List<DbValidationError>());
        }
</code>```

Client
All that remains now is to initialise the classes. Don't forget you will need to supply the TenantId each time you new up the context. See the below example (note the use of 'example', these classes are all disposable...).

```<code>    var context = new ApplicationUserDbContext<ApplicationUser>("DefaultConnection");
var userStore = new ApplicationUserStore<ApplicationUser>(context) { TenantId = 1 };
var userManager = new UserManager<ApplicationUser, string>(userStore);
</code>```

Body:
I want to develop an application in MVC using Identity Framework 1.0 which allow users to register with same username used by some other user.

When deleting a user I want to set its IsDeleted custom property to true rather than deleting the user from database. In this case another user can use the UserName of the user whose IsDeleted is set to true.

But the default UserManager.CreateAsync(user, password); method is preventing doing this.

I had overridden the ValidateEntity method of IdentityDbContext like this

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
    if ((entityEntry != null) && (entityEntry.State == EntityState.Added))
    {
        ApplicationUser user = entityEntry.Entity as ApplicationUser;
        if ((user != null) && this.Users.Any<ApplicationUser>(u => string.Equals(u.UserName, user.UserName) && u.IsDeleted==false))
        {
            return new DbEntityValidationResult(entityEntry, new List<DbValidationError>()) {
                ValidationErrors = {
                    new DbValidationError("User", string.Format(CultureInfo.CurrentCulture,
                       "", new object[] { user.UserName }))
                }
            };
        }
        IdentityRole role = entityEntry.Entity as IdentityRole;
        if ((role != null) && this.Roles.Any<IdentityRole>(r => string.Equals(r.Name, role.Name)))
        {
            return new DbEntityValidationResult(entityEntry, new List<DbValidationError>()) {
                ValidationErrors = {
                    new DbValidationError("Role", string.Format(CultureInfo.CurrentCulture,
                        "", new object[] { role.Name })) } };
        }
    }
    return base.ValidateEntity(entityEntry, items);
}

Here is my register method where user is created

public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email.ToLower(), CreatedBy = model.UserName, CreatedDate = DateTime.UtcNow, };

        user.ConfirmedEmail = false;
        var result = await _accountService.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {

            TempData["MessageConfirm"] = user.Email;
            return RedirectToAction("Confirm", "Account");
        }
        else
        {
            AddErrors(result);
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}

ValidateEntity method should be executed when await _accountService.CreateAsync(user, model.Password); executes. But it is executing after the register method completes it's execution. So the result throws error.

Any suggestions how I can achieve this?

Body:
My pet peeve is when people decide to give advice in lieu of answering the question asked.  usernames don't have to be unique.  The db key is userid not user name.  If you have application that services several companies there is a chance that employees of different companies will have the same username.  In order to do this you have to extent aspnet identity.

https://www.scottbrady91.com/ASPNET-Identity/Quick-and-Easy-ASPNET-Identity-Multitenancy

IdentityUser
To start with we’ll need to add the claim of TenantId (you can rename this as fits your business requirements) by extending the IdentityUser class. Whilst this is conceptually a claim, we will take advantage of the AspNetUser table and add TenantId as a property, as we will be querying by this property a fair bit. For simplicity I have added the TenantId as an int however a non-iterative alternative would be to use a string.

    public class ApplicationUser : IdentityUser {
    public int TenantId { get; set; }
}

UserStore
Next we’ll implement the UserStore for our new user that is aware of our new property. Here we are using a property within our UserStore class to set our TenantId, allowing us to override the base implementation with our multi-tenanted implementation.

    public class ApplicationUserStore<TUser> : UserStore<TUser>
  where TUser : ApplicationUser {
    public ApplicationUserStore(DbContext context)
      : base(context) {
    }

    public int TenantId { get; set; }
}

CreateUserAsync

public override Task CreateAsync(TUser user) {
if (user == null) {
    throw new ArgumentNullException("user");
}

user.TenantId = this.TenantId;
return base.CreateAsync(user);

}

FindByEmailAsync

public override Task<TUser> FindByEmailAsync(string email) {
return this.GetUserAggregateAsync(u => u.Email.ToUpper() == email.ToUpper()
    && u.TenantId == this.TenantId);

}

FindByNameAsync

public override Task<TUser> FindByNameAsync(string userName) {
return this.GetUserAggregateAsync(u => u.UserName.ToUpper() == userName.ToUpper()
    && u.TenantId == this.TenantId);

}

UserValidator
Whilst the default UserValidator has hardcoded checks for duplicate user names, our new implementation of the UserStore methods FindByNameAsync and FindByEmailAsync will allow for the correct multi-tenanted behaviour (assuming you have set a TenantId within the UserStore). This means we can take full advantage of the default UserValidator and extend it if necessary.

IdentityDbContext
Now here’s an awkward bit. The ASP.NET Identity team have again hardcoded a check for duplicate usernames within the IdentityDbContext class, however this time it is both within the ValidateEntity method and in the EF database schema itself using an index.

The index can be solved by extending the OnModelCreating method to change the unique index based on username to also look for our TenantId (a composite index). This saves us losing this useful index and optimises our database for multitenancy. You can do this with the following override method:

        public class ApplicationUserDbContext<TUser> : IdentityDbContext<TUser>
      where TUser : ApplicationUser {
        public ApplicationUserDbContext(string nameOrConnectionString)
          : base(nameOrConnectionString) {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);

            var user = modelBuilder.Entity<TUser>();

            user.Property(u => u.UserName)
                .IsRequired()
                .HasMaxLength(256)
                .HasColumnAnnotation("Index", new IndexAnnotation(
                    new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 1}));

            user.Property(u => u.TenantId)
                .IsRequired()
                .HasColumnAnnotation("Index", new IndexAnnotation(
                    new IndexAttribute("UserNameIndex") { IsUnique = true, Order = 2 }));
        }
    }

The ValidateEntity method is a bit more tricky however, as we will have to reimplement the entire method in order to remove the hardcoded username checks:

        protected override DbEntityValidationResult ValidateEntity(
          DbEntityEntry entityEntry, IDictionary<object, object> items) {
            if (entityEntry != null && entityEntry.State == EntityState.Added) {
                var errors = new List<DbValidationError>();
                var user = entityEntry.Entity as TUser;

                if (user != null) {
                    if (this.Users.Any(u => string.Equals(u.UserName, user.UserName)
                      && u.TenantId == user.TenantId)) {
                        errors.Add(new DbValidationError("User",
                          string.Format("Username {0} is already taken for AppId {1}",
                            user.UserName, user.TenantId)));
                    }

                    if (this.RequireUniqueEmail
                      && this.Users.Any(u => string.Equals(u.Email, user.Email)
                      && u.TenantId == user.TenantId)) {
                        errors.Add(new DbValidationError("User",
                          string.Format("Email Address {0} is already taken for AppId {1}",
                            user.UserName, user.TenantId)));
                    }
                }
                else {
                    var role = entityEntry.Entity as IdentityRole;

                    if (role != null && this.Roles.Any(r => string.Equals(r.Name, role.Name))) {
                        errors.Add(new DbValidationError("Role",
                          string.Format("Role {0} already exists", role.Name)));
                    }
                }
                if (errors.Any()) {
                    return new DbEntityValidationResult(entityEntry, errors);
                }
            }

            return new DbEntityValidationResult(entityEntry, new List<DbValidationError>());
        }

Client
All that remains now is to initialise the classes. Don't forget you will need to supply the TenantId each time you new up the context. See the below example (note the use of 'example', these classes are all disposable...).

    var context = new ApplicationUserDbContext<ApplicationUser>("DefaultConnection");
var userStore = new ApplicationUserStore<ApplicationUser>(context) { TenantId = 1 };
var userManager = new UserManager<ApplicationUser, string>(userStore);


问:
What is the best free (or under 200 dollar) database manager software?
I am currently using Toad, but am not very satisied.</p>

答: Dbvisualiser http://www.dbvis.com/</p>

Body: Dbvisualiser http://www.dbvis.com/