问:
How to define empty parameter for Protocol Buffers rpc method?
I have a method that I would like defined called FindAll which requires no parameters.  ProtoC is complaining.

Expected type name.

This is for line:

rpc findAll () returns (BenchmarksList);

```<code>syntax = "proto3";

package helloWorldGRPC;

service HelloWorldGRPCService {
    rpc findById (BenchmarksById) returns (Benchmarks);
    rpc findAll () returns (BenchmarksList);
}

message BenchmarksById {
    string id = 1;
}

message BenchmarksList {
    repeated Benchmarks benchmarks = 1;
}

message Benchmarks {
    string trans_id = 1;
    string protocol = 2;
    string database = 3;
    string updated_at = 4;
    string created_at = 5;
    repeated Action actions = 6;
}

message Action {
    string trans_id = 1;
    int32 payload_length = 2;
    string payload = 3;
    string status = 4;
    string updated_at = 5;
    string created_at = 6;
}
</code>```

答: The preferred way is to pass Empty - as tooling may recognize and optimize for that scenario. But in reality, there is nothing "special" about that type and any message - empty or otherwise - will suffice.

Body:
I have a method that I would like defined called FindAll which requires no parameters.  ProtoC is complaining.

Expected type name.

This is for line:

rpc findAll () returns (BenchmarksList);

syntax = "proto3";

package helloWorldGRPC;

service HelloWorldGRPCService {
    rpc findById (BenchmarksById) returns (Benchmarks);
    rpc findAll () returns (BenchmarksList);
}

message BenchmarksById {
    string id = 1;
}

message BenchmarksList {
    repeated Benchmarks benchmarks = 1;
}

message Benchmarks {
    string trans_id = 1;
    string protocol = 2;
    string database = 3;
    string updated_at = 4;
    string created_at = 5;
    repeated Action actions = 6;
}

message Action {
    string trans_id = 1;
    int32 payload_length = 2;
    string payload = 3;
    string status = 4;
    string updated_at = 5;
    string created_at = 6;
}


来源: stackexchange

问:
Where should the page gets redirect if create failed in api
I have created a rails api. In that if the create in api success then I post it in the api. But if it is not success where should I redirect it to?</p>

答:
There isn't a redirect, you just respond with a different status to notify the frontend that the create failed and, hopefully, why it failed (validations).

This is how a controller generated with scaffold responds by default to json requests.

def create
  @object = Object.new(object_params)

  respond_to do |format|
    if @object.save
      format.html { redirect_to @object, notice: 'Object was successfully created.' }
      format.json { render :show, status: :created, location: @object }
    else
      format.html { render :new }
      format.json { render json: @object.errors, status: :unprocessable_entity }
    end
  end
end
```

ContentLicense: CC BY-SA 4.0


问:
Ansible, how to trust certificates?
Im using the following from svn module:

```<code>- subversion:
    repo: https://subversion:80/repos/xt_tools/
    dest: ~/.build/xt_tools
</code>```

I am getting this error: "Server certificate verification failed: certificate issued for a different hostname, issuer is not trusted (https://subversion:80)"

As these are VMs (CentOS/7) i spin up as needed, this is a problem i will continually run into.  Im thinking there must be a way to either automatically generate a certificate or auto accept when prompted.

Any ideas?

答:
I would think it's either that you add those CA certs to the machine's trust store, or use the executable: option to point to a custom script that runs svn along with providing the --trust-server-cert-failures=unknown-ca,cn-mismatch,other or whatever is appropriate for your specific CA mismatch. You may even be able to get away with executable: /path/to/svn --trust-server-cert-failure=and-so-forth but that depends on the nuances of self.run_command so ... try it, I guess?

There seems to be some options that are available via a per-user config file, but given that the subversion documentation is all but abandoned, you'll have to read the source to discover whether trust-server-cert-failures is included in that config somewhere

Title: Ansible, how to trust certificates?

Body:
Im using the following from svn module:

- subversion:
    repo: https://subversion:80/repos/xt_tools/
    dest: ~/.build/xt_tools

I am getting this error: "Server certificate verification failed: certificate issued for a different hostname, issuer is not trusted (https://subversion:80)"

As these are VMs (CentOS/7) i spin up as needed, this is a problem i will continually run into.  Im thinking there must be a way to either automatically generate a certificate or auto accept when prompted.

Any ideas?


问:
C# binary data conversion to string
Here is the deal. I found a source code and changed it a little bit so i can retrieve data from a receiver that is on com6. The data i am receiving is binary. What i want is to convert it to a string so i can cut parts of the string and decode them seperately. how can i dot his?
The source code is beneath. </p>

```<code>using System;
using System.IO.Ports;
using System.Threading;

public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;

    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 1000;
        _serialPort.WriteTimeout = 1000;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {

            try
            {

                string message = _serialPort.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

            portName = "COM6";

        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        baudRate = "9600";

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        parity = "None";

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        dataBits = "8";

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        stopBits = "One";

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        handshake = "None";

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}
</code>```

答:
Data from ports will always come in binary(bytes), therefore it depends on how to interpret the data. Assuming that the bytes are ASCII, you can encode it to a string as follows:</p>

```<code>byte[] binaryData ; // assuming binaryData contains the bytes from the port.

string ascii =  Encoding.ASCII.GetString(binaryData);
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# binary data conversion to string

Body:
Here is the deal. I found a source code and changed it a little bit so i can retrieve data from a receiver that is on com6. The data i am receiving is binary. What i want is to convert it to a string so i can cut parts of the string and decode them seperately. how can i dot his?
The source code is beneath.

using System;
using System.IO.Ports;
using System.Threading;

public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;

    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 1000;
        _serialPort.WriteTimeout = 1000;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {

            try
            {

                string message = _serialPort.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

            portName = "COM6";

        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        baudRate = "9600";

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        parity = "None";

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        dataBits = "8";

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        stopBits = "One";

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        handshake = "None";

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}

Body:
Data from ports will always come in binary(bytes), therefore it depends on how to interpret the data. Assuming that the bytes are ASCII, you can encode it to a string as follows:

byte[] binaryData ; // assuming binaryData contains the bytes from the port.

string ascii =  Encoding.ASCII.GetString(binaryData);


问:
I want to do the expandable list view as below in attached image. How can I achieve this type of functionality in flutter?

How can I achieve this?. I have tried customizing ExpansionTile but not able to get similar effects on expansion and collapse. Mainly the prefix icon is bigger in size and so the expandable text is not close to the date. Also, the suffix icon for expanding/collapsing not fully covered with the background color.

I am also attaching an image that I have tried. I have used https://pub.dev/packages/expandable#-readme-tab- to achieve a similar effect but no luck.

I am really stuck at this place and want any kind of help.
Your help will be appreciated.
Thanks.

答:
Just implemented, try this:</p>

```<code>ListView.builder(
        itemCount: 20,
        itemBuilder: (context, index) {
          return ExpandableNotifier(
            child: Card(
              elevation: 4,
              child: Expandable(
                collapsed: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 105,
                  child: ExpandableButton(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: ClipOval(
                            child: Container(
                              height: 80,
                              width: 80,
                              color: Colors.yellow,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.symmetric(vertical: 20),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  'Welkom bij Haaer',
                                  style: TextStyle(
                                    fontSize: 14.0,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                Text(
                                  '2019/06/01 11:04',
                                  style: TextStyle(
                                    color: Colors.grey,
                                    fontSize: 12.0,
                                  ),
                                ),
                                Text(
                                  'blablablablablablablablablablablablablablablablablablablablablabla'
                                  'blablablablablablablablablablablablablablablablablablablablablabla'
                                  'blablablablablablablablablablablablablablablablablablablablablabla',
                                  softWrap: true,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          color: Colors.yellow,
                          width: 30,
                          height: 105,
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                expanded: Container(
                  height: 200,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: ClipOval(
                          child: Container(
                            height: 80,
                            width: 80,
                            color: Colors.purple,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.symmetric(vertical: 20),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                'Welkom bij Haaer',
                                style: TextStyle(
                                  fontSize: 14.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Text(
                                '2019/06/01 11:04',
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 12.0,
                                ),
                              ),
                              Text(
                                'blablablablablablablablablablablablablablablablablablablablablabla'
                                'blablablablablablablablablablablablablablablablablablablablablabla'
                                'blablablablablablablablablablablablablablablablablablablablablabla',
                                softWrap: true,
                              ),
                              SizedBox(
                                height: 5,
                              ),
                              Container(
                                width: 80,
                                height: 20,
                                child: RaisedButton(
                                  padding: EdgeInsets.all(0),
                                  color: Colors.purple,
                                  child: Text('show'),
                                  onPressed: () {},
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      ExpandableButton(
                        child: Container(
                          color: Colors.purple,
                          width: 30,
                          height: 200,
                          child: Icon(
                            Icons.keyboard_arrow_down,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        },
      ),
</code>```

Body:
Just implemented, try this:

ListView.builder(
        itemCount: 20,
        itemBuilder: (context, index) {
          return ExpandableNotifier(
            child: Card(
              elevation: 4,
              child: Expandable(
                collapsed: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 105,
                  child: ExpandableButton(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: ClipOval(
                            child: Container(
                              height: 80,
                              width: 80,
                              color: Colors.yellow,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.symmetric(vertical: 20),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  'Welkom bij Haaer',
                                  style: TextStyle(
                                    fontSize: 14.0,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                Text(
                                  '2019/06/01 11:04',
                                  style: TextStyle(
                                    color: Colors.grey,
                                    fontSize: 12.0,
                                  ),
                                ),
                                Text(
                                  'blablablablablablablablablablablablablablablablablablablablablabla'
                                  'blablablablablablablablablablablablablablablablablablablablablabla'
                                  'blablablablablablablablablablablablablablablablablablablablablabla',
                                  softWrap: true,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                ),
                              ],
                            ),
                          ),
                        ),
                        Container(
                          color: Colors.yellow,
                          width: 30,
                          height: 105,
                          child: Icon(
                            Icons.keyboard_arrow_right,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                expanded: Container(
                  height: 200,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10),
                        child: ClipOval(
                          child: Container(
                            height: 80,
                            width: 80,
                            color: Colors.purple,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.symmetric(vertical: 20),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                'Welkom bij Haaer',
                                style: TextStyle(
                                  fontSize: 14.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Text(
                                '2019/06/01 11:04',
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 12.0,
                                ),
                              ),
                              Text(
                                'blablablablablablablablablablablablablablablablablablablablablabla'
                                'blablablablablablablablablablablablablablablablablablablablablabla'
                                'blablablablablablablablablablablablablablablablablablablablablabla',
                                softWrap: true,
                              ),
                              SizedBox(
                                height: 5,
                              ),
                              Container(
                                width: 80,
                                height: 20,
                                child: RaisedButton(
                                  padding: EdgeInsets.all(0),
                                  color: Colors.purple,
                                  child: Text('show'),
                                  onPressed: () {},
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      ExpandableButton(
                        child: Container(
                          color: Colors.purple,
                          width: 30,
                          height: 200,
                          child: Icon(
                            Icons.keyboard_arrow_down,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        },
      ),


问:
How to prevent previous fragment to show up after pressing back button using navigation controller?
I am trying to use the navigation controller right now. I want to move from LoginFragment to HomeFragment. In LoginFragment I use this code below to move to HomeFragment.

```<code>Navigation.findNavController(view).navigate(homeDestination)
</code>```

However, when I tap the back button in the HomeFragment, it will go back to LoginFragment, I expect that when I tap the button it will close the app.

In old way, if I use activity instead of using Fragment, I usually do something like this to get that expected behaviour:

```<code>val intent = Intent(this,HomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
</code>```

By using those flags, I use to get the expected behavior. But I don't how to implement the same behavior using the navigation controller.

答:
I was following the answer of Ian but I had been having bad luck since I didn't know what the popUpTo would be.

So we have to use the id Of nav Graph there.

app:popUpTo="@+id/idOfNavGraph". //id of nav graph

```<code><action
  android:id="@+id/go_home"
  app:destination="@+id/home_fragment"
  app:popUpTo="@+id/idOfNavGraph". //id of nav graph
  app:popUpToInclusive="true"/>
</code>```

Body:
I am trying to use the navigation controller right now. I want to move from LoginFragment to HomeFragment. In LoginFragment I use this code below to move to HomeFragment.

Navigation.findNavController(view).navigate(homeDestination)

However, when I tap the back button in the HomeFragment, it will go back to LoginFragment, I expect that when I tap the button it will close the app.

In old way, if I use activity instead of using Fragment, I usually do something like this to get that expected behaviour:

val intent = Intent(this,HomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)

By using those flags, I use to get the expected behavior. But I don't how to implement the same behavior using the navigation controller.

Body:
I was following the answer of Ian but I had been having bad luck since I didn't know what the popUpTo would be.

So we have to use the id Of nav Graph there.

app:popUpTo="@+id/idOfNavGraph". //id of nav graph

<action
  android:id="@+id/go_home"
  app:destination="@+id/home_fragment"
  app:popUpTo="@+id/idOfNavGraph". //id of nav graph
  app:popUpToInclusive="true"/>


问:
Write the result of the query into a table
Need to write the result to a table</p>

```<code>select
    convert(datetime, dbo.time(table1.col1))
from
    table1
order by
    col1
</code>```

答:
Temp table (no order by):</p>

```<code>SELECT
    CONVERT(SMALLDATETIME, dbo.time(table1.col1)) AS ConvertedDate
INTO #TempTable
FROM
    table1
</code>```

Body:
Need to write the result to a table

select
    convert(datetime, dbo.time(table1.col1))
from
    table1
order by
    col1

Body:
Temp table (no order by):

SELECT
    CONVERT(SMALLDATETIME, dbo.time(table1.col1)) AS ConvertedDate
INTO #TempTable
FROM
    table1


问:
Not Found: /available.html "GET /available.html HTTP/1.1" 404 2319
I am trying to create a path for the second function on my views page so I can create a buyers page and connect it to the database, but I am having difficulties finding help online for this specific problem so if someone could help and also show me a good series to watch to help with the creation of this private server ran website.

```<code>Page not found (404)
Not Found: /favicon.ico
[01/Jun/2020 23:18:35] "GET /favicon.ico HTTP/1.1" 404 2310
Request Method: GET
Request URL: http://127.0.0.1:8000/available.html
Using the URLconf defined in TJWEXOTICS.urls, Django tried these URL patterns, in this order:

admin
[name='home-page']
[name='available-page']
The current path, available.html, didn't match any of these.
</code>```

it says this after i run the server and then try to go to the pythons page:

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to >False, and Django will display a standard 404 page.

heres the urls.py paths:

```<code>    from django.urls import path

    from . import views

    urlpatterns = [
         path(r'', views.title, name='home-page'),
         path(r'', views.available, name='available-page')
    ]
</code>```

Here is the views.py code:

```<code>from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from .models import Snake

# Create your views here.

def title(request):
    return render(request, 'TJW/Homepage.html')

def available(request):

    # return render(request, 'TJW/available.html')

    all_snakes = Snake.objects.all()
    html = 'TJW/available.html'
    for snake in all_snakes:
        path = '/TJW/' + str(Snake.id) + '/'
        html += '<a href= "' + path + '" >' + Snake.snake_mutation + '</a><br>'
    return HttpResponse(html)
</code>```

答:
You have to add a path:

```<code>path('available/', views.available, name='available-page')
</code>```

And, go the the path to check if available view is working or not. Now, your available page will look like. http://localhost:8000/available/

Body:
I am trying to create a path for the second function on my views page so I can create a buyers page and connect it to the database, but I am having difficulties finding help online for this specific problem so if someone could help and also show me a good series to watch to help with the creation of this private server ran website.

Page not found (404)
Not Found: /favicon.ico
[01/Jun/2020 23:18:35] "GET /favicon.ico HTTP/1.1" 404 2310
Request Method: GET
Request URL: http://127.0.0.1:8000/available.html
Using the URLconf defined in TJWEXOTICS.urls, Django tried these URL patterns, in this order:

admin
[name='home-page']
[name='available-page']
The current path, available.html, didn't match any of these.

it says this after i run the server and then try to go to the pythons page:

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to >False, and Django will display a standard 404 page.

heres the urls.py paths:

    from django.urls import path

    from . import views

    urlpatterns = [
         path(r'', views.title, name='home-page'),
         path(r'', views.available, name='available-page')
    ]

Here is the views.py code:

from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from .models import Snake

# Create your views here.

def title(request):
    return render(request, 'TJW/Homepage.html')

def available(request):

    # return render(request, 'TJW/available.html')

    all_snakes = Snake.objects.all()
    html = 'TJW/available.html'
    for snake in all_snakes:
        path = '/TJW/' + str(Snake.id) + '/'
        html += '' + Snake.snake_mutation + '
'
    return HttpResponse(html)

Body:
You have to add a path:

path('available/', views.available, name='available-page')

And, go the the path to check if available view is working or not. Now, your available page will look like. http://localhost:8000/available/


问:
Running parallel Testng tests in Selenium
I have a BaseClass which has @BeforeSuite method that takes browser and other login parameters from xml. I want to run 2 parallel tests with different parameters. Since i am using parameters in @BeforeSuite so it takes values only once and not running any parallel execution. I cannot use parameters in @BeforeTest or @BeforeMethod or @BeforeClass as I need to use these parameters only once for each test and i have multiple test cases in each class.

My xml is as below;

```<code>    <listeners>
    <listener class-name="Utility.Listeners" />
    </listeners>

 <test name="Tests1" >

      <parameter name="Browser" value="chrome" />
 <parameter name="username" value="d1" />
 <parameter name="password" value="P1" />
 <parameter name="Brand" value="TC" />

    <groups>
        <run>
            <include name="NatP"  />
        </run>
    </groups>

    <classes  >
     <class name="Maven.Dashboard"/>
     <class name="Maven.TopBottomWidget"/>
     <class name="Maven.Dashboard_BE"/>

     </classes>
</test>
</code>```

```<code>      <parameter name="Browser" value="chrome" />
 <parameter name="username" value="d1K" />
 <parameter name="password" value="P1K" />
 <parameter name="Brand" value="TCK" />

    <groups>
        <run>
            <include name="NatP"  />
        </run>
    </groups>

    <classes  >

     <class name="Maven.Dashboard"/>
     <class name="Maven.TopBottomWidget"/>
     <class name="Maven.Dashboard_BE"/>

    </classes>
</test>
</code>```

答:
You could try programmatic execution of testng by using the below code. You have to pass the parameters as maven run time arguments like below,

mvn clean install exec:java "-Dexec.mainClass=org.package.Test" "-DskipTests" "-Dexec.classpathScope=test" "-DBrowser=chrome,firefox"

The Test class is present inside src/test/java/, hence the classpathScope is mentioned as test in the above command. Also using the above maven command we are executing the main function of the Test class. This main method will in turn trigger the testng execution. The main method parse the existing testng XML file and add the arguments as parameters to each test. Each test will be run parallel with the thread size equal to the number of arguments you pass.

```<code>    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang.StringUtils;
    import org.testng.TestNG;
    import org.testng.xml.Parser;
    import org.testng.xml.XmlSuite;
    import org.testng.xml.XmlTest;

    import java.io.File;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;

    public class Test {

    public static void main(String[] args) throws Exception {

        List<String> browserList = StringUtils.isEmpty(System.
                getProperty("Browser")) ? new ArrayList<>() :
                Arrays.asList(System.getProperty("Browser").split(","));
        TestNG tng = new TestNG();
        File initialFile = new File("testng.xml");
        InputStream inputStream = FileUtils.openInputStream(initialFile);
        Parser p = new Parser(inputStream);
        List<XmlSuite> suites = p.parseToList();
        List<XmlSuite> modifiedSuites = new ArrayList<>();
        for (XmlSuite suite : suites) {
            XmlSuite modifiedSuite = new XmlSuite();
            modifiedSuite.setParallel(suite.getParallel());
            modifiedSuite.setThreadCount(browserList.size());
            modifiedSuite.setName(suite.getName());
            modifiedSuite.setListeners(suite.getListeners());
            List<XmlTest> tests = suite.getTests();
            for (XmlTest test : tests) {
                for (int i = 0; i < browserList.size(); i++) {
                    XmlTest modifedtest = new XmlTest(modifiedSuite);
                    HashMap<String, String> parametersMap = new HashMap<>();
                    parametersMap.put("browser", browserList.get(i));

                    modifedtest.setParameters(parametersMap);
                    modifedtest.setXmlClasses(test.getXmlClasses());
                }
            }
            modifiedSuites.add(modifiedSuite);
        }
        inputStream.close();
        tng.setXmlSuites(modifiedSuites);
        tng.run();
    }
}
</code>```

Body:
I have a BaseClass which has @BeforeSuite method that takes browser and other login parameters from xml. I want to run 2 parallel tests with different parameters. Since i am using parameters in @BeforeSuite so it takes values only once and not running any parallel execution. I cannot use parameters in @BeforeTest or @BeforeMethod or @BeforeClass as I need to use these parameters only once for each test and i have multiple test cases in each class.

My xml is as below;

    <listeners>
    <listener class-name="Utility.Listeners" />
    </listeners>

 <test name="Tests1" >

      <parameter name="Browser" value="chrome" />
 <parameter name="username" value="d1" />
 <parameter name="password" value="P1" />
 <parameter name="Brand" value="TC" />

    <groups>
        <run>
            <include name="NatP"  />
        </run>
    </groups>

    <classes  >
     <class name="Maven.Dashboard"/>
     <class name="Maven.TopBottomWidget"/>
     <class name="Maven.Dashboard_BE"/>

     </classes>
</test>

      <parameter name="Browser" value="chrome" />
 <parameter name="username" value="d1K" />
 <parameter name="password" value="P1K" />
 <parameter name="Brand" value="TCK" />

    <groups>
        <run>
            <include name="NatP"  />
        </run>
    </groups>

    <classes  >

     <class name="Maven.Dashboard"/>
     <class name="Maven.TopBottomWidget"/>
     <class name="Maven.Dashboard_BE"/>

    </classes>
</test>

Body:
You could try programmatic execution of testng by using the below code. You have to pass the parameters as maven run time arguments like below,

mvn clean install exec:java "-Dexec.mainClass=org.package.Test" "-DskipTests" "-Dexec.classpathScope=test" "-DBrowser=chrome,firefox"

The Test class is present inside src/test/java/, hence the classpathScope is mentioned as test in the above command. Also using the above maven command we are executing the main function of the Test class. This main method will in turn trigger the testng execution. The main method parse the existing testng XML file and add the arguments as parameters to each test. Each test will be run parallel with the thread size equal to the number of arguments you pass.

    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang.StringUtils;
    import org.testng.TestNG;
    import org.testng.xml.Parser;
    import org.testng.xml.XmlSuite;
    import org.testng.xml.XmlTest;

    import java.io.File;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;

    public class Test {

    public static void main(String[] args) throws Exception {

        List<String> browserList = StringUtils.isEmpty(System.
                getProperty("Browser")) ? new ArrayList<>() :
                Arrays.asList(System.getProperty("Browser").split(","));
        TestNG tng = new TestNG();
        File initialFile = new File("testng.xml");
        InputStream inputStream = FileUtils.openInputStream(initialFile);
        Parser p = new Parser(inputStream);
        List<XmlSuite> suites = p.parseToList();
        List<XmlSuite> modifiedSuites = new ArrayList<>();
        for (XmlSuite suite : suites) {
            XmlSuite modifiedSuite = new XmlSuite();
            modifiedSuite.setParallel(suite.getParallel());
            modifiedSuite.setThreadCount(browserList.size());
            modifiedSuite.setName(suite.getName());
            modifiedSuite.setListeners(suite.getListeners());
            List<XmlTest> tests = suite.getTests();
            for (XmlTest test : tests) {
                for (int i = 0; i < browserList.size(); i++) {
                    XmlTest modifedtest = new XmlTest(modifiedSuite);
                    HashMap<String, String> parametersMap = new HashMap<>();
                    parametersMap.put("browser", browserList.get(i));

                    modifedtest.setParameters(parametersMap);
                    modifedtest.setXmlClasses(test.getXmlClasses());
                }
            }
            modifiedSuites.add(modifiedSuite);
        }
        inputStream.close();
        tng.setXmlSuites(modifiedSuites);
        tng.run();
    }
}


问:
The links rotate but end up in a completely different area of the page?
I would like the link to rotate in place but they end up rotating and being in a different area of the page..

/* CSS: */

.link:hover {
  transform: rotate(90deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--HTML:-->

<div class="link">
  <h2>Food</h2>
</div>
<div class="link">
  <h2>Entertainment</h2>
</div>
<div class="link">
  <h2>Entertainment Schedule</h2>
</div>
<div class="link">
  <h2>Past Lou Fests</h2>
</div>
<div class="link">
  <h2>Take the Lou Fest survey!</h2>
</div></code>```

答:
You have to set transform-origin CSS attribute value to control the transformation origin for your rotated tag:

/* CSS: */

.link:hover {
  transform: rotate(90deg);
  transform-origin: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--HTML:-->

<div class="link">
  <h2>Food</h2>
</div>
<div class="link">
  <h2>Entertainment</h2>
</div>
<div class="link">
  <h2>Entertainment Schedule</h2>
</div>
<div class="link">
  <h2>Past Lou Fests</h2>
</div>
<div class="link">
  <h2>Take the Lou Fest survey!</h2>
</div></code>```

Body:
I would like the link to rotate in place but they end up rotating and being in a different area of the page..

/* CSS: */

.link:hover {
  transform: rotate(90deg);
}

Food

Entertainment

Entertainment Schedule

Past Lou Fests

Take the Lou Fest survey!

Body:
You have to set transform-origin CSS attribute value to control the transformation origin for your rotated tag:

/* CSS: */

.link:hover {
  transform: rotate(90deg);
  transform-origin: 50px;
}

<!--HTML:-->

<div class="link">
  <h2><a href="loufestfood.html">Food</a></h2>
</div>
<div class="link">
  <h2><a href="loufestent.html">Entertainment</a></h2>
</div>
<div class="link">
  <h2><a href="LfEntSched.html">Entertainment Schedule</a></h2>
</div>
<div class="link">
  <h2><a href="pastLouFests.html">Past Lou Fests</a></h2>
</div>
<div class="link">
  <h2><a href="LouFestSurvey.html">Take the Lou Fest survey!</a></h2>
</div>


问:
how to add class to 9 divs random in javascript avoid repetition
Hi Guys anyone who can help me please.
I want to add class radom to 9 divs without repetition and it must at least skip 3 divs before adding next class.

My current problem it doesn't skip divs it just adding from index 0 to 8 without skipping any index.

I want to add 9 classes random to divs. Please see my code below.

jQuery(document).ready(function( $ ){
    // Your code in here
var classes = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"];

  $(".productRow .productWrapper .productItem").each(function(){
    var getClass = classes.splice(~~(Math.random()*classes.length), 1)[0];
    $(this).addClass(getClass);
    $(this).append("
");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="productRow">
    <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>

        <div class="productWrapper">
        <div class="productItem">
            <img class="productIgm" src="/img/1515_hero.png">
        <h6>Test</h6>
        Buy
        </div>
        </div>
</div></code>```

答:
This will loop through each element and check if it's at least 3 away from the previous element. If so, it'll flip a coin (i.e. rando(true, false)) to decide if we should add a random class to that element or proceed to the next one.

var elements = $(".normal");
var classes = ["green", "blue", "orange"];
var MIN_SEPARATION = 3;

var skipped = MIN_SEPARATION;
for(var i = 0; i < elements.length; i++){
  if(++skipped > MIN_SEPARATION && rando(true, false)){
    skipped = 0;
    elements.eq(i).addClass(rando(classes).value);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.normal{
  height:15px;
  margin-top:1px;
  background:#eee;
}

div.green{
  background:green;
}

div.blue{
  background:blue;
}

div.orange{
  background:orange;
}</code>```

```
</div>
</div>
</p>

<p>I used randojs in this code to simplify the randomness and make it easier to read, so if you want to use this code, just remember to paste this in the head of your HTML document:</p>

```
```

<p>I see that you're already using jquery, so you should already know to also post this (or wherever you're sourcing your jquery in from) in the head of your HTML document:</p>

```
```

Body:
Hi Guys anyone who can help me please.
I want to add class radom to 9 divs without repetition and it must at least skip 3 divs before adding next class.

My current problem it doesn't skip divs it just adding from index 0 to 8 without skipping any index.

I want to add 9 classes random to divs. Please see my code below.

jQuery(document).ready(function( $ ){
    // Your code in here
var classes = ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"];

  $(".productRow .productWrapper .productItem").each(function(){
    var getClass = classes.splice(~~(Math.random()*classes.length), 1)[0];
    $(this).addClass(getClass);
    $(this).append("
");
  });
});

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Test

        Buy

Body:
This will loop through each element and check if it's at least 3 away from the previous element. If so, it'll flip a coin (i.e. rando(true, false)) to decide if we should add a random class to that element or proceed to the next one.

var elements = $(".normal");
var classes = ["green", "blue", "orange"];
var MIN_SEPARATION = 3;

var skipped = MIN_SEPARATION;
for(var i = 0; i < elements.length; i++){
  if(++skipped > MIN_SEPARATION && rando(true, false)){
    skipped = 0;
    elements.eq(i).addClass(rando(classes).value);
  }
}

.normal{
  height:15px;
  margin-top:1px;
  background:#eee;
}

div.green{
  background:green;
}

div.blue{
  background:blue;
}

div.orange{
  background:orange;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://randojs.com/1.0.0.js"></script>
<div class="normal"></div>
<div class="normal"></div>
<div class="normal"></div>
<div class="normal"></div>
<div class="normal"></div>
<div class="normal"></div>
<div class="normal"></div>
<div class="normal"></div>
<div class="normal"></div>

I used randojs in this code to simplify the randomness and make it easier to read, so if you want to use this code, just remember to paste this in the head of your HTML document:

<script src="https://randojs.com/1.0.0.js"></script>

I see that you're already using jquery, so you should already know to also post this (or wherever you're sourcing your jquery in from) in the head of your HTML document:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
SOLR search filter by relevancy score
So each SOLR search result has their own relevancy score:

https://wiki.apache.org/solr/SolrRelevancyFAQ

"How can I see the relevancy scores for search results

Request that the pseudo-field named "score" be returned by adding it
  to the fl (field list) parameter. The "score" will then appear along
  with the stored fields in returned documents. q=Justice
  League&fl=*,score"

My question is...is it possible to filter SOLR results by this relevancy score?

Eg. perform a query in the nature of the following

```<code>Search for keyword "LOL" and only fetch documents whose relevancy score > 50
</code>```

If it's possible how would you go about specifying this query syntactically?

答:
solr 6.6:

add a solr filter query (fq):

```<code>q=SEARCH_PHRASE
&fq={!frange l=50.0}query($q,0)
</code>```

in this case solr will return the result with "score" >= 50.0

$q in query($q,0) - it's like a reference to a q parameter

Title: SOLR search filter by relevancy score

Body:
So each SOLR search result has their own relevancy score:

https://wiki.apache.org/solr/SolrRelevancyFAQ

"How can I see the relevancy scores for search results

Request that the pseudo-field named "score" be returned by adding it
  to the fl (field list) parameter. The "score" will then appear along
  with the stored fields in returned documents. q=Justice
  League&fl=*,score"

My question is...is it possible to filter SOLR results by this relevancy score?

Eg. perform a query in the nature of the following

Search for keyword "LOL" and only fetch documents whose relevancy score > 50

If it's possible how would you go about specifying this query syntactically?

Body:
solr 6.6:

add a solr filter query (fq):

q=SEARCH_PHRASE
&fq={!frange l=50.0}query($q,0)

in this case solr will return the result with "score" >= 50.0

$q in query($q,0) - it's like a reference to a q parameter


问:
Is there a contain's method?
I know there's a method contain(), it looks like this:

```<code>Dim arr() as string = {"apple","banana","orange"}
For each fruit in arr
 If fruit.contains("app") Then
  Return True
 End If
Next
</code>```

It will return true because "apple" contains letter "a". This is not what I want. I want it to return true only when "apple" contains the whole word "app". Is there any method or function to do this?

答:
You can use:</p>

```<code>If fruit.IndexOf("app") <> -1 Then
  Return True
End If
</code>```

Title: Is there a contain's method?

Body:
I know there's a method contain(), it looks like this:

Dim arr() as string = {"apple","banana","orange"}
For each fruit in arr
 If fruit.contains("app") Then
  Return True
 End If
Next

It will return true because "apple" contains letter "a". This is not what I want. I want it to return true only when "apple" contains the whole word "app". Is there any method or function to do this?

Body:
You can use:

If fruit.IndexOf("app") <> -1 Then
  Return True
End If


问:
mysql if value = "0" then get other value
I have a table as follows:

```<code>+-----------+------+--------+
| stockcode | year | equity |
+-----------+------+--------+
| AALI      | 2016 |  17347 |
| AALI      | 2017 |  18236 |
| AALI      | 2018 |  18990 |
| AALI      | 2019 |  18521 |
| ABBA      | 2016 |    132 |
| ABBA      | 2017 |    104 |
| ABBA      | 2018 |    203 |
| ABBA      | 2019 |      0 |
| ABDA      | 2016 |   1232 |
| ABDA      | 2017 |   1375 |
| ABDA      | 2018 |   1334 |
| ABDA      | 2019 |   1254 |
+-----------+------+--------+
</code>```

I need a query to get equity values based on the last year.
and if the value of the equity in 2019 = 0, get the value in 2018.

I tried to make it this way but it didn't work(blank page):

```<code>SELECT IF(equity <> '0', equity, SELECT equity FROM table_equity WHERE year='2018' AND stockcode='".$stockcode."') as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"
</code>```

but when I try with code like this it's work:

```<code>SELECT IF(equity <> '0', "active", "nonactive") as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"
</code>```

but of course the results were not what I wanted

So how to?

答:
Use 2 copies of a table - one will provide current year data and another for previous year. Use CASE operator and replace zero/null with the value for previous year (or zero if the data for previous year not exists in a table).

```<code>SELECT t1.stockcode,
       t1.year,
       CASE WHEN t1.equity > 0
            -- get current value if it is positive
            THEN t1.equity
            -- get previous value if current is zero,
            -- and get zero if no data for previous year
            ELSE COALESCE(t2.equity, 0) END equity,
       -- show previous year value, or zero if it is not present
       COALESCE(t2.equity, 0) previous_year_equity
FROM source_table t1
LEFT JOIN source_table t2 ON t1.year = t2.year + 1
                         AND t1.stockcode = t2.stockcode
</code>```

fiddle

Body:
I have a table as follows:

+-----------+------+--------+
| stockcode | year | equity |
+-----------+------+--------+
| AALI      | 2016 |  17347 |
| AALI      | 2017 |  18236 |
| AALI      | 2018 |  18990 |
| AALI      | 2019 |  18521 |
| ABBA      | 2016 |    132 |
| ABBA      | 2017 |    104 |
| ABBA      | 2018 |    203 |
| ABBA      | 2019 |      0 |
| ABDA      | 2016 |   1232 |
| ABDA      | 2017 |   1375 |
| ABDA      | 2018 |   1334 |
| ABDA      | 2019 |   1254 |
+-----------+------+--------+

I need a query to get equity values based on the last year.
and if the value of the equity in 2019 = 0, get the value in 2018.

I tried to make it this way but it didn't work(blank page):

SELECT IF(equity <> '0', equity, SELECT equity FROM table_equity WHERE year='2018' AND stockcode='".$stockcode."') as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"

but when I try with code like this it's work:

SELECT IF(equity <> '0', "active", "nonactive") as equity FROM table_equity WHERE year='2019' AND stockcode='".$stockcode."'"

but of course the results were not what I wanted

So how to?

Body:
Use 2 copies of a table - one will provide current year data and another for previous year. Use CASE operator and replace zero/null with the value for previous year (or zero if the data for previous year not exists in a table).

SELECT t1.stockcode,
       t1.year,
       CASE WHEN t1.equity > 0
            -- get current value if it is positive
            THEN t1.equity
            -- get previous value if current is zero,
            -- and get zero if no data for previous year
            ELSE COALESCE(t2.equity, 0) END equity,
       -- show previous year value, or zero if it is not present
       COALESCE(t2.equity, 0) previous_year_equity
FROM source_table t1
LEFT JOIN source_table t2 ON t1.year = t2.year + 1
                         AND t1.stockcode = t2.stockcode

fiddle


答:
```<code>SELECT CONVERT(smalldatetime, dbo.time(table1.col1)) AS col1
INTO #tableX
FROM table1
ORDER BY col1;
</code>```

Title: Write the result of the query into a table


问:
Log warning: Thread starvation or clock leap detected (housekeeper delta=springHikariConnectionPool)
I'm using HikariCP 2.4.6 and at Tomcat 8 startup, I get a warning message:

```<code>01-Aug-2016 11:18:01.599 INFO [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'Spring MVC Dispatcher Servlet'
[2016-08-01 11:18:01,654] Artifact blueberry:war exploded: Artifact is deployed successfully
[2016-08-01 11:18:01,655] Artifact blueberry:war exploded: Deploy took 33,985 milliseconds
Aug 01 2016 11:26:52.802 AM [DEV] (HikariPool.java:614)
WARN : com.zaxxer.hikari.pool.HikariPool - 9m13s102ms - Thread starvation or clock leap detected (housekeeper delta=springHikariConnectionPool).
</code>```

I don't see any other errors or issues reading/writing from the DB.  Is this something to be concerned about?  I tried searching around, but no luck.

We're also using Hibernate 4.3.8.Final over MySQL 5 and the MySQL 5.1.39 connector with Spring 4.1.0.RELEASE. We're working to upgrade to Hibernate 5 and will see whether this goes away, but don't know whether that will matter.

答: I was facing this issue in a spring boot MySQL work in an AWS T2 micro 1GB RAM instance . After an hours effort and nothing moving forward , observed that CPU usage was going towards 100% . Then I made the instance T2 medium having 4 GB RAM and 2 vCPUs. After that I faced no problem </p>

Body:
I'm using HikariCP 2.4.6 and at Tomcat 8 startup, I get a warning message:

01-Aug-2016 11:18:01.599 INFO [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'Spring MVC Dispatcher Servlet'
[2016-08-01 11:18:01,654] Artifact blueberry:war exploded: Artifact is deployed successfully
[2016-08-01 11:18:01,655] Artifact blueberry:war exploded: Deploy took 33,985 milliseconds
Aug 01 2016 11:26:52.802 AM [DEV] (HikariPool.java:614)
WARN : com.zaxxer.hikari.pool.HikariPool - 9m13s102ms - Thread starvation or clock leap detected (housekeeper delta=springHikariConnectionPool).

I don't see any other errors or issues reading/writing from the DB.  Is this something to be concerned about?  I tried searching around, but no luck.

We're also using Hibernate 4.3.8.Final over MySQL 5 and the MySQL 5.1.39 connector with Spring 4.1.0.RELEASE. We're working to upgrade to Hibernate 5 and will see whether this goes away, but don't know whether that will matter.


问:
writing integer input to vector container in C++
likewise we do in array

```<code>for (.....)
  cin>>a[i];
</code>```

how we can do this using vectors. i declared a vector of integers

```<code>vector<int> v;
</code>```

now i need to take inputs from console and add append those in vector.i am using vector because i donot know the limit.

答:
You can also dynamically allocate an array and then use it in a vector.

Here it is what you can do,

```<code>#include<bits/stdc++.h>
int main()
{
 int n;cin>>n;
 vector<int>v(n);
 for(int i=0;i<n;i++){
 cin>>v[i];
}
for(auto x:v){
cout<<x<<" "<<endl;
}
}

</code>```

Its an Easy approach you can do.

ContentLicense: CC BY-SA 2.5

Body:
likewise we do in array

for (.....)
  cin>>a[i];

how we can do this using vectors. i declared a vector of integers

vector<int> v;

now i need to take inputs from console and add append those in vector.i am using vector because i donot know the limit.

Body:
You can also dynamically allocate an array and then use it in a vector.

Here it is what you can do,

#include<bits/stdc++.h>
int main()
{
 int n;cin>>n;
 vector<int>v(n);
 for(int i=0;i<n;i++){
 cin>>v[i];
}
for(auto x:v){
cout<<x<<" "<<endl;
}
}

Its an Easy approach you can do.


问:
Rails 6 heroku Precompiling assets failed
compile fail with rails and omniauth on heroku

```<code>remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        rake aborted!
remote:        NoMethodError: undefined method `[]' for nil:NilClass
remote:        /tmp/build_f21d4b6cc71ba2ef116eca0b20a72d4b/config/initializers/devise.rb:263:in `block in <main>'
remote:        /tmp/build_f21d4b6cc71ba2ef116eca0b20a72d4b/vendor/bundle/ruby/2.7.0/gems/devise-4.7.1/lib/devise.rb:311:in `setup'
remote:        /tmp/build_f21d4b6cc71ba2ef116eca0b20a72d4b/config/initializers/devise.rb:5:in `<main>'
</code>```

I follow the devise .rb to 263 which is where I add twitter omniauth

```<code>config.omniauth :twitter, Rails.application.credentials.twitter[:app_id], Rails.application.credentials.twitter[:app_secret]
</code>```

I am storing my credentials stored in config/credentials.yml.enc

答:
The problem was caused by not being able to access the credentials.yml in production. We could access the master key value in production as it is not committed.

I fixed the issue by adding the master.key-value in Heroku, under settings, config vars master key

Body:
compile fail with rails and omniauth on heroku

remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        rake aborted!
remote:        NoMethodError: undefined method `[]' for nil:NilClass
remote:        /tmp/build_f21d4b6cc71ba2ef116eca0b20a72d4b/config/initializers/devise.rb:263:in `block in '
remote:        /tmp/build_f21d4b6cc71ba2ef116eca0b20a72d4b/vendor/bundle/ruby/2.7.0/gems/devise-4.7.1/lib/devise.rb:311:in `setup'
remote:        /tmp/build_f21d4b6cc71ba2ef116eca0b20a72d4b/config/initializers/devise.rb:5:in `'

I follow the devise .rb to 263 which is where I add twitter omniauth

config.omniauth :twitter, Rails.application.credentials.twitter[:app_id], Rails.application.credentials.twitter[:app_secret]

I am storing my credentials stored in config/credentials.yml.enc


问:
Is there any python libraries to detect latitude and longitude of detected object using camera?
I wanted to detect an object using satellite camera with latitude and longitude.</p>

答:
Not exactly sure by what you mean by detected object using camera. I think you mean latitude and longitude of landmarks in a photo.

If that is what you mean you must check you Google Vision API : https://cloud.google.com/vision/docs/detecting-landmarks

It detects famous landmarks from images and provides you with their latitude and longitude.


问:
ETS table - Updating maps as records
Sample code:

```<code>
defmodule Foo do

  def fast_cars_cache do
    fast_cars =
    {
      %{color: "Red", make: "Mclaren", mileage: 15641.469},
      %{color: "Blue", make: "Ferrari", mileage: 120012.481},
      %{color: "Red", make: "Ferrari", mileage: 29831.021},
      %{color: "Black", make: "Ferrari", mileage: 24030.674},
      %{color: "Cobalt", make: "Ferrari", mileage: 412.811},
      %{color: "Blue", make: "Koenigsegg", mileage: 250.762},
      %{color: "Cobalt", make: "Koenigsegg", mileage: 1297.76},
      %{color: "Titanium", make: "Koenigsegg", mileage: 5360.336},
      %{color: "Blue", make: "Maserati", mileage: 255.78}
    }

    if Enum.member?(:ets.all(), :fast_cars_cache) do
      :ets.delete(:fast_cars_cache)
      :ets.new(:fast_cars_cache, [:duplicate_bag, :public, :named_table])
      :ets.insert(:fast_cars_cache, fast_cars)
    else
      :ets.new(:fast_cars_cache, [:duplicate_bag, :public, :named_table])
      :ets.insert(:fast_cars_cache, fast_cars)
    end
  end

  def update_record do
    fast_cars_cache()

    old_record = :ets.first(:fast_cars_cache)

    new_record =
    %{color: "Black", make: old_record.make, mileage: 1641.469}

    :ets.delete(:fast_cars_cache, {old_record})
    |> IO.inspect(label: "Old record deleted")

    :ets.insert(:fast_cars_cache, {new_record})
    :ets.tab2list(:fast_cars_cache)
  end

end
</code>```

Output:

```<code>
iex(1)> Foo.update_record
Old record deleted: true
[
  {%{color: "Red", make: "Mclaren", mileage: 15641.469},
   %{color: "Blue", make: "Ferrari", mileage: 120012.481},
   %{color: "Red", make: "Ferrari", mileage: 29831.021},
   %{color: "Black", make: "Ferrari", mileage: 24030.674},
   %{color: "Cobalt", make: "Ferrari", mileage: 412.811},
   %{color: "Blue", make: "Koenigsegg", mileage: 250.762},
   %{color: "Cobalt", make: "Koenigsegg", mileage: 1297.76},
   %{color: "Titanium", make: "Koenigsegg", mileage: 5360.336},
   %{color: "Blue", make: "Maserati", mileage: 255.78}},
  {%{color: "Black", make: "Mclaren", mileage: 1641.469}}
]
</code>```

Observations/Questions:

According to the IO.inspect, old_record was deleted yet, as tab2list reveals, this record still exists. Why is that?

If, in fact, old_record was never deleted, what adjustments does the code need to accomplish this?

Ideally, I'd like to make use of :ets.select_replace, if applicable, to perform this update all in one step but I can't make heads or tails of the stipulations for the match specification requirement. It'd be really helpful if someone could disambiguate it with an example or two based on the sample above.

As always, thanks so much for your helpful guidance and suggestions :)

答:
You should clearly distinguish maps and tuples. Map is a key-value structure. Tuple is not.

:ets records are tuples, not maps.

Your initial structure is a tuple of maps. One single tuple, having many maps. It gets inserted as a single element into :ets, which is clearly visible in your output (check curly braces.)

I would guess you were to insert many elements into the cache.

iex|1 ▶ :ets.new(:fast_cars_cache, [:duplicate_bag, :public, :named_table])
iex|2 ▶ fast_cars = [
...|2 ▶   {"Red", "Mclaren", 15641.469},
...|2 ▶   {"Blue", "Ferrari", 120012.481},
...|2 ▶   {"Red", "Ferrari", 29831.021}
...|2 ▶ ]
iex|3 ▶ :ets.insert(:fast_cars_cache, fast_cars)
```

<p><code>:ets.first/1</code>, as it’s stated in the documentation, returns <em>the first key</em>. <code>:ets.detele/2</code> deletes a record <em>by key</em> and your code wraps whatever was returned from <code>:ets.first/1</code> into a one-element tuple, making <code>:ets.delete/2</code> a no-op no matter what (and yes, <code>:ets.delete/2</code> <em>always</em> returns <code>true</code>.)</p>

<pre class="lang-rb prettyprint-override"><code>iex|4 ▶ :ets.first(:fast_cars_cache)
#⇒ "Red"
iex|5 ▶ :ets.delete(:fast_cars_cache, {"Red"}) # NOOP
#⇒ true
iex|6 ▶ :ets.delete(:fast_cars_cache, "Red") # DELETED
#⇒ true
</code>```

Then if you want to insert a new record, create a tuple and insert it, don’t create a map wrapped into a single-element tuple. To get the old record by key, one usually uses :ets.lookup/2, or more sophisticated :ets.select.

iex|7 ▶ [{_, make, _}|_] = :ets.lookup(:fast_cars_cache, "Red")
iex|8 ▶ new_record = {"Black", make, 1641.469}
iex|9 ▶ :ets.insert(:fast_cars_cache, new_record)
```

I have linked enough documentation to leave using :ets.select_replace/2 as homework.

Title: ETS table - Updating maps as records

Body:
Sample code:

defmodule Foo do

  def fast_cars_cache do
    fast_cars =
    {
      %{color: "Red", make: "Mclaren", mileage: 15641.469},
      %{color: "Blue", make: "Ferrari", mileage: 120012.481},
      %{color: "Red", make: "Ferrari", mileage: 29831.021},
      %{color: "Black", make: "Ferrari", mileage: 24030.674},
      %{color: "Cobalt", make: "Ferrari", mileage: 412.811},
      %{color: "Blue", make: "Koenigsegg", mileage: 250.762},
      %{color: "Cobalt", make: "Koenigsegg", mileage: 1297.76},
      %{color: "Titanium", make: "Koenigsegg", mileage: 5360.336},
      %{color: "Blue", make: "Maserati", mileage: 255.78}
    }

    if Enum.member?(:ets.all(), :fast_cars_cache) do
      :ets.delete(:fast_cars_cache)
      :ets.new(:fast_cars_cache, [:duplicate_bag, :public, :named_table])
      :ets.insert(:fast_cars_cache, fast_cars)
    else
      :ets.new(:fast_cars_cache, [:duplicate_bag, :public, :named_table])
      :ets.insert(:fast_cars_cache, fast_cars)
    end
  end

  def update_record do
    fast_cars_cache()

    old_record = :ets.first(:fast_cars_cache)

    new_record =
    %{color: "Black", make: old_record.make, mileage: 1641.469}

    :ets.delete(:fast_cars_cache, {old_record})
    |> IO.inspect(label: "Old record deleted")

    :ets.insert(:fast_cars_cache, {new_record})
    :ets.tab2list(:fast_cars_cache)
  end

end

Output:

iex(1)> Foo.update_record
Old record deleted: true
[
  {%{color: "Red", make: "Mclaren", mileage: 15641.469},
   %{color: "Blue", make: "Ferrari", mileage: 120012.481},
   %{color: "Red", make: "Ferrari", mileage: 29831.021},
   %{color: "Black", make: "Ferrari", mileage: 24030.674},
   %{color: "Cobalt", make: "Ferrari", mileage: 412.811},
   %{color: "Blue", make: "Koenigsegg", mileage: 250.762},
   %{color: "Cobalt", make: "Koenigsegg", mileage: 1297.76},
   %{color: "Titanium", make: "Koenigsegg", mileage: 5360.336},
   %{color: "Blue", make: "Maserati", mileage: 255.78}},
  {%{color: "Black", make: "Mclaren", mileage: 1641.469}}
]

Observations/Questions:

According to the IO.inspect, old_record was deleted yet, as tab2list reveals, this record still exists. Why is that?

If, in fact, old_record was never deleted, what adjustments does the code need to accomplish this?

Ideally, I'd like to make use of :ets.select_replace, if applicable, to perform this update all in one step but I can't make heads or tails of the stipulations for the match specification requirement. It'd be really helpful if someone could disambiguate it with an example or two based on the sample above.

As always, thanks so much for your helpful guidance and suggestions :)

Body:
You should clearly distinguish maps and tuples. Map is a key-value structure. Tuple is not.

:ets records are tuples, not maps.

Your initial structure is a tuple of maps. One single tuple, having many maps. It gets inserted as a single element into :ets, which is clearly visible in your output (check curly braces.)

I would guess you were to insert many elements into the cache.

iex|1 ▶ :ets.new(:fast_cars_cache, [:duplicate_bag, :public, :named_table])
iex|2 ▶ fast_cars = [
...|2 ▶   {"Red", "Mclaren", 15641.469},
...|2 ▶   {"Blue", "Ferrari", 120012.481},
...|2 ▶   {"Red", "Ferrari", 29831.021}
...|2 ▶ ]
iex|3 ▶ :ets.insert(:fast_cars_cache, fast_cars)

:ets.first/1, as it’s stated in the documentation, returns the first key. :ets.detele/2 deletes a record by key and your code wraps whatever was returned from :ets.first/1 into a one-element tuple, making :ets.delete/2 a no-op no matter what (and yes, :ets.delete/2 always returns true.)

iex|4 ▶ :ets.first(:fast_cars_cache)
#⇒ "Red"
iex|5 ▶ :ets.delete(:fast_cars_cache, {"Red"}) # NOOP
#⇒ true
iex|6 ▶ :ets.delete(:fast_cars_cache, "Red") # DELETED
#⇒ true

Then if you want to insert a new record, create a tuple and insert it, don’t create a map wrapped into a single-element tuple. To get the old record by key, one usually uses :ets.lookup/2, or more sophisticated :ets.select.

iex|7 ▶ [{_, make, _}|_] = :ets.lookup(:fast_cars_cache, "Red")
iex|8 ▶ new_record = {"Black", make, 1641.469}
iex|9 ▶ :ets.insert(:fast_cars_cache, new_record)

I have linked enough documentation to leave using :ets.select_replace/2 as homework.


问:
Debugging Access Violation errors?
What tips can you share to help locate and fix access violations when writing applications in Delphi?

I believe access violations are usually caused by trying to access something in memory that has not yet been created such as an Object etc?

I find it hard to identify what triggers the access violations and then where to make the required changes to try and stop/fix them.

A example is a personal project I am working on now. I am storing in TTreeView Node.Data property some data for each node. Nodes can be multiple selected and exported (the export iterates through each selected node and saves specific data to a text file - the information saved to the text file is what is stored in the nodes.data). Files can also be imported into the Treeview (saving the contents of the text files into the node.data).

The issue in that example is if I import files into the Treeview and then export them, it works perfect. However if I add a node at runtime and export them I get:

"Access Violation at address 00405772 in module 'Project1.exe'. Read of address 00000388."

My thoughts on that must be the way I am assigning the data to created nodes, maybe differently to the way I assign it when they are imported, but it all looks ok to me. The access violation only shows up when exporting, and this never happens with imported files.

I am NOT looking for a fix to the above example, but mainly advice/tips how to find and fix such type of errors. I don't often get access violations, but when I do they are really hard to track down and fix.

So advice and tips would be very useful.

答:
It means your code is accessing some part of the memory it isn't allowed to. That usually means you have a pointer or object reference pointing to the wrong memory. Maybe because it is not initialized or is already released.

Use a debugger, like Delphi. It will tell you on what line of code the AV occurred. From there figure out your problem by looking at the callstack and local variables etc. Sometimes it also helps if you compile with Debug DCUs.

If you don't have a debugger because it only happens on a client side, you might want to use MadExcept or JclDebug to log the exception with callstack and have it send to you. It gives you less details but might point you in the right direction.

There are some tools that might be able to find these kind of problems earlier by checking more aggressively. The FastMM memory manager has such options.

EDIT

"Access Violation at address 00405772
  in module 'Project1.exe'. Read of
  address 00000388."

So your problem results in a AV at addresss 00405772 in module 'Project1.exe'. The Delphi debugger will bring you to the right line of code (or use Find Error).

It is trying to read memory at address 00000388. That is pretty close to 00000000 (nil), so that would probably mean accessing some pointer/reference to an array or dynamic array that is nil. If it was an array of bytes, it would be item 388. Or it could be a field of a rather large object or record with lots of fields. The object or record pointer/reference would be nil.

Title: Debugging Access Violation errors?


问:
Zend Adapter Transaction Rollback Failed MSSQL
I have this odd error, i use MSSQL 2008 R2 and ZendFw 1.12

First.. the rollback didn’t fail inside try..

```<code>   // Zend_DB_Table Adapter
   $adapter = Zend_Db_Table::getDefaultAdapter();

   // Start Transaction
   $adapter->beginTransaction();

   try {
          $adapter->rollBack();
          return (int) 1;
   } catch (Exception $e) {
          throw new Api_Exception($e->getMessage(), $e->getCode(), $e);
   }
</code>```

But.. the rollback failed inside catch..

Yes i deliberately create error on try bellow to make it goes inside catch..

```<code>   // Zend_DB_Table Adapter
   $adapter = Zend_Db_Table::getDefaultAdapter();

   // Start Transaction
   $adapter->beginTransaction();

   try {
          return (int) A;
   } catch (Exception $e) {
          $adapter->rollBack();
          throw new Api_Exception($e->getMessage(), $e->getCode(), $e);
   }
</code>```

It returns.. Zend_Db_Adapter_Sqlsrv_Exception: A transaction must be started by calling sqlsrv_begin_transaction before calling sqlsrv_commit or sqlsrv_rollback.

Any clue please?

答:
hi go and see this link Rollback in SQL

you can use safe and easy code for run 100% (run all line of query) or no run any off them

```<code>|query 1| = like insert into or select or ...
|count of lines| = number off query

DECLARE @rowcount int  set @rowcount = 0 ;
BEGIN TRANSACTION [Tran1]
BEGIN TRY
 <Query 1> ; set @rowcount = (@rowcount + @@ROWCOUNT);
 <Query 2> ; set @rowcount = (@rowcount + @@ROWCOUNT);
...
IF @rowcount =  <count of lines>
  COMMIT TRANSACTION[Tran1]
ELSE
  ROLLBACK TRANSACTION[Tran1]
END TRY
  BEGIN CATCH
  ROLLBACK TRANSACTION[Tran1]
END CATCH
</code>```

for example this code run 2 insert into line query but or run all of him or no run anything and ROLLBACK

```<code>DECLARE @rowcount int  set @rowcount = 0 ;
BEGIN TRANSACTION [Tran1]
BEGIN TRY
 insert into [database].[dbo].[tbl1] (fld1) values('1') ;
    set @rowcount = (@rowcount + @@ROWCOUNT);
 insert into [database].[dbo].[tbl2] (fld1) values('2') ;
    set @rowcount = (@rowcount + @@ROWCOUNT);

IF @rowcount =  2
  COMMIT TRANSACTION[Tran1]
ELSE
  ROLLBACK TRANSACTION[Tran1]
END TRY
  BEGIN CATCH
  ROLLBACK TRANSACTION[Tran1]
END CATCH
</code>```

Body:
I have this odd error, i use MSSQL 2008 R2 and ZendFw 1.12

First.. the rollback didn’t fail inside try..

   // Zend_DB_Table Adapter
   $adapter = Zend_Db_Table::getDefaultAdapter();

   // Start Transaction
   $adapter->beginTransaction();

   try {
          $adapter->rollBack();
          return (int) 1;
   } catch (Exception $e) {
          throw new Api_Exception($e->getMessage(), $e->getCode(), $e);
   }

But.. the rollback failed inside catch..

Yes i deliberately create error on try bellow to make it goes inside catch..

   // Zend_DB_Table Adapter
   $adapter = Zend_Db_Table::getDefaultAdapter();

   // Start Transaction
   $adapter->beginTransaction();

   try {
          return (int) A;
   } catch (Exception $e) {
          $adapter->rollBack();
          throw new Api_Exception($e->getMessage(), $e->getCode(), $e);
   }

It returns.. Zend_Db_Adapter_Sqlsrv_Exception: A transaction must be started by calling sqlsrv_begin_transaction before calling sqlsrv_commit or sqlsrv_rollback.

Any clue please?

Body:
hi go and see this link Rollback in SQL

you can use safe and easy code for run 100% (run all line of query) or no run any off them

|query 1| = like insert into or select or ...
|count of lines| = number off query

DECLARE @rowcount int  set @rowcount = 0 ;
BEGIN TRANSACTION [Tran1]
BEGIN TRY
 <Query 1> ; set @rowcount = (@rowcount + @@ROWCOUNT);
 <Query 2> ; set @rowcount = (@rowcount + @@ROWCOUNT);
...
IF @rowcount =  <count of lines>
  COMMIT TRANSACTION[Tran1]
ELSE
  ROLLBACK TRANSACTION[Tran1]
END TRY
  BEGIN CATCH
  ROLLBACK TRANSACTION[Tran1]
END CATCH

for example this code run 2 insert into line query but or run all of him or no run anything and ROLLBACK

DECLARE @rowcount int  set @rowcount = 0 ;
BEGIN TRANSACTION [Tran1]
BEGIN TRY
 insert into [database].[dbo].[tbl1] (fld1) values('1') ;
    set @rowcount = (@rowcount + @@ROWCOUNT);
 insert into [database].[dbo].[tbl2] (fld1) values('2') ;
    set @rowcount = (@rowcount + @@ROWCOUNT);

IF @rowcount =  2
  COMMIT TRANSACTION[Tran1]
ELSE
  ROLLBACK TRANSACTION[Tran1]
END TRY
  BEGIN CATCH
  ROLLBACK TRANSACTION[Tran1]
END CATCH


问:
How to know if an npm package can be imported with ES6 import syntax?
Besides going through the documentation of the package and trial/error attempts, how can I know for sure if an npm packaged can be imported with the ES6 import syntax?

Is there a file inside the package folder that I can check?

I constantly question myself about this.

For example:

The md5 package DOCS only mentions md5 = require('md5'); but I've just tested and it works with import md5 from 'md5'

How can I inspect the package and know for sure?

答:
You must check if the module/package has a dist or a src folder. If the package has a dist folder, Then it can be imported using es6's import statement. Otherwise if it has a src folder, Then it can't be imported using es6's import statement and you must use cjs's require function to import such modules. If you try to import a cjs module using the import statement, You will get the following error:

```<code>Syntax Error: Cannot use import statement outside a module
</code>```

Body:
You must check if the module/package has a dist or a src folder. If the package has a dist folder, Then it can be imported using es6's import statement. Otherwise if it has a src folder, Then it can't be imported using es6's import statement and you must use cjs's require function to import such modules. If you try to import a cjs module using the import statement, You will get the following error:

Syntax Error: Cannot use import statement outside a module


问:
ITMS-90809: Deprecated API Usage -- Apple will stop accepting submissions of apps that use UIWebView APIs
Yesterday, I uploaded my App to TestFlight and after a while Apple sent me this warning:

ITMS-90809: Deprecated API Usage - Apple will stop accepting submissions of apps that use UIWebView APIs . See https://developer.apple.com/documentation/uikit/uiwebview for more information.

The thing is that I don't use UIWebView in my app so I tried to update my pods but still the same thing.By the way this is my 3rd build on TestFlight and this is the first time apple sends me this. Any ideas?

Update

These are my pods:

```<code>pod 'Firebase/Core'
pod 'Firebase/Firestore'
pod 'Firebase/MLVision'
pod 'Firebase/MLVisionTextModel'
pod 'SVProgressHUD'
pod 'SPPermission/Camera'
pod 'SPPermission/PhotoLibrary'
pod 'Mantis'
pod 'SwiftKeychainWrapper'
pod 'SwiftyOnboard'
pod 'Fabric'
pod 'Crashlytics'
</code>```

Update 2

Seems like I found the frameworks with the issue.

```<code>Binary file ./Pods/FirebaseMLCommon/Frameworks/FirebaseMLCommon.framework/FirebaseMLCommon matches
Binary file ./Pods/Crashlytics/iOS/Crashlytics.framework/Crashlytics matches
Binary file ./Pods/GoogleMobileVision/Detector/Frameworks/GoogleMobileVision.framework/GoogleMobileVision matches
</code>```

So now do I have to wait for google to fix them and update my pods?

答:
For project with cocoapods:</p>

```<code>grep -r UIWebView Pods/
</code>```

Body:
Yesterday, I uploaded my App to TestFlight and after a while Apple sent me this warning:

ITMS-90809: Deprecated API Usage - Apple will stop accepting submissions of apps that use UIWebView APIs . See https://developer.apple.com/documentation/uikit/uiwebview for more information.

The thing is that I don't use UIWebView in my app so I tried to update my pods but still the same thing.By the way this is my 3rd build on TestFlight and this is the first time apple sends me this. Any ideas?

Update

These are my pods:

pod 'Firebase/Core'
pod 'Firebase/Firestore'
pod 'Firebase/MLVision'
pod 'Firebase/MLVisionTextModel'
pod 'SVProgressHUD'
pod 'SPPermission/Camera'
pod 'SPPermission/PhotoLibrary'
pod 'Mantis'
pod 'SwiftKeychainWrapper'
pod 'SwiftyOnboard'
pod 'Fabric'
pod 'Crashlytics'

Update 2

Seems like I found the frameworks with the issue.

Binary file ./Pods/FirebaseMLCommon/Frameworks/FirebaseMLCommon.framework/FirebaseMLCommon matches
Binary file ./Pods/Crashlytics/iOS/Crashlytics.framework/Crashlytics matches
Binary file ./Pods/GoogleMobileVision/Detector/Frameworks/GoogleMobileVision.framework/GoogleMobileVision matches

So now do I have to wait for google to fix them and update my pods?

Body:
For project with cocoapods:

grep -r UIWebView Pods/


问:
Is it possible to force the app from going into power save mode?
How to force the app from going into power save mode in Android?</p>

答:
You want a wake lock. See:

http://developer.android.com/reference/android/os/PowerManager.WakeLock.html


问:
subscript out of range error while trying to copy a button
I have code that was working when the sheet was named "Sheet1".

I changed the name to "Custom".

I get

subscript out of range

with this line:

```<code>Set xButton = Sheets("Custom").OLEObjects(ButtonName)
</code>```

It was working with:

```<code>Set xButton = Sheets("Sheet1").OLEObjects(ButtonName)
</code>```

答:
I suspect you have renamed the worksheets using the (name) property which refers to the code name of the worksheet.

E.g:

Sheets("Custom").OLEObjects(ButtonName) refers to a worksheet which the sheet name property has been changed to "Custom".

Custom.OLEObjects(ButtonName) refers to a worksheet which the code name property has been changed to "Custom"

You can read more about both properties in the following docs:

Codename Property

Name Property

 Other things to consider:

It's generally best to explicitly declare your workbook. If you don't, VBA uses ActiveWorkbook by default which means you can get Subscript out of range errors if your code is running and you have a different workbook in focus.

You can do this like:

ThisWorkbook.Sheets("Custom") or,

Say you have 2 workbooks, WorkbookA and WorkbookB:

WorkbookA.Sheets("Custom") or WorkbookB.Sheets("Custom") etc.

Body:
I have code that was working when the sheet was named "Sheet1".

I changed the name to "Custom".

I get

subscript out of range

with this line:

Set xButton = Sheets("Custom").OLEObjects(ButtonName)

It was working with:

Set xButton = Sheets("Sheet1").OLEObjects(ButtonName)


问:
What is the best way to handle exceptions in Perl?
I've noticed that Exception.pm and Error.pm don't seem to be extensively used in the Perl community.  Is that due to the large footprint of eval for exception handling?

Also Perl programs appear to have a much more lenient policy regarding exception handling in general.  Is there a compelling reason for this?

In any event what would be the best method for exception handling in Perl?

答:
As it has been mentioned you can use the traditional way with eval, but if you want to use more elaborate exception trapping, including with exception objects, then I recommend using the try-catch-finally blocks.
There are quite a few perl modules that provide it such as Nice::Try and Syntax::Keyword::Try, but Syntax::Keyword::Try does not provide exception variable assignment or exception class catch like

```<code>  try
  {
    # something
  }
  catch( Exception $e )
  {
    # catch this in $e
  }
</code>```

Full disclosure: I am the developer of Nice::Try

Body:
As it has been mentioned you can use the traditional way with eval, but if you want to use more elaborate exception trapping, including with exception objects, then I recommend using the try-catch-finally blocks.
There are quite a few perl modules that provide it such as Nice::Try and Syntax::Keyword::Try, but Syntax::Keyword::Try does not provide exception variable assignment or exception class catch like

  try
  {
    # something
  }
  catch( Exception $e )
  {
    # catch this in $e
  }

Full disclosure: I am the developer of Nice::Try


问:
How to amend Java code to send multiple email attachments, using Sketchware?
I'm really new to Java and have been building an app on Sketchware. If you're not familiar with it, it uses block programming and you can inject your own code in custom blocks.

As the storage of all app views are local only, I need all the output PDFs to be attached to an email on the press of a button.

The below code works to attach one file but need 6 files attached. All being called from /Documents/ folder on the android device. How can I achieve this?

```<code>emailIntent.putExtra(
    Intent.EXTRA_STREAM,
    Uri.fromFile(
        new java.io.File(Environment.getExternalStorageDirectory() +"/Documents/filename.pdf")
    )
);
</code>```

The filenames I have are in one folder, and are named filename1.pdf, filename2.pdf, etc.

If I try repeating this code with each filename, filename6.pdf will be the only file attached to the email.

Here's the Sketchware block diagram:

答:
Maybe that will do the job for you.

Here is the code you need to create an emailIntent that contains multiple attachments. The key change is ACTION_SEND_MULTIPLE.

```<code>public static void email(Context context, String emailTo, String emailCC,
    String subject, String emailText, List<String> filePaths)
{
    //need to "send multiple" to get more than one attachment
    final Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    emailIntent.setType("text/plain");
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
        new String[]{emailTo});
    emailIntent.putExtra(android.content.Intent.EXTRA_CC,
        new String[]{emailCC});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
    //has to be an ArrayList
    ArrayList<Uri> uris = new ArrayList<Uri>();
    //convert from paths to Android friendly Parcelable Uri's
    for (String file : filePaths)
    {
        File fileIn = new File(file);
        Uri u = Uri.fromFile(fileIn);
        uris.add(u);
    }
    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
</code>```

Update

Post discussion in chat-room I would like to conclude that it is not possible to send multiple attachments in email with Sketchware, as it does not offer Intent.ACTION_SEND_MULTIPLE functionality. You need to send multiple emails with attachments one by one.

Above mentioned code will suffice the job you need when you have the liberty to code and this will work with Android as mentioned here.

All I could read about Sketchware is that only one file can be attached at a time, see here.

Body:
I'm really new to Java and have been building an app on Sketchware. If you're not familiar with it, it uses block programming and you can inject your own code in custom blocks.

As the storage of all app views are local only, I need all the output PDFs to be attached to an email on the press of a button.

The below code works to attach one file but need 6 files attached. All being called from /Documents/ folder on the android device. How can I achieve this?

emailIntent.putExtra(
    Intent.EXTRA_STREAM,
    Uri.fromFile(
        new java.io.File(Environment.getExternalStorageDirectory() +"/Documents/filename.pdf")
    )
);

The filenames I have are in one folder, and are named filename1.pdf, filename2.pdf, etc.

If I try repeating this code with each filename, filename6.pdf will be the only file attached to the email.

Here's the Sketchware block diagram:

Body:
Maybe that will do the job for you.

Here is the code you need to create an emailIntent that contains multiple attachments. The key change is ACTION_SEND_MULTIPLE.

public static void email(Context context, String emailTo, String emailCC,
    String subject, String emailText, List<String> filePaths)
{
    //need to "send multiple" to get more than one attachment
    final Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
    emailIntent.setType("text/plain");
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
        new String[]{emailTo});
    emailIntent.putExtra(android.content.Intent.EXTRA_CC,
        new String[]{emailCC});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
    emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
    //has to be an ArrayList
    ArrayList<Uri> uris = new ArrayList<Uri>();
    //convert from paths to Android friendly Parcelable Uri's
    for (String file : filePaths)
    {
        File fileIn = new File(file);
        Uri u = Uri.fromFile(fileIn);
        uris.add(u);
    }
    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}

Update

Post discussion in chat-room I would like to conclude that it is not possible to send multiple attachments in email with Sketchware, as it does not offer Intent.ACTION_SEND_MULTIPLE functionality. You need to send multiple emails with attachments one by one.

Above mentioned code will suffice the job you need when you have the liberty to code and this will work with Android as mentioned here.

All I could read about Sketchware is that only one file can be attached at a time, see here.


问:
Debugging rails web service
I have an android app as client and a rails REST webservice.Rails application is running on the local host.I have installed the fast debugger on Netbeans.I am using WEBrick server right now.

I am using ruby 1.9.2 and rails 3.0.1 version and my netbeans IDE is 6.9 .

When i run my application I have found that the application is deployed properly on to the server and the output is shown on the console but when i debug my application nothing happens and no output is shown on the console and when i try to hit localhost:3000 from the browser it displays 'could not connect to the web server cannot show http://localhost:3000'

Thanks

答:
It worked when i changed the ruby platform from 1.9.2 to 1.8.7-p174.

P.S. :Sometimes the gem paths set by netbeans would be wrong.Please check it and correct it if it is wrong.

Title: Debugging rails web service


问:
How to do logging in React Native
How can I log a variable in React Native, like using console.log when developing for web?

答:
There are multiple ways to log.

console.warn() will go through the log in the mobile screen itself. It can be useful if you want to log small things and don’t want to bother opening console.

Another is console.log(), for which you will have to open the browser's console to view the logs. With the newer React Native 0.62+, you can see the log in node itself. So they've made it much the easier to view logs in newer version.

Title: How to do logging in React Native


问:
Binary numbers of N digits
for generating binary numbers in n digit

i did this to get upto 16 binary numbers.

```<code>n = 6                       # for 6 digits
for i in xrange(16):
    b = bin(i)[2:]
    l = len(b)
    b = str(0) * (n - l) + b
    print b
</code>```

it results like this

```<code>000000
000001
000010
000011
000100
000101
000110
000111
001000
001001
001010
001011
001100
001101
001110
001111
</code>```

but what i want is to get these values without adding a series of 0s in prefix.

can anyone help me for this.

  thanks

答:
You can use list comprehension and bit conversions together like this:
n = range

```<code>def binary_list(n):
    return ['{:0{}b}'.format(i, n) for i in range(n*n-1)]

print(binary_list(3)) -->
['000', '001', '010', '011', '100', '101', '110', '111']

</code>```

or if you want to store each number in its own index do:

```<code>def binary_list(n):
    return [[int(j) for j in '{:0{}b}'.format(i, n)] for i in range(n*n-1)]

print(binary_list(3))--->
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

</code>```

Title: Binary numbers of N digits

Body:
for generating binary numbers in n digit

i did this to get upto 16 binary numbers.

n = 6                       # for 6 digits
for i in xrange(16):
    b = bin(i)[2:]
    l = len(b)
    b = str(0) * (n - l) + b
    print b

it results like this

000000
000001
000010
000011
000100
000101
000110
000111
001000
001001
001010
001011
001100
001101
001110
001111

but what i want is to get these values without adding a series of 0s in prefix.

can anyone help me for this.

  thanks

Body:
You can use list comprehension and bit conversions together like this:
n = range

def binary_list(n):
    return ['{:0{}b}'.format(i, n) for i in range(n*n-1)]

print(binary_list(3)) -->
['000', '001', '010', '011', '100', '101', '110', '111']

or if you want to store each number in its own index do:

def binary_list(n):
    return [[int(j) for j in '{:0{}b}'.format(i, n)] for i in range(n*n-1)]

print(binary_list(3))--->
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]