问:
Test if Convert.ChangeType will work between two types
This is a follow-up to this question about converting values with reflection. Converting an object of a certain type to another type can be done like this:

```<code>object convertedValue = Convert.ChangeType(value, targetType);
</code>```

Given two Type instances (say FromType and ToType), is there a way to test whether the conversion will succeed?

E.g. can I write an extension method like this:

```<code>public static class TypeExtensions
{
    public static bool CanChangeType(this Type fromType, Type toType)
    {
        // what to put here?
    }
}
</code>```

EDIT: This is what I have right now. Ugly, but I don't see another way yet...

```<code>bool CanChangeType(Type sourceType, Type targetType)
{
  try
  {
    var instanceOfSourceType = Activator.CreateInstance(sourceType);
    Convert.ChangeType(instanceOfSourceType, targetType);
    return true; // OK, it can be converted
  }
  catch (Exception ex)
  {
    return false;
  }
</code>```

答:
Based on what has already been answered on both questions I came up with this, (needs c#7)

```<code>public static object ChangeType(object value, Type conversion)
    {
        var type = conversion;

        if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
            {
                return null;
            }

            type = Nullable.GetUnderlyingType(type);
        }

        return Convert.ChangeType(value, type);
    }

public static (bool IsSuccess, object Value) TryChangeType(object value, Type conversionType)
    {
        (bool IsSuccess, object Value) response = (false, null);
        var isNotConvertible =
            conversionType == null
                || value == null
                || !(value is IConvertible)
            || !(value.GetType() == conversionType);
        if (isNotConvertible)
        {
            return response;
        }
        try
        {
            response = (true, ChangeType(value, conversionType));
        }
        catch (Exception)
        {
            response.Value = null;
        }

        return response;
    }
}
</code>```

Production code example:

```<code>public Item()
    {
        foreach (var pinfo in GetType().GetProperties())
        {
            object value = 0;
            var response = ReflectionHelpers.TryChangeType(value, pinfo.PropertyType);
            if(response.IsSuccess)
            {
                pinfo.SetValue(this, response.Value);
            }
        }
    }
</code>```

This starts all properties possible with 0.

Body:
This is a follow-up to this question about converting values with reflection. Converting an object of a certain type to another type can be done like this:

object convertedValue = Convert.ChangeType(value, targetType);

Given two Type instances (say FromType and ToType), is there a way to test whether the conversion will succeed?

E.g. can I write an extension method like this:

public static class TypeExtensions
{
    public static bool CanChangeType(this Type fromType, Type toType)
    {
        // what to put here?
    }
}

EDIT: This is what I have right now. Ugly, but I don't see another way yet...

bool CanChangeType(Type sourceType, Type targetType)
{
  try
  {
    var instanceOfSourceType = Activator.CreateInstance(sourceType);
    Convert.ChangeType(instanceOfSourceType, targetType);
    return true; // OK, it can be converted
  }
  catch (Exception ex)
  {
    return false;
  }

Body:
Based on what has already been answered on both questions I came up with this, (needs c#7)

public static object ChangeType(object value, Type conversion)
    {
        var type = conversion;

        if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
            {
                return null;
            }

            type = Nullable.GetUnderlyingType(type);
        }

        return Convert.ChangeType(value, type);
    }

public static (bool IsSuccess, object Value) TryChangeType(object value, Type conversionType)
    {
        (bool IsSuccess, object Value) response = (false, null);
        var isNotConvertible =
            conversionType == null
                || value == null
                || !(value is IConvertible)
            || !(value.GetType() == conversionType);
        if (isNotConvertible)
        {
            return response;
        }
        try
        {
            response = (true, ChangeType(value, conversionType));
        }
        catch (Exception)
        {
            response.Value = null;
        }

        return response;
    }
}

Production code example:

public Item()
    {
        foreach (var pinfo in GetType().GetProperties())
        {
            object value = 0;
            var response = ReflectionHelpers.TryChangeType(value, pinfo.PropertyType);
            if(response.IsSuccess)
            {
                pinfo.SetValue(this, response.Value);
            }
        }
    }

This starts all properties possible with 0.


来源: stackexchange

问:
How to connect an Arduino Uno Wifi Developer's Edition to PHP
I want to send data from my arduino uno wifi to PHP which in turn sends the value to Firebase. The PHP code works since I can manually send data to the database from my browser. However, I am not able to do so from the arduino uno wifi.

Here are my codes:

```<code>#include <Wire.h>
#include <UnoWiFiDevEd.h>

void setup() {
  Wifi.begin();
  Wifi.println("REST Server is up");
}

void loop() {
  while(Wifi.available()){
    process(Wifi);
  }
  delay(50);
}

void process(WifiData client){
  client.println("POST /xxx.php?value=22.00 HTTP/1.1");
  client.println("HOST: xxx.xxx.com");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.println();
}
</code>```

答:
Look at the RestClient example of UnoWiFiDevEd library. You must use Ciao object to send a request. (The example doesn't work because arduino.org is off)

If you find out that the UnoWiFiDevEd library and the factory firmware of Uno WiFi are very limited, strange and slow, you can change the firmware to WiFi Link and use the general networking WiFi Link library with Uno WiFi Serial1.

ContentLicense: CC BY-SA 3.0

Body:
I want to send data from my arduino uno wifi to PHP which in turn sends the value to Firebase. The PHP code works since I can manually send data to the database from my browser. However, I am not able to do so from the arduino uno wifi.

Here are my codes:

#include <Wire.h>
#include <UnoWiFiDevEd.h>

void setup() {
  Wifi.begin();
  Wifi.println("REST Server is up");
}

void loop() {
  while(Wifi.available()){
    process(Wifi);
  }
  delay(50);
}

void process(WifiData client){
  client.println("POST /xxx.php?value=22.00 HTTP/1.1");
  client.println("HOST: xxx.xxx.com");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.println();
}


问:
How to push Android Project to existing private empty repository in github with Android Studio?
I am trying to push android project to private empty repo with android studio . But I cannot find simple solution. How can I do this ? </p>

答:
If you are pushing to a private repo in a local location ie. a private server.:

Assuming you have set up local git repository, cd into the remote location and clone your local repository with git clone 'path to local repo'

cloning will set the local repo as a remote, so we have to remove that with git remote remove origin

make the remote repo bare with git config --bool core.bare true

Then in your local repository add the remote with git remote add origin 'location to remote git repo'

Now you should be able to push to remote in Android studio.


问:
Django test(django.test.client) put call, with many headers don't work

Django (2.0)

Python 3.5.2

Without REMOTE_ADDR it works very well:

```<code>client = Client()

response = client.put('/api/v1/person/address/',{},
    HTTP_API_KEY=self.model_login_director.token)
</code>```

With REMOTE_ADDR in a put() call doesn't work (but works for GET and POST requests).

```<code>client = Client()

response = client.put('/api/v1/person/address/',{},
    REMOTE_ADDR='127.0.0.8',
    HTTP_API_KEY=self.model_login_director.token)
</code>```

Message error

```<code>Traceback (most recent call last):
      File "/home/wborba/project/willcode/sofia/api/test/testsControllerPersonAddress.py", line 577, in test_person_address_update_address_id_missing
        HTTP_API_KEY=self.model_login_director.token)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 548, in put
        response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 366, in put
        secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 404, in generic
        return self.request(**r)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 485, in request
        raise exc_value
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner
        response = get_response(request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 69, in view
        return self.dispatch(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 89, in dispatch
        return handler(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
        return view_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 62, in _wrapper
        return bound_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/home/wborba/project/willcode/sofia/api/Business/Auth.py", line 145, in wrap
        return function(request, model_login, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 58, in bound_func
        return func.__get__(self, type(self))(*args2, **kwargs2)
    TypeError: put() takes 2 positional arguments but 3 were given
</code>```

答:
Solved!

it was just my lack of attention.
In the method that meets the PUT request, missing there were some mandatory parameters, for example:

```<code>def put(self,request,model_login,*args,**kwargs):
</code>```

i have worked with https://docs.djangoproject.com/en/2.0/topics/class-based-views/

Body:
Django (2.0)

Python 3.5.2

Without REMOTE_ADDR it works very well:

client = Client()

response = client.put('/api/v1/person/address/',{},
    HTTP_API_KEY=self.model_login_director.token)

With REMOTE_ADDR in a put() call doesn't work (but works for GET and POST requests).

client = Client()

response = client.put('/api/v1/person/address/',{},
    REMOTE_ADDR='127.0.0.8',
    HTTP_API_KEY=self.model_login_director.token)

Message error

Traceback (most recent call last):
      File "/home/wborba/project/willcode/sofia/api/test/testsControllerPersonAddress.py", line 577, in test_person_address_update_address_id_missing
        HTTP_API_KEY=self.model_login_director.token)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 548, in put
        response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 366, in put
        secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 404, in generic
        return self.request(**r)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 485, in request
        raise exc_value
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner
        response = get_response(request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 69, in view
        return self.dispatch(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 89, in dispatch
        return handler(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
        return view_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 62, in _wrapper
        return bound_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/home/wborba/project/willcode/sofia/api/Business/Auth.py", line 145, in wrap
        return function(request, model_login, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 58, in bound_func
        return func.__get__(self, type(self))(*args2, **kwargs2)
    TypeError: put() takes 2 positional arguments but 3 were given

Body:
Solved!

it was just my lack of attention.
In the method that meets the PUT request, missing there were some mandatory parameters, for example:

def put(self,request,model_login,*args,**kwargs):

i have worked with https://docs.djangoproject.com/en/2.0/topics/class-based-views/


问:
extracting lines if the first field matches another list saved in a different file -- shell command
I have two files. One contains a list of items, e.g.,

Allie
Bob
John
Laurie
```

<p>Another file (file2) contains a different list of items in a different order, but some items might overlap with the items in file 1, e.g, </p>

<pre class="lang-none prettyprint-override"><code>Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23
</code>```

I want to intersect these two files and extract only those lines from file 2 whose first field matches an item in field 1.

i.e., my output should be

Allie 45 56 67 23
Laurie 45 56 6 75
```

<p>(preferably in this order, but it's OK if not)</p>

<p><code>grep -f file1 file2</code> doesn't do what I want. </p>

<p>I also need something efficient because the second file is HUGE.</p>

<p>I also tried this:</p>

```awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1
```

答:
No need for complex joins, it is a filtering function

```<code>$ grep -wFf file1 file2

Laurie 45 56 6 75
Allie 45 56 67 23
</code>```

has the benefit or keeping the order in file2 as well. -w option is for full word matches to eliminate sub-string matches to create false positives.  Of course if your sample input is not representative and your data may contain key like entries in other fields this will not work without qualifying beginning of line.

Body:
I have two files. One contains a list of items, e.g.,

Allie
Bob
John
Laurie

Another file (file2) contains a different list of items in a different order, but some items might overlap with the items in file 1, e.g,

Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23

I want to intersect these two files and extract only those lines from file 2 whose first field matches an item in field 1.

i.e., my output should be

Allie 45 56 67 23
Laurie 45 56 6 75

(preferably in this order, but it's OK if not)

grep -f file1 file2 doesn't do what I want.

I also need something efficient because the second file is HUGE.

I also tried this:

awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1

Body:
No need for complex joins, it is a filtering function

$ grep -wFf file1 file2

Laurie 45 56 6 75
Allie 45 56 67 23

has the benefit or keeping the order in file2 as well. -w option is for full word matches to eliminate sub-string matches to create false positives.  Of course if your sample input is not representative and your data may contain key like entries in other fields this will not work without qualifying beginning of line.


问:
Getting error: package com.mydomain.databinding does not exist when building multi-module project and class with databinding as generic type
I have a multi-module project where I set my databinding classes as a generic type requirement:

```<code>public abstract class BaseActivity<DataBinding extends ViewDataBinding> {
    //Rest of the code...
}
</code>```

However, if I extend this activity on a submodule, sometimes I get the following build error:

error: cannot find symbol public void myMethod(MyActivityBinding dataBinding) {

error: package com.mydomain.databinding does not exist import com.mydomain.databinding.MyActivityBinding;

Sometimes, creating another activity that extends from MyActivity and putting it on the main app module fixes the issue. But in some cases I can't pinpoint the problem, and I consistently get the same error message.

I already tried cleaning and rebuilding the project and also invalidating Android Studio cache and restarting it without success.

Any ideas on how to at least investigate what could be causing this problem?

答:
Not sure about the root cause of the problem but I have similar issue and posted answer here https://stackoverflow.com/a/47718646/3160214

In few words, this is how solution looks like:

```<code>class A<BINDING extends ViewDataBinding> extends BaseActivity<BINDING> {
    protected ABinding binding;

    void init(){
        binding = (ABinding) DataBindingUtil.setContentView(this, R.layout.a);
    }
}
</code>```

and pass the same binding to the child class from the submodule

```<code>class B<ABinding> {
    // you can use instance in this class
}
</code>```

Body:
I have a multi-module project where I set my databinding classes as a generic type requirement:

public abstract class BaseActivity<DataBinding extends ViewDataBinding> {
    //Rest of the code...
}

However, if I extend this activity on a submodule, sometimes I get the following build error:

error: cannot find symbol public void myMethod(MyActivityBinding dataBinding) {

error: package com.mydomain.databinding does not exist import com.mydomain.databinding.MyActivityBinding;

Sometimes, creating another activity that extends from MyActivity and putting it on the main app module fixes the issue. But in some cases I can't pinpoint the problem, and I consistently get the same error message.

I already tried cleaning and rebuilding the project and also invalidating Android Studio cache and restarting it without success.

Any ideas on how to at least investigate what could be causing this problem?

Body:
Not sure about the root cause of the problem but I have similar issue and posted answer here https://stackoverflow.com/a/47718646/3160214

In few words, this is how solution looks like:

class A<BINDING extends ViewDataBinding> extends BaseActivity<BINDING> {
    protected ABinding binding;

    void init(){
        binding = (ABinding) DataBindingUtil.setContentView(this, R.layout.a);
    }
}

and pass the same binding to the child class from the submodule

class B<ABinding> {
    // you can use instance in this class
}


问:
Java RequestDispatcher returns null in Jetty Embedded app
I have the following code

```<code>//response.sendRedirect("Cmmdc");
RequestDispatcher requestDispatcher=request.getRequestDispatcher("Cmmdc");
System.out.println(requestDispatcher);--- **NULL**
requestDispatcher.forward(request,response);
</code>```

My main:

```<code>Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);

handler.addServletWithMapping(Start.class, "/Start");
handler.addServletWithMapping(Cmmdc.class, "/Cmmdc");
handler.addServletWithMapping(OptiuneServlet.class, "/OptiuneServlet");
handler.addServletWithMapping(Prim.class, "/Prim");
handler.addServletWithMapping(ValidatorCMMDC.class, "/ValidatorCMMDC");
handler.addServletWithMapping(ValidatorPrim.class, "/ValidatorPrim");
System.out.println("Start server jetty embedded");
server.start();
server.join();
</code>```

My question is how should I call the cmmdc servlet to return a reference and not null?

答:
RequestDispatcher requires a ServletContext (no way around that).

Your setup has none.

Don't use ServletHandler directly like that, use ServletContextHandler instead.

Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
context.addServlet(Start.class, "/Start");
// etc ...
server.start();
server.join();
```

Body:
I have the following code

//response.sendRedirect("Cmmdc");
RequestDispatcher requestDispatcher=request.getRequestDispatcher("Cmmdc");
System.out.println(requestDispatcher);--- **NULL**
requestDispatcher.forward(request,response);

My main:

Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);

handler.addServletWithMapping(Start.class, "/Start");
handler.addServletWithMapping(Cmmdc.class, "/Cmmdc");
handler.addServletWithMapping(OptiuneServlet.class, "/OptiuneServlet");
handler.addServletWithMapping(Prim.class, "/Prim");
handler.addServletWithMapping(ValidatorCMMDC.class, "/ValidatorCMMDC");
handler.addServletWithMapping(ValidatorPrim.class, "/ValidatorPrim");
System.out.println("Start server jetty embedded");
server.start();
server.join();

My question is how should I call the cmmdc servlet to return a reference and not null?


问:
How do you enable customers use their openid on your website, just like stackoverflow?
I want customers to use their openId on my site. I googled for this but didn't find any good tutorial. I use PHP and MySQL.

There is one at Plaxo. But it says we should download something from JanRain.com.

I saw the openId module of Drupal. It doesn't want anything to be downloaded.

Can anyone tell me what to do exactly?

答:
Zend Framework has also developed an OpenID Component that can be used as a standalone (i.e. not dependent upon the rest of the framework), or, at the very least, requires minimal interaction (I believe it uses a responce object for redirection).

Either way, it's Yet Another Option, and especially usefull if building a ZF backed site.

OwnerDisplayName: iSattar

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: J. Kenzal Hunter Sr.


问:
Making an svg image object clickable with onclick, avoiding absolute positioning
I have tried to change the images on my site from img to svg, changing img tags to embed and object tags. But, implementing the onclick function, which previously was contained in the img tag, is proving most difficult.

I found onclick had no effect when placed inside the object or embed tag.

So, I made a div exclusively for the svg, and placed onclick in this div tag.  But, no effect unless visitor clicks on the edges/padding of the image.

I have read about overlaying a div, but am trying to avoid using absolute positioning, or specifying position at all.

Is there another way to apply onclick to a svg?

Has anyone encountered this problem? Questions and suggestions are welcome.

答:
If you just use inline svg there is no problem.

<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">
  <circle id="circle1" r="30" cx="34" cy="34" onclick="circle1.style.fill='yellow';"
            style="fill: red; stroke: blue; stroke-width: 2"/>
  </svg>
  ```


问:
W3C CSS Validator shows error on svg rule: "only 0 can be a unit"
I have an svg that changes its fill and stroke on hover with some transition. I tried using W3C CSS Validator on my css and one of the errors that showed up was this:

```<code>only 0 can be a unit. You must put a unit after your number : 2
</code>```

But I cannot identify nor understand what the error is. What is wrong in here:

```<code>svg a:hover circle {
  fill: #ffff00;
  fill-opacity: .5;
  stroke: black;
  stroke-width: 2;
  transition: 200ms;
  transition-timing-function: ease-in-out;
  -webkit-transition: 200ms;
  -webkit-transition-timing-function: ease-in-out
}
</code>```

答: You need a unit (e.g. px) after the 2 in stroke-width: 2;. So like stroke-width: 2px;. Zero (0) is allowed because it has no value and a unit is irrelevant on it.

Body:
I have an svg that changes its fill and stroke on hover with some transition. I tried using W3C CSS Validator on my css and one of the errors that showed up was this:

only 0 can be a unit. You must put a unit after your number : 2

But I cannot identify nor understand what the error is. What is wrong in here:

svg a:hover circle {
  fill: #ffff00;
  fill-opacity: .5;
  stroke: black;
  stroke-width: 2;
  transition: 200ms;
  transition-timing-function: ease-in-out;
  -webkit-transition: 200ms;
  -webkit-transition-timing-function: ease-in-out
}


问:
What's the difference between "?android:" and "@android:" in an android layout xml file?
What's the difference between "?android:" and "@android:" in an android layout xml file?  They seem to be interchangeable ways of reusing android SDK resources.

The only difference I discovered is illustrated by the following example.

Here the TextView's right edge is rendered aligned with the left edge of the ImageButton

```<code> <RelativeLayout
    android:id="@id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888888">
    <TextView
        android:id="@android:id/text1"
        android:layout_alignParentLeft="true"
        android:text="blah blah"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@android:id/button1" />
    <ImageButton
        android:id="@android:id/button1"
        android:layout_alignParentRight="true"
        style="@style/PlusButton" />
</RelativeLayout>
</code>```

Here, however, the right edge of the TextView is aligned with the right edge of the RelativeLayout.  The TextView overlaps the ImageButton.

```<code><RelativeLayout
    android:id="@id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888888">
    <TextView
        android:id="@android:id/text1"
        android:layout_alignParentLeft="true"
        android:text="blah blah"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="?android:id/button1" />
    <ImageButton
        android:id="?android:id/button1"
        android:layout_alignParentRight="true"
        style="@style/PlusButton" />
</RelativeLayout>
</code>```

The only difference between the two layouts is the use of @android vs ?android.  Both compile with no errors.

Thanks much.

答:
Prefixing the ID with a question mark indicates that you want to access a style attribute that's defined in a style theme, rather than hard-coding the attribute.

See "Referencing Style Attributes" here: accessing-resources

Body:
What's the difference between "?android:" and "@android:" in an android layout xml file?  They seem to be interchangeable ways of reusing android SDK resources.

The only difference I discovered is illustrated by the following example.

Here the TextView's right edge is rendered aligned with the left edge of the ImageButton

 <RelativeLayout
    android:id="@id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888888">
    <TextView
        android:id="@android:id/text1"
        android:layout_alignParentLeft="true"
        android:text="blah blah"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@android:id/button1" />
    <ImageButton
        android:id="@android:id/button1"
        android:layout_alignParentRight="true"
        style="@style/PlusButton" />
</RelativeLayout>

Here, however, the right edge of the TextView is aligned with the right edge of the RelativeLayout.  The TextView overlaps the ImageButton.

<RelativeLayout
    android:id="@id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888888">
    <TextView
        android:id="@android:id/text1"
        android:layout_alignParentLeft="true"
        android:text="blah blah"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="?android:id/button1" />
    <ImageButton
        android:id="?android:id/button1"
        android:layout_alignParentRight="true"
        style="@style/PlusButton" />
</RelativeLayout>

The only difference between the two layouts is the use of @android vs ?android.  Both compile with no errors.

Thanks much.


问:
python unittest handle exception handling
I want to unittest an exception handling in my unittest and I'm using assertRaises to check if exception is thrown.

```<code>class Add():
    def __init__(self, x, y):
        if type(x) != int or type(y) != int:
            raise Exception('Not a valid number')

Add(None, None)

import unittest
from test2 import Add
class TestAdd(unittest.TestCase):
    def test_check_for_valid_nos(self):
        self.assertRaises(Exception, Add(None,None))

if __name__ == '__main__':
    unittest.main()
</code>```

When I run this piece of code it still raises exception. I expect the test to pass saying that the exception has been raised.

答:
You should not directly execute your Add function when passing it to assertRaises, rather pass the positional arguments afterwards.

```<code>assertRaises(Exception, Add, None, None)
</code>```

This allows the internal implementation of assertRaises to control executing your function and checking for the right exception. If you invoke the function directly, such as assertRaises(Exception, Add(None, None)), then assertRaises must fully evaluate Add(None, None) before its own function body can execute, because it has to consume the result of that function call as an argument for its input. This is an unprotected call to Add with arguments that will trigger an exception, so the Exception is raised before the actual function body of assertRaises is ever used.

Body:
I want to unittest an exception handling in my unittest and I'm using assertRaises to check if exception is thrown.

class Add():
    def __init__(self, x, y):
        if type(x) != int or type(y) != int:
            raise Exception('Not a valid number')

Add(None, None)

import unittest
from test2 import Add
class TestAdd(unittest.TestCase):
    def test_check_for_valid_nos(self):
        self.assertRaises(Exception, Add(None,None))

if __name__ == '__main__':
    unittest.main()

When I run this piece of code it still raises exception. I expect the test to pass saying that the exception has been raised.

Body:
You should not directly execute your Add function when passing it to assertRaises, rather pass the positional arguments afterwards.

assertRaises(Exception, Add, None, None)

This allows the internal implementation of assertRaises to control executing your function and checking for the right exception. If you invoke the function directly, such as assertRaises(Exception, Add(None, None)), then assertRaises must fully evaluate Add(None, None) before its own function body can execute, because it has to consume the result of that function call as an argument for its input. This is an unprotected call to Add with arguments that will trigger an exception, so the Exception is raised before the actual function body of assertRaises is ever used.


问:
Transpose rows and columns in a 2D array
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:

```<code>    //Creating rows and columns for text file
    echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($result as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";
}

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}
</code>```

My first table displays as expected and looks somthing like this:

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

I need it to appear as such (i.e rotating the position of the rows and columns):

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

I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

答:
This should give you what you need.

```<code>function transpose($array_one) {
    $array_two = [];
    foreach ($array_one as $key => $item) {
        foreach ($item as $subkey => $subitem) {
            $array_two[$subkey][$key] = $subitem;
        }
    }
    return $array_two;
}
</code>```

Then just pipe your existing array into the function and render the resulting array.

Body:
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:

    //Creating rows and columns for text file
    echo "
Data Table
";
    echo "
";
    foreach($result as $key=>$value){
        echo "
";
        foreach($value as $v){
            echo "".$v."	";
        }
        echo "
";

    }
    echo "
";
}

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}

My first table displays as expected and looks somthing like this:

1 2 3 4 5
6 7 8 9 10

I need it to appear as such (i.e rotating the position of the rows and columns):

1 6
2 7
3 8
4 9
5 10

I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

Body:
This should give you what you need.

function transpose($array_one) {
    $array_two = [];
    foreach ($array_one as $key => $item) {
        foreach ($item as $subkey => $subitem) {
            $array_two[$subkey][$key] = $subitem;
        }
    }
    return $array_two;
}

Then just pipe your existing array into the function and render the resulting array.


问:
Universal Framework Binaries: Why Build Simulator and Archive Device?
I am using a script provided by Greg Brown to successfully build a universal framework binary. Here are the two lines that invoke xcodebuild:

xcodebuild archive -project $FRAMEWORK_DIR/$FRAMEWORK.xcodeproj -scheme $FRAMEWORK -sdk iphoneos SYMROOT=$BUILD

xcodebuild build -project $FRAMEWORK_DIR/$FRAMEWORK.xcodeproj -target $FRAMEWORK -sdk iphonesimulator SYMROOT=$BUILD

Note that the archive action is being used to produce the device (arm64 architecture) whereas the build action is being used to produce the simulator (x86_64 architecture).

In a different article entitled iOS 9 Universal Cocoa Touch Frameworks the author remarks: "Note that you will both have to build with your Simulator and Archive with your device to get a universal."

So, what's up with build vs archive? Why not build both?

答:
So, what's up with build vs archive? Why not build both?

The way it works is that Apple doesn't allow simulator binaries (x86_64 and i386) to be uploaded to the app store. If your frameworks contain those binaries, then you won't be able to upload the containing app to the app store.

You would distribute your framework with all the possible binaries so that it can run on Simulators and devices alike. But would like to strip off those Simulator binaries before uploading to the app store.

P.S. I've explained this in detail in another answer here. The answer also explains as to why the issue doesn't exist when using frameworks via Cocoapods.

Edit:

The difference between build vs archive is that archive accepts a scheme to run.

```<code>An Xcode scheme defines a collection of targets to build, a configuration to use when building, and a collection of tests to execute.
</code>```

Also,

```<code>You cannot use archive option for the iOS Simulator platform.
</code>```

You could essentially use xcodebuild build for both of the platforms. You will essentially get the same result. The commands that I use to build my framework are as follows (both commands use the build action):

```<code>xcodebuild -target ${PROJECT_NAME} ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphoneos BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build
xcodebuild -target ${PROJECT_NAME} ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphonesimulator BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build
</code>```

Body:
So, what's up with build vs archive? Why not build both?

The way it works is that Apple doesn't allow simulator binaries (x86_64 and i386) to be uploaded to the app store. If your frameworks contain those binaries, then you won't be able to upload the containing app to the app store.

You would distribute your framework with all the possible binaries so that it can run on Simulators and devices alike. But would like to strip off those Simulator binaries before uploading to the app store.

P.S. I've explained this in detail in another answer here. The answer also explains as to why the issue doesn't exist when using frameworks via Cocoapods.

Edit:

The difference between build vs archive is that archive accepts a scheme to run.

An Xcode scheme defines a collection of targets to build, a configuration to use when building, and a collection of tests to execute.

Also,

You cannot use archive option for the iOS Simulator platform.

You could essentially use xcodebuild build for both of the platforms. You will essentially get the same result. The commands that I use to build my framework are as follows (both commands use the build action):

xcodebuild -target ${PROJECT_NAME} ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphoneos BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build
xcodebuild -target ${PROJECT_NAME} ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphonesimulator BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" clean build


问:
Scaffold-DbContext doesn't produce models
I am trying to run Scaffold-DbContext to generate some models from an old system. I am running the following command:

Scaffold-DbContext "Data Source=localhost\SQLEXPRESS;Initial Catalog=MAINT_TRAINING;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer

The problem is that I get absolutely no output... No models, no errors, no confirmations...

The tables in the DB all have primary keys.

Am I doing something wrong?

答:
You may be hitting issue #10298. Try adding the following to your *.csproj:

<PropertyGroup>
  <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>
```


问:
How to pass runtime parameter to ViewComponent Invoke method
I am trying out the .net Core ViewComponents instead of partial views.  Here is my scenario.
I have a View that contains a few kendo listbox controls.  When an item in any of the listbox is clicked, I need to invoke a webcomponent with the selected item id in the listbox.  I also need to keep the ViewComponents hidden until the user clicks on a listbox item.  Each listbox has it's own ViewComponent because the control in the viewcomponent is different for each listbox.  So, I will have to hide some viewcomponents and show only the relevant component for the listbox.  I have no clue how to pass the item id in any listbox when selected, to the Invoke method.

Here is my main view (non essential code removed)

```<code><div style="height:25%; width:100%; background-color:antiquewhite;">
    <b>Sections:</b>
        @(Html.Kendo().ListBox()
                    .Name( "SectionListBox" )
                    .Selectable( ListBoxSelectable.Single )
                    .DataTextField( "Name" )
                    .DataValueField( "id" )
                    //.DataSource( ds => ds.Read( r => r.Action( "GetAllPageSectionsAsync", "Home" ) ) )
                    .Events( e => e.Change( "onSectionSelected" ) )
                    .HtmlAttributes( new { style = "width:95%;height:85%;" } )
        )
</div>
<div style="height:25%; width:100%; background-color:cornsilk;">
    <b>Fields:</b>
        @(Html.Kendo().ListBox()
                    .Name( "FieldListBox" )
                    .Selectable( ListBoxSelectable.Single )
                    .DataTextField( "Name" )
                    .DataValueField( "id" )
                    //.DataSource( ds => ds.Read( r => r.Action( "GetAllFieldsAsync", "Home" ) ) )
                    .HtmlAttributes( new { style = "width:95%;height:85%;" } )
        )
</div>
<div class="col-md-8" style="height:100%">
    <div class="col-md-12" style="height:100%;">
        <div id="AttrGridDiv" class="col-md-5" style="height:40%;">
            <label>Attributes</label>
            @await Component.InvokeAsync( "PageAttributes", new { pageId = 123 } )
        </div>
    </div>
</div>
</code>```

and here is my component view:

```<code>@model IEnumerable<aaaaaaaa>

@(Html.Kendo().Grid<dynamic>()
.Name( "Attributes" )
.Selectable()
.Sortable()
.Scrollable()
.Events( e => e.Change( "onAttributeGridSelected" ) )
.HtmlAttributes( new { style = "width:100%;" } )
//.DataSource( ds => ds
//.Ajax()
//.Read( r => r.Action( "GetPages", "Home" ).Type( HttpVerbs.Post ) ) )
)
</code>```

and here is my View Component:

```<code>[ViewComponent(Name ="PageAttributes")]
public class PageAttibutesViewComponent : ViewComponent
{
    private IRulesEngineService reService;

    public PageAttibutesViewComponent( IRulesEngineService _reService)
    {
        reService = _reService;
    }

    public async Task<IViewComponentResult> InvokeAsync(int pageId)
    {
        var pageAttribs = await reService.GetAllPageAttributesAsync( pageId );
        return View( pageAttribs );
    }
}
</code>```

I have only shown one of the components.  I have a few similar components that I need to invoke based on which listbox is selected the components will render different controls.

So, again, my questions are:

How to invoke the component from the view Conditionally?

How to pass the selected id from the chosen listbox to the invoke
method?

答:
ViewComponents are processed by Razor (or any alternative view engine that supports the feature). What you try to achieve happens in the browser, but you need some server-side processing as well.

As I see it, you must (1) capture the ListBox change (Javascript), then (2) post it back to the controller (again Javscript) which (3) will process the request, change the model depending on what was submitted (C#), and finally (4) return the view with changed model, so that you the view can figure out how (what param value) to invoke the ViewComponent in question (C#, Razor). You may also decide to return a different view, but that is somewhat uncommon. Not so very straightforward, but this is web. Long ago, in web forms check boxes and drop downs had property PostBack (or simillar), which, when checked, did basically the same.

In effect, the post back to the controller, the changed view model, and finally the view, rendered with the changed model result in change of ViewComponent's invocation.

There are three types of ViewComponent invocations in Core 2.0. You can read about them here: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components#invoking-a-view-component.

Body:
I am trying out the .net Core ViewComponents instead of partial views.  Here is my scenario.
I have a View that contains a few kendo listbox controls.  When an item in any of the listbox is clicked, I need to invoke a webcomponent with the selected item id in the listbox.  I also need to keep the ViewComponents hidden until the user clicks on a listbox item.  Each listbox has it's own ViewComponent because the control in the viewcomponent is different for each listbox.  So, I will have to hide some viewcomponents and show only the relevant component for the listbox.  I have no clue how to pass the item id in any listbox when selected, to the Invoke method.

Here is my main view (non essential code removed)

    Sections:
        @(Html.Kendo().ListBox()
                    .Name( "SectionListBox" )
                    .Selectable( ListBoxSelectable.Single )
                    .DataTextField( "Name" )
                    .DataValueField( "id" )
                    //.DataSource( ds => ds.Read( r => r.Action( "GetAllPageSectionsAsync", "Home" ) ) )
                    .Events( e => e.Change( "onSectionSelected" ) )
                    .HtmlAttributes( new { style = "width:95%;height:85%;" } )
        )

    Fields:
        @(Html.Kendo().ListBox()
                    .Name( "FieldListBox" )
                    .Selectable( ListBoxSelectable.Single )
                    .DataTextField( "Name" )
                    .DataValueField( "id" )
                    //.DataSource( ds => ds.Read( r => r.Action( "GetAllFieldsAsync", "Home" ) ) )
                    .HtmlAttributes( new { style = "width:95%;height:85%;" } )
        )

            Attributes
            @await Component.InvokeAsync( "PageAttributes", new { pageId = 123 } )

and here is my component view:

@model IEnumerable<aaaaaaaa>

@(Html.Kendo().Grid<dynamic>()
.Name( "Attributes" )
.Selectable()
.Sortable()
.Scrollable()
.Events( e => e.Change( "onAttributeGridSelected" ) )
.HtmlAttributes( new { style = "width:100%;" } )
//.DataSource( ds => ds
//.Ajax()
//.Read( r => r.Action( "GetPages", "Home" ).Type( HttpVerbs.Post ) ) )
)

and here is my View Component:

[ViewComponent(Name ="PageAttributes")]
public class PageAttibutesViewComponent : ViewComponent
{
    private IRulesEngineService reService;

    public PageAttibutesViewComponent( IRulesEngineService _reService)
    {
        reService = _reService;
    }

    public async Task<IViewComponentResult> InvokeAsync(int pageId)
    {
        var pageAttribs = await reService.GetAllPageAttributesAsync( pageId );
        return View( pageAttribs );
    }
}

I have only shown one of the components.  I have a few similar components that I need to invoke based on which listbox is selected the components will render different controls.

So, again, my questions are:

How to invoke the component from the view Conditionally?

How to pass the selected id from the chosen listbox to the invoke
method?


问:
Updating a map from a high-rate data flow
I have a multi-threaded Java application where a method [update(key, value)] updates a ConcurrentHashMap. For each key there will be more values received than can be put in the map and so once a key has been updated only the newest value of the threads waiting should be used to then update the map again. Or maybe there is some kind of lock that can be used where there is only ever 1 thread waiting - the one that has reached the lock last (effectively disposing of the thread already waiting)? It is important that the whole map is not locked which is why I haven't used a synchronized block around a normal HashMap as even if there are threads waiting on key A, key B should still be allowed to be updated as long as there are no threads already updating the value stored for B.

More succinctly, how do you update a map where key-value pairs are being received faster than updates can be made, using the last received value as the next update? So in the time A is updated to 1, values of 5, 3, 6, 8 are then received meaning the next update of A will be to 8.

答:
This is a difficult problem, and the root of the difficulty is in capturing the order in which the updates arrive.

If the updates already have an associated (fine grained) timestamp, then the solution is fairly straight-forward:

Define a Value class that hold the actual value and a timestamp.  It needs a synchronized setIfNewer(ActualValue v, Timestamp t) which updates the actual value if the supplied timestamp is more recent.

Define the map as ConcurrentHashMap<Key, Value>.

Use putIfAbsent to put values into the map.  If the putIfAbsent() returns a non-null value, use setIfNewer(...) to update it.

Note that this only works if the map updates can keep up in the long term; i.e. average data rate is not too high to cope with.

If the updates do not have an associated timestamp, then you've got a problem.  If you are having difficulty keeping up with the updates, then you will have difficulty adding an timestamp to the updates that accurately reflects the arrival time.  And that means that there is a risk that updates will be (in effect) reordered.  (If this is the case then I don't think the problem is solvable ... without changing the problem; see below.)

Some things that might work:

Do some profiling / performance analysis to figure out where the bottleneck really is.  It might not be in doing the map updates at all.  (After all ConcurrentHashMap is designed to be highly scalable.)

If there is strong affinity between the threads and the key values, then you could try 1) de-duping the updates in each thread using a per-thread LRU map, or 2) use a per-thread counter instead of a timestamp.

You could try partitioning the map based on the keyspace.

You could try adding more processors and/or more memory ... depending on what your profiling and monitoring are reporting.

You could try partitioning the entire application based on the keyspace.  If the real problem is that the application cannot keep up, this may be the only possible approach.


问:
How to select rows with information in a text file by using linux command
I just want to select certain info in separated rows in a text file. How do I deal with this?

For selecting row, which contains "SUBSCRIBERIDENTIFIER" and another row contains "LATEST_OFFLINE_TIME"

My output to look like following:

SUBSCRIBERIDENTIFIER=23481XXXXXX02

LATEST_OFFLINE_TIME=20170330191209

答: $ awk '/SUBSCRIBERIDENTIFIER/,/LATEST_OFFLINE_TIME/' file.txt


问:
3d patches from a 3d matrix
I have a 3d matrix (3x3x3), and I need to extract 3d patches (2x2x2) and transform them in vectors.

In 2d, simply:

I=randi(5,3,3);

2d_patches=im2col(I,[2 2],'sliding');

What about 3d?

I=randi(5,3,3,3);

3d_patches= ???

im2col just works in 2d. In 3d I should recombine the vectors 1 and 7, 2 and 8, ...
Is there any fast function for this task?

答:
Here is the other direction:
(It is pretty slow and there is definitely a faster way)

```<code>function [img] = patch2im_2d_time(patch, size_img, size_patch, size_skip, border)
Nx = size_img(1);
Ny = size_img(2);
Nt = size_img(5);

psz1 = size_patch(1);
psz2 = size_patch(2);
psz3 = size_patch(3);

%Extract blocks. One could save a lot here.
patches  = reshape(patch, [psz1 psz2 psz3 size(patch,2)]);
c = 1;
img2 = zeros(squeeze(size_img));
%Count for each pixel how many times we added smth to it.
add_count = zeros(size_img);

%The first three loops, loop through all the pixels in the image
for d=1:Nt-psz3+1
    for j=1:Nx-psz2+1
        for i=1:Ny-psz1+1
            %Here we get the next patch. The next patch is always
            %the patch that has the pixel at i,j,d at its top front corner.
            current_patch = patches(:,:,:,c);
            %counter for the next patch
            c = c + 1;
            %In this loop we add the patch values of each pixel in the
            %patch to the image. i,j,d is the base. We add the offset
            %ii jj and dd to it. This iteration takes psz^3 many
            %iterations.
            for dd=1:psz3
                for ii=1:psz2
                    for jj=1:psz1
                        img2(i+ii-1,j+jj-1,d+dd-1) = img2(i+ii-1,j+jj-1,d+dd-1) + current_patch(ii,jj,dd);
                        add_count(i+ii-1,j+jj-1,d+dd-1) = add_count(i+ii-1,j+jj-1,d+dd-1) + 1;
                    end
                end
            end

        end
    end
end
    img = flipud(rot90(img2 ./ add_count,1));
end
</code>```

Remember that MATLAB uses col major.

Title: 3d patches from a 3d matrix

Body:
Here is the other direction:
(It is pretty slow and there is definitely a faster way)

function [img] = patch2im_2d_time(patch, size_img, size_patch, size_skip, border)
Nx = size_img(1);
Ny = size_img(2);
Nt = size_img(5);

psz1 = size_patch(1);
psz2 = size_patch(2);
psz3 = size_patch(3);

%Extract blocks. One could save a lot here.
patches  = reshape(patch, [psz1 psz2 psz3 size(patch,2)]);
c = 1;
img2 = zeros(squeeze(size_img));
%Count for each pixel how many times we added smth to it.
add_count = zeros(size_img);

%The first three loops, loop through all the pixels in the image
for d=1:Nt-psz3+1
    for j=1:Nx-psz2+1
        for i=1:Ny-psz1+1
            %Here we get the next patch. The next patch is always
            %the patch that has the pixel at i,j,d at its top front corner.
            current_patch = patches(:,:,:,c);
            %counter for the next patch
            c = c + 1;
            %In this loop we add the patch values of each pixel in the
            %patch to the image. i,j,d is the base. We add the offset
            %ii jj and dd to it. This iteration takes psz^3 many
            %iterations.
            for dd=1:psz3
                for ii=1:psz2
                    for jj=1:psz1
                        img2(i+ii-1,j+jj-1,d+dd-1) = img2(i+ii-1,j+jj-1,d+dd-1) + current_patch(ii,jj,dd);
                        add_count(i+ii-1,j+jj-1,d+dd-1) = add_count(i+ii-1,j+jj-1,d+dd-1) + 1;
                    end
                end
            end

        end
    end
end
    img = flipud(rot90(img2 ./ add_count,1));
end

Remember that MATLAB uses col major.


问:
Is it good to use Kubernetes from Rancher container management platform?
If it isn't good, why?

In another words, what's the different from original Kubernetes?

答:
IMO using Kubernetes with Rancher is a great idea. I'm managing the rancher instances at my company and we'll move from Cattle to Kubernetes for several reasons:

Kubernetes

- Now widely used

- Open source

- Big companies supports its development

- RANCHER 2.0 WILL BE BUILT FOR KUBERNETES FIRST

I strongly recommand you to use Kubernetes if you plan to use Rancher.


问:
Setting the value of an array index

Hello Everyone,

I was trying to work out how to set Diff[0] equal to the sum of an equation and I found that when:

```<code>int a = 0;

System.out.println(Data[0] - Data[1]);   //The calculation is possible and correct

Diff[a] = Data[0] - Data[1];   //But this line outputs a value of 0

Diff[0] = Data[0] - Data[1];   //I have also tried this but still a value of 0
</code>```

Here is my code: No Errors

```<code>public static void main(String[] args) {

    Scanner numbers = new Scanner(System.in);

    int Numbers;
    int A;
    int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5, g = 6, h = 7, i = 8, j = 9, k = 10, l = 11, m = 12, n = 13, o = 14, p = 15, q = 16, r = 17;
    int num;
    int lengthOfArray;

    System.out.println("Welcome to Stone Pile");
    System.out.println("\nEnter the number of stones:");
    Numbers = numbers.nextInt();

    int Data[] = new int[Numbers];
    for (A = 0; A < Data.length; A++) {
        for (num = 1; num < Numbers; num++) {
            int numGen = ThreadLocalRandom.current().nextInt(1, 21);
            Data[A] = numGen;
        }
    }

    lengthOfArray = Data.length;

    System.out.println("\n");

    System.out.println(Data.length + " This is the length of the Data Array");

    System.out.println("\n");

    System.out.println(Data[0]);
    System.out.println(Data[1]);
    System.out.println(Data[2]);
    System.out.println(Data[3]);
    System.out.println(Data[4]);
    System.out.println(Data[5]);
    System.out.println(Data[6]);
    System.out.println(Data[7]);
    System.out.println(Data[8]);
    System.out.println(Data[9]);

    System.out.println("\n");

    int Diff[] = new int[20];

    System.out.println(Diff.length + " This is length of the Diff Array");

    System.out.println("\n");

    System.out.println(Diff[0]);
    System.out.println(Diff[1]);
    System.out.println(Diff[2]);
    System.out.println(Diff[3]);
    System.out.println(Diff[4]);
    System.out.println(Diff[5]);
    System.out.println(Diff[6]);
    System.out.println(Diff[7]);
    System.out.println(Diff[8]);
    System.out.println(Diff[9]);

    switch (lengthOfArray) {
        case 2:
            Diff[a] = Data[0] - Data[1];
            break;

        case 3:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            break;

        case 4:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            break;

        case 5:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            break;

        case 6:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            break;

        case 7:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            break;

        case 8:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            break;

        case 9:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            break;

        case 10:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            break;

        case 11:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            break;

        case 12:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            break;

        case 13:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            break;

        case 14:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            break;

        case 15:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            break;

        case 16:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            break;

        case 17:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            Diff[p] = Data[15] - Data[16];
            break;

        case 18:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            Diff[p] = Data[15] - Data[16];
            Diff[q] = Data[16] - Data[17];
            break;

        case 19:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            Diff[p] = Data[15] - Data[16];
            Diff[q] = Data[16] - Data[17];
            Diff[r] = Data[16] - Data[18];
            break;
    }
</code>```

Output:

20 This is the length of the Data Array

9
17
5
20
20
17
17
3
7
6

20 This is length of the Diff Array

0
0
0
0
0
0
0
0
0
0

The numbers in the Diff array should not be all 0's

I wondering if there's a way I can set the value of an array index, based off an equation.

答: Ignoring the ugly code, you should move the stub of printing Diff array after the switch stub. You printed Diff array out before assigning it with values.

Title: Setting the value of an array index

Body:
Hello Everyone,

I was trying to work out how to set Diff[0] equal to the sum of an equation and I found that when:

int a = 0;

System.out.println(Data[0] - Data[1]);   //The calculation is possible and correct

Diff[a] = Data[0] - Data[1];   //But this line outputs a value of 0

Diff[0] = Data[0] - Data[1];   //I have also tried this but still a value of 0

Here is my code: No Errors

public static void main(String[] args) {

    Scanner numbers = new Scanner(System.in);

    int Numbers;
    int A;
    int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5, g = 6, h = 7, i = 8, j = 9, k = 10, l = 11, m = 12, n = 13, o = 14, p = 15, q = 16, r = 17;
    int num;
    int lengthOfArray;

    System.out.println("Welcome to Stone Pile");
    System.out.println("\nEnter the number of stones:");
    Numbers = numbers.nextInt();

    int Data[] = new int[Numbers];
    for (A = 0; A < Data.length; A++) {
        for (num = 1; num < Numbers; num++) {
            int numGen = ThreadLocalRandom.current().nextInt(1, 21);
            Data[A] = numGen;
        }
    }

    lengthOfArray = Data.length;

    System.out.println("\n");

    System.out.println(Data.length + " This is the length of the Data Array");

    System.out.println("\n");

    System.out.println(Data[0]);
    System.out.println(Data[1]);
    System.out.println(Data[2]);
    System.out.println(Data[3]);
    System.out.println(Data[4]);
    System.out.println(Data[5]);
    System.out.println(Data[6]);
    System.out.println(Data[7]);
    System.out.println(Data[8]);
    System.out.println(Data[9]);

    System.out.println("\n");

    int Diff[] = new int[20];

    System.out.println(Diff.length + " This is length of the Diff Array");

    System.out.println("\n");

    System.out.println(Diff[0]);
    System.out.println(Diff[1]);
    System.out.println(Diff[2]);
    System.out.println(Diff[3]);
    System.out.println(Diff[4]);
    System.out.println(Diff[5]);
    System.out.println(Diff[6]);
    System.out.println(Diff[7]);
    System.out.println(Diff[8]);
    System.out.println(Diff[9]);

    switch (lengthOfArray) {
        case 2:
            Diff[a] = Data[0] - Data[1];
            break;

        case 3:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            break;

        case 4:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            break;

        case 5:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            break;

        case 6:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            break;

        case 7:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            break;

        case 8:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            break;

        case 9:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            break;

        case 10:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            break;

        case 11:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            break;

        case 12:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            break;

        case 13:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            break;

        case 14:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            break;

        case 15:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            break;

        case 16:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            break;

        case 17:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            Diff[p] = Data[15] - Data[16];
            break;

        case 18:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            Diff[p] = Data[15] - Data[16];
            Diff[q] = Data[16] - Data[17];
            break;

        case 19:
            Diff[a] = Data[0] - Data[1];
            Diff[b] = Data[1] - Data[2];
            Diff[c] = Data[2] - Data[3];
            Diff[d] = Data[3] - Data[4];
            Diff[e] = Data[4] - Data[5];
            Diff[f] = Data[5] - Data[6];
            Diff[g] = Data[6] - Data[7];
            Diff[h] = Data[7] - Data[8];
            Diff[i] = Data[8] - Data[9];
            Diff[j] = Data[9] - Data[10];
            Diff[k] = Data[10] - Data[11];
            Diff[l] = Data[11] - Data[12];
            Diff[m] = Data[12] - Data[13];
            Diff[n] = Data[13] - Data[14];
            Diff[o] = Data[14] - Data[15];
            Diff[p] = Data[15] - Data[16];
            Diff[q] = Data[16] - Data[17];
            Diff[r] = Data[16] - Data[18];
            break;
    }

Output:

20 This is the length of the Data Array

9
17
5
20
20
17
17
3
7
6

20 This is length of the Diff Array

0
0
0
0
0
0
0
0
0
0

The numbers in the Diff array should not be all 0's

I wondering if there's a way I can set the value of an array index, based off an equation.


问:
Visual Studio 2010 default zoom level
Is there a way to set the default zoom level in Visual Studio 2010?  The problem is that I find font size 10 to be too small, but font size 11 is too big.  It just so happens that 90% zoom level with font size 11 gives the perfect size I am looking for.  I would like to be able to have VS automatically always zoom the editor to 90%.</p>

答: I think that Ctrl+Scroll changes the zoom in Visual Studio. Every time you open it, you could just press a key and flick the mouse wheel. I bet you could also write an extension that does this... Though I've never written a Visual Studio extension, so I don't really know what the APIs offer. </p>

Title: Visual Studio 2010 default zoom level


问:
Terraform dynamic variable
I'm creating subnets as part of a seperate terraform template and exporting the IDs as follows.

```<code>output "subnet-aza-dev" {
  value = "${aws_subnet.subnet-aza-dev.id}"
}
output "subnet-azb-dev" {
  value = "${aws_subnet.subnet-azb-dev.id}"
}
output "subnet-aza-test" {
  value = "${aws_subnet.subnet-aza-test.id}"
}
output "subnet-azb-test" {
  value = "${aws_subnet.subnet-azb-test.id}"
}
...
</code>```

I'm then intending to lookup these IDs in another template which is reused to provision multiple environments. Example below shows my second template is calling a module to provision an EC2 instance and is passing through the subnet_id.

```<code>variable "environment" {
    description = "Environment name"
    default     = "dev"
}

module "sql-1-ec2" {
  source     = "../modules/ec2winserver_sql"
  ...
  subnet_id  = "${data.terraform_remote_state.env-shared.subnet-aza-dev}"
}
</code>```

What I'd like to do is pass the environment variable as part of the lookup for the subnet_id e.g.

```<code>subnet_id  = "${data.terraform_remote_state.env-shared.subnet-aza-${var.environment}"
</code>```

However I'm aware that variable interpolation isn't supported. I've tried using a map inside of the first terraform template to export them all to a 'subnet' which I could then use to lookup from the second template. This didn't work as I was unable to output variables inside of the map.

This sort of design pattern is something I've used previously with CloudFormation, however I'm much newer to terraform. Am I missing something obvious here?

答:
Worked out a way to do this using data sources

```<code>variable "environment" {
    description = "Environment name"
    default     = "dev"
}

module "sql-1-ec2" {
  source     = "../modules/ec2winserver_sql"
  ...
  subnet_id  = "${data.aws_subnet.subnet-aza.id}"
}

data "aws_subnet" "subnet-aza" {
  filter {
    name   = "tag:Name"
    values = ["${var.product}-${var.environment}-${var.environmentno}-subnet-aza"]
  }
}
data "aws_subnet" "subnet-azb" {
  filter {
    name   = "tag:Name"
    values = ["${var.product}-${var.environment}-${var.environmentno}-subnet-azb"]
  }
}
</code>```

Whilst this works and fulfils my original need, I'd like to improve on this by moving the data blocks to within the module, so that there's less repetition. Still working on that one though...

Title: Terraform dynamic variable

Body:
I'm creating subnets as part of a seperate terraform template and exporting the IDs as follows.

output "subnet-aza-dev" {
  value = "${aws_subnet.subnet-aza-dev.id}"
}
output "subnet-azb-dev" {
  value = "${aws_subnet.subnet-azb-dev.id}"
}
output "subnet-aza-test" {
  value = "${aws_subnet.subnet-aza-test.id}"
}
output "subnet-azb-test" {
  value = "${aws_subnet.subnet-azb-test.id}"
}
...

I'm then intending to lookup these IDs in another template which is reused to provision multiple environments. Example below shows my second template is calling a module to provision an EC2 instance and is passing through the subnet_id.

variable "environment" {
    description = "Environment name"
    default     = "dev"
}

module "sql-1-ec2" {
  source     = "../modules/ec2winserver_sql"
  ...
  subnet_id  = "${data.terraform_remote_state.env-shared.subnet-aza-dev}"
}

What I'd like to do is pass the environment variable as part of the lookup for the subnet_id e.g.

subnet_id  = "${data.terraform_remote_state.env-shared.subnet-aza-${var.environment}"

However I'm aware that variable interpolation isn't supported. I've tried using a map inside of the first terraform template to export them all to a 'subnet' which I could then use to lookup from the second template. This didn't work as I was unable to output variables inside of the map.

This sort of design pattern is something I've used previously with CloudFormation, however I'm much newer to terraform. Am I missing something obvious here?

Body:
Worked out a way to do this using data sources

variable "environment" {
    description = "Environment name"
    default     = "dev"
}

module "sql-1-ec2" {
  source     = "../modules/ec2winserver_sql"
  ...
  subnet_id  = "${data.aws_subnet.subnet-aza.id}"
}

data "aws_subnet" "subnet-aza" {
  filter {
    name   = "tag:Name"
    values = ["${var.product}-${var.environment}-${var.environmentno}-subnet-aza"]
  }
}
data "aws_subnet" "subnet-azb" {
  filter {
    name   = "tag:Name"
    values = ["${var.product}-${var.environment}-${var.environmentno}-subnet-azb"]
  }
}

Whilst this works and fulfils my original need, I'd like to improve on this by moving the data blocks to within the module, so that there's less repetition. Still working on that one though...


答:
You can just extract the columns of the sub-arrays one-by-one:

```<code>foreach(reset($result) as $key => $values) {
    $transpose[] = array_column($result, $key);
}
</code>```

However this is probably better and should work even if the keys are different in each array:

```<code>$transpose = array_map(null, ...$result);
</code>```

Title: Transpose rows and columns in a 2D array

Body:
You can just extract the columns of the sub-arrays one-by-one:

foreach(reset($result) as $key => $values) {
    $transpose[] = array_column($result, $key);
}

However this is probably better and should work even if the keys are different in each array:

$transpose = array_map(null, ...$result);


问:
Confusion as to initialization (or lack thereof) of object
```<code>package lab9;

import java.util.Scanner;
import java.util.Date;

public class AccountManager
{
    // the account
    private Account account;
    // reader for reading user input
    private Scanner reader;
    private Transaction transaction;
    private AccountManager accountmanager;

    /**
     * Constructor for objects of class AccountManager
     */
    public AccountManager(Account account, Transaction transaction, AccountManager accountmanager)
    {
        this.account = account;
        reader = new Scanner(System.in);
        this.transaction =transaction;
        this.accountmanager=accountmanager;

    }

    public void start()
    {
        System.out.println("WELCOME TO THE ACCOUNT MANAGER APPLICATION");
        boolean finished = false;

        for(int i=0; i<3; i++)
        {
            // get amount
            System.out.print("Transaction amount to add?\n>");
            String inputAmount = reader.nextLine();
            double amount = Double.parseDouble(inputAmount);

            // get type
            System.out.print("Transaction type?\n>");
            String type = reader.nextLine();

            // TO DO: get reference
            System.out.print ("Transaction reference?\n>");

            // date is today's date
            Date date = new Date();

            // TO DO: create transaction and add to account

            System.out.println("Transaction added");
            account.displayTransactions();

            // TO DO: display balance
        }
    }

    public static void main(String[] args)
    {

        Transaction t=new Transaction();

        Customer cust = new Customer("Fernando", "Alonso");
        Account account = new Account(cust, "12345");
        AccountManager accountmanager= new AccountManager (account,t, accountmanager);

        // TO DO: create AccountManager object and call start method

    }

}
</code>```

Enclosed is my code. I am trying to create an AccountManager object and call its
start method.

However, I am getting an error identifying that the Accountmanager object may not have been intialized.

I am confused by this greatly; I thought

```<code>this.accountmanager=accountmanager;
</code>```

Was the initialization of the accountmanager object? My (limited) understanding is that the initialization involves =.

such as

```<code>a=10;
</code>```

And if that were true, then that to me suggests that this.accountmanager=accountmanager would be valid? (Which I am assuming is incorrect, but just wanted to provide my thinking process).

I had previously gotten an error returned to me, identifying that a non-static variable transaction cannot be referenced from a static context.

To remedy this I included:

```<code> Transaction t=new Transaction();
</code>```

So that in fell in the scope of the static method. Is that legal/correct?

Error message:

```<code> AccountManager accountmanager= new AccountManager (account, t, accountmanager);
</code>```

"variable accountmanager might not have been initialized"

答:
This is the problem:

```<code>AccountManager accountmanager= new AccountManager (account, t, accountmanager);
</code>```

You're declaring a variable, and trying to read from that variable in the same statement that gives it an initial value.

Here's a simpler example, to show how it's nonsensical:

```<code>int y = 10;
int x = y + x;
</code>```

What would you expect the value of x to be at the end of that? You've said its initial value should be the value of y plus its current value... but it doesn't have a current value, because you're trying to find its initial value!

I strongly suspect that you shouldn't have that their constructor parameter at all though. Why does one AccountManager need a reference to another? You should:

Remove the accountmanager field

Remove the accountmanager constructor parameter

Change the local variable declaration and initialization to:

```<code>AccountManager accountManager= new AccountManager(account, t);
</code>```

(Note the capital M in accountManager, to follow Java naming conventions. I'd probably rename t to transaction for clarity too.)

Body:
package lab9;

import java.util.Scanner;
import java.util.Date;

public class AccountManager
{
    // the account
    private Account account;
    // reader for reading user input
    private Scanner reader;
    private Transaction transaction;
    private AccountManager accountmanager;

    /**
     * Constructor for objects of class AccountManager
     */
    public AccountManager(Account account, Transaction transaction, AccountManager accountmanager)
    {
        this.account = account;
        reader = new Scanner(System.in);
        this.transaction =transaction;
        this.accountmanager=accountmanager;

    }

    public void start()
    {
        System.out.println("WELCOME TO THE ACCOUNT MANAGER APPLICATION");
        boolean finished = false;

        for(int i=0; i<3; i++)
        {
            // get amount
            System.out.print("Transaction amount to add?\n>");
            String inputAmount = reader.nextLine();
            double amount = Double.parseDouble(inputAmount);

            // get type
            System.out.print("Transaction type?\n>");
            String type = reader.nextLine();

            // TO DO: get reference
            System.out.print ("Transaction reference?\n>");

            // date is today's date
            Date date = new Date();

            // TO DO: create transaction and add to account

            System.out.println("Transaction added");
            account.displayTransactions();

            // TO DO: display balance
        }
    }

    public static void main(String[] args)
    {

        Transaction t=new Transaction();

        Customer cust = new Customer("Fernando", "Alonso");
        Account account = new Account(cust, "12345");
        AccountManager accountmanager= new AccountManager (account,t, accountmanager);

        // TO DO: create AccountManager object and call start method

    }

}

Enclosed is my code. I am trying to create an AccountManager object and call its
start method.

However, I am getting an error identifying that the Accountmanager object may not have been intialized.

I am confused by this greatly; I thought

this.accountmanager=accountmanager;

Was the initialization of the accountmanager object? My (limited) understanding is that the initialization involves =.

such as

a=10;

And if that were true, then that to me suggests that this.accountmanager=accountmanager would be valid? (Which I am assuming is incorrect, but just wanted to provide my thinking process).

I had previously gotten an error returned to me, identifying that a non-static variable transaction cannot be referenced from a static context.

To remedy this I included:

 Transaction t=new Transaction();

So that in fell in the scope of the static method. Is that legal/correct?

Error message:

 AccountManager accountmanager= new AccountManager (account, t, accountmanager);

"variable accountmanager might not have been initialized"

Body:
This is the problem:

AccountManager accountmanager= new AccountManager (account, t, accountmanager);

You're declaring a variable, and trying to read from that variable in the same statement that gives it an initial value.

Here's a simpler example, to show how it's nonsensical:

int y = 10;
int x = y + x;

What would you expect the value of x to be at the end of that? You've said its initial value should be the value of y plus its current value... but it doesn't have a current value, because you're trying to find its initial value!

I strongly suspect that you shouldn't have that their constructor parameter at all though. Why does one AccountManager need a reference to another? You should:

Remove the accountmanager field

Remove the accountmanager constructor parameter

Change the local variable declaration and initialization to:

AccountManager accountManager= new AccountManager(account, t);

(Note the capital M in accountManager, to follow Java naming conventions. I'd probably rename t to transaction for clarity too.)


问:
Why do I only receive a single alert from the following javascript?
This is a javascript function inside of a HTML  tag, however - when I move the alert(currentalbum) below the for loop, the second alert does not run - only the first, why?

```<code>function populatetracks(albumvalue) {
    var currentalbum = albumvalue;
    alert(currentalbum); // #1

    document.getElementById("TracksList").options.length = 0;

    for(i = 0; albums[albumvalue].tracks.length - 1; i++) {
        var s = document.getElementById('TracksList');
        var opt = document.createElement('option');
        opt.appendChild( document.createTextNode(albums[albumvalue].tracks[i].title));
        opt.value = i;
        s.appendChild(opt);
    }

    alert(currentalbum); // #2
}
</code>```

'#1' does produce an alert, but '#2' doesn't.

答:
As noted, not sure how your for loop is supposed to stop.

This has no evaluation in it, just an incrementor

```<code>for(i=0; albums[albumvalue].tracks.length -1; i++){
</code>```

Maybe try this (might need to change  '='  to  '<='  )

```<code>for(i=0; i < albums[albumvalue].tracks.length -1; i++){
</code>```

Body:
This is a javascript function inside of a HTML  tag, however - when I move the alert(currentalbum) below the for loop, the second alert does not run - only the first, why?

function populatetracks(albumvalue) {
    var currentalbum = albumvalue;
    alert(currentalbum); // #1

    document.getElementById("TracksList").options.length = 0;

    for(i = 0; albums[albumvalue].tracks.length - 1; i++) {
        var s = document.getElementById('TracksList');
        var opt = document.createElement('option');
        opt.appendChild( document.createTextNode(albums[albumvalue].tracks[i].title));
        opt.value = i;
        s.appendChild(opt);
    }

    alert(currentalbum); // #2
}

'#1' does produce an alert, but '#2' doesn't.

Body:
As noted, not sure how your for loop is supposed to stop.

This has no evaluation in it, just an incrementor

for(i=0; albums[albumvalue].tracks.length -1; i++){

Maybe try this (might need to change  '='  to  '<='  )

for(i=0; i < albums[albumvalue].tracks.length -1; i++){


答:
It would be easier to achieve this with loops:

```<code>for(int i=0; i<Data.length-1; i++){
    Diff[i] = Data[i]-Data[i+1];
    System.out.println(Diff[i]);
}
</code>```

These four lines could replace your entire switch statement and all of the "println(Diff..." lines. (Note that the reason you're getting the wrong Diff output is because you print the Diffs before you set their values)

Title: Setting the value of an array index

Body:
It would be easier to achieve this with loops:

for(int i=0; i<Data.length-1; i++){
    Diff[i] = Data[i]-Data[i+1];
    System.out.println(Diff[i]);
}

These four lines could replace your entire switch statement and all of the "println(Diff..." lines. (Note that the reason you're getting the wrong Diff output is because you print the Diffs before you set their values)


问:
React truncate multi line text by line
I need to truncate card title (text) with react.

I try to use dotdotdot component https://www.npmjs.com/package/react-dotdotdot but it doesn't work with simple component.

```<code>const content = ({title}) => <Dotdotdot clamp={2}><p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Est rem magni totam quos sapiente aliquid praesentium quae sint illo quas dicta cum illum dolorum quis eveniet, corrupti porro placeat, consequatur reprehenderit aliquam distinctio voluptates voluptate, temporibus omnis. Cum quis tenetur laborum minus accusantium provident eveniet, corrupti, reiciendis aliquam suscipit hic?</p></Dotdotdot>
</code>```

It doesn't work in ie11 and mozilla.
In -web-kit i have -webkit-line-clamp but in mozilla and ie it doesn't work.

Do anybody know decision for this task?

答:
I don't know if you want that issue to get resolved or asking for other options as well.

But I usually use react-lines-ellipsis for ellipsis.
If you can go with other alternatives then you can check demo in other broswers as well.

ContentLicense: CC BY-SA 4.0

Title: React truncate multi line text by line

Body:
I need to truncate card title (text) with react.

I try to use dotdotdot component https://www.npmjs.com/package/react-dotdotdot but it doesn't work with simple component.

const content = ({title}) => <Dotdotdot clamp={2}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Est rem magni totam quos sapiente aliquid praesentium quae sint illo quas dicta cum illum dolorum quis eveniet, corrupti porro placeat, consequatur reprehenderit aliquam distinctio voluptates voluptate, temporibus omnis. Cum quis tenetur laborum minus accusantium provident eveniet, corrupti, reiciendis aliquam suscipit hic?
</Dotdotdot>

It doesn't work in ie11 and mozilla.
In -web-kit i have -webkit-line-clamp but in mozilla and ie it doesn't work.

Do anybody know decision for this task?


问:
Will the Microsoft-Teams bot get any event when bot is added by editing an existing message?
When a Microsoft-teams bot is added to an existing message on a channel, by editing the message, would it be possible to notify the bot about the message?

I tried this scenario and looks like bot is not receiving any events for such cases. Is there any interface or mechanism available to notify the bot about the message?

答: When you edit a Teams message and add any @ mention - whether it's to a user or a bot - it doesn't generate new notifications. This has been a gap ever since we added the ability to edit messages.</p>