问:
Static method that returns the current class' name regardless of inheritance
My problem is that MethodBase.GetCurrentMethod().DeclaringType.Name only works if called on an instance of a class. If called from a static function, it returns the topmost parent class' name regardless of how many times it has been sub-classed.

For example

```<code>public class ReflectionObject {

    public static string Name() {
        return MethodBase.GetCurrentMethod().DeclaringType.Name;
    }
}
public class DerivedObject : ReflectionObject {
}
</code>```

Calling DerivedObject.Name() returns ReflectionObject and not DerivedObject like I need it to. Any ideas?

答:
Static inheritance doesn't work like inheritance of normal methods. The behavior you observe happens instead (it acts as a method of the parent class, not of the child). User Daniel Earwicker put it really well in this answer. In short, static methods are tied to their declaring type.

Now, regarding your specific problem, there isn't a way to make what you're trying to do work. There are however a few alternative ways to achieve your desired result. The simplest is to just use a property instead of a method.

```<code>public class ReflectionObject
{
    public string Name
    {
        get {
            return this.GetType().Name;
        }
    }
}
</code>```

Then if you had a method such as this in your child class:

```<code>public class DerivedObject : ReflectionObject
{
    public string MyName()
    {
        return this.Name;
    }
}
</code>```

..calling something like new DerivedObject().MyName() would return "DerivedObject" as is your desired result. Using this in the property instead of GetType() is also an option:

```<code>MethodBase.GetCurrentMethod().DeclaringType.Name;
</code>```

Of course, since you don't mention your use case I cannot know of any limitations you may have. Generally, this is the easiest way to get the name of a child class.

Body:
My problem is that MethodBase.GetCurrentMethod().DeclaringType.Name only works if called on an instance of a class. If called from a static function, it returns the topmost parent class' name regardless of how many times it has been sub-classed.

For example

public class ReflectionObject {

    public static string Name() {
        return MethodBase.GetCurrentMethod().DeclaringType.Name;
    }
}
public class DerivedObject : ReflectionObject {
}

Calling DerivedObject.Name() returns ReflectionObject and not DerivedObject like I need it to. Any ideas?

Body:
Static inheritance doesn't work like inheritance of normal methods. The behavior you observe happens instead (it acts as a method of the parent class, not of the child). User Daniel Earwicker put it really well in this answer. In short, static methods are tied to their declaring type.

Now, regarding your specific problem, there isn't a way to make what you're trying to do work. There are however a few alternative ways to achieve your desired result. The simplest is to just use a property instead of a method.

public class ReflectionObject
{
    public string Name
    {
        get {
            return this.GetType().Name;
        }
    }
}

Then if you had a method such as this in your child class:

public class DerivedObject : ReflectionObject
{
    public string MyName()
    {
        return this.Name;
    }
}

..calling something like new DerivedObject().MyName() would return "DerivedObject" as is your desired result. Using this in the property instead of GetType() is also an option:

MethodBase.GetCurrentMethod().DeclaringType.Name;

Of course, since you don't mention your use case I cannot know of any limitations you may have. Generally, this is the easiest way to get the name of a child class.


来源: stackexchange

问:
Generating random password into input with input length using Javascript
```<code><form name="pgenerate">
<input type="text" size=18 name="output">
<input type="button" value="Generate Password" ><br />
<b>Password Length:</b> <input type="text" name="thelength" size=3 value="7">
</form>
</code>```

How can i make a random password generator that will generate password inside an input you can use in you projects or systems

答:
Try this pure JS solution:

function generateRandomPassword (passwordLength) {
    var outputPassword = "";
    var allPossibleChars  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < passwordLength; i++) {
        outputPassword += allPossibleChars.charAt(Math.floor(Math.random() * allPossibleChars.length));
    }
    return outputPassword;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="pgenerate">
<input type="text" size=18 id="output" name="output">
<input type="button" value="Generate Password" onclick="document.getElementById('output').value = generateRandomPassword(document.getElementById('thelength').value);"><br />
<b>Password Length:</b> <input type="text" id="thelength" name="thelength" size=3 value="7">
</form></code>```

If you want to add more possible chars simply update allPossibleChars.

ContentLicense: CC BY-SA 3.0

Body:
<form name="pgenerate">
<input type="text" size=18 name="output">
<input type="button" value="Generate Password" >

Password Length: <input type="text" name="thelength" size=3 value="7">
</form>

How can i make a random password generator that will generate password inside an input you can use in you projects or systems

Body:
Try this pure JS solution:

function generateRandomPassword (passwordLength) {
    var outputPassword = "";
    var allPossibleChars  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < passwordLength; i++) {
        outputPassword += allPossibleChars.charAt(Math.floor(Math.random() * allPossibleChars.length));
    }
    return outputPassword;
}

<form name="pgenerate">
<input type="text" size=18 id="output" name="output">
<input type="button" value="Generate Password" onclick="document.getElementById('output').value = generateRandomPassword(document.getElementById('thelength').value);"><br />
<b>Password Length:</b> <input type="text" id="thelength" name="thelength" size=3 value="7">
</form>

If you want to add more possible chars simply update allPossibleChars.


问:
what is the use of if else statements?
I don't quite understand the meaning of else if statements.

why not just to continue with the if statements in case one is false?

it works the same.

example with if only that will work the same with else if:

```<code>function testSize(num) {

  if (num < 5){

     return "Tiny";
  }

  if (num < 10){

    return "small";
  }

  return "Change Me";

}

testSize(7);
</code>```

答:
In your actual code you specify a return statement in the code associated to the if statement.

Suppose you don't specify a return statement or suppose today you specify a return statement but tomorrow you remove it to do a common return at the end of the method.

This code will test each condition even if the first one is true :

```<code>  if (num < 5){
     // do something
  }

  if (num < 10){
     // do something
  }
</code>```

This code will not test the next condition if the first one is true :

```<code>  if (num < 5){
     // do something
  }

  else if (num < 10){
     // do something
  }
</code>```

These two ways of doing have two distinct meanings.

When you have a series of if statements, you expect that more than one condition may be true.

When you have a series of if-else-if statements, you expect to have not more than one condition true.

Using the first form (a series of if)  while functionally you expect to have not more than one condition true is misleading.

Besides, if the code is modified and you add a condition that is both true for two if statements while you don't want have this case, it would create an issue.

Title: what is the use of if else statements?

Body:
I don't quite understand the meaning of else if statements.

why not just to continue with the if statements in case one is false?

it works the same.

example with if only that will work the same with else if:

function testSize(num) {

  if (num < 5){

     return "Tiny";
  }

  if (num < 10){

    return "small";
  }

  return "Change Me";

}

testSize(7);

Body:
In your actual code you specify a return statement in the code associated to the if statement.

Suppose you don't specify a return statement or suppose today you specify a return statement but tomorrow you remove it to do a common return at the end of the method.

This code will test each condition even if the first one is true :

  if (num < 5){
     // do something
  }

  if (num < 10){
     // do something
  }

This code will not test the next condition if the first one is true :

  if (num < 5){
     // do something
  }

  else if (num < 10){
     // do something
  }

These two ways of doing have two distinct meanings.

When you have a series of if statements, you expect that more than one condition may be true.

When you have a series of if-else-if statements, you expect to have not more than one condition true.

Using the first form (a series of if)  while functionally you expect to have not more than one condition true is misleading.

Besides, if the code is modified and you add a condition that is both true for two if statements while you don't want have this case, it would create an issue.


问:
How to set AssemblyTitleAttribute in NETCore1.1
In .NETCore1.1, next code

```<code>typeof(Program).GetTypeInfo().Assembly.GetCustomAttributes().ToList()
</code>```

returns list of custom assembly attributes and one of them is AssemblyTitleAttribute. By default this attribute value returns project name, but how can I set any other value?

Tried to add assembly information file AssemblyInfo.cs how it's described here, but getting error

error CS0579: Duplicate 'System.Reflection.AssemblyTitleAttribute'
  attribute

答:
Right now properties could be defined in .csproj or using AssemblyInfo.cs, but only the one place could be used, otherwise "Duplicate" errors are generated.

If you want to use AssemblyInfo.cs, add the following into .csproj to avoid duplication errors:

```<code><PropertyGroup>
  <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
</code>```

If you are interesting how does it work, look into GenerateAssemblyInfo task.

Otherwise remove AssemblyInfo.cs and add the following into your .csproj file:

```<code><PropertyGroup>
  <AssemblyTitle>My library</AssemblyTitle>
</PropertyGroup>
</code>```

Body:
In .NETCore1.1, next code

typeof(Program).GetTypeInfo().Assembly.GetCustomAttributes().ToList()

returns list of custom assembly attributes and one of them is AssemblyTitleAttribute. By default this attribute value returns project name, but how can I set any other value?

Tried to add assembly information file AssemblyInfo.cs how it's described here, but getting error

error CS0579: Duplicate 'System.Reflection.AssemblyTitleAttribute'
  attribute

Body:
Right now properties could be defined in .csproj or using AssemblyInfo.cs, but only the one place could be used, otherwise "Duplicate" errors are generated.

If you want to use AssemblyInfo.cs, add the following into .csproj to avoid duplication errors:

<PropertyGroup>
  <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>

If you are interesting how does it work, look into GenerateAssemblyInfo task.

Otherwise remove AssemblyInfo.cs and add the following into your .csproj file:

<PropertyGroup>
  <AssemblyTitle>My library</AssemblyTitle>
</PropertyGroup>


问:
array of pointers and pointer to an array in c++
i have a class in which it's protected section i need to declare an array with unknown size (the size is given to the constructor as a parameter), so i looked around and found out that the best possible solution is to declare an array of pointers, each element points to an integer:

```<code>int* some_array_;
</code>```

and simply in the constructor i'll use the "new" operator:

```<code>some_array_ = new int[size];
</code>```

and it worked, my question is: can i declare an array in a class without defining the size? and if yes how do i do it, if not then why does it work for pointers and not for a normal array?

EDIT: i know vecotrs will solve the problem but i can't use them on my HW

答: You have to think about how this works from the compiler's perspective.  A pointer uses a specific amount of space (usually 4 bytes) and you request more space with the new operator.  But how much space does an empty array use?  It can't be 0 bytes and the compiler has no way of knowing what space to allocate for an array without any elements and therefore it is not allowed.</p>

Body:
i have a class in which it's protected section i need to declare an array with unknown size (the size is given to the constructor as a parameter), so i looked around and found out that the best possible solution is to declare an array of pointers, each element points to an integer:

int* some_array_;

and simply in the constructor i'll use the "new" operator:

some_array_ = new int[size];

and it worked, my question is: can i declare an array in a class without defining the size? and if yes how do i do it, if not then why does it work for pointers and not for a normal array?

EDIT: i know vecotrs will solve the problem but i can't use them on my HW


问:
Combining multiple 'elsif' statements
I try to programm snakes in Ruby. In order to get myself more familiar with Ruby. I define the position of every part of the snake through saving its X and Y value in two 1D arrays one for a X value and one for a Y value.

```<code> $x = [2,...]
 $y = [2,...]
</code>```

(What I forgot to tell is that the head of the Snake moves through user input while the rest just inherits its position from the part before like this.)

```<code>def length(f)
if $length >= f
    $y[f] = $y[f-1]
    $x[f] = $x[f-1]
end
end
</code>```

In order to get a field for the Snake to move around I programmed this.

```<code>for a in (1..20)
  for b in (1..20)
    print " X "
  end
  puts" "
end
</code>```

Which gives me a 20*20 field.

I then tried to display every part of the snake like on the field like this.(While also drawing a boarder around the field.)

```<code>for a in (1..20)
for b in (1..20)
    if a == 1 || a == 20
        if b == 1 || b == 20
            print " + "
        else
            print " - "
        end
    elsif b == 1 || b == 20
        print " | "
    elsif a == $x[0] && b == $y[0]
        body
    elsif a == $x[1] && b == $y[1]
        body
    elsif a == $x[2] && b == $y[2]
        body
    elsif a == $x[3] && b == $y[3]
        body
    elsif a == $x[4] && b == $y[4]
        body
    else
        print "   "
    end

end
puts""
end
</code>```

This works but if the user is really good/ has a lot of spare time I need to make allot of elsif for every one represents a part of the snake if the snake should have as a limit a length of 100 I would need to make 100 elsif statements.(The body is just:

```<code>def body
print " # ".green
end
</code>```

)

I tried fixing it with a for loop like this:

```<code>for c in (1..100)
  if a == $x[c] && b == $y[c]
    body
  end
end
</code>```

and this

```<code> loop do
    $x.size.times do |index|
        if $x[index] == a && $y[index] == b
            body
        end
    end
    break
 end
</code>```

But sadly this didn't gave the desired outcome for this interfered with the ifthat draws the boarders of the field.

Is there a way to combine these multiple elsif statements?

Every help would be highly appreciated. ( Sorry for being to vague in the first draft.)

答:
I would start with something like this:</p>

```<code>(1..20).each do |a|
  (1..20).each do |b|
    if [1, 20].include?(a)
      print([1, 20].include?(b) ? ' + ' : ' - ')

    elsif (1..100).any? { |i| a == $x[i] && b == $y[i] }
      body

    else
      print('   ')
    end

    puts('')
  end
end
</code>```

Title: Combining multiple 'elsif' statements

Body:
I try to programm snakes in Ruby. In order to get myself more familiar with Ruby. I define the position of every part of the snake through saving its X and Y value in two 1D arrays one for a X value and one for a Y value.

 $x = [2,...]
 $y = [2,...]

(What I forgot to tell is that the head of the Snake moves through user input while the rest just inherits its position from the part before like this.)

def length(f)
if $length >= f
    $y[f] = $y[f-1]
    $x[f] = $x[f-1]
end
end

In order to get a field for the Snake to move around I programmed this.

for a in (1..20)
  for b in (1..20)
    print " X "
  end
  puts" "
end

Which gives me a 20*20 field.

I then tried to display every part of the snake like on the field like this.(While also drawing a boarder around the field.)

for a in (1..20)
for b in (1..20)
    if a == 1 || a == 20
        if b == 1 || b == 20
            print " + "
        else
            print " - "
        end
    elsif b == 1 || b == 20
        print " | "
    elsif a == $x[0] && b == $y[0]
        body
    elsif a == $x[1] && b == $y[1]
        body
    elsif a == $x[2] && b == $y[2]
        body
    elsif a == $x[3] && b == $y[3]
        body
    elsif a == $x[4] && b == $y[4]
        body
    else
        print "   "
    end

end
puts""
end

This works but if the user is really good/ has a lot of spare time I need to make allot of elsif for every one represents a part of the snake if the snake should have as a limit a length of 100 I would need to make 100 elsif statements.(The body is just:

def body
print " # ".green
end

)

I tried fixing it with a for loop like this:

for c in (1..100)
  if a == $x[c] && b == $y[c]
    body
  end
end

and this

 loop do
    $x.size.times do |index|
        if $x[index] == a && $y[index] == b
            body
        end
    end
    break
 end

But sadly this didn't gave the desired outcome for this interfered with the ifthat draws the boarders of the field.

Is there a way to combine these multiple elsif statements?

Every help would be highly appreciated. ( Sorry for being to vague in the first draft.)

Body:
I would start with something like this:

(1..20).each do |a|
  (1..20).each do |b|
    if [1, 20].include?(a)
      print([1, 20].include?(b) ? ' + ' : ' - ')

    elsif (1..100).any? { |i| a == $x[i] && b == $y[i] }
      body

    else
      print('   ')
    end

    puts('')
  end
end


问:
Pause/user input (warndlg) issue in Matlab GUI
Prior to saving a file I wish to have a Warning Dialog. In the script below there is no stop for pressing the warndlg OK and the script moves automatically continue to the uiputfile. How can I pause between them/enforce user to press the OK before the uiputfile?

Script:

```<code>warndlg('May take time due to image size')
[file,path] = uiputfile('*.tif', 'Save As');
if file == 0
  return;
end
</code>```

答:
You can use the uiwait function:

```<code>uiwait(warndlg('May take time due to image size'))
</code>```

It will block the execution of your script until the OK button is pressed.

Body:
Prior to saving a file I wish to have a Warning Dialog. In the script below there is no stop for pressing the warndlg OK and the script moves automatically continue to the uiputfile. How can I pause between them/enforce user to press the OK before the uiputfile?

Script:

warndlg('May take time due to image size')
[file,path] = uiputfile('*.tif', 'Save As');
if file == 0
  return;
end

Body:
You can use the uiwait function:

uiwait(warndlg('May take time due to image size'))

It will block the execution of your script until the OK button is pressed.

ContentLicense: CC BY-SA 4.0


答:
Lets say that you have an integer array of size 2. So you have Array[0,1]
Arrays are continuous byte of memery, so if you declare one and then you want to add one or more elements to end of that array, the exact next position (in this case :at index 2(or the 3rd integer) ) has a high chance of being already allocated so in that case you just cant do it. A solution is to create a new array (in this case of 3 elements) , copy the initial array into the new and in the last position add the new integer. Obviously this has a high cost so we dont do it.

A solution to this problem in C++ is Vector and in Java are ArrayLists.

Title: array of pointers and pointer to an array in c++


问:
PhpMyAdmin fail to export any Database
It will just give me the below error on localhost/phpmyadmin/export.php

Fatal error: Call to a member function getHeader() on a non-object in C:\xampp\phpMyAdmin\libraries\common.inc.php on line 1067

I've already replaced installation and no luck so far. Can anyone help me?

答:
Make sure you have Profiling turned-off in phpmyadmin.

To check that, you can run any query inside phpmyadmin and look for Profiling checkbox, make sure it's unchecked.

Title: PhpMyAdmin fail to export any Database


问:
Yii2 Rest - Custom action and OPTIONS method
I'm having trouble with the following action "/login" route action in my UsersController class

```<code>public function actionLogin(){
        $data = Yii::$app->getRequest()->getBodyParams();
        $model = new Usuario();

        //Validamos que se hayan recibido los campos
        if(empty($data['email']) || empty($data['password'])){
            throw new \yii\web\BadRequestHttpException("Debe ingresar email y password");
        }

        //Validamos usuario y contraseña
        $usuario = $model->findByUsername($data['email']);
        if(empty($usuario) || !$usuario->validatePassword($data['password'])){
            throw new \yii\web\UnauthorizedHttpException("Usuario y/o contraseña incorrectos");
        }
        return $usuario;
    }
</code>```

The situation is that I'm using POST method to perform login, and I'm calling this route from a different domain, so the frontend library first try to call /login route with OPTIONS method to check if it is allowed or not to call /login with POST..

The problem is that the built in functionality of yii2 rest ActiveController is only for /users and /users/{id}

If I manually add this /login route to be available in both POST and OPTIONS through actions verbFilter, then yii Is trying to actually call the login action with the OPTIONS request. I mean, it is trying to perform login. Of course it can't, because it is not sending email and passwords fields, but I can see an error in the log file.

So, my question is... Is there any way to configure correctly this "custom" routes actions and make OPTIONS performs transparently? Because I'm expecting that login action not get executed when calling it with OPTIONS, but instead to return directly the OPTIONS allowed methods headers.

Update Info: Added URL manager rules

```<code>'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => true,
        'rules' => [
            [
                'class' => 'yii\rest\UrlRule',
                'controller' => ['v1/users'],
                'pluralize' => false,
                'tokens' => [
                    '{id}' => '<id:\\w+>'
                ]
            ],
            //Rutas usuario
            'v1/login' => '/v1/users/login'
        ],
    ],
</code>```

答:
```<code>'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => ['v1/users'],
        'pluralize' => false,
        'tokens' => [
            '{id}' => '<id:\\w+>'
        ]
    ],
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => ['v1/login' => '/v1/users/login'],
        'patterns' => [
            'POST' => 'login',
            'OPTIONS' => 'options',
        ]
    ]
],
</code>```

Body:
I'm having trouble with the following action "/login" route action in my UsersController class

public function actionLogin(){
        $data = Yii::$app->getRequest()->getBodyParams();
        $model = new Usuario();

        //Validamos que se hayan recibido los campos
        if(empty($data['email']) || empty($data['password'])){
            throw new \yii\web\BadRequestHttpException("Debe ingresar email y password");
        }

        //Validamos usuario y contraseña
        $usuario = $model->findByUsername($data['email']);
        if(empty($usuario) || !$usuario->validatePassword($data['password'])){
            throw new \yii\web\UnauthorizedHttpException("Usuario y/o contraseña incorrectos");
        }
        return $usuario;
    }

The situation is that I'm using POST method to perform login, and I'm calling this route from a different domain, so the frontend library first try to call /login route with OPTIONS method to check if it is allowed or not to call /login with POST..

The problem is that the built in functionality of yii2 rest ActiveController is only for /users and /users/{id}

If I manually add this /login route to be available in both POST and OPTIONS through actions verbFilter, then yii Is trying to actually call the login action with the OPTIONS request. I mean, it is trying to perform login. Of course it can't, because it is not sending email and passwords fields, but I can see an error in the log file.

So, my question is... Is there any way to configure correctly this "custom" routes actions and make OPTIONS performs transparently? Because I'm expecting that login action not get executed when calling it with OPTIONS, but instead to return directly the OPTIONS allowed methods headers.

Update Info: Added URL manager rules

'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => true,
        'rules' => [
            [
                'class' => 'yii\rest\UrlRule',
                'controller' => ['v1/users'],
                'pluralize' => false,
                'tokens' => [
                    '{id}' => '<id:\\w+>'
                ]
            ],
            //Rutas usuario
            'v1/login' => '/v1/users/login'
        ],
    ],


答:
```<code>if(condition) {...}
if(condition) {...}
if(condition) {...}
</code>```

In above code, even if the first or second condition is true, third condition have to be checked.

```<code>if(condition) {}
else if(condition){}
else if(condition){}
</code>```

Here if first condition is true, next two will not be checked. So, it saves time and is more readable logically.

Title: what is the use of if else statements?

Body:
if(condition) {...}
if(condition) {...}
if(condition) {...}

In above code, even if the first or second condition is true, third condition have to be checked.

if(condition) {}
else if(condition){}
else if(condition){}

Here if first condition is true, next two will not be checked. So, it saves time and is more readable logically.


问:
How to interpolate the GPS readings in the real time in java
I am trying to build a real-time car monitoring application using Android. The cars would appear on the map with their current position. The problem is that the updating of the position via the GPS is slow. So the solution that was suggested for that is to use interpolation, and get the missing coordinates until the GPS updates the position. All proposed solutions I found need us to have two GPS coordinates points to interpolate between them, but since I am trying to work in the real time, I only have the initial GPS coordinates to add up to. Can anyone help in how I could achieve this? Or is there any other proposed method I could use?</p>

答:
Polymer has a great answer using linear prediction. However, there are some better prediction methods if you need them.

What i would use is Double Exponential Smoothing. This will not only take the previous positions into account, but also all the other positions.

If your GPS can also give the precision of each detection, you can use a kalman filter. Not an easy filter, but a really good one.


问:
How to get second value via c# StartsWith() method
```<code>string text = "Today is a good day for help. **David Diaz He went to school.  **David Diaz like apple. ";
</code>```

How to get how many times the text **David Diaz occurs in the string text?

UPDATED MY QUESTION

答:
```<code>var text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";

var pos = 0;
var num = 0;
var search = "**David Diaz";
 while ((pos = text.IndexOf(search, pos)) > -1)
{
    num ++;
    pos += search.Length;
}

Console.WriteLine(num);
</code>```

you can try out this in dotnetfiddle

Body:
string text = "Today is a good day for help. **David Diaz He went to school.  **David Diaz like apple. ";

How to get how many times the text **David Diaz occurs in the string text?

UPDATED MY QUESTION

Body:
var text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";

var pos = 0;
var num = 0;
var search = "**David Diaz";
 while ((pos = text.IndexOf(search, pos)) > -1)
{
    num ++;
    pos += search.Length;
}

Console.WriteLine(num);

you can try out this in dotnetfiddle


问:
Font location for django-cairo-text
Where do you put custom fonts for django-cairo-text?

https://github.com/akaihola/django-cairo-text

答: Wherever the font engine for your OS expects them to be. If you want to use a custom font file then you'll need to load it manually then inject it into the CAIROTEXT_PRESETS setting.

ContentLicense: CC BY-SA 2.5

Title: Font location for django-cairo-text


问:
Store a line of data into a file
I have been working on my Huffman project. Almost finished, now the only thing I need to do is to store in an output file. Here is my decode function.

```<code>void decode(struct Node * root, int * encodeString)
{
    int i;
    struct Node * temp = root;
    for (i = 0; encodeString[i] != -1; i++)
{

            if (encodeString[i] == 1)
    {
                    temp = temp -> right;
            }
    else
    {
                    temp = temp -> left;
            }

            if (isLeaf(temp))
    {
                    printf("%c", temp -> character);
                    temp = root;
            }

    }

}
</code>```

Calling in main function

```<code>decode(start, encodedString);
    printf("\n");
</code>```

Result of decompression:

```<code>Fred Fish 1 2 3 4 5 6 7 8 9 10
</code>```

I will later call it in the main function. When I call, the decoded string would be printed. Is there a way to read these characters. I did not go with fgets() because I don't know the size of the chars. I tried scanf("%99c", line) but it does not work, please advise

答:
In order to be able to print something onto a file you first have to open the desired file.
Use function fopen to do so.

If you set the mode parameter to "r" you will just be able to read from that file. If you want to write, as you said, use the option "w".

You can write on the file by using one of the available functions such as fwrite. But there are quite a few others, just do your research.

When you're finished remember to close the file you have previously opened though a call to fclose.

Title: Store a line of data into a file

Body:
I have been working on my Huffman project. Almost finished, now the only thing I need to do is to store in an output file. Here is my decode function.

void decode(struct Node * root, int * encodeString)
{
    int i;
    struct Node * temp = root;
    for (i = 0; encodeString[i] != -1; i++)
{

            if (encodeString[i] == 1)
    {
                    temp = temp -> right;
            }
    else
    {
                    temp = temp -> left;
            }

            if (isLeaf(temp))
    {
                    printf("%c", temp -> character);
                    temp = root;
            }

    }

}

Calling in main function

decode(start, encodedString);
    printf("\n");

Result of decompression:

Fred Fish 1 2 3 4 5 6 7 8 9 10

I will later call it in the main function. When I call, the decoded string would be printed. Is there a way to read these characters. I did not go with fgets() because I don't know the size of the chars. I tried scanf("%99c", line) but it does not work, please advise


问:
get mongodb _id object after upsert with php
is it possible to get the new/updated _id after the query?
example code:</p>

```<code>$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$mongodb->db->collection->update( $key, $data, array( 'upsert' => true ) );
</code>```

<p>$key is not holding the new/old _id object and i assume that $data will not either because its just an instruction. </p>

答:
Yes -- It is possible using a single query.

MongoDB includes a findAndModify command that can atomically modify a document and return it (by default it actually returns the document before it's been modified).

The PHP drivers don't include a convenient method for this on the collection class (yet -- check out this bug), but it can still be used (note that my PHP is terrible, so I may very well have made a syntax error in the following snippet):

```<code>$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$result = $mongodb->db->command( array(
    'findAndModify' => 'collection',
    'query' => $key,
    'update' => $data,
    'new' => true,        # To get back the document after the upsert
    'upsert' => true,
    'fields' => array( '_id' => 1 )   # Only return _id field
) );
$id = $result['value']['_id'];
</code>```

Body:
is it possible to get the new/updated _id after the query?
example code:

$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$mongodb->db->collection->update( $key, $data, array( 'upsert' => true ) );

$key is not holding the new/old _id object and i assume that $data will not either because its just an instruction.

Body:
Yes -- It is possible using a single query.

MongoDB includes a findAndModify command that can atomically modify a document and return it (by default it actually returns the document before it's been modified).

The PHP drivers don't include a convenient method for this on the collection class (yet -- check out this bug), but it can still be used (note that my PHP is terrible, so I may very well have made a syntax error in the following snippet):

$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$result = $mongodb->db->command( array(
    'findAndModify' => 'collection',
    'query' => $key,
    'update' => $data,
    'new' => true,        # To get back the document after the upsert
    'upsert' => true,
    'fields' => array( '_id' => 1 )   # Only return _id field
) );
$id = $result['value']['_id'];


问:
The return value of the “logout” is the return value of his previous command
When I debug ssh, I find that the return value of "logout" is his previous command. for example,

```<code>[server1 ~] $ ssh root@server2

/* login server2 from server1 */

[root@server2 ~]# it's an bad command

-bash: it: command not found

[root@server2 ~]# echo $?

127

/* the return value is 127 */

[root@server2 ~]# it's an bad command

-bash: it: command not found

[root@server2 ~]# logout

Connection to server1 closed.

[server1 ~ ]$ echo $?

127

/* the return value is 127 too */
</code>```

Can anyone tell me why the return value of logout is set this way?

答:
The answer should be obvious: for scripting.

Consider a typical thing to do without ssh, say:

```<code>grep -q crap file
if [ $? -eq 0 ]; then
    echo something something
fi
</code>```

If you suddenly need to perform grep on a remote machine, but want to act on the outcome on the local machine, you can just prefix the grep command with ssh invocation and everything will be fine.

Body:
When I debug ssh, I find that the return value of "logout" is his previous command. for example,

[server1 ~] $ ssh root@server2

/* login server2 from server1 */

[root@server2 ~]# it's an bad command

-bash: it: command not found

[root@server2 ~]# echo $?

127

/* the return value is 127 */

[root@server2 ~]# it's an bad command

-bash: it: command not found

[root@server2 ~]# logout

Connection to server1 closed.

[server1 ~ ]$ echo $?

127

/* the return value is 127 too */

Can anyone tell me why the return value of logout is set this way?

Body:
The answer should be obvious: for scripting.

Consider a typical thing to do without ssh, say:

grep -q crap file
if [ $? -eq 0 ]; then
    echo something something
fi

If you suddenly need to perform grep on a remote machine, but want to act on the outcome on the local machine, you can just prefix the grep command with ssh invocation and everything will be fine.


问:
How to write multiple try statements in one block in python?
I want to do:

```<code>try:
    do()
except:
    do2()
except:
    do3()
except:
    do4()
</code>```

If do() fails, execute do2(), if do2() fails too, exceute do3() and so on.

best Regards

答:
```<code>import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
</code>```

Body:
I want to do:

try:
    do()
except:
    do2()
except:
    do3()
except:
    do4()

If do() fails, execute do2(), if do2() fails too, exceute do3() and so on.

best Regards


问:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?
I have a string like:

```<code> SomeCamel WasEnteringText
</code>```

I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.

Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.

I tried:

```<code>    my $camel = "SomeCamel WasEnteringText";
    #or
    my $camel = " SomeCamel WasEntering Text";
    $camel =~ s/^[A-Z]/\s[A-Z]/g;
    #and
    $camel =~ s/([\w']+)/\u$1/g;
</code>```

and many more combinations of =~s//g; after much reading.

I need a guru to direct this camel towards an oasis of answers.

OK, based on the input below I now have:

```<code>$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Which gets it done but seems excessive. Works though.

答:
Try:

```<code>$camel =~ s/(?<! )([A-Z])/ $1/g; # Search for "(?<!pattern)" in perldoc perlre
$camel =~ s/^ (?=[A-Z])//; # Strip out extra starting whitespace followed by A-Z
</code>```

Please note that the obvious try of $camel =~ s/([^ ])([A-Z])/$1 $2/g; has a bug: it doesn't work if there are capital letters following one another (e.g. "ABCD" will be transformed into "ABCD" and not "A B C D")

Body:
I have a string like:

 SomeCamel WasEnteringText

I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.

Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.

I tried:

    my $camel = "SomeCamel WasEnteringText";
    #or
    my $camel = " SomeCamel WasEntering Text";
    $camel =~ s/^[A-Z]/\s[A-Z]/g;
    #and
    $camel =~ s/([\w']+)/\u$1/g;

and many more combinations of =~s//g; after much reading.

I need a guru to direct this camel towards an oasis of answers.

OK, based on the input below I now have:

$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;

Which gets it done but seems excessive. Works though.

Body:
Try:

$camel =~ s/(?<! )([A-Z])/ $1/g; # Search for "(?<!pattern)" in perldoc perlre
$camel =~ s/^ (?=[A-Z])//; # Strip out extra starting whitespace followed by A-Z

Please note that the obvious try of $camel =~ s/([^ ])([A-Z])/$1 $2/g; has a bug: it doesn't work if there are capital letters following one another (e.g. "ABCD" will be transformed into "ABCD" and not "A B C D")


问:
How to make progress bar with dotted lines?
Maybe you've already seen such a progress bar? Share links for example. Are there any ideas how to do it? Thank you!
Image progress bar </p>

答:
I think that canvas is not the best solution...

You can easy create this with SVG:

Some Lines as an sample, modify it to solve your problem:

```<code>      var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      svg.setAttribute('width', '200');
      svg.setAttribute('height', '200');
      svg.setAttribute("viewBox", "0 0 200 200");
      svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

    var myLine=document.createElementNS("http://www.w3.org/2000/svg", "line");
      with(myLine){
        setAttribute("x1", "100");
        setAttribute("y1", "5");
        setAttribute("x2", "100");
        setAttribute("y2", "15");
        setAttribute("stroke", "#ccc");
        setAttribute("stroke-width", "2");
        setAttribute("transform", "rotate(0,100,100)");

      }
    var myNodes=[];
    var els=100;
    var step = 360/els;
    for (var i=0;i<els;i++){
      myNodes[i]=myLine.cloneNode(true);
      myNodes[i].setAttribute("transform", "rotate("+i*step+",100,100)");
      svg.appendChild(myNodes[i]);
    }

    //make 30% red;
    var percent=30;
    for (i=0;i<=percent;i++){
      myNodes[i].setAttribute("stroke", "#f00");
    }
    document.body.appendChild(svg);
</code>```

see a liddle fiddle

Body:
I think that canvas is not the best solution...

You can easy create this with SVG:

Some Lines as an sample, modify it to solve your problem:

      var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      svg.setAttribute('width', '200');
      svg.setAttribute('height', '200');
      svg.setAttribute("viewBox", "0 0 200 200");
      svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

    var myLine=document.createElementNS("http://www.w3.org/2000/svg", "line");
      with(myLine){
        setAttribute("x1", "100");
        setAttribute("y1", "5");
        setAttribute("x2", "100");
        setAttribute("y2", "15");
        setAttribute("stroke", "#ccc");
        setAttribute("stroke-width", "2");
        setAttribute("transform", "rotate(0,100,100)");

      }
    var myNodes=[];
    var els=100;
    var step = 360/els;
    for (var i=0;i<els;i++){
      myNodes[i]=myLine.cloneNode(true);
      myNodes[i].setAttribute("transform", "rotate("+i*step+",100,100)");
      svg.appendChild(myNodes[i]);
    }

    //make 30% red;
    var percent=30;
    for (i=0;i<=percent;i++){
      myNodes[i].setAttribute("stroke", "#f00");
    }
    document.body.appendChild(svg);

see a liddle fiddle


问:
Packaging JAR with libraries of Bouncy Castle into single JAR
I made my own wrapper classes and I would like that wrapper classes to be used by anyone using my compiled JAR file.

This jar file also contained a lib folder and it has bouncy castle libraries as well, since the wrapper purpose is to make things easier for the caller. So now my library with name MyLibrary.JAR is built.

Now when I have included this jar as a library in another project I see the following error

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/bouncycastle/operator/OperatorCreationException

I checked MyLibrary.Jar file and found that inside there is another Lib folder and all the bouncy castle libraries are there, so why am I still seeing this error? My Library jar has these structure folders

Inside the lib folder I am having following libraries

I am not interested in using manual zip and unzip jar and add these libraries I am looking for something I will set on the NetBeans and It will generate the JAR file along with the dependent bouncy castle libraies.

答:
Okay I found it , I need to add the build properties like below in order to have an automated build single library </p>

```<code> <target name="-post-jar">
    <jar jarfile="dist/PKIFrapper.jar" >
    <zipfileset src="${dist.jar}" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcmail-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcpg-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcpkix-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcprov-ext-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcprov-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bctest-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/commons-codec-1.10-javadoc.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/commons-codec-1.10-sources.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/commons-codec-1.10.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/log4j-1.2-api-2.3-javadoc.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/log4j-1.2-api-2.3-sources.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/log4j-1.2-api-2.3.jar" excludes="META-INF/*" />

    <manifest>

        <attribute name="Main-Class" value="MyLibrary.*"/>
    </manifest>
    </jar>
</target>
</code>```

Body:
Okay I found it , I need to add the build properties like below in order to have an automated build single library

 <target name="-post-jar">
    <jar jarfile="dist/PKIFrapper.jar" >
    <zipfileset src="${dist.jar}" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcmail-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcpg-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcpkix-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcprov-ext-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bcprov-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/bctest-jdk15on-155.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/commons-codec-1.10-javadoc.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/commons-codec-1.10-sources.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/commons-codec-1.10.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/log4j-1.2-api-2.3-javadoc.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/log4j-1.2-api-2.3-sources.jar" excludes="META-INF/*" />
    <zipfileset src="src/lib/log4j-1.2-api-2.3.jar" excludes="META-INF/*" />

    <manifest>

        <attribute name="Main-Class" value="MyLibrary.*"/>
    </manifest>
    </jar>
</target>


问:
UTF-8 String decoding in Python
In a project I need a PHP and a Python module (Python 3.5.2). As well as a configfile which both modules use. The Python configparser has problems reading special characters from the configfile, like german mutated vowel (ä,ö,ü, e.g.). From the PHP side I use the utf-8 encoding to bypass the problem:

```<code>    utf8_encode ("Köln") //result: KÃ¶ln
</code>```

From the Python side I tried the decode function:

```<code>    "KÃ¶ln".decode("utf-8", "strict")
</code>```

I expected the result "Köln" but just got the result "KÃ¶ln" again.
What do I have do to do to decode my String?

答:
Try these lines added on the top of your document:

```<code># -*- coding: latin-1 -*-
# Encoding schema https://www.python.org/dev/peps/pep-0263
</code>```

This may help you, more documentation here

Title: UTF-8 String decoding in Python

Body:
In a project I need a PHP and a Python module (Python 3.5.2). As well as a configfile which both modules use. The Python configparser has problems reading special characters from the configfile, like german mutated vowel (ä,ö,ü, e.g.). From the PHP side I use the utf-8 encoding to bypass the problem:

    utf8_encode ("Köln") //result: KÃ¶ln

From the Python side I tried the decode function:

    "KÃ¶ln".decode("utf-8", "strict")

I expected the result "Köln" but just got the result "KÃ¶ln" again.
What do I have do to do to decode my String?

Body:
Try these lines added on the top of your document:

# -*- coding: latin-1 -*-
# Encoding schema https://www.python.org/dev/peps/pep-0263

This may help you, more documentation here


问:
How do you download a website?
Search engine bots crawl the web and download each page they go to for analysis, right?

How exactly do they download a page? What way do they store the pages?

I am asking because I want to run an analysis on a few webpages. I could scrape the page by going to the address but wouldn't it make more sense to download the pages to my computer and work on them from there?

答: You can use the debugging tools built into Firefox (or firebug) and Chrome to examine how the page works. As far as downloading them directly, I am not sure. You could maybe try viewing the page source in your browser, and then copy and paste the code.</p>

Title: How do you download a website?


问:
SQL stored procedure to save SUM and use it inside the same SP
This is for a project for a university class.

I'm creating an SP that declares a float to save the total price from another table values and uses it to insert and update another table, but the problem is that the @total is always NULL. If I take the "SELECT ... SUM" and execute it outside the SP with my values, it works!!

```<code>CREATE PROC grocery.sp_PagamentoTotalValorVenda
@idVenda INT,
@tipoPagamento INT
AS
    DECLARE @total FLOAT
    DECLARE @idContaCorr INT
    DECLARE @idCliente INT

    SELECT @total=SUM(PROD.PVP)
    FROM grocery.ITEM_VENDA AS IV JOIN grocery.PRODUTO AS PROD ON IV.ID_produto = PROD.ID
    WHERE IV.ID_venda=@idVenda
BEGIN
    SELECT @idContaCorr=CONTCORR.ID,@idCliente=VEN.Nif_cliente
    FROM grocery.VENDA AS VEN JOIN grocery.CONTA_CORRENTE AS CONTCORR ON VEN.Nif_cliente=CONTCORR.Nif_cliente
END
BEGIN
    UPDATE grocery.VENDA
    SET Valor=@total
    WHERE ID=@idVenda
END
IF(@tipoPagamento=3)
BEGIN
    INSERT INTO grocery.PAGAMENTO
    (ID_venda,Valor,ID_conta_corr,ID_tipo_pag)
    VALUES
    (@idVenda,@total,@idContaCorr,@tipoPagamento);
    EXEC grocery.sp_InsertOUTContaCorrente @idContaCorr, @total
END
ELSE
BEGIN
    INSERT INTO grocery.PAGAMENTO
    (ID_venda,Valor,ID_tipo_pag)
    VALUES
    (@idVenda,@total,@tipoPagamento)
END
GO
</code>```

All the code related to this SP is here PasteBin

答:
As written, the BEGIN is in the wrong place:

```<code>CREATE PROC grocery.sp_PagamentoTotalValorVenda (
    @idVenda INT,
    @tipoPagamento INT
) AS
BEGIN
    DECLARE @total FLOAT;
    DECLARE @idContaCorr INT;
    DECLARE @idCliente INT;

    SELECT @total = SUM(PROD.PVP)
    FROM grocery.ITEM_VENDA AS IV JOIN
         grocery.PRODUTO AS PROD
         ON IV.ID_produto = PROD.ID
    WHERE IV.ID_venda = @idVenda;
</code>```

Note: Business applications should almost never use FLOAT.  Your data type should be either MONEY or DECIMAL/NUMERIC.  These are fixed point types and more accurate when rounding and comparing monetary values.

Body:
This is for a project for a university class.

I'm creating an SP that declares a float to save the total price from another table values and uses it to insert and update another table, but the problem is that the @total is always NULL. If I take the "SELECT ... SUM" and execute it outside the SP with my values, it works!!

CREATE PROC grocery.sp_PagamentoTotalValorVenda
@idVenda INT,
@tipoPagamento INT
AS
    DECLARE @total FLOAT
    DECLARE @idContaCorr INT
    DECLARE @idCliente INT

    SELECT @total=SUM(PROD.PVP)
    FROM grocery.ITEM_VENDA AS IV JOIN grocery.PRODUTO AS PROD ON IV.ID_produto = PROD.ID
    WHERE IV.ID_venda=@idVenda
BEGIN
    SELECT @idContaCorr=CONTCORR.ID,@idCliente=VEN.Nif_cliente
    FROM grocery.VENDA AS VEN JOIN grocery.CONTA_CORRENTE AS CONTCORR ON VEN.Nif_cliente=CONTCORR.Nif_cliente
END
BEGIN
    UPDATE grocery.VENDA
    SET Valor=@total
    WHERE ID=@idVenda
END
IF(@tipoPagamento=3)
BEGIN
    INSERT INTO grocery.PAGAMENTO
    (ID_venda,Valor,ID_conta_corr,ID_tipo_pag)
    VALUES
    (@idVenda,@total,@idContaCorr,@tipoPagamento);
    EXEC grocery.sp_InsertOUTContaCorrente @idContaCorr, @total
END
ELSE
BEGIN
    INSERT INTO grocery.PAGAMENTO
    (ID_venda,Valor,ID_tipo_pag)
    VALUES
    (@idVenda,@total,@tipoPagamento)
END
GO

All the code related to this SP is here PasteBin

Body:
As written, the BEGIN is in the wrong place:

CREATE PROC grocery.sp_PagamentoTotalValorVenda (
    @idVenda INT,
    @tipoPagamento INT
) AS
BEGIN
    DECLARE @total FLOAT;
    DECLARE @idContaCorr INT;
    DECLARE @idCliente INT;

    SELECT @total = SUM(PROD.PVP)
    FROM grocery.ITEM_VENDA AS IV JOIN
         grocery.PRODUTO AS PROD
         ON IV.ID_produto = PROD.ID
    WHERE IV.ID_venda = @idVenda;

Note: Business applications should almost never use FLOAT.  Your data type should be either MONEY or DECIMAL/NUMERIC.  These are fixed point types and more accurate when rounding and comparing monetary values.


问:
How to display Firebase data in HTML [object Object] currently displaying
I've set up the Javascript below to display all the objects in my Firebase database. But when I display it on my webpage it only returns [object Object]. What am I missing?

```<code> events.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
    var eventkey = childSnapshot.key;
    var eventdata = childSnapshot.val();

    var card = document.createElement('div');
    card.setAttribute('class', 'card');
    document.body.appendChild(card);

    var cardtitle = document.createElement('p');
    cardtitle.innerHTML = eventdata;
    card.appendChild(cardtitle);

   console.log(event);
   });
});
</code>```

Thanks for your help

答:
I got it working. Saw this post which helped: Display data from Firebase database in a HTML page

This is what I changed:

```<code>// displays event listings on browse.html - modified 3/6/17
   events.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
    var eventkey = childSnapshot.key;
    var eventdata = childSnapshot.val();

    // listing data to be displayed
    var browsetitle = childSnapshot.val().title; // added this
    var browsecity = childSnapshot.val().city; // added this

    var card = document.createElement('div');
    card.setAttribute('class', 'card');
    document.body.appendChild(card);

    var cardtitle = document.createElement('p');
    cardtitle.innerHTML = browsetitle + browsecity; // added this
    card.appendChild(cardtitle);

   console.log(eventdata); // changed this to see what was going on
    });
 });
</code>```

Body:
I've set up the Javascript below to display all the objects in my Firebase database. But when I display it on my webpage it only returns [object Object]. What am I missing?

 events.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
    var eventkey = childSnapshot.key;
    var eventdata = childSnapshot.val();

    var card = document.createElement('div');
    card.setAttribute('class', 'card');
    document.body.appendChild(card);

    var cardtitle = document.createElement('p');
    cardtitle.innerHTML = eventdata;
    card.appendChild(cardtitle);

   console.log(event);
   });
});

Thanks for your help

Body:
I got it working. Saw this post which helped: Display data from Firebase database in a HTML page

This is what I changed:

// displays event listings on browse.html - modified 3/6/17
   events.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
    var eventkey = childSnapshot.key;
    var eventdata = childSnapshot.val();

    // listing data to be displayed
    var browsetitle = childSnapshot.val().title; // added this
    var browsecity = childSnapshot.val().city; // added this

    var card = document.createElement('div');
    card.setAttribute('class', 'card');
    document.body.appendChild(card);

    var cardtitle = document.createElement('p');
    cardtitle.innerHTML = browsetitle + browsecity; // added this
    card.appendChild(cardtitle);

   console.log(eventdata); // changed this to see what was going on
    });
 });


问:
loop through new.env() R (quantmod)
I am new to R, loop and quantmod.
I am trying to build a database that can be used be used easier for calculations (in a column format).

I was wondering how you would use a "loop" to automate the process below.
I am simply binding two datasets together.

As you can see, I have bound two datasets together using rbind, Google and Apple stock prices. If I was to have 100 stocks, this process would take a very long time, thus I was wondering how I could automate this process?

```<code>library(quantmod)
tickers<- c("AAPL", "GOOG")
all<- new.env()
getSymbols(tickers,src="google", env = all, from = Sys.Date()-100, to = Sys.Date())

apple_share<- all$AAPL
colnames(apple_share)<- c("Open", "High", "Low", "Close", "Volume")
apple_share$Ticker<- rep(1, nrow(apple_share))

google_share<- all$GOOG
colnames(google_share)<- c("Open", "High", "Low", "Close", "Volume")
google_share$Ticker<- rep(2, nrow(google_share))

combined_data<- rbind(apple_share,google_share)
</code>```

Many thanks,

Shoups

Title: loop through new.env() R (quantmod)

Body:
I am new to R, loop and quantmod.
I am trying to build a database that can be used be used easier for calculations (in a column format).

I was wondering how you would use a "loop" to automate the process below.
I am simply binding two datasets together.

As you can see, I have bound two datasets together using rbind, Google and Apple stock prices. If I was to have 100 stocks, this process would take a very long time, thus I was wondering how I could automate this process?

library(quantmod)
tickers<- c("AAPL", "GOOG")
all<- new.env()
getSymbols(tickers,src="google", env = all, from = Sys.Date()-100, to = Sys.Date())

apple_share<- all$AAPL
colnames(apple_share)<- c("Open", "High", "Low", "Close", "Volume")
apple_share$Ticker<- rep(1, nrow(apple_share))

google_share<- all$GOOG
colnames(google_share)<- c("Open", "High", "Low", "Close", "Volume")
google_share$Ticker<- rep(2, nrow(google_share))

combined_data<- rbind(apple_share,google_share)

Many thanks,

Shoups

Body:
We can get the values using mget

lst <- Map(cbind, mget(tickers, envir = all), Ticker = seq_along(tickers))
lst <- lapply(lst, function(x) setNames(x, sub("[^.]+\\.", "", names(x))))
newdat <- do.call(rbind, lst)
head(newdat)
#             Open   High    Low  Close   Volume Ticker
#2017-02-23 137.38 137.48 136.30 136.53 20788186      1
#2017-02-23 830.12 832.46 822.88 831.33  1472771      2
#2017-02-24 135.91 136.66 135.28 136.66 21776585      1
#2017-02-24 827.73 829.00 824.20 828.64  1392202      2
#2017-02-27 137.14 137.44 136.28 136.93 20257426      1
#2017-02-27 824.55 830.50 824.00 829.28  1101466      2


问:
PHP - take element from array and push it at the beginning
Is there a simple way to take specific array element, and place it at the beginning of the array?

For example I have this array:

```<code>$array = [

    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Joana Doe',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Some Name',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Another Name',
        'age'  => 44,
        'sex'  => 'f'
    ],

];
</code>```

and I want to take array where name is Some Name, and place it at the beginning  of the array.

答:
Of course. Simple element swapping.</p>

```<code>$tmp = $array[2]; // 3rd element
$array[2] = $array[0]; // set 3rd to values with 1st
$array[0] = $tmp; // set first to values with 3rd
</code>```

Body:
Is there a simple way to take specific array element, and place it at the beginning of the array?

For example I have this array:

$array = [

    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Joana Doe',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Some Name',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Another Name',
        'age'  => 44,
        'sex'  => 'f'
    ],

];

and I want to take array where name is Some Name, and place it at the beginning  of the array.

Body:
Of course. Simple element swapping.

$tmp = $array[2]; // 3rd element
$array[2] = $array[0]; // set 3rd to values with 1st
$array[0] = $tmp; // set first to values with 3rd


问:
jcarousel - How do I link an image to a url?
Using jcarousel connected carousels, I would like to link each image to an url. I have tried adding link tags around each image, but the link only works if the image is the first or the last in the slideshow, otherwise, clicking on the image skips to the next slide.
An example can be seen here:
https://www.bostonrescue.net/special-needs-spotlight/special-needs-spotlight.html

HEAD:

```<code><link href="../styles.css" rel="stylesheet" type="text/css"/>
<link href="../jcarousel.connected-carousels.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/jquery.jcarousel.min.js"></script>
<script type="text/javascript" src="/scripts/jcarousel.connected-carousels.js"></script>
</code>```

HTML:

```<code><div class="connected-carousels">
  <div class="stage">
    <div class="carousel carousel-stage">
      <ul>
        <li><a href="/url_1.html"><img src="/image_1.jpg" alt="Image 1" /></a><br /><a href="/url_1.html">Image 1</a></li>
        <li><a href="/url_2.html"><img src="/image_2.jpg" alt="Image 2" /></a><br /><a href="/url_2.html">Image 2</a></li>
        <li><a href="/url_3.html"><img src="/image_3.jpg" alt="Image 3" /></a><br /><a href="/url_3.html">Image 3</a></li>
      </ul>
    </div>
    <a href="#" class="prev prev-stage"><span>‹</span></a>
    <a href="#" class="next next-stage"><span>›</span></a>
</div>
</code>```

CSS:

```<code> /** Stage container **/

.connected-carousels .stage {
    width: 585px;
    margin: 20px auto;
    position: relative;
}

.connected-carousels .carousel img {
    border-style: solid;
    border-width: 2px;
    margin: 0px 5px 5px 0px;
    height: 200px;
}

.connected-carousels .photo-credits {
    position: absolute;
    right: 15px;
    bottom: 0;
    font-size: 13px;
    color: #fff;
    text-shadow: 0 0 1px rgba(0, 0, 0, 0.85);
    opacity: .66;
}

.connected-carousels .photo-credits a {
    color: #fff;
}

/** Navigation container **/

.connected-carousels .navigation {
    width: 500px;
    margin: 20px auto;
    position: relative;
}

/** Shared carousel styles **/

.connected-carousels .carousel {
    overflow: hidden;
    position: relative;
}

.connected-carousels .carousel ul {
    width: 20000em;
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
}

.connected-carousels .carousel li {
    float: left;
    text-align: center;
}

/** Stage carousel specific styles **/

.connected-carousels .carousel-stage {
    height: 225px;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
       -moz-border-radius: 5px;
            border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

/** Navigation carousel specific styles **/

.connected-carousels .carousel-navigation {
    height: 60px;
    width: 480px;
    background: #fff;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
       -moz-border-radius: 5px;
            border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

.connected-carousels .carousel-navigation li {
    cursor: pointer;
}

.connected-carousels .carousel-navigation li img {
    display: block;
    border: 5px solid #fff;
}

.connected-carousels .carousel-navigation li.active img {
    border-color: #ccc;
}

/** Stage carousel controls **/

.connected-carousels .prev-stage,
.connected-carousels .next-stage {
    display: block;
    position: absolute;
    top: 0;
    width: 305px;
    height: 410px;
    color: #fff;
}

.connected-carousels .prev-stage {
    left: 0;
}

.connected-carousels .next-stage {
    right: 0;
}

.connected-carousels .prev-stage.inactive,
.connected-carousels .next-stage.inactive {
    display: none;
}

.connected-carousels .prev-stage span,
.connected-carousels .next-stage span {
    display: none;
    position: absolute;
    top: 25%;
    width: 30px;
    height: 30px;
    text-align: center;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 24px/27px Arial, sans-serif;
    -webkit-border-radius: 30px;
       -moz-border-radius: 30px;
            border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-stage span {
    left: 20px;
}

.connected-carousels .next-stage span {
    right: 20px;
}

.connected-carousels .prev-stage:hover span,
.connected-carousels .next-stage:hover span {
    display: block;
}

/** Navigation carousel controls **/

.connected-carousels .prev-navigation,
.connected-carousels .next-navigation {
    display: block;
    position: absolute;
    width: 30px;
    height: 30px;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 16px/29px Arial, sans-serif;
    -webkit-border-radius: 30px;
       -moz-border-radius: 30px;
            border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-navigation {
    left: -15px;
    top: 22px;
    text-indent: 6px;
}

.connected-carousels .next-navigation {
    right: -15px;
    top: 22px;
    text-indent: 20px;
}

.connected-carousels .prev-navigation.inactive,
.connected-carousels .next-navigation.inactive {
    opacity: .5;
    cursor: default;
}
</code>```

JAVASCRIPT: jcarousel.connected-carousels.js (connector function loaded in addition to jquery.jcarousel.min.js)

```<code>(function($) {
    // This is the connector function.
    // It connects one item from the navigation carousel to one item from the
    // stage carousel.
    // The default behaviour is, to connect items with the same index from both
    // carousels. This might _not_ work with circular carousels!
    var connector = function(itemNavigation, carouselStage) {
        return carouselStage.jcarousel('items').eq(itemNavigation.index());
    };

    $(function() {
        // Setup the carousels. Adjust the options for both carousels here.
        var carouselStage      = $('.carousel-stage').jcarousel();
        var carouselNavigation = $('.carousel-navigation').jcarousel();

        // We loop through the items of the navigation carousel and set it up
        // as a control for an item from the stage carousel.
        carouselNavigation.jcarousel('items').each(function() {
            var item = $(this);

            // This is where we actually connect to items.
            var target = connector(item, carouselStage);

            item
                .on('jcarouselcontrol:active', function() {
                    carouselNavigation.jcarousel('scrollIntoView', this);
                    item.addClass('active');
                })
                .on('jcarouselcontrol:inactive', function() {
                    item.removeClass('active');
                })
                .jcarouselControl({
                    target: target,
                    carousel: carouselStage
                });
        });

        // Setup controls for the stage carousel
        $('.prev-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

        $('.next-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });

        // Setup controls for the navigation carousel
        $('.prev-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

        $('.next-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });
    });
})(jQuery);
</code>```

答:
In order to achieve your result you need to change the height, width of your:

```<code>.connected-carousels .prev-stage,
.connected-carousels .next-stage
</code>```

var connector = function(itemNavigation, carouselStage) {
    return carouselStage.jcarousel('items').eq(itemNavigation.index());
};

$(function() {
    // Setup the carousels. Adjust the options for both carousels here.
    var carouselStage      = $('.carousel-stage').jcarousel();
    var carouselNavigation = $('.carousel-navigation').jcarousel();

    // We loop through the items of the navigation carousel and set it up
    // as a control for an item from the stage carousel.
    carouselNavigation.jcarousel('items').each(function() {
        var item = $(this);

        // This is where we actually connect to items.
        var target = connector(item, carouselStage);

        item
                .on('jcarouselcontrol:active', function() {
                    carouselNavigation.jcarousel('scrollIntoView', this);
                    item.addClass('active');
                })
                .on('jcarouselcontrol:inactive', function() {
                    item.removeClass('active');
                })
                .jcarouselControl({
                    target: target,
                    carousel: carouselStage
                });
    });

    // Setup controls for the stage carousel
    $('.prev-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

    $('.next-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });

    // Setup controls for the navigation carousel
    $('.prev-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

    $('.next-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/** Stage container **/
.connected-carousels .stage {
    width: 450px;
    margin: 20px auto;
    position: relative;
}

.connected-carousels .carousel img {
    border-style: solid;
    border-width: 2px;
    margin: 0px 5px 5px 0px;
    height: 200px;
}

.connected-carousels .photo-credits {
    position: absolute;
    right: 15px;
    bottom: 0;
    font-size: 13px;
    color: #fff;
    text-shadow: 0 0 1px rgba(0, 0, 0, 0.85);
    opacity: .66;
}

.connected-carousels .photo-credits a {
    color: #fff;
}

/** Navigation container **/
.connected-carousels .navigation {
    width: 500px;
    margin: 20px auto;
    position: relative;
}

/** Shared carousel styles **/
.connected-carousels .carousel {
    overflow: hidden;
    position: relative;
}

.connected-carousels .carousel ul {
    width: 20000em;
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
}

.connected-carousels .carousel li {
    float: left;
    text-align: center;
}

/** Stage carousel specific styles **/
.connected-carousels .carousel-stage {
    height: 250px;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

/** Navigation carousel specific styles **/
.connected-carousels .carousel-navigation {
    height: 60px;
    width: 480px;
    background: #fff;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

.connected-carousels .carousel-navigation li {
    cursor: pointer;
}

.connected-carousels .carousel-navigation li img {
    display: block;
    border: 5px solid #fff;
}

.connected-carousels .carousel-navigation li.active img {
    border-color: #ccc;
}

/** Stage carousel controls **/
.connected-carousels .prev-stage,
.connected-carousels .next-stage {
    display: block;
    position: absolute;
    top: 100px;
    left: 410px;
    width: 30px;
    height: 20px;
    color: #fff;
}

.connected-carousels .prev-stage {
    left: 0;
}

.connected-carousels .next-stage {
    right: 0;
}

.connected-carousels .prev-stage.inactive,
.connected-carousels .next-stage.inactive {
    display: none;
}

.connected-carousels .prev-stage span,
.connected-carousels .next-stage span {
    display: none;
    position: absolute;
    top: 25%;
    width: 30px;
    height: 30px;
    text-align: center;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 24px/27px Arial, sans-serif;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-stage span {
    left: 20px;
}

.connected-carousels .next-stage span {
    right: 20px;
}

.connected-carousels .prev-stage:hover span,
.connected-carousels .next-stage:hover span {
    display: block;
}

/** Navigation carousel controls **/
.connected-carousels .prev-navigation,
.connected-carousels .next-navigation {
    display: block;
    position: absolute;
    width: 30px;
    height: 30px;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 16px/29px Arial, sans-serif;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-navigation {
    left: -15px;
    top: 22px;
    text-indent: 6px;
}

.connected-carousels .next-navigation {
    right: -15px;
    top: 22px;
    text-indent: 20px;
}

.connected-carousels .prev-navigation.inactive,
.connected-carousels .next-navigation.inactive {
    opacity: .5;
    cursor: default;
}</code>```

Image 1

Image 2

Image 3

Image 4

Image 5

        ‹
        ›

```

Body:
Using jcarousel connected carousels, I would like to link each image to an url. I have tried adding link tags around each image, but the link only works if the image is the first or the last in the slideshow, otherwise, clicking on the image skips to the next slide.
An example can be seen here:
https://www.bostonrescue.net/special-needs-spotlight/special-needs-spotlight.html

HEAD:

<link href="../styles.css" rel="stylesheet" type="text/css"/>
<link href="../jcarousel.connected-carousels.css" rel="stylesheet" type="text/css"/>

HTML:

Image 1

Image 2

Image 3

    ‹
    ›

CSS:

 /** Stage container **/

.connected-carousels .stage {
    width: 585px;
    margin: 20px auto;
    position: relative;
}

.connected-carousels .carousel img {
    border-style: solid;
    border-width: 2px;
    margin: 0px 5px 5px 0px;
    height: 200px;
}

.connected-carousels .photo-credits {
    position: absolute;
    right: 15px;
    bottom: 0;
    font-size: 13px;
    color: #fff;
    text-shadow: 0 0 1px rgba(0, 0, 0, 0.85);
    opacity: .66;
}

.connected-carousels .photo-credits a {
    color: #fff;
}

/** Navigation container **/

.connected-carousels .navigation {
    width: 500px;
    margin: 20px auto;
    position: relative;
}

/** Shared carousel styles **/

.connected-carousels .carousel {
    overflow: hidden;
    position: relative;
}

.connected-carousels .carousel ul {
    width: 20000em;
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
}

.connected-carousels .carousel li {
    float: left;
    text-align: center;
}

/** Stage carousel specific styles **/

.connected-carousels .carousel-stage {
    height: 225px;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
       -moz-border-radius: 5px;
            border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

/** Navigation carousel specific styles **/

.connected-carousels .carousel-navigation {
    height: 60px;
    width: 480px;
    background: #fff;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
       -moz-border-radius: 5px;
            border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

.connected-carousels .carousel-navigation li {
    cursor: pointer;
}

.connected-carousels .carousel-navigation li img {
    display: block;
    border: 5px solid #fff;
}

.connected-carousels .carousel-navigation li.active img {
    border-color: #ccc;
}

/** Stage carousel controls **/

.connected-carousels .prev-stage,
.connected-carousels .next-stage {
    display: block;
    position: absolute;
    top: 0;
    width: 305px;
    height: 410px;
    color: #fff;
}

.connected-carousels .prev-stage {
    left: 0;
}

.connected-carousels .next-stage {
    right: 0;
}

.connected-carousels .prev-stage.inactive,
.connected-carousels .next-stage.inactive {
    display: none;
}

.connected-carousels .prev-stage span,
.connected-carousels .next-stage span {
    display: none;
    position: absolute;
    top: 25%;
    width: 30px;
    height: 30px;
    text-align: center;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 24px/27px Arial, sans-serif;
    -webkit-border-radius: 30px;
       -moz-border-radius: 30px;
            border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-stage span {
    left: 20px;
}

.connected-carousels .next-stage span {
    right: 20px;
}

.connected-carousels .prev-stage:hover span,
.connected-carousels .next-stage:hover span {
    display: block;
}

/** Navigation carousel controls **/

.connected-carousels .prev-navigation,
.connected-carousels .next-navigation {
    display: block;
    position: absolute;
    width: 30px;
    height: 30px;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 16px/29px Arial, sans-serif;
    -webkit-border-radius: 30px;
       -moz-border-radius: 30px;
            border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
       -moz-box-shadow: 0 0 2px #999;
            box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-navigation {
    left: -15px;
    top: 22px;
    text-indent: 6px;
}

.connected-carousels .next-navigation {
    right: -15px;
    top: 22px;
    text-indent: 20px;
}

.connected-carousels .prev-navigation.inactive,
.connected-carousels .next-navigation.inactive {
    opacity: .5;
    cursor: default;
}

JAVASCRIPT: jcarousel.connected-carousels.js (connector function loaded in addition to jquery.jcarousel.min.js)

(function($) {
    // This is the connector function.
    // It connects one item from the navigation carousel to one item from the
    // stage carousel.
    // The default behaviour is, to connect items with the same index from both
    // carousels. This might _not_ work with circular carousels!
    var connector = function(itemNavigation, carouselStage) {
        return carouselStage.jcarousel('items').eq(itemNavigation.index());
    };

    $(function() {
        // Setup the carousels. Adjust the options for both carousels here.
        var carouselStage      = $('.carousel-stage').jcarousel();
        var carouselNavigation = $('.carousel-navigation').jcarousel();

        // We loop through the items of the navigation carousel and set it up
        // as a control for an item from the stage carousel.
        carouselNavigation.jcarousel('items').each(function() {
            var item = $(this);

            // This is where we actually connect to items.
            var target = connector(item, carouselStage);

            item
                .on('jcarouselcontrol:active', function() {
                    carouselNavigation.jcarousel('scrollIntoView', this);
                    item.addClass('active');
                })
                .on('jcarouselcontrol:inactive', function() {
                    item.removeClass('active');
                })
                .jcarouselControl({
                    target: target,
                    carousel: carouselStage
                });
        });

        // Setup controls for the stage carousel
        $('.prev-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

        $('.next-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });

        // Setup controls for the navigation carousel
        $('.prev-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

        $('.next-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });
    });
})(jQuery);

Body:
In order to achieve your result you need to change the height, width of your:

.connected-carousels .prev-stage,
.connected-carousels .next-stage

var connector = function(itemNavigation, carouselStage) {
    return carouselStage.jcarousel('items').eq(itemNavigation.index());
};

$(function() {
    // Setup the carousels. Adjust the options for both carousels here.
    var carouselStage      = $('.carousel-stage').jcarousel();
    var carouselNavigation = $('.carousel-navigation').jcarousel();

    // We loop through the items of the navigation carousel and set it up
    // as a control for an item from the stage carousel.
    carouselNavigation.jcarousel('items').each(function() {
        var item = $(this);

        // This is where we actually connect to items.
        var target = connector(item, carouselStage);

        item
                .on('jcarouselcontrol:active', function() {
                    carouselNavigation.jcarousel('scrollIntoView', this);
                    item.addClass('active');
                })
                .on('jcarouselcontrol:inactive', function() {
                    item.removeClass('active');
                })
                .jcarouselControl({
                    target: target,
                    carousel: carouselStage
                });
    });

    // Setup controls for the stage carousel
    $('.prev-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

    $('.next-stage')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });

    // Setup controls for the navigation carousel
    $('.prev-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '-=1'
            });

    $('.next-navigation')
            .on('jcarouselcontrol:inactive', function() {
                $(this).addClass('inactive');
            })
            .on('jcarouselcontrol:active', function() {
                $(this).removeClass('inactive');
            })
            .jcarouselControl({
                target: '+=1'
            });
});

/** Stage container **/
.connected-carousels .stage {
    width: 450px;
    margin: 20px auto;
    position: relative;
}

.connected-carousels .carousel img {
    border-style: solid;
    border-width: 2px;
    margin: 0px 5px 5px 0px;
    height: 200px;
}

.connected-carousels .photo-credits {
    position: absolute;
    right: 15px;
    bottom: 0;
    font-size: 13px;
    color: #fff;
    text-shadow: 0 0 1px rgba(0, 0, 0, 0.85);
    opacity: .66;
}

.connected-carousels .photo-credits a {
    color: #fff;
}

/** Navigation container **/
.connected-carousels .navigation {
    width: 500px;
    margin: 20px auto;
    position: relative;
}

/** Shared carousel styles **/
.connected-carousels .carousel {
    overflow: hidden;
    position: relative;
}

.connected-carousels .carousel ul {
    width: 20000em;
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
}

.connected-carousels .carousel li {
    float: left;
    text-align: center;
}

/** Stage carousel specific styles **/
.connected-carousels .carousel-stage {
    height: 250px;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

/** Navigation carousel specific styles **/
.connected-carousels .carousel-navigation {
    height: 60px;
    width: 480px;
    background: #fff;
    border: 10px solid #fff;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

.connected-carousels .carousel-navigation li {
    cursor: pointer;
}

.connected-carousels .carousel-navigation li img {
    display: block;
    border: 5px solid #fff;
}

.connected-carousels .carousel-navigation li.active img {
    border-color: #ccc;
}

/** Stage carousel controls **/
.connected-carousels .prev-stage,
.connected-carousels .next-stage {
    display: block;
    position: absolute;
    top: 100px;
    left: 410px;
    width: 30px;
    height: 20px;
    color: #fff;
}

.connected-carousels .prev-stage {
    left: 0;
}

.connected-carousels .next-stage {
    right: 0;
}

.connected-carousels .prev-stage.inactive,
.connected-carousels .next-stage.inactive {
    display: none;
}

.connected-carousels .prev-stage span,
.connected-carousels .next-stage span {
    display: none;
    position: absolute;
    top: 25%;
    width: 30px;
    height: 30px;
    text-align: center;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 24px/27px Arial, sans-serif;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-stage span {
    left: 20px;
}

.connected-carousels .next-stage span {
    right: 20px;
}

.connected-carousels .prev-stage:hover span,
.connected-carousels .next-stage:hover span {
    display: block;
}

/** Navigation carousel controls **/
.connected-carousels .prev-navigation,
.connected-carousels .next-navigation {
    display: block;
    position: absolute;
    width: 30px;
    height: 30px;
    background: #4E443C;
    color: #fff;
    text-decoration: none;
    text-shadow: 0 0 1px #000;
    font: 16px/29px Arial, sans-serif;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 30px;
    -webkit-box-shadow: 0 0 2px #999;
    -moz-box-shadow: 0 0 2px #999;
    box-shadow: 0 0 2px #999;
}

.connected-carousels .prev-navigation {
    left: -15px;
    top: 22px;
    text-indent: 6px;
}

.connected-carousels .next-navigation {
    right: -15px;
    top: 22px;
    text-indent: 20px;
}

.connected-carousels .prev-navigation.inactive,
.connected-carousels .next-navigation.inactive {
    opacity: .5;
    cursor: default;
}

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jcarousel/0.3.5/jquery.jcarousel.min.js"></script>

<div class="connected-carousels">
    <div class="stage">
        <div class="carousel carousel-stage">
            <ul>
                <li><a href="/url_1.html"><img src="https://dummyimage.com/100x100/fff/000&text=1" alt="Image 1" /></a><br /><a href="/url_1.html">Image 1</a></li>
                <li><a href="/url_2.html"><img src="https://dummyimage.com/100x100/fff/000&text=2" alt="Image 2" /></a><br /><a href="/url_2.html">Image 2</a></li>
                <li><a href="/url_3.html"><img src="https://dummyimage.com/100x100/fff/000&text=3" /></a><br /><a href="/url_3.html">Image 3</a></li>
                <li><a href="/url_4.html"><img src="https://dummyimage.com/100x100/fff/000&text=4" /></a><br /><a href="/url_4.html">Image 4</a></li>
                <li><a href="/url_5.html"><img src="https://dummyimage.com/100x100/fff/000&text=5" /></a><br /><a href="/url_5.html">Image 5</a></li>
            </ul>
        </div>
        <a href="#" class="prev prev-stage"><span>&lsaquo;</span></a>
        <a href="#" class="next next-stage"><span>&rsaquo;</span></a>
    </div>
</div>


问:
Run Facebook Flow on a Continuos Integration Meteor application
I have a Meteor application with Circle CI as continuous integration service.

Facebook Flow is running locally with the following .flowconfig:

```<code>[ignore]
.*/node_modules/.*

[options]
module.name_mapper='^\/\(.*\)$' -> '<PROJECT_ROOT>/\1'
module.name_mapper='^meteor\/\(.*\):\(.*\)$' -> '<PROJECT_ROOT>/.meteor/local/build/programs/server/packages/\1_\2'
module.name_mapper='^meteor\/\(.*\)$' -> '<PROJECT_ROOT>/.meteor/local/build/programs/server/packages/\1'
</code>```

In CI I get errors like:

```<code>client/main.jsx:4
  4: import { Meteor } from 'meteor/meteor';
                            ^^^^^^^^^^^^^^^ meteor/meteor. Required module not found
</code>```

Flow seems not to find my modules. The rewrite rules do not apply. With SSH access to Circle CI I found ot that the <PROJECT_ROOT>/.meteor/local directory is not present.

Once I run meteor on the CI machine the directory will appear.

Problem: If I run meteor the Meteor server will start up and my test will time out.

As far as I see I need to either

Adapt my .flowconfig or

Find a way to get Meteor to create the directory without running meteor or

Find a way to kill the meteor process once the server is running.

答:
I ran into the same issue and came up with my own derivation based on the OP's answer. I run this script on every CI build to ensure that Meteor will always install any new atmosphere packages that I'm shipping with.

```<code>#!/bin/bash

# Install meteor
if [ -d ~/.meteor ]; then sudo ln -s ~/.meteor/meteor /usr/local/bin/meteor; fi
if [ ! -e $HOME/.meteor/meteor ]; then curl https://install.meteor.com | sh; fi

OUTPUT=/tmp/meteor-launch.log
PROGRAM=meteor
$PROGRAM > $OUTPUT  &
PID=$!
echo Program is running under pid: $PID

# Start meteor to install atmosphere packages
while true; do
   tail -1 $OUTPUT
   grep "Your application is crashing." $OUTPUT
   # Cancel the program once meteor has started
   if [ $? -eq 0 ] ; then
      break
   fi
   sleep 10
done

kill $PID || echo "Killing process with pid $PID failed, try manual kill with -9 argument."
</code>```

Body:
I have a Meteor application with Circle CI as continuous integration service.

Facebook Flow is running locally with the following .flowconfig:

[ignore]
.*/node_modules/.*

[options]
module.name_mapper='^\/\(.*\)$' -> '<PROJECT_ROOT>/\1'
module.name_mapper='^meteor\/\(.*\):\(.*\)$' -> '<PROJECT_ROOT>/.meteor/local/build/programs/server/packages/\1_\2'
module.name_mapper='^meteor\/\(.*\)$' -> '<PROJECT_ROOT>/.meteor/local/build/programs/server/packages/\1'

In CI I get errors like:

client/main.jsx:4
  4: import { Meteor } from 'meteor/meteor';
                            ^^^^^^^^^^^^^^^ meteor/meteor. Required module not found

Flow seems not to find my modules. The rewrite rules do not apply. With SSH access to Circle CI I found ot that the <PROJECT_ROOT>/.meteor/local directory is not present.

Once I run meteor on the CI machine the directory will appear.

Problem: If I run meteor the Meteor server will start up and my test will time out.

As far as I see I need to either

Adapt my .flowconfig or

Find a way to get Meteor to create the directory without running meteor or

Find a way to kill the meteor process once the server is running.

Body:
I ran into the same issue and came up with my own derivation based on the OP's answer. I run this script on every CI build to ensure that Meteor will always install any new atmosphere packages that I'm shipping with.

#!/bin/bash

# Install meteor
if [ -d ~/.meteor ]; then sudo ln -s ~/.meteor/meteor /usr/local/bin/meteor; fi
if [ ! -e $HOME/.meteor/meteor ]; then curl https://install.meteor.com | sh; fi

OUTPUT=/tmp/meteor-launch.log
PROGRAM=meteor
$PROGRAM > $OUTPUT  &
PID=$!
echo Program is running under pid: $PID

# Start meteor to install atmosphere packages
while true; do
   tail -1 $OUTPUT
   grep "Your application is crashing." $OUTPUT
   # Cancel the program once meteor has started
   if [ $? -eq 0 ] ; then
      break
   fi
   sleep 10
done

kill $PID || echo "Killing process with pid $PID failed, try manual kill with -9 argument."


问:
Try/exception command in while loop (Python)
I am trying to create a function that extracts a batch of patients in a given directory of CT scans. Some patients' scans fail during image segmentation, so I am looping over the list until I find the "batch number" of patients with successful segmentation. However, the code below loops infinitely when I run it. I do not understand why the 'break' does not terminate the loop.

Any ideas would be greatly appreciated!:)

```<code>INPUT_FOLDER = "D:\CT\stage1\stage1"

patients = os.listdir(INPUT_FOLDER)
patients.sort()

#start, n_batch are given as parameters.

data = start    #initialize index for list 'validation_patients'
valid_patient_list = []   #create an empty list for patient data with successful segmentation

while True:   #iterate over variable 'data' until the list of valid patients is completed

    try:
        x = patients[data]
        load_scan(INPUT_FOLDER + '\\' + x)
        valid_patient_list.append(data)

        if len(valid_patient_list) == n_batch:  #escape while loop when the list length is equal to designated batch size

            break

        else: data += 1 #if the length of list is smaller than the desired batch number, go for the next patient

    except IndexError:
        data += 1 # go for the next data: do not add this one to the list
        continue

#some more code below that deals with the valid_patient_list, but the loop runs infinitely..
</code>```

答:
Well if you get an IndexError on patients[data], it is because data >= len(patients), an index out of range error, so patients[data+1] will also raise an IndexErorr.

This causes your code to go to an infinite loop between raising and catching exceptions, and the code never reaches the 'break' part.

Body:
I am trying to create a function that extracts a batch of patients in a given directory of CT scans. Some patients' scans fail during image segmentation, so I am looping over the list until I find the "batch number" of patients with successful segmentation. However, the code below loops infinitely when I run it. I do not understand why the 'break' does not terminate the loop.

Any ideas would be greatly appreciated!:)

INPUT_FOLDER = "D:\CT\stage1\stage1"

patients = os.listdir(INPUT_FOLDER)
patients.sort()

#start, n_batch are given as parameters.

data = start    #initialize index for list 'validation_patients'
valid_patient_list = []   #create an empty list for patient data with successful segmentation

while True:   #iterate over variable 'data' until the list of valid patients is completed

    try:
        x = patients[data]
        load_scan(INPUT_FOLDER + '\\' + x)
        valid_patient_list.append(data)

        if len(valid_patient_list) == n_batch:  #escape while loop when the list length is equal to designated batch size

            break

        else: data += 1 #if the length of list is smaller than the desired batch number, go for the next patient

    except IndexError:
        data += 1 # go for the next data: do not add this one to the list
        continue

#some more code below that deals with the valid_patient_list, but the loop runs infinitely..


问:
ASP.Net Core RC2 JWT Bearer token
Does anyone have a complete example of using JWT bearer tokens with ASP.Net Core RC2 Identity? Preferably showing how to create the token also.

Thanks,
Paul

答:
I have a full example for ASP.NET Core with JWT auth: https://github.com/wilsonwu/netcoreauth

By the way, the database is SQL Server.

Title: ASP.Net Core RC2 JWT Bearer token