问:
git push is failing because of not asking token for login
I have a github repository in my organisation where I am a member of it.
I did cloning of that repository from intelliJ into using the token which i have created in my git account. I have added the remote in intelliJ using the same server name and token.

I am able to clone this repository and after updating the code, while trying to push the code  back to repository it is again asking for the userID and password. It is not showing the option to login with token itself, as shown below. (If I give the username and password instead of token it will not work)

Because of this i am not able to push any code changes into git. This was working fine earlier either without asking any login page or with login page which have option to provide token. I didnt make any changes in settings, but now facing this issue for last few days.

Is there anything that i have to make changes in settings?
Any help appreciated!

答:
IDE saves all passwords, including GitHub token, according to the settings in Settings | Appearance & Behavior | System Settings | Passwords.
Make sure IDE is configured to save passwords either in Keychain or in KeePass, so you won't be prompted to enter login and password again.

When prompted for credentials, either enter token as username and leave the password field empty or use the token instead of your password.
(Please see: https://intellij-support.jetbrains.com/hc/en-us/articles/206537004-How-to-access-GIT-remote-repositories-with-2-factor-authentication)

Regarding SSH connection:
IDE relies on command-line Git, whereas in its turn Git sends a request to SSH client, so it may worth to check ssh config and see how it's configured.
Also please check whether you have SSH or HTTPS URL specified under VCS | Git | Remotes..


来源: stackexchange

问:
RegEx to match stuff between parentheses
I'm having a tough time getting this to work. I have a string like:

```<code>something/([0-9])/([a-z])
</code>```

And I need regex or a method of getting each match between the parentheses and return an array of matches like:

```<code>[
  [0-9],
  [a-z]
]
</code>```

The regex I'm using is /\((.+)\)/ which does seem to match the right thing if there is only one set of parenthesis.

How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.

答:
You need to make your regex pattern 'non-greedy' by adding a ? after the .+

By default, * and + are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

Non-greedy makes the pattern only match the shortest possible match.

See Watch Out for The Greediness! for a better explanation.

Or alternately, change your regex to

```<code>\(([^\)]+)\)
</code>```

which will match any grouping of parentheses that do not, themselves, contain parentheses.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a tough time getting this to work. I have a string like:

something/([0-9])/([a-z])

And I need regex or a method of getting each match between the parentheses and return an array of matches like:

[
  [0-9],
  [a-z]
]

The regex I'm using is /\((.+)\)/ which does seem to match the right thing if there is only one set of parenthesis.

How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.

Body:
You need to make your regex pattern 'non-greedy' by adding a ? after the .+

By default, * and + are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

Non-greedy makes the pattern only match the shortest possible match.

See Watch Out for The Greediness! for a better explanation.

Or alternately, change your regex to

\(([^\)]+)\)

which will match any grouping of parentheses that do not, themselves, contain parentheses.

ContentLicense: CC BY-SA 4.0


问:
Passing get paramter to controller
I realise this is probably a simple question. I'm trying to pass a get parameter to Scala Play controller :

I'm using Play2 and reading the doc:
https://www.playframework.com/documentation/2.8.x/ScalaActions it does not seem to be specified.

Here is my function in a controller:

```<code>  def sj(name: String) = Action { implicit request =>

      println("Name: "+name)
      println("Request is:"+request)
      Ok(Json.toJson(List(1,2,3)).toString());

  }
</code>```

Route points to this controller:

```<code>GET     /chart/data                    controllers.ChartController.sj
</code>```

Invoking http://localhost:9000/chart/data?name=test

invokes the function sj defined above but the println statements are not being printed to the console. How to pass the get parameter "name" to a controller function ?

答: As per comment by @Mario Galic use GET /chart/data controllers.ChartController.sj(name) in routes file.

Title: Passing get paramter to controller

Body:
I realise this is probably a simple question. I'm trying to pass a get parameter to Scala Play controller :

I'm using Play2 and reading the doc:
https://www.playframework.com/documentation/2.8.x/ScalaActions it does not seem to be specified.

Here is my function in a controller:

  def sj(name: String) = Action { implicit request =>

      println("Name: "+name)
      println("Request is:"+request)
      Ok(Json.toJson(List(1,2,3)).toString());

  }

Route points to this controller:

GET     /chart/data                    controllers.ChartController.sj

Invoking http://localhost:9000/chart/data?name=test

invokes the function sj defined above but the println statements are not being printed to the console. How to pass the get parameter "name" to a controller function ?


问:
executing command using ssh.net long text how parse this backspaces?
I have some large project that connect to many devices over SSH.NET

i have some issue that when i do shells.Read() and output have some long line i get output like

```<code>"description <XC descritption long , id123123123 IP:120.120.120.20 VC\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b$ <XC descritption long, id123123123  IP:120.120.120.20 VCI         \b\b\b\b\b\b\b\b\bD:2500\r\ndescription <XC descritption long, id123123123  IP:120.120.120.20 VCID:2500\r\n  ^\r\n% Invalid input detected at '^' marker.\r\n\r\ngateway2#"
</code>```

i googled a little and found that it  is some way of sending long lines to output if it does not fit inside one line of this 'virtual terminal window' ?

my question is how to parse it programaticly without any actual textbox that would do this automaticly so i get what i should so only

```<code> description <XC descritption long, id123123123  IP:120.120.120.20 VCID:2500\r\n  ^\r\n% Invalid input detected at '^' marker.\r\n\r\ngateway2#"
</code>```

?
i would need to count this \b and do some cutting based of numbers of them ? or is it some 'proper' way to do this ?

thanks and regards !

答:
You have to parse the backspaces and remove the preceding character (if it exists).

I'd use a method along the lines of the following:

```<code>public static string ParseBackspaces(string input)
{
    List<char> characters = new List<char>(input);
    int index = 0;
    while (index < characters.Count)
    {
        int back1 = index - 1;
        if (back1 >= 0 && characters[index] == '\b')
        {
            characters.RemoveRange(back1, 2);
            index = back1;
            continue;
        }
        else if (characters[index] == '\b')
        {
            characters.RemoveAt(index);
            continue;
        }
        index++;
    }
    return new String(characters.ToArray());
}
</code>```

Here's a fiddle showing your string once parsed by this method: https://dotnetfiddle.net/79U8sH

Body:
I have some large project that connect to many devices over SSH.NET

i have some issue that when i do shells.Read() and output have some long line i get output like

"description <XC descritption long , id123123123 IP:120.120.120.20 VC\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b$ <XC descritption long, id123123123  IP:120.120.120.20 VCI         \b\b\b\b\b\b\b\b\bD:2500\r\ndescription <XC descritption long, id123123123  IP:120.120.120.20 VCID:2500\r\n  ^\r\n% Invalid input detected at '^' marker.\r\n\r\ngateway2#"

i googled a little and found that it  is some way of sending long lines to output if it does not fit inside one line of this 'virtual terminal window' ?

my question is how to parse it programaticly without any actual textbox that would do this automaticly so i get what i should so only

 description <XC descritption long, id123123123  IP:120.120.120.20 VCID:2500\r\n  ^\r\n% Invalid input detected at '^' marker.\r\n\r\ngateway2#"

?
i would need to count this \b and do some cutting based of numbers of them ? or is it some 'proper' way to do this ?

thanks and regards !

Body:
You have to parse the backspaces and remove the preceding character (if it exists).

I'd use a method along the lines of the following:

public static string ParseBackspaces(string input)
{
    List<char> characters = new List<char>(input);
    int index = 0;
    while (index < characters.Count)
    {
        int back1 = index - 1;
        if (back1 >= 0 && characters[index] == '\b')
        {
            characters.RemoveRange(back1, 2);
            index = back1;
            continue;
        }
        else if (characters[index] == '\b')
        {
            characters.RemoveAt(index);
            continue;
        }
        index++;
    }
    return new String(characters.ToArray());
}

Here's a fiddle showing your string once parsed by this method: https://dotnetfiddle.net/79U8sH


问:
How to pass common arguments in Dart?
Say, I have:

```<code>callback.orderBy('foo', reverse: true).localToThis();
callback.orderBy('foo', reverse: true);
</code>```

You can see in both callbacks, I am passing same arguments,

```<code>'foo', reverse: true
</code>```

Is there any way I can make them something (a variable or a method) so that I can use something like this:

```<code>callback.orderBy(common).localToThis();
callback.orderBy(common);
</code>```

答:
callback.orderBy('foo', reverse: true).localToThis();
callback.orderBy('foo', reverse: true);
```
</blockquote>

<p>If you're calling the same function with the same set of arguments, if the function has no side-effects, you might as well just save the result and avoid calling the function again.</p>

<p>If the function does have side-effects or if you want to call the function with only some of its arguments the same, you could use a partial function application to bind arguments:</p>

<pre class="lang-dart prettyprint-override"><code>final orderBy = () => callback.orderBy('foo', reverse: true);
orderBy().localToThis();
orderBy();
</code>```

Title: How to pass common arguments in Dart?

Body:
Say, I have:

callback.orderBy('foo', reverse: true).localToThis();
callback.orderBy('foo', reverse: true);

You can see in both callbacks, I am passing same arguments,

'foo', reverse: true

Is there any way I can make them something (a variable or a method) so that I can use something like this:

callback.orderBy(common).localToThis();
callback.orderBy(common);

Body:
callback.orderBy('foo', reverse: true).localToThis();
callback.orderBy('foo', reverse: true);

If you're calling the same function with the same set of arguments, if the function has no side-effects, you might as well just save the result and avoid calling the function again.

If the function does have side-effects or if you want to call the function with only some of its arguments the same, you could use a partial function application to bind arguments:

final orderBy = () => callback.orderBy('foo', reverse: true);
orderBy().localToThis();
orderBy();


问:
export bing map image using html2canvas. Only Pins show during export, base map doesn't load
I have a .aspx page that finds the location of properties and places a pin at this location. I load the map in fine but when using html2canvas, My base map wont load. I am new to bing maps and this functionality and don't know what to do next. I don't know if i am supposed to load in a layer or tile source but here is my code for the following:

```<code>             <%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="comparableMapping.aspx.vb" Inherits="*.comparableMapping" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script charset="UTF-8" type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script charset="UTF-8" type="text/javascript" src="/Scripts/html2canvas.js"></script>
<script type="text/javascript">

    var pinInfobox = null;
    var map = null;
    var currprop;
    var defaultInfobox = new Microsoft.Maps.Infobox();
    var layer1 = new Microsoft.Maps.EntityCollection();
    var MM = Microsoft.Maps;
    var PushPinsEntity = new Microsoft.Maps.EntityCollection();

    function GetMap() {
        map = new MM.Map(document.getElementById("mapDiv"),
                          {
                              credentials: "-",
                              width: 1100,
                              height: 650,
                              enablesearchlogo: false,
                              showScalebar: false,
                              zoom: 7
                          });
        map.entities.clear();
        <%=mapLocations()%>

    }

    function displayInfoBox(e) {
        var obj = e.target;
        var pinLoc = e.target.getLocation();
        var pinId = e.target.getText() - 1;
        var pinId = e.target.pinId - 1;
        currprop = props[pinId].split("~");

        var name = currprop[0];
        if (name !== null) {
            var info = name + "<br/>";
            info += currprop[5] + "<br/>";
            info += currprop[6] + ", " + currprop[7] + " " + currprop[8] + "";
        } else {
            var info = currprop[5] + "<br/>";
            info += currprop[6] + ", " + currprop[7] + " " + currprop[8] + "";
        }
        //closeInfoWindow();
        //map.entities.remove(defaultInfobox);

        //var infoboxOptions = { title: currprop[1], width: 250, height: 140, description: info, offset: new Microsoft.Maps.Point(-1, 45) };
        var infoboxOptions = { title: currprop[1], description: info };
        defaultInfobox = new Microsoft.Maps.Infobox(map.getCenter(), infoboxOptions);
        defaultInfobox.setLocation(pinLoc);
        map.entities.push(defaultInfobox);
        //Microsoft.Maps.Events.addHandler(defaultInfobox, 'mouseleave', function () { defaultInfobox.setOptions({ visible: false }); });
    }

    function closeInfoWindow() {
        el = document.getElementById('InfoWindow');
        el.style.display = 'none';
    }

    function zoomInToProperty(e) {
        var loc = new Microsoft.Maps.Location(currprop[3], currprop[4]);
        map.setView({ center: loc, zoom: 20 });
    }

    function zoomOutOfProperty(e) {
        var viewRect = Microsoft.Maps.LocationRect.fromLocations(locs);
        if (locs.length > 1) { map.setView({ bounds: viewRect }) } else { map.setView({ center: locs[0], zoom: 6 }) };
    }

    function captureScreen() {
        html2canvas($("#mapDiv"), {
            logging: true,
            useCORS: true,
            onrendered: function (canvas) {
                //document.body.appendChild(canvas);
                var img = canvas.toDataURL("image/png");
                window.open(img);
                //var a = document.createElement('a');
                //a.download = name;
                //a.href = canvas.toDataURL('image/png');
                //document.body.appendChild(a);
                //a.click();
            },
        });

    }
 </script>
 </asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<div style="margin-top:10px;">
    <div id='mapDiv' class="map">
    <script type=”text/javascript”>GetMap();</script></div><br />
    <input id="load" value="save" type="button" onclick="captureScreen();"/>
    </div>
    <div style="clear:left;"></div>
</asp:Content>
</code>```

答: Just need to enable:enableCORS: true in the maps option, too need config userCORS: true, in options in the html2canvas scripts

Body:
I have a .aspx page that finds the location of properties and places a pin at this location. I load the map in fine but when using html2canvas, My base map wont load. I am new to bing maps and this functionality and don't know what to do next. I don't know if i am supposed to load in a layer or tile source but here is my code for the following:

             <%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="comparableMapping.aspx.vb" Inherits="*.comparableMapping" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

 </asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">

    <input id="load" value="save" type="button" onclick="captureScreen();"/>

</asp:Content>


问:
SQL Server 2008 2mb Limit for XML?
I am trying to output a long XML result from SMSS.

When I right click on the results and 'save results as...', I can only get a 2mb file?

I have changed the settings in SMSS via Tools -> Options -> Query Results -> SQL Server -> Results to Grid, for XML data to be unlimited.

However, it still seems to be truncating my XML results?

So, how can I bypass this problem and output my XML result to a file?

Thanks

答:
Just Restart the SMSS after making the changes, it works fine.

SMSS via Tools -> Options -> Query Results -> SQL Server -> Results to Grid, for XML data to be unlimited.

Screenshot

ContentLicense: CC BY-SA 2.5

Title: SQL Server 2008 2mb Limit for XML?


问:
HTML Input Radio Value="false" Posts NULL
In FireFox, I have a radio input with it's value set to the string "false" (not sure if there's any possible distinction from boolean false).

```<code><input name="test_1" type="radio" value="false" />
</code>```

When I post the form, I get:

```<code>print_r($_POST["test_1"]);

Array
(
    [test_1] =>
)
</code>```

Which suggests that the browser casts the string "false" to Boolean FALSE or NULL.

What is the expected behavior?

What if I specifically want the string "false" to be returned?

答: My understanding is that if the radio button is checked the value is POSTed otherwise an empty string is sent. In your case if the radio button is checked "false" will be sent otherwise an empty string is sent.</p>

Body:
In FireFox, I have a radio input with it's value set to the string "false" (not sure if there's any possible distinction from boolean false).

<input name="test_1" type="radio" value="false" />

When I post the form, I get:

print_r($_POST["test_1"]);

Array
(
    [test_1] =>
)

Which suggests that the browser casts the string "false" to Boolean FALSE or NULL.

What is the expected behavior?

What if I specifically want the string "false" to be returned?


问:
I want to add background in JFrame how could I?
Here is my code how can I add a background in it I tried every possible solution but the picture won't show up in the background.

what should I do can anyone help me?

```<code>  public class Triangle {
        JLabel l1;
        public static void main(String[] args) {
            new Triangle();
        }

        public Triangle() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }

                    JFrame frame = new JFrame("Testing");

                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new TestPane());
                    frame.setSize(400,400);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);

                }
            });
        }

        public class TestPane extends JPanel {

            private Polygon poly;

           {

                poly = new Polygon(
                    new int[]{110, 150, 50},
                    new int[]{200, 0, 0},
                        3);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 400);

            }

            protected void paintComponent(Graphics g) {
                super.paintComponent(g);

                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(Color.blue);
                g2.fill(poly);
                 g2.setColor(Color.red);
                 g2.fillRect(0,0,25,75);
                 g2.setColor(Color.green);
                 g2.fillOval(200,100,100,50);
                 g2.setColor(Color.green);
                 g2.fillOval(300,300,250,250);

            }
        }
    }
</code>```

Here is my code how can I add a background in it I tried every possible solution but the picture won't show up in the background.

what should I do can anyone help me?

答:
Set background color to the JPanel

Try this:

```<code>TestPane myPane = new TestPane();
myPane.setBackground(Color.green);
frame.add(myPane);
</code>```

Body:
Here is my code how can I add a background in it I tried every possible solution but the picture won't show up in the background.

what should I do can anyone help me?

  public class Triangle {
        JLabel l1;
        public static void main(String[] args) {
            new Triangle();
        }

        public Triangle() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }

                    JFrame frame = new JFrame("Testing");

                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new TestPane());
                    frame.setSize(400,400);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);

                }
            });
        }

        public class TestPane extends JPanel {

            private Polygon poly;

           {

                poly = new Polygon(
                    new int[]{110, 150, 50},
                    new int[]{200, 0, 0},
                        3);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 400);

            }

            protected void paintComponent(Graphics g) {
                super.paintComponent(g);

                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(Color.blue);
                g2.fill(poly);
                 g2.setColor(Color.red);
                 g2.fillRect(0,0,25,75);
                 g2.setColor(Color.green);
                 g2.fillOval(200,100,100,50);
                 g2.setColor(Color.green);
                 g2.fillOval(300,300,250,250);

            }
        }
    }

Here is my code how can I add a background in it I tried every possible solution but the picture won't show up in the background.

what should I do can anyone help me?

Body:
Set background color to the JPanel

Try this:

TestPane myPane = new TestPane();
myPane.setBackground(Color.green);
frame.add(myPane);


问:
SQL SUM to ignore NULL value
I have a table TEST_TABLE as follows:

```<code>Name     x_col       y_col
=======================
Jay     NULL     2
</code>```

This is a simplistic representation of a much larger issue but will suffice.

When I do the following query I get NULL returned

```<code>SELECT SUM(x_col + y_col) FROM TEST_TABLE WHERE Name='Jay'
</code>```

I want it to be 2. I thought the SUM() method ignores NULL values. How can I ignore values that are null in this query? Or actually in general, as this is a problem for a lot of my algorithms.

答:
Use COALESCE to replace NULL with 0.</p>

```<code>SELECT sum(coalesce(x_col, 0) + coalesce(y_col, 0)) FROM TEST_TABLE WHERE Name='Jay'
</code>```

Title: SQL SUM to ignore NULL value

Body:
I have a table TEST_TABLE as follows:

Name     x_col       y_col
=======================
Jay     NULL     2

This is a simplistic representation of a much larger issue but will suffice.

When I do the following query I get NULL returned

SELECT SUM(x_col + y_col) FROM TEST_TABLE WHERE Name='Jay'

I want it to be 2. I thought the SUM() method ignores NULL values. How can I ignore values that are null in this query? Or actually in general, as this is a problem for a lot of my algorithms.

Body:
Use COALESCE to replace NULL with 0.

SELECT sum(coalesce(x_col, 0) + coalesce(y_col, 0)) FROM TEST_TABLE WHERE Name='Jay'


答:
You get NULL because NULL + 2 returns NULL.  The SUM() has only one row, and if the + expression is NULL, then the SUM() returns NULL.

If you want NULL to be treated as 0, the use COALESCE():

```<code>SELECT SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0))
FROM TEST_TABLE
WHERE Name = 'Jay';
</code>```

One final note.  If you start with your data and filtered out all rows, then the result will still be NULL.  To get 0, you need an additional COALESCE():

```<code>SELECT COALESCE(SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0)), 0)
FROM TEST_TABLE
WHERE Name = 'Jayden';
</code>```

Title: SQL SUM to ignore NULL value

Body:
You get NULL because NULL + 2 returns NULL.  The SUM() has only one row, and if the + expression is NULL, then the SUM() returns NULL.

If you want NULL to be treated as 0, the use COALESCE():

SELECT SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0))
FROM TEST_TABLE
WHERE Name = 'Jay';

One final note.  If you start with your data and filtered out all rows, then the result will still be NULL.  To get 0, you need an additional COALESCE():

SELECT COALESCE(SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0)), 0)
FROM TEST_TABLE
WHERE Name = 'Jayden';


问:
switch while won't loop
This is part of a program I'm writting. My main porblem is that once it goes trough one of the cases, tit won't loop so it's useless as it is. Any help? (Sorry for the variables in Spanish, also a couple of functions i created appear in the cose which are in the program and work just fine so I don't thin they have anything to do with the problem).</p>

```<code>static void Main(string[] args)
    {
        int minutos_restantes = 480;
        int opcion;
        int valorComercial = 0;
        Tarea[] listado_tareas = new Tarea[10];

        CrearTareas(ref listado_tareas);

        Console.WriteLine("1. Mostrar tareas. \n2. Asignar tarea \n3. Salir, \n Elige opción: ");
        opcion = Convert.ToInt32(Console.ReadLine());

        switch (opcion)
        {
            case 1:
                Imprimirtareas(listado_tareas);
                break;

            case 2:
                Console.WriteLine("Seleccionar número de tarea: ");
                int n = Convert.ToInt32(Console.ReadLine())-1;

                if (n < 0 || n > 10)
                {
                    Console.WriteLine("TAREA INEXISTENTE");
                }

                else if (listado_tareas[n].realizada == true)
                {
                    Console.WriteLine("TAREA YA REALIZADA");
                }

                else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
                {
                    Console.WriteLine("TIEMPO INSUFICIENTE");
                }

                else
                {
                    listado_tareas[n].realizada = true;
                    minutos_restantes -= listado_tareas[n].tiempo;
                }

                break;
        } while (opcion != 3) ;

    }
</code>```

答:
I don't think you can loop over a switch like this.
Try doing the while separate:</p>

```<code>do
{
    switch (opcion)
    {
        case 1:
            Imprimirtareas(listado_tareas);
            break;

        case 2:
            Console.WriteLine("Seleccionar número de tarea: ");
            int n = Convert.ToInt32(Console.ReadLine())-1;

            if (n < 0 || n > 10)
            {
                Console.WriteLine("TAREA INEXISTENTE");
            }

            else if (listado_tareas[n].realizada == true)
            {
                Console.WriteLine("TAREA YA REALIZADA");
            }

            else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
            {
                Console.WriteLine("TIEMPO INSUFICIENTE");
            }

            else
            {
                listado_tareas[n].realizada = true;
                minutos_restantes -= listado_tareas[n].tiempo;
            }

            break;
    }

}while (opcion != 3) ;
</code>```

Title: switch while won't loop

Body:
This is part of a program I'm writting. My main porblem is that once it goes trough one of the cases, tit won't loop so it's useless as it is. Any help? (Sorry for the variables in Spanish, also a couple of functions i created appear in the cose which are in the program and work just fine so I don't thin they have anything to do with the problem).

static void Main(string[] args)
    {
        int minutos_restantes = 480;
        int opcion;
        int valorComercial = 0;
        Tarea[] listado_tareas = new Tarea[10];

        CrearTareas(ref listado_tareas);

        Console.WriteLine("1. Mostrar tareas. \n2. Asignar tarea \n3. Salir, \n Elige opción: ");
        opcion = Convert.ToInt32(Console.ReadLine());

        switch (opcion)
        {
            case 1:
                Imprimirtareas(listado_tareas);
                break;

            case 2:
                Console.WriteLine("Seleccionar número de tarea: ");
                int n = Convert.ToInt32(Console.ReadLine())-1;

                if (n < 0 || n > 10)
                {
                    Console.WriteLine("TAREA INEXISTENTE");
                }

                else if (listado_tareas[n].realizada == true)
                {
                    Console.WriteLine("TAREA YA REALIZADA");
                }

                else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
                {
                    Console.WriteLine("TIEMPO INSUFICIENTE");
                }

                else
                {
                    listado_tareas[n].realizada = true;
                    minutos_restantes -= listado_tareas[n].tiempo;
                }

                break;
        } while (opcion != 3) ;

    }

Body:
I don't think you can loop over a switch like this.
Try doing the while separate:

do
{
    switch (opcion)
    {
        case 1:
            Imprimirtareas(listado_tareas);
            break;

        case 2:
            Console.WriteLine("Seleccionar número de tarea: ");
            int n = Convert.ToInt32(Console.ReadLine())-1;

            if (n < 0 || n > 10)
            {
                Console.WriteLine("TAREA INEXISTENTE");
            }

            else if (listado_tareas[n].realizada == true)
            {
                Console.WriteLine("TAREA YA REALIZADA");
            }

            else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
            {
                Console.WriteLine("TIEMPO INSUFICIENTE");
            }

            else
            {
                listado_tareas[n].realizada = true;
                minutos_restantes -= listado_tareas[n].tiempo;
            }

            break;
    }

}while (opcion != 3) ;


问:
Best practices for storing images locally to avoid problems when the image source is down (security too)?
I'm using argocd and helm charts to deploy multiple applications in a cluster. My cluster happens to be on bare metal, but I don't think that matters for this question. Also, sorry, this is probably a pretty basic question.

I ran into a problem yesterday where one of the remote image sources used by one of my helm charts was down. This brought me to a halt because I couldn't stand up one of the main services for my cluster without that image and I didn't have a local copy of it.

So, my question is, what would you consider to be best practice for storing images locally to avoid this kind of problem? Can I store charts and images locally once I've pulled them for the first time so that I don't have to always rely on third parties? Is there a way to set up a pass-through cache for helm charts and docker images?

答:
As one of the options:

Create your own helm chart repository to store helm charts locally (optionally)

Create local image registry and push there needed images, also tag them accordingly for future simplicity

On each node add insecure registry by editing /etc/docker/daemon.json and adding

{
 "insecure-registries" : ["myregistrydomain.com:5000"]
}

restart docker service on each node to apply changes

change your helm charts templates, set proper image path from local repo

recreate chart with new properties, (optionally)push chart to created in step 1 local helm repo

FInally install the chart - this time it should pick up images from local repo.

You may also be interested in Kubernetes-Helm Charts pointing to a local docker image


问:
i hide some imageViews inside recycler view, but when i do scroll down all imageViews hide

Hello Team!!

I'm new on android but i have knoweledge in html and javascript. So i have a JSON that have some options(img,or not img) and i create a recycler view to list this JSON and all ok, later i try that hide some imageView of card because the JSON show that this doesn't have picture. It works fine

But when i do scroll down to bottom limit all imageViews hide, i don't know how solve it and i search in web but i can't find some solution for this issue.

Code in adapter

```<code>@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onBindViewHolder(postViewHolder postViewHolder, int position) {
    addPostTimeline addPost = addPostTimelines.get(position);
    try {
        CircleImageView img=postViewHolder.imgFoto;
        JSONObject fileson=addPost.getDatosTimeine().getJSONObject("file");

        // postViewHolder.imgTimeLine = @+id/image_timeline

        if(!fileson.getBoolean("err")){ // si tiene archivos adjuntos
            switch (fileson.getString("type")){
                case "Pic":
                    imageTimeline imgTm=new imageTimeline(fileson.getString("src"), postViewHolder.imgTimeLine);
                    imgTm.execute();
                break;
                default:
                    postViewHolder.imgTimeLine.setVisibility(View.GONE);
                break;
            }
        }else{
            postViewHolder.contentFiles.setVisibility(View.GONE);
        }
        putImgProfile putImg=new putImgProfile(addPost.getDatosTimeine().getString("pDir"), img);
        putImg.execute();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

Structure of card with recycler

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    android:id="@+id/cvManana"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    card_view:cardCornerRadius="4dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">
    <LinearLayout android:background="@drawable/textlines"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="6dp"
        android:paddingBottom="6dp"
        android:orientation="vertical"
        android:id="@+id/post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/imgPerfil"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="8dp"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_load_img" />
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_fechaPost"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="hace 44 minutos sep. 22º 16"
                        android:textColor="#999" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_nickname"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingRight="12dp"
                        android:text="SonickSeven"
                        android:textColor="#24650e"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:id="@+id/contentTextStory">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/tv_postTimeLine"
                    android:textColor="#666"
                    android:textSize="15dp"
                    android:layout_gravity="left"
                    android:text="historias"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/contentFiles">
                <!-- image to hide -->
                <ImageView
                    android:id="@+id/image_timeline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:cropToPadding="false"
                    android:scaleType="fitStart"
                    card_view:srcCompat="@drawable/campo_manana" />
                <!-- end imagen to hide -->
            </LinearLayout>
            <LinearLayout
                android:paddingTop="4dp"
                android:paddingBottom="7dp"
                android:layout_gravity="left"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <LinearLayout
                    android:gravity="right"
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_reply"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_reply_gray"/>
                    <TextView
                        android:id="@+id/countReply"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_share"
                        android:scaleType="centerCrop"
                        android:layout_gravity="center_vertical"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_share_gray"/>
                    <TextView
                        android:id="@+id/countShare"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:layout_gravity="center_vertical"
                        android:id="@+id/bt_like"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_like_gray"/>
                    <TextView
                        android:id="@+id/countLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_dislike"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_nolike_gray"/>
                    <TextView
                        android:id="@+id/countNoLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</code>```

i saw that when i go to bottom of scroll and up the switch trigger again, but it doesn't could because the recycler view run all array JSON. Sorry i can understand how work android-java

答:
Try this in onBindViewHolder method:

```<code>@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onBindViewHolder(postViewHolder postViewHolder, int position) {
addPostTimeline addPost = addPostTimelines.get(position);

try {

CircleImageView img=postViewHolder.imgFoto;
JSONObject fileson=addPost.getDatosTimeine().getJSONObject("file");

if(!fileson.getBoolean("err") && fileson.getString("type").equals("pic")){

//image must be visible and no error
postViewHolder.imgTimeLine.setVisibility(View.VISIBLE);
postViewHolder.contentFiles.setVisibility(View.VISIBLE);

imageTimeline imgTm=new imageTimeline(fileson.getString("src"), postViewHolder.imgTimeLine);
imgTm.execute();

}else if(!fileson.getBoolean("err") && !fileson.getString("type").equals("pic")){

//image shouldn't be visible and no error

postViewHolder.imgTimeLine.setVisibility(View.GONE);
postViewHolder.contentFiles.setVisibility(View.VISIBLE);

}else{

//error

postViewHolder.imgTimeLine.setVisibility(View.GONE);
postViewHolder.contentFiles.setVisibility(View.GONE);

}

putImgProfile putImg=new putImgProfile(addPost.getDatosTimeine().getString("pDir"), img);
putImg.execute();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

Body:
Hello Team!!

I'm new on android but i have knoweledge in html and javascript. So i have a JSON that have some options(img,or not img) and i create a recycler view to list this JSON and all ok, later i try that hide some imageView of card because the JSON show that this doesn't have picture. It works fine

But when i do scroll down to bottom limit all imageViews hide, i don't know how solve it and i search in web but i can't find some solution for this issue.

Code in adapter

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onBindViewHolder(postViewHolder postViewHolder, int position) {
    addPostTimeline addPost = addPostTimelines.get(position);
    try {
        CircleImageView img=postViewHolder.imgFoto;
        JSONObject fileson=addPost.getDatosTimeine().getJSONObject("file");

        // postViewHolder.imgTimeLine = @+id/image_timeline

        if(!fileson.getBoolean("err")){ // si tiene archivos adjuntos
            switch (fileson.getString("type")){
                case "Pic":
                    imageTimeline imgTm=new imageTimeline(fileson.getString("src"), postViewHolder.imgTimeLine);
                    imgTm.execute();
                break;
                default:
                    postViewHolder.imgTimeLine.setVisibility(View.GONE);
                break;
            }
        }else{
            postViewHolder.contentFiles.setVisibility(View.GONE);
        }
        putImgProfile putImg=new putImgProfile(addPost.getDatosTimeine().getString("pDir"), img);
        putImg.execute();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Structure of card with recycler

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    android:id="@+id/cvManana"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    card_view:cardCornerRadius="4dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">
    <LinearLayout android:background="@drawable/textlines"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="6dp"
        android:paddingBottom="6dp"
        android:orientation="vertical"
        android:id="@+id/post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/imgPerfil"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="8dp"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_load_img" />
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_fechaPost"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="hace 44 minutos sep. 22º 16"
                        android:textColor="#999" />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_nickname"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingRight="12dp"
                        android:text="SonickSeven"
                        android:textColor="#24650e"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:id="@+id/contentTextStory">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/tv_postTimeLine"
                    android:textColor="#666"
                    android:textSize="15dp"
                    android:layout_gravity="left"
                    android:text="historias"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/contentFiles">

                <ImageView
                    android:id="@+id/image_timeline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:cropToPadding="false"
                    android:scaleType="fitStart"
                    card_view:srcCompat="@drawable/campo_manana" />

            </LinearLayout>
            <LinearLayout
                android:paddingTop="4dp"
                android:paddingBottom="7dp"
                android:layout_gravity="left"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <LinearLayout
                    android:gravity="right"
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_reply"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_reply_gray"/>
                    <TextView
                        android:id="@+id/countReply"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_share"
                        android:scaleType="centerCrop"
                        android:layout_gravity="center_vertical"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_share_gray"/>
                    <TextView
                        android:id="@+id/countShare"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:layout_gravity="center_vertical"
                        android:id="@+id/bt_like"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_like_gray"/>
                    <TextView
                        android:id="@+id/countLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                <LinearLayout
                    android:layout_weight="1.0"
                    android:layout_width="match_parent"
                    android:gravity="right"
                    android:layout_height="wrap_content">
                    <ImageButton
                        android:id="@+id/bt_dislike"
                        android:layout_gravity="center_vertical"
                        android:scaleType="centerCrop"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:background="@mipmap/ic_nolike_gray"/>
                    <TextView
                        android:id="@+id/countNoLike"
                        android:text="(3)"
                        android:textSize="12dp"
                        android:layout_gravity="center"
                        android:textColor="#999"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

i saw that when i go to bottom of scroll and up the switch trigger again, but it doesn't could because the recycler view run all array JSON. Sorry i can understand how work android-java

Body:
Try this in onBindViewHolder method:

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onBindViewHolder(postViewHolder postViewHolder, int position) {
addPostTimeline addPost = addPostTimelines.get(position);

try {

CircleImageView img=postViewHolder.imgFoto;
JSONObject fileson=addPost.getDatosTimeine().getJSONObject("file");

if(!fileson.getBoolean("err") && fileson.getString("type").equals("pic")){

//image must be visible and no error
postViewHolder.imgTimeLine.setVisibility(View.VISIBLE);
postViewHolder.contentFiles.setVisibility(View.VISIBLE);

imageTimeline imgTm=new imageTimeline(fileson.getString("src"), postViewHolder.imgTimeLine);
imgTm.execute();

}else if(!fileson.getBoolean("err") && !fileson.getString("type").equals("pic")){

//image shouldn't be visible and no error

postViewHolder.imgTimeLine.setVisibility(View.GONE);
postViewHolder.contentFiles.setVisibility(View.VISIBLE);

}else{

//error

postViewHolder.imgTimeLine.setVisibility(View.GONE);
postViewHolder.contentFiles.setVisibility(View.GONE);

}

putImgProfile putImg=new putImgProfile(addPost.getDatosTimeine().getString("pDir"), img);
putImg.execute();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答:
The ! character is used to denote a destructive method: that is a method that permanently alters one or more of the variables passed to it.

For example:

Pretend you have a plus_one method that adds 1 to the number passed to it.

if we have

```<code>a = 1
</code>```

Then we could do

```<code>b=a.plus_one
</code>```

and still have a = 1. However if plus_one were a destructive method (and as a result were called with plus_one!) doing the following:

```<code>     a.plus_one!
</code>```

would permanently alter the value of a to be 2.

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

Body:
The ! character is used to denote a destructive method: that is a method that permanently alters one or more of the variables passed to it.

For example:

Pretend you have a plus_one method that adds 1 to the number passed to it.

if we have

a = 1

Then we could do

b=a.plus_one

and still have a = 1. However if plus_one were a destructive method (and as a result were called with plus_one!) doing the following:

     a.plus_one!

would permanently alter the value of a to be 2.


问:
Div Not Taking Up Full Space

The Problem

I'm having an issue where a max-width is being set on my div from somewhere but I'm not sure where it is as I have checked the styling package that I'm using (Semantic UI) as well as my own internal styles and I am not able to find the place where it is derived from (As shown in image 1, it is in a style tag, but that is only the compiled Semantic UI code as seen in image 2).
(Image 1)

(Image 2)

Because of the issue shown, this is what shows inside of the app

Expected Behavior

This is what the expected behavior is: (It takes up the whole space instead of being restricted)

Code

App.css

```<code>html,
body,
.app {
  height: 100vh;
  background: #eee;
  padding: 1em;
}

/* SidePanel.js */
.menu {
  padding-bottom: 2em;
}

/* Messages.js */
.messages {
  height: 70vh;
  overflow-y: scroll;
}

/* MessageForm.js */
.message__form {
  position: fixed !important;
  bottom: 1em;
  margin-left: 320px !important;
  left: 0;
  right: 1em;
  z-index: 200;
}

.emoijpicker {
  position: absolute;
}

/* Message.js */
.message__self {
  border-left: 2px solid orange;
  padding-left: 8px;
}

.message__image {
  padding: 1em;
}
</code>```

Messages.js (Some parts not included due to relevancy)

```<code>import { Segment, Comment } from "semantic-ui-react";
...

  render() {
    // prettier-ignore
    const { messagesRef, messages, channel, user, numUniqueUsers, searchTerm, searchResults, searchLoading, privateChannel, isChannelStarred, typingUsers, messagesLoading } = this.state;

    return (
      <React.Fragment>
        <MessagesHeader
          channelName={this.displayChannelName(channel)}
          numUniqueUsers={numUniqueUsers}
          handleSearchChange={this.handleSearchChange}
          searchLoading={searchLoading}
          isPrivateChannel={privateChannel}
          handleStar={this.handleStar}
          isChannelStarred={isChannelStarred}
        />

        <Segment>
          <Comment.Group className="messages">
            {this.displayMessageSkeleton(messagesLoading)}
            {searchTerm
              ? this.displayMessages(searchResults)
              : this.displayMessages(messages)}
            {this.displayTypingUsers(typingUsers)}
            <div ref={node => (this.messagesEnd = node)} />
          </Comment.Group>
        </Segment>

        <MessageForm
          messagesRef={messagesRef}
          currentChannel={channel}
          currentUser={user}
          isPrivateChannel={privateChannel}
          getMessagesRef={this.getMessagesRef}
        />
      </React.Fragment>
    );
  }
}

export default connect(
  null,
  { setUserPosts }
)(Messages);

</code>```

答:
As godfather suggested in the comments, I tried an override on the .ui class and I got the expected behavior with this addition to the App.css file:

App.css

```<code>...
.ui {
  max-width: 100% !important;
}
...
</code>```

Title: Div Not Taking Up Full Space

Body:
The Problem

I'm having an issue where a max-width is being set on my div from somewhere but I'm not sure where it is as I have checked the styling package that I'm using (Semantic UI) as well as my own internal styles and I am not able to find the place where it is derived from (As shown in image 1, it is in a style tag, but that is only the compiled Semantic UI code as seen in image 2).
(Image 1)

(Image 2)

Because of the issue shown, this is what shows inside of the app

Expected Behavior

This is what the expected behavior is: (It takes up the whole space instead of being restricted)

Code

App.css

html,
body,
.app {
  height: 100vh;
  background: #eee;
  padding: 1em;
}

/* SidePanel.js */
.menu {
  padding-bottom: 2em;
}

/* Messages.js */
.messages {
  height: 70vh;
  overflow-y: scroll;
}

/* MessageForm.js */
.message__form {
  position: fixed !important;
  bottom: 1em;
  margin-left: 320px !important;
  left: 0;
  right: 1em;
  z-index: 200;
}

.emoijpicker {
  position: absolute;
}

/* Message.js */
.message__self {
  border-left: 2px solid orange;
  padding-left: 8px;
}

.message__image {
  padding: 1em;
}

Messages.js (Some parts not included due to relevancy)

import { Segment, Comment } from "semantic-ui-react";
...

  render() {
    // prettier-ignore
    const { messagesRef, messages, channel, user, numUniqueUsers, searchTerm, searchResults, searchLoading, privateChannel, isChannelStarred, typingUsers, messagesLoading } = this.state;

    return (
      <React.Fragment>
        <MessagesHeader
          channelName={this.displayChannelName(channel)}
          numUniqueUsers={numUniqueUsers}
          handleSearchChange={this.handleSearchChange}
          searchLoading={searchLoading}
          isPrivateChannel={privateChannel}
          handleStar={this.handleStar}
          isChannelStarred={isChannelStarred}
        />

        <Segment>
          <Comment.Group className="messages">
            {this.displayMessageSkeleton(messagesLoading)}
            {searchTerm
              ? this.displayMessages(searchResults)
              : this.displayMessages(messages)}
            {this.displayTypingUsers(typingUsers)}

 (this.messagesEnd = node)} />
          </Comment.Group>
        </Segment>

        <MessageForm
          messagesRef={messagesRef}
          currentChannel={channel}
          currentUser={user}
          isPrivateChannel={privateChannel}
          getMessagesRef={this.getMessagesRef}
        />
      </React.Fragment>
    );
  }
}

export default connect(
  null,
  { setUserPosts }
)(Messages);

Body:
As godfather suggested in the comments, I tried an override on the .ui class and I got the expected behavior with this addition to the App.css file:

App.css

...
.ui {
  max-width: 100% !important;
}
...


问:
How to set the value of partialErrorsByItemID on CKError for testing?
I want to test my error handling for a class handling CloudKit Operations. I'd like to be able to construct a CKError with a particular partial error, so that I can pass it into the Operation's completion block under test.

I can init a CKError with the .partialError code but as the partialErrorsByItemID Dictionary is get-only, I can't set the partial errors.

```<code>let error = CKError(.partialError)
error.partialErrorsByItemID = ["TestItemID": CKError(.zoneNotFound)] // => Cannot assign to property: 'partialErrorsByItemID' is a get-only property
</code>```

Is there a way to control the value of partialErrorsByItemID?

答:
You can assign the value of partialErrorsByItemID by providing the relevant key/value pair in the userInfo Dictionary, and using the init(_:userInfo:) initializer:

```<code>let error = CKError(.partialFailure, userInfo: [
    CKPartialErrorsByItemIDKey: ["TestItemID": CKError(.zoneNotFound)]
])
</code>```

Body:
I want to test my error handling for a class handling CloudKit Operations. I'd like to be able to construct a CKError with a particular partial error, so that I can pass it into the Operation's completion block under test.

I can init a CKError with the .partialError code but as the partialErrorsByItemID Dictionary is get-only, I can't set the partial errors.

let error = CKError(.partialError)
error.partialErrorsByItemID = ["TestItemID": CKError(.zoneNotFound)] // => Cannot assign to property: 'partialErrorsByItemID' is a get-only property

Is there a way to control the value of partialErrorsByItemID?

Body:
You can assign the value of partialErrorsByItemID by providing the relevant key/value pair in the userInfo Dictionary, and using the init(_:userInfo:) initializer:

let error = CKError(.partialFailure, userInfo: [
    CKPartialErrorsByItemIDKey: ["TestItemID": CKError(.zoneNotFound)]
])


问:
How to loop over an array of data that saved to a JSONObject and put it in a JSONArray?
I have fields in my HTML, say for example 2 rows of fields which I loop over on my controller.

I want it to result to something like this:

```<code>{
"specifications":
[
    {
      "name" : "height",
      "value" : "cm"
    },
    {
      "name" : "weight",
      "value" : "kg"
    }
  ]
}
</code>```

But every time I loop using my code below, I only get the last row of the iteration saved to my JSONArray

```<code>JSONObject itemTypeObj = new JSONObject();
JSONArray itemTypeArray = new JSONArray();
JSONObject itemTypeSpecs = new JSONObject();
ArrayList<String> values = new ArrayList();

        for(int x = 0; x < specName.length; x++){

            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {

                for (String v : specValue[x].split(",")) {
                    values.add(v.trim());
                }

                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }

            values.clear();

            itemTypeArray.put(itemTypeSpecs);

        }

itemTypeObj.put("specifications", itemTypeArray);
</code>```

Result becomes like this instead of the one I expect from above

```<code>{"specifications":
  [
   {
    "name":"Weight",
    "value":"kg"
   },
   {
    "name":"Weight",
    "value":"kg"
   }
  ]
}
</code>```

I can't find the reason why it's only getting the last row. Any help is appreciated. Thank you.

答:
You should crate array list and JSONObject inside first "for loop".Because you change always same objects Can yo try this?</p>

```<code>        JSONObject itemTypeObj = new JSONObject();
        JSONArray itemTypeArray = new JSONArray();

        for (int x = 0; x < specName.length; x++) {
            List<String> values = new ArrayList();
            JSONObject itemTypeSpecs = new JSONObject();
            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {
                for (String v : specValue[x].split(","))
                    values.add(v.trim());
                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }
            itemTypeArray.put(itemTypeSpecs);
        }
        itemTypeObj.put("specifications", itemTypeArray);
</code>```

Body:
I have fields in my HTML, say for example 2 rows of fields which I loop over on my controller.

I want it to result to something like this:

{
"specifications":
[
    {
      "name" : "height",
      "value" : "cm"
    },
    {
      "name" : "weight",
      "value" : "kg"
    }
  ]
}

But every time I loop using my code below, I only get the last row of the iteration saved to my JSONArray

JSONObject itemTypeObj = new JSONObject();
JSONArray itemTypeArray = new JSONArray();
JSONObject itemTypeSpecs = new JSONObject();
ArrayList<String> values = new ArrayList();

        for(int x = 0; x < specName.length; x++){

            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {

                for (String v : specValue[x].split(",")) {
                    values.add(v.trim());
                }

                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }

            values.clear();

            itemTypeArray.put(itemTypeSpecs);

        }

itemTypeObj.put("specifications", itemTypeArray);

Result becomes like this instead of the one I expect from above

{"specifications":
  [
   {
    "name":"Weight",
    "value":"kg"
   },
   {
    "name":"Weight",
    "value":"kg"
   }
  ]
}

I can't find the reason why it's only getting the last row. Any help is appreciated. Thank you.

Body:
You should crate array list and JSONObject inside first "for loop".Because you change always same objects Can yo try this?

        JSONObject itemTypeObj = new JSONObject();
        JSONArray itemTypeArray = new JSONArray();

        for (int x = 0; x < specName.length; x++) {
            List<String> values = new ArrayList();
            JSONObject itemTypeSpecs = new JSONObject();
            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {
                for (String v : specValue[x].split(","))
                    values.add(v.trim());
                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }
            itemTypeArray.put(itemTypeSpecs);
        }
        itemTypeObj.put("specifications", itemTypeArray);


问:
Mocking a method with prophet
Assume there is a method

```<code>public function updateTimestamp($sessionId, $data)
{
    return $this->memcached->touch($sessionId, time() + $this->ttl);
}
</code>```

that I'd like to test. Infection changes the + in time() + $this->ttl to - and all my tests are still passing. So I'd like to make a test that will mock Memcached's touch in it and will conditionally return true/false basing on the second argument passed to it.

So doing something like:

```<code>    // $ttl is set;
    $memcachedMock
        ->touch(
            'sessionId',
            $certainValuePassedToTouch
        )
        ->willReturn(
            $certainValuePassedToTouch >= time() + $ttl
                ? true
                : false
        )
        ;
</code>```

There are two problems now:

I don't know how to make such a condition for an arbitrary integer parameter passed to the method being mocked

basing on time() seems to be very unreliable, so how can I reliably test it if time() is used in the method itself?

答:
Maybe can you take a look on this tools :

https://github.com/php-mock/php-mock

https://github.com/php-mock/php-mock-phpunit

Based on PHP's namespace fallback policy (https://www.php.net/manual/en/language.namespaces.fallback.php), it allow to mock php native functions like time(), date(), etc.

Title: Mocking a method with prophet

Body:
Assume there is a method

public function updateTimestamp($sessionId, $data)
{
    return $this->memcached->touch($sessionId, time() + $this->ttl);
}

that I'd like to test. Infection changes the + in time() + $this->ttl to - and all my tests are still passing. So I'd like to make a test that will mock Memcached's touch in it and will conditionally return true/false basing on the second argument passed to it.

So doing something like:

    // $ttl is set;
    $memcachedMock
        ->touch(
            'sessionId',
            $certainValuePassedToTouch
        )
        ->willReturn(
            $certainValuePassedToTouch >= time() + $ttl
                ? true
                : false
        )
        ;

There are two problems now:

I don't know how to make such a condition for an arbitrary integer parameter passed to the method being mocked

basing on time() seems to be very unreliable, so how can I reliably test it if time() is used in the method itself?


问:
Can we place JavaScript Code along c# in .NetCore WebApi
I have a method in my asp.net Core web Api that has for role sending Emails  , using SmtpClient.
the Body of the message is this html string:

```<code>  @"<html>
         <head>
              <style>
                   #modalHeader{
                        background-color:#6495ED;
                        color:white;
                        text-align: center;
                        height:80px;
                       }
                        .example_b {
                                      color: #fff !important;
                                      text-transform: uppercase;
                                      text-decoration: none;
                                      background: #60a3bc;
                                      padding: 20px;
                                      border-radius: 50px;
                                      display: inline-block;
                                      border: none;
                                      transition: all 0.4s ease 0s;
                                     }
                                    .example_b:hover {
                                            text-shadow: 0px 0px 6px rgba(255, 255, 255, 1);
                                            -webkit-box-shadow: 0px 5px 40px -10px rgba(0,0,0,0.57);
                                            -moz-box-shadow: 0px 5px 40px -10px rgba(0,0,0,0.57);
                                            transition: all 0.4s ease 0s;
                                            }
                                </style>
                            </head>
                      <body>
                        <p>Bonjour,<br>
                            Afin d’authentifier votre connexion sur le système de prise de rendez-vous à distance de la " + Structure + @" Nous vous invitons à  confirmer votre mail en cliquant sur ce lien
                         </p>
                    <div style='border:1px solid black'>
                          //<div id='modalHeader'>Confirmation d'Email</div>
                            //<br>
                                //<br>
                            <div id='modalBody'>
                              <div class='button_cont' align='center'>
                                <a class='example_b' href='" + url + "' target='_blank' rel='nofollow noopener'>Confirmer Votre Email</a>" +
                                "</div> </div> <br/> </div> </body> </html>";
</code>```

as you see i m using a href to trigger a call to another method in service , the problem with that is that it opens to me a blank page each time i click the button , so the solution would be to add an event instead to the button using javascript.

My question is how can i add Js to c# code in asp.net core 2.1 ?
is adding just script tag inside the html tag would make the work of letting JS doing the work ?

答: You can't execute javascript inside an email. This used to be possible in the 90's and early 2000's, but it is no longer possible.</p>

Body:
I have a method in my asp.net Core web Api that has for role sending Emails  , using SmtpClient.
the Body of the message is this html string:

  @"

Bonjour,

                            Afin d’authentifier votre connexion sur le système de prise de rendez-vous à distance de la " + Structure + @" Nous vous invitons à  confirmer votre mail en cliquant sur ce lien

                          //
Confirmation d'Email

                            //

                                //

                                Confirmer Votre Email" +
                                "

  ";

as you see i m using a href to trigger a call to another method in service , the problem with that is that it opens to me a blank page each time i click the button , so the solution would be to add an event instead to the button using javascript.

My question is how can i add Js to c# code in asp.net core 2.1 ?
is adding just script tag inside the html tag would make the work of letting JS doing the work ?


问:
unable to get transaction using ious in when running corda 4.0 example
I am unable to view transactions of IOUS when running the corda 4.0 example.

I have tried in many ways to change the code but the given example itself not working.

http://localhost:50005/api/example/my-ious

There was an unexpected error (type=Internal Server Error, status=500).
net.corda.core.utilities.Try$Success (erased) -> value() -> net.corda.core.node.services.Vault$Page (erased) -> states(java.util.List>) -> java.util.List>> -> net.corda.core.contracts.StateAndRef -> state(net.corda.core.contracts.TransactionState) -> net.corda.core.contracts.TransactionState -> data(net.corda.core.contracts.ContractState) -> Cannot construct evolution serializer for remote type com.example.state.IOUState: net.corda.core.contracts.LinearState, net.corda.core.contracts.ContractState, net.corda.core.schemas.QueryableState borrower (optional): net.corda.core.identity.Party name: net.corda.core.identity.CordaX500Name commonName (optional): java.lang.String country: java.lang.String locality: java.lang.String organisation: java.lang.String organisationUnit (optional): java.lang.String state (optional): java.lang.String owningKey: java.security.PublicKey lender (optional): net.corda.core.identity.Party name: net.corda.core.identity.CordaX500Name commonName (optional): java.lang.String country: java.lang.String locality: java.lang.String organisation: java.lang.String organisationUnit (optional): java.lang.String state (optional): java.lang.String owningKey: java.security.PublicKey linearId: net.corda.core.contracts.UniqueIdentifier externalId (optional): java.lang.String id: java.util.UUID value (optional): java.lang.Integer Local type int of property value is not assignable from remote type class java.lang.Intege

答:
The repository referred to in this has been archived. Please use the most recent repository here: https://github.com/corda/samples-java/tree/master/Basic/cordapp-example.

It seems to be working fine.


答:
Go for something like this:

```<code>int opcion = 0;
do
{
    opcion = Convert.ToInt32(Console.ReadLine());
    switch (opcion)
    {
        ...
    }
} while (opcion != 3);
</code>```

Check this one too: While Loop in C# with Switch Statement

Title: switch while won't loop

Body:
Go for something like this:

int opcion = 0;
do
{
    opcion = Convert.ToInt32(Console.ReadLine());
    switch (opcion)
    {
        ...
    }
} while (opcion != 3);

Check this one too: While Loop in C# with Switch Statement


问:
How do I know which cell is highlighted in jexcell javascript library?
I want to merge the cells marked with jexcel. I don't know how to do that. More specifically, I want to merge cells into a dynamic state and write them into merged cells in MySQL. How to do it</p>

```<code><div id="example"></div>
<script>

var data = [
  ['', 'Ford', 'Tesla', 'Toyota', 'Honda'],
  ['2017', 10, 11, 12, 13],
  ['2018', 20, 11, 14, 13],
  ['2019', 30, 15, 12, 13]
];

var container = document.getElementById('example');
var hot = new Handsontable(container, {
  data: data,
  rowHeaders: true,
  colHeaders: true,
  filters: true,
  dropdownMenu: true,
  contextMenu: true
});

</script>
</code>```

答:
Your Question is not clear but I'll try to answer it to the best of my ability.

if I ignore the example you provided and focus on jExcel, we can merge cells using setMerge and for that we need to know:

the address of the first cell

the numbers of selected rows

numbers of selected columns

we can extract this info from:

```<code>$("#spreadsheet").jexcel("getSelectedRows", true);
$("#spreadsheet").jexcel("getSelectedColumns", true);
</code>```

in theory this alone should work, but jExcel deselects cells when it loses focus (ie when user clicks a button) that's why I used a workarround to store the selection of cells in an object, and later used that object to merge cells.

HTML:

```<code><div id="spreadsheet"></div>
<br>
<input id="myB" type="button" value="Merge Selected" />
</code>```

Javascript:

```<code>var mySlection = {};
var options = {
  minDimensions: [10, 10],
  onselection: storeSelection
};

$(document).ready(function() {
  var mySpreadsheet = $("#spreadsheet").jexcel(options);

  $("#myB").click(function() {
    //Merge Cells using the stored selection
    $("#spreadsheet").jexcel("setMerge", mySlection.firstcell, mySlection.colspan, mySlection.rowspan)
    /*
    you may now store the following values to your MySQL
    mySlection.firstcell
    mySlection.colspan
    mySlection.rowspan
    */
  });
});

function storeSelection() {
  var sRows = $("#spreadsheet").jexcel("getSelectedRows", true);
  var sCols = $("#spreadsheet").jexcel("getSelectedColumns", true);

  mySlection.firstcell = [sCols[0], sRows[0]];
  mySlection.colspan = sCols.length;
  mySlection.rowspan = sRows.length;
}
</code>```

Requirements: jQuery, jExcel and jSuites v3

Here's a Working Example at CodePen

Body:
Your Question is not clear but I'll try to answer it to the best of my ability.

if I ignore the example you provided and focus on jExcel, we can merge cells using setMerge and for that we need to know:

the address of the first cell

the numbers of selected rows

numbers of selected columns

we can extract this info from:

$("#spreadsheet").jexcel("getSelectedRows", true);
$("#spreadsheet").jexcel("getSelectedColumns", true);

in theory this alone should work, but jExcel deselects cells when it loses focus (ie when user clicks a button) that's why I used a workarround to store the selection of cells in an object, and later used that object to merge cells.

HTML:

<div id="spreadsheet"></div>
<br>
<input id="myB" type="button" value="Merge Selected" />

Javascript:

var mySlection = {};
var options = {
  minDimensions: [10, 10],
  onselection: storeSelection
};

$(document).ready(function() {
  var mySpreadsheet = $("#spreadsheet").jexcel(options);

  $("#myB").click(function() {
    //Merge Cells using the stored selection
    $("#spreadsheet").jexcel("setMerge", mySlection.firstcell, mySlection.colspan, mySlection.rowspan)
    /*
    you may now store the following values to your MySQL
    mySlection.firstcell
    mySlection.colspan
    mySlection.rowspan
    */
  });
});

function storeSelection() {
  var sRows = $("#spreadsheet").jexcel("getSelectedRows", true);
  var sCols = $("#spreadsheet").jexcel("getSelectedColumns", true);

  mySlection.firstcell = [sCols[0], sRows[0]];
  mySlection.colspan = sCols.length;
  mySlection.rowspan = sRows.length;
}

Requirements: jQuery, jExcel and jSuites v3

Here's a Working Example at CodePen


问:
Iterate over three lists simultaneously in R
I would like to ask how to iterate over three lists simultaneously in R.  Actually the same function as purr::walk2 does for two lists, but for three or more lists. I suppose that function I should use is purr::pwalk but not sure.

So I have 3 lists (same length):

```<code>buffers_points_with_data <-
  list.files(
    path = "data/buffers_points_with_data",
    pattern = "*.csv$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_CZ_moved <-
  list.files(
    path = "data/species_data_CZ_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_GBIF_moved <-
  list.files(
    path = "data/species_data_GBIF_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )
</code>```

And want to run:
Read first chr from list buffers_points_with_data, then first chr from second list, first chr from third list, continue to the end of script and start with second chr for each and so on.

```<code>{
    clim <- read.csv("data/buffers_points_with_data/Acer negundo.csv", header = TRUE, sep = ",") #replace by 1st list
    occ.sp1 <- na.exclude(read.table("data/species_data_CZ_moved/Acer negundo.txt", h = TRUE)) #replace by 2nd list
    occ.sp2 <- na.exclude(read.table("data/species_data_GBIF_moved/Acer negundo.txt", h = TRUE)) #replace by 3rd list
#code continues
}
</code>```

I am pretty new to R and programming so I do apologies if this question has been asked elsewhere or  the text is somewhat confusing.

Any help or suggestions would be great.
Thank You.

答:
You can use Map that can iterate over 3 lists simultaneously.

```<code>data <- Map(function(x, y, z) {
   clim <- read.csv(x, header = TRUE, sep = ",")
   occ.sp1 <- na.exclude(read.table(y, header = TRUE))
   occ.sp2 <- na.exclude(read.table(z, header = TRUE))
   #Do something
   #Do something
}, buffers_points_with_data, species_data_CZ_moved, species_data_GBIF_moved)
</code>```

Body:
I would like to ask how to iterate over three lists simultaneously in R.  Actually the same function as purr::walk2 does for two lists, but for three or more lists. I suppose that function I should use is purr::pwalk but not sure.

So I have 3 lists (same length):

buffers_points_with_data <-
  list.files(
    path = "data/buffers_points_with_data",
    pattern = "*.csv$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_CZ_moved <-
  list.files(
    path = "data/species_data_CZ_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )

species_data_GBIF_moved <-
  list.files(
    path = "data/species_data_GBIF_moved",
    pattern = "*.txt$",
    full.names = TRUE,
    recursive = FALSE
  )

And want to run:
Read first chr from list buffers_points_with_data, then first chr from second list, first chr from third list, continue to the end of script and start with second chr for each and so on.

{
    clim <- read.csv("data/buffers_points_with_data/Acer negundo.csv", header = TRUE, sep = ",") #replace by 1st list
    occ.sp1 <- na.exclude(read.table("data/species_data_CZ_moved/Acer negundo.txt", h = TRUE)) #replace by 2nd list
    occ.sp2 <- na.exclude(read.table("data/species_data_GBIF_moved/Acer negundo.txt", h = TRUE)) #replace by 3rd list
#code continues
}

I am pretty new to R and programming so I do apologies if this question has been asked elsewhere or  the text is somewhat confusing.

Any help or suggestions would be great.
Thank You.

Body:
You can use Map that can iterate over 3 lists simultaneously.

data <- Map(function(x, y, z) {
   clim <- read.csv(x, header = TRUE, sep = ",")
   occ.sp1 <- na.exclude(read.table(y, header = TRUE))
   occ.sp2 <- na.exclude(read.table(z, header = TRUE))
   #Do something
   #Do something
}, buffers_points_with_data, species_data_CZ_moved, species_data_GBIF_moved)


问:
Ionic Capacitor 404 eror - inappbrowser is not in the npm registry
I got an error 404 from running inappbrowser plugin

```<code>npm install @ionic-enterprise/inappbrowser

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@ionic-enterprise%2finappbrowser - Not found
npm ERR! 404
npm ERR! 404  '@ionic-enterprise/inappbrowser@latest' is not in the npm registry.
</code>```

I have also run npm config set registry https://registry.npmjs.org/  but still get the same error

答: @ionic-enterprise/inappbrowser is a private plugin, you can only install it if you are a paid customer or are on trial period. If you are in one of those situations, contact support so they can help you configure your machine to install packages from the private registry.

Body:
I got an error 404 from running inappbrowser plugin

npm install @ionic-enterprise/inappbrowser

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@ionic-enterprise%2finappbrowser - Not found
npm ERR! 404
npm ERR! 404  '@ionic-enterprise/inappbrowser@latest' is not in the npm registry.

I have also run npm config set registry https://registry.npmjs.org/  but still get the same error


问:
Typescript: How to use Generic Type in functions
I have the following structure:

```<code>export interface Complex {
    getId<T>(entity: T): string
}

const test: Complex = {
    getId<Number>(entity){return "1"} // does not work 'entity is implicitly any'
}
</code>```

Why do I have to declare the type of entity as entity:Number in order to make it work?

答:
Because you declare interface which has a Generic Type Function (getById).

To reference to generic as a type, you must do this:

```<code>interface Complex<T> {
  getId(entity: T): string;
}

const test: Complex<Number> = {
  getId(entity) {
    return entity.toString();
  }
}
</code>```

The use-case of what you did might be following:

```<code>interface AbstractFactory {
  create<T>(data: T): string;
}

const factory: AbstractFactory = {
  create<T>(data: T): string {
    return data.toString();
  }
}

factory.create<Number>(123);
</code>```

Body:
I have the following structure:

export interface Complex {
    getId<T>(entity: T): string
}

const test: Complex = {
    getId<Number>(entity){return "1"} // does not work 'entity is implicitly any'
}

Why do I have to declare the type of entity as entity:Number in order to make it work?

Body:
Because you declare interface which has a Generic Type Function (getById).

To reference to generic as a type, you must do this:

interface Complex<T> {
  getId(entity: T): string;
}

const test: Complex<Number> = {
  getId(entity) {
    return entity.toString();
  }
}

The use-case of what you did might be following:

interface AbstractFactory {
  create<T>(data: T): string;
}

const factory: AbstractFactory = {
  create<T>(data: T): string {
    return data.toString();
  }
}

factory.create<Number>(123);


问:
UML help C# Design Principles
I have a problem understanding an UML below:

Specifically, what is the relationship between PersistentSet and ThirdPartyPersistentSet?
What is the relationship between PersistentObject and ThirdPartyPersistentSet?

Please note that the UML is from Agile Principles, Patterns, and Practices in C#
By Martin C. Robert, Martin Micah 2006. Chapter 10

Thanks in advance!

答:
Specifically, what is the relationship between PersistentSet and ThirdPartyPersistentSet?

PersistentSet has-many ThirdPartyPersistentSets

What is the relationship between PersistentObject and ThirdPartyPersistentSet?

ThirdPartyPersistentSet is dependent on (uses-a) PersistentObject

all of the lines in a uml class diagram indicate dependencies of one sort or another except for the dashed like to a comment (dog-eared box). a solid line with no arrows indicates a two (2) way (bi-directional) dependency.

Title: UML help C# Design Principles


问:
How to insert an element at the last position in an array dynamically in C?
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

```<code>temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
</code>```

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

```<code>void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}
</code>```

Current output:

```<code>exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens
</code>```

Desired output:

```<code>tmp[5] = {1, 2, 5, 6, 8}
</code>```

答:
Your definition of push requires the 3rd parameter to be the position to place the element. However, the expression sizeof(tmp)/sizeof(tmp[0]) provides the size of the array and it will thus index past the array's last element (because indexes in C go from 0..n-1). This in itself can cause a segmentation fault.

Neither did you provide a terminating condition for your loop. It will continue forever.

Your solution could simply be:

```<code>for(int i=0, j=0; i<10; i++)
   if(temp[i]) push(tmp, temp[i], j++);
</code>```

Body:
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}

Current output:

exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens

Desired output:

tmp[5] = {1, 2, 5, 6, 8}

Body:
Your definition of push requires the 3rd parameter to be the position to place the element. However, the expression sizeof(tmp)/sizeof(tmp[0]) provides the size of the array and it will thus index past the array's last element (because indexes in C go from 0..n-1). This in itself can cause a segmentation fault.

Neither did you provide a terminating condition for your loop. It will continue forever.

Your solution could simply be:

for(int i=0, j=0; i<10; i++)
   if(temp[i]) push(tmp, temp[i], j++);


问:
Sorting list with rules with python
I have a list like this

```<code>['File3', 'File007', 'File3a', 'File10', 'File11', 'File1', 'File4', 'File5', 'File9', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File6']
</code>```

When I sort it with sorted() in python. it will become like this:

```<code>['File007', 'File1', 'File10', 'File11', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File8', 'File8b1', 'File8b11', 'File8b2', 'File9']
</code>```

But what I want is:

```<code>['File1', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File007', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File9', 'File10', 'File11']
</code>```

The number sort it must be:
File1, File2, File3, File10

not like:
File1, File10, File2, File3

if it has 0 digit like this File007, it will count as 7

if it has alphabet after number, like File3a, it will sort like this:
File3, File3a, File3b, ...

is there a ways to add this rules in sorting the list?

答:
Yes, you can use a function that is run during the sorting process</p>

```<code># Sort a list based on removing leading zeros
def mysort(x):
    return int(str(x).replace("0",""))

L = ["002", "013", "001", "005"]

print ("Normal sorting :", sorted(L))
print ("Sorted with key:", sorted(L, key = mysort))
</code>```

Title: Sorting list with rules with python

Body:
I have a list like this

['File3', 'File007', 'File3a', 'File10', 'File11', 'File1', 'File4', 'File5', 'File9', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File6']

When I sort it with sorted() in python. it will become like this:

['File007', 'File1', 'File10', 'File11', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File8', 'File8b1', 'File8b11', 'File8b2', 'File9']

But what I want is:

['File1', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File007', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File9', 'File10', 'File11']

The number sort it must be:
File1, File2, File3, File10

not like:
File1, File10, File2, File3

if it has 0 digit like this File007, it will count as 7

if it has alphabet after number, like File3a, it will sort like this:
File3, File3a, File3b, ...

is there a ways to add this rules in sorting the list?

Body:
Yes, you can use a function that is run during the sorting process

# Sort a list based on removing leading zeros
def mysort(x):
    return int(str(x).replace("0",""))

L = ["002", "013", "001", "005"]

print ("Normal sorting :", sorted(L))
print ("Sorted with key:", sorted(L, key = mysort))


问:
Azure App Service - Set-AzWebApp : Operation returned an invalid status code 'Conflict'
I am trying to run Set-AzWebApp command to set web application properties

```<code>Set-AzWebApp -AppSettings $settings -ResourceGroupName $resourceGroupName -Name $appServiceName
</code>```

$settings is a Hashtable.
I get this message back with no additional details

Set-AzWebApp : Operation returned an invalid status code 'Conflict'

Any ideas?

答: Solved: As it turns out I had a space that crept into my keyname within the $settings hashtable. This cause Azure app service to throw a 409 Conflict</p>

Body:
I am trying to run Set-AzWebApp command to set web application properties

Set-AzWebApp -AppSettings $settings -ResourceGroupName $resourceGroupName -Name $appServiceName

$settings is a Hashtable.
I get this message back with no additional details

Set-AzWebApp : Operation returned an invalid status code 'Conflict'

Any ideas?