问:
Recursively print and remove files matching one of two patterns
I need it to search for all files - in the current directory as well as in its sub-directories - with a name ending by ~, or a name that start and end by #.
Here's my code

```<code>#!/bin/bash
find . -type f -exec -delete grep ^#.*#$ | grep .~$
</code>```

Where's my mistake?

答:
You don't need grep for that.

```<code>find . -type f \( -name '*~' -o -name '#*#' \) -print # -delete
</code>```

Uncomment -delete to remove the files it lists. You can substitute -delete with -exec rm {} + when the former is not available.

Body:
I need it to search for all files - in the current directory as well as in its sub-directories - with a name ending by ~, or a name that start and end by #.
Here's my code

#!/bin/bash
find . -type f -exec -delete grep ^#.*#$ | grep .~$

Where's my mistake?

Body:
You don't need grep for that.

find . -type f \( -name '*~' -o -name '#*#' \) -print # -delete

Uncomment -delete to remove the files it lists. You can substitute -delete with -exec rm {} + when the former is not available.


来源: stackexchange

问:
How to catch Maximize started event using Window Message, etc
I was able to get Maximized and Size changed events, but not Maximize started.</p>

答:
I found solution for my problem.
Here is hook method that you can add for your code and do all needed staff before Window Maximized event occurs.

```<code>    private static void WmWindowPos(IntPtr hwnd, IntPtr lParam)
    {
        WINDOWPOS wpos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
        IntPtr monitorContainingApplication = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

        if (monitorContainingApplication == IntPtr.Zero)
            return;

        var monitorInfo = new MONITORINFO();
        GetMonitorInfo(monitorContainingApplication, monitorInfo);
        var rcWorkArea = monitorInfo.rcWork;

        if (wpos.x == rcWorkArea.left &&
            wpos.y == rcWorkArea.top &&
            wpos.cx == rcWorkArea.right &&
            wpos.cy == rcWorkArea.bottom)
        {
            // Do required staff before windows maximized state has changed
        }
    }
</code>```

Add this method to WindowProc like this

```<code>    private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case 0x0046: //  WM_WINDOWPOSCHANGING
                WmWindowPos(hwnd, lParam);
                break;
        }

        return (IntPtr)0;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I found solution for my problem.
Here is hook method that you can add for your code and do all needed staff before Window Maximized event occurs.

    private static void WmWindowPos(IntPtr hwnd, IntPtr lParam)
    {
        WINDOWPOS wpos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
        IntPtr monitorContainingApplication = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

        if (monitorContainingApplication == IntPtr.Zero)
            return;

        var monitorInfo = new MONITORINFO();
        GetMonitorInfo(monitorContainingApplication, monitorInfo);
        var rcWorkArea = monitorInfo.rcWork;

        if (wpos.x == rcWorkArea.left &&
            wpos.y == rcWorkArea.top &&
            wpos.cx == rcWorkArea.right &&
            wpos.cy == rcWorkArea.bottom)
        {
            // Do required staff before windows maximized state has changed
        }
    }

Add this method to WindowProc like this

    private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case 0x0046: //  WM_WINDOWPOSCHANGING
                WmWindowPos(hwnd, lParam);
                break;
        }

        return (IntPtr)0;
    }


问:
How to get string value from a enum in typescript?
I have an enum of string values. I want to pass a string value to enum and get the value from it.

```<code>export enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}
</code>```

I have class as well

```<code>class Item {
type:string;
id:string
date:string
}
</code>```

Now i am calling below function

```<code>function sendData(type:OperationType) {
//Do some work
}
</code>```

Now i want to pass the value in enum like this but i am not able to do

```<code>//Here item.type = "CREATE"

sendData(OperationType[item.type])
</code>```

But this is now allowed i get compile time error of wrong type. Please tell me how can i achieve?

EDIT:
Error is

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof OperationType'.

答:
What's wrong here is the type of the parameter inside the sendData fn definition.
That should be a string. You are telling ts that that is an Enum type, not the actual string.

so the fn definition should look like this:

```<code>function sendData(type: String) {
//Do some work
}
</code>```

Body:
I have an enum of string values. I want to pass a string value to enum and get the value from it.

export enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}

I have class as well

class Item {
type:string;
id:string
date:string
}

Now i am calling below function

function sendData(type:OperationType) {
//Do some work
}

Now i want to pass the value in enum like this but i am not able to do

//Here item.type = "CREATE"

sendData(OperationType[item.type])

But this is now allowed i get compile time error of wrong type. Please tell me how can i achieve?

EDIT:
Error is

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof OperationType'.

Body:
What's wrong here is the type of the parameter inside the sendData fn definition.
That should be a string. You are telling ts that that is an Enum type, not the actual string.

so the fn definition should look like this:

function sendData(type: String) {
//Do some work
}


问:
How to get Audio level in Kurento to show on UI
I am developing multiparty conferencing in nodejs using kurento (kurento-utils-js on client side and kurento-client package on server side)

When someone speaks (either local or on remote stream), I want to show the audio level on user interface (UI) to just show that he/she is speaking.

答:
You can use hark API provided by kurentoUtils. Tweak the threshold between [-100, 0] to see which values works best for you. -50 works for me.

```<code>const speechEvent =kurentoUtils.WebRtcPeer.hark(stream, { threshold: -50 });
speechEvent.on('speaking', () => {
 /* do something on the UI */
});
speechEvent.on('stopped_speaking', () => {
  /* do something on the UI */
});
</code>```

Body:
You can use hark API provided by kurentoUtils. Tweak the threshold between [-100, 0] to see which values works best for you. -50 works for me.

const speechEvent =kurentoUtils.WebRtcPeer.hark(stream, { threshold: -50 });
speechEvent.on('speaking', () => {
 /* do something on the UI */
});
speechEvent.on('stopped_speaking', () => {
  /* do something on the UI */
});


问:
JSON Schema: Dependency across array elements
What is the right way to require an array element with particular field if other array element is presented?

E.g. forcing bread in case if butter is here:

```<code>+-------+-------+--------+
| valid | bread | butter |
+-------+-------+--------+
|   +   |   -   |   -    |
|   +   |   +   |   -    |
|   +   |   +   |   +    |
|   -   |   -   |   +    |
+-------+-------+--------+
</code>```

Products example:

```<code>{
  "products": [
    {
      "name": "butter"
    },
    {
      "name": "bread"
    }
  ]
}
</code>```

Based on post and Combining schemas, it is possible to check that there is NO butter, otherwise array has bread:

```<code>{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Complex Array",

  "anyOf": [
    { "not": { "$ref": "#/definitions/contains-name-butter" } },
    { "$ref": "#/definitions/contains-name-bread" }
  ],
  "definitions": {
    "contains-name-butter": {
      "type": "object",
      "properties": {
        "products": {
          "type": "array",
          "contains": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "pattern": "^butter$"
              }
            }
          }
        }
      }
    },
    "contains-name-bread": {
      "type": "object",
      "properties": {
        "products": {
          "type": "array",
          "contains": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "pattern": "^bread$"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Now if bread got removed - schema validation will break.

If there any way to make it simpler? Especially if in future adding more dependency is planned.

答:
In logical terms, what you seem to want is: if the array contains an item with property "name" whose value is "butter", then require an item with property "name" and value "bread":

```<code>  "type" : "array",
  "if" : {
    "contains" : {
      "type: "object",
      "properties" : {
        "name" : {
          "const" : "butter"
        }
      }
    }
  },
  "then" : {
    "contains" : {
      "required": [ "name" ],
      "properties" : {
        "name" : {
          "const" : "bread"
        }
      }
    }
  }
}
</code>```

(I also, simplified "pattern": "^bread$" as "const":"bread".)

Body:
What is the right way to require an array element with particular field if other array element is presented?

E.g. forcing bread in case if butter is here:

+-------+-------+--------+
| valid | bread | butter |
+-------+-------+--------+
|   +   |   -   |   -    |
|   +   |   +   |   -    |
|   +   |   +   |   +    |
|   -   |   -   |   +    |
+-------+-------+--------+

Products example:

{
  "products": [
    {
      "name": "butter"
    },
    {
      "name": "bread"
    }
  ]
}

Based on post and Combining schemas, it is possible to check that there is NO butter, otherwise array has bread:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Complex Array",

  "anyOf": [
    { "not": { "$ref": "#/definitions/contains-name-butter" } },
    { "$ref": "#/definitions/contains-name-bread" }
  ],
  "definitions": {
    "contains-name-butter": {
      "type": "object",
      "properties": {
        "products": {
          "type": "array",
          "contains": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "pattern": "^butter$"
              }
            }
          }
        }
      }
    },
    "contains-name-bread": {
      "type": "object",
      "properties": {
        "products": {
          "type": "array",
          "contains": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "pattern": "^bread$"
              }
            }
          }
        }
      }
    }
  }
}

Now if bread got removed - schema validation will break.

If there any way to make it simpler? Especially if in future adding more dependency is planned.

Body:
In logical terms, what you seem to want is: if the array contains an item with property "name" whose value is "butter", then require an item with property "name" and value "bread":

  "type" : "array",
  "if" : {
    "contains" : {
      "type: "object",
      "properties" : {
        "name" : {
          "const" : "butter"
        }
      }
    }
  },
  "then" : {
    "contains" : {
      "required": [ "name" ],
      "properties" : {
        "name" : {
          "const" : "bread"
        }
      }
    }
  }
}

(I also, simplified "pattern": "^bread$" as "const":"bread".)


问:
unable to find few visio objects on visual studio 2019
I am trying to write a visio application. If I write in Macro (within visio app), I get all objects. However, when I try to write same code in Visual Studio 2019, I cant find references. Like ActiveWindow or visSectionAction. I am trying to follow this: Add Menu Action Programatically to Visio

What references am I missing. I added nuget package, added office object library.
TIA

答:
To use Visio object model from a .NET application, you need to add a reference to Visio type library to that application. This is Microsoft.Office.Interop.Visio. You could start over in the Microsoft documentation: https://learn.microsoft.com/en-us/visualstudio/vsto/visio-object-model-overview

The global VBA objects, like ActiveWindow, are available as app.ActiveWindow (assuming the "app" is the root Visio Application object you access). In case of an Add-In:

var w = Globals.ThisAddIn.Application.ActiveWindow
```

<p>or in case you need to access from a method of the add-in:</p>

```var w = Application.ActiveWindow
```

Enumerations should be prefixed with its type: VisSectionIndices.visSectionAction.

Please note that the answer in the linked question explains how to add a menu item to a shape, not to the application. If you want to extend application menu rather than shape menu (?), you need to add your menu item to the ribbon definition.

Body:
To use Visio object model from a .NET application, you need to add a reference to Visio type library to that application. This is Microsoft.Office.Interop.Visio. You could start over in the Microsoft documentation: https://learn.microsoft.com/en-us/visualstudio/vsto/visio-object-model-overview

The global VBA objects, like ActiveWindow, are available as app.ActiveWindow (assuming the "app" is the root Visio Application object you access). In case of an Add-In:

var w = Globals.ThisAddIn.Application.ActiveWindow

or in case you need to access from a method of the add-in:

var w = Application.ActiveWindow

Enumerations should be prefixed with its type: VisSectionIndices.visSectionAction.

Please note that the answer in the linked question explains how to add a menu item to a shape, not to the application. If you want to extend application menu rather than shape menu (?), you need to add your menu item to the ribbon definition.


问:
How to save / keep checkbox checked?
I'm working on web application project (clinic & laboratory) it's all about sending tests. i used code below to select the test category first then the test name which related in this category. but when i moving to another category. the old one with selected input will reset . who to save them temporary before sending it to data base? i'm still newbie at ajax.

```<code>    <?php
// Dashboard page
        include('CONFIG.PHP');
        $query = "SELECT * FROM `test_categories` ORDER BY `test_categories`.`CATEGORY_ID` DESC";
        $statement = $connect->prepare($query);
        $statement->execute();
        $result = $statement->fetchAll();
        foreach($result as $row)
        {
        ?>
        <div class="">
        <label>
        <input  type="checkbox" class="common_selector category" value="<?php echo $row['CATEGORY_NAME']; ?>">
        <?php echo $row['CATEGORY_NAME']; ?></label>
        </div>
        <?php
        }
        ?>

    ===============================================
        <script>
        $(document).ready(function(){

            filter_data();

            function filter_data()
            {
                $('.filter_data').html('<div id="loading" style="" ></div>');
                var action = 'fetch_data';
                var brand = get_filter('category');
                $.ajax({
                    url:"FUNCTIONS.PHP",
                    method:"POST",
                    data:{action:action, category:category},
                    success:function(data){
                        $('.filter_data').html(data);
                    }
                });
            }

            function get_filter(class_name)
            {
                var filter = [];
                $('.'+class_name+':checked').each(function(){
                    filter.push($(this).val());
                });
                return filter;
            }

            $('.common_selector').click(function(){
                $('input').not(this).prop('checked', false);
                filter_data();
            });
        });
        </script>

    ==========================================
    // FUNCTIONS PAGE

        if(isset($_POST["action"]))
        {
            include 'CONFIG.PHP';
            $query = "";
            if(isset($_POST["category"]))
            {
                $category_filter = implode("','", $_POST["category"]);
                $query .= "
                SELECT * FROM `tests` WHERE TEST_CATEGORY = ('".$category_filter."') ORDER BY `tests`.`TEST_ID` DESC
                ";
            }

            $statement = $connect->prepare($query);
            $statement->execute();
            $result = $statement->fetchAll();
            $total_row = $statement->rowCount();
            $output = '';
            if($total_row > 0)
            {
                foreach($result as $row)
                {
                    $output .= "

                    <div class='TEST'>
        <input id='toggle". $row['TEST_ID']."' name='REQUESTED_TEST[]' type='checkbox' value='" . $row['TEST_NAME'] . "'>
        <label for='toggle". $row['TEST_ID']."'>" . $row['TEST_NAME'] . "</label>
        </div>

                    ";
                }
            }
            else
            {
                $output = '<h3 class="text-center">'. LANG('NO_DATA_FOUND').'</h3>';
            }
            echo $output;
        }
</code>```

答:
As per your requirement you have to do below changes.

In function file add onchange event

```<code><input class='selected_test' id='toggle". $row['TEST_ID']."' name='REQUESTED_TEST[]' type='checkbox' value='toggle" . $row['TEST_ID'] . "' onchange=\"updatetests()\">
</code>```

In Dashboard file add that javascript function

```<code>function updatetests(){
    var oldval = $('input[name=seltests]').val();
    var seltests = [];
    if( oldval != "" ) {
        seltests = $('input[name=seltests]').val().split(',');
    }
    jQuery.each( jQuery('.selected_test:checked'), function( i, val ) {
      seltests.push($(this).val());
    });
    seltests = seltests.filter((v, i, a) => a.indexOf(v) === i);
    $('input[name=seltests]').val( seltests.join(",") );
}
</code>```

Title: How to save / keep checkbox checked?

Body:
I'm working on web application project (clinic & laboratory) it's all about sending tests. i used code below to select the test category first then the test name which related in this category. but when i moving to another category. the old one with selected input will reset . who to save them temporary before sending it to data base? i'm still newbie at ajax.

    <?php
// Dashboard page
        include('CONFIG.PHP');
        $query = "SELECT * FROM `test_categories` ORDER BY `test_categories`.`CATEGORY_ID` DESC";
        $statement = $connect->prepare($query);
        $statement->execute();
        $result = $statement->fetchAll();
        foreach($result as $row)
        {
        ?>

        <input  type="checkbox" class="common_selector category" value="<?php echo $row['CATEGORY_NAME']; ?>">
        <?php echo $row['CATEGORY_NAME']; ?>

        <?php
        }
        ?>

    ===============================================

    ==========================================
    // FUNCTIONS PAGE

        if(isset($_POST["action"]))
        {
            include 'CONFIG.PHP';
            $query = "";
            if(isset($_POST["category"]))
            {
                $category_filter = implode("','", $_POST["category"]);
                $query .= "
                SELECT * FROM `tests` WHERE TEST_CATEGORY = ('".$category_filter."') ORDER BY `tests`.`TEST_ID` DESC
                ";
            }

            $statement = $connect->prepare($query);
            $statement->execute();
            $result = $statement->fetchAll();
            $total_row = $statement->rowCount();
            $output = '';
            if($total_row > 0)
            {
                foreach($result as $row)
                {
                    $output .= "

        <input id='toggle". $row['TEST_ID']."' name='REQUESTED_TEST[]' type='checkbox' value='" . $row['TEST_NAME'] . "'>
        " . $row['TEST_NAME'] . "

                    ";
                }
            }
            else
            {
                $output = '
'. LANG('NO_DATA_FOUND').'
';
            }
            echo $output;
        }

Body:
As per your requirement you have to do below changes.

In function file add onchange event

<input class='selected_test' id='toggle". $row['TEST_ID']."' name='REQUESTED_TEST[]' type='checkbox' value='toggle" . $row['TEST_ID'] . "' onchange=\"updatetests()\">

In Dashboard file add that javascript function

function updatetests(){
    var oldval = $('input[name=seltests]').val();
    var seltests = [];
    if( oldval != "" ) {
        seltests = $('input[name=seltests]').val().split(',');
    }
    jQuery.each( jQuery('.selected_test:checked'), function( i, val ) {
      seltests.push($(this).val());
    });
    seltests = seltests.filter((v, i, a) => a.indexOf(v) === i);
    $('input[name=seltests]').val( seltests.join(",") );
}


问:
Can't assign multiple HTML elements in the .css() function
I have 4 divs filter1, filter2, filter3, filter4 and I have an anchor tag inside of them and an image, I want to make it so that when you hover on a filter div, the anchor tag gets the other color, the only problem is that I cannot change the color via JavaScript, which is what I am trying to achieve.

I want to change the color of the anchor when I hover (or in JS mouseOver) any of the filter div.

The only problem is I cannot define multiple HTML tags in the .css function in JavaScript.

I am trying to achieve this:

$(".filter1").mouseover(function () {
  $(".filter , li , a").css("color", "pink");
});
```

<p>The only problem is, now every .filter function, every <code>li</code> tag and every <code>anchor</code> tag in my HTML documents get color pink when I hover over any of these.</p>

<p>What I have right now:</p>

<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
  $(".filter1").mouseover(function () {
    $(".filter ").css("color", "pink");
  });
  $(".filter1").mouseout(function () {
    $(".filter li a").css("color", "#FFFF");
  });

  //also filter2, filter3, filter4 etc

});
</code>```

How can I resolve this?

答:
Without seeing the actual structure of a div, I'm going to think this should work.

You can do this with plain CSS:

```<code>.filter1:hover a{
  color:pink;
}
</code>```

Body:
I have 4 divs filter1, filter2, filter3, filter4 and I have an anchor tag inside of them and an image, I want to make it so that when you hover on a filter div, the anchor tag gets the other color, the only problem is that I cannot change the color via JavaScript, which is what I am trying to achieve.

I want to change the color of the anchor when I hover (or in JS mouseOver) any of the filter div.

The only problem is I cannot define multiple HTML tags in the .css function in JavaScript.

I am trying to achieve this:

$(".filter1").mouseover(function () {
  $(".filter , li , a").css("color", "pink");
});

The only problem is, now every .filter function, every li tag and every anchor tag in my HTML documents get color pink when I hover over any of these.

What I have right now:

$(document).ready(function () {
  $(".filter1").mouseover(function () {
    $(".filter ").css("color", "pink");
  });
  $(".filter1").mouseout(function () {
    $(".filter li a").css("color", "#FFFF");
  });

  //also filter2, filter3, filter4 etc

});

How can I resolve this?

Body:
Without seeing the actual structure of a div, I'm going to think this should work.

You can do this with plain CSS:

.filter1:hover a{
  color:pink;
}


问:
Pangram String Error On My Hackerrank Code
I found this question on Hackerrank where I have to write a method to say whether or not a given string is a pangram. A sentence is a pangram if it contains all 26 letters of the alphabet. The input will only contain characters that are alphabetical (uppercase or lowercase) and spaces.

Here's the code I've gotten so far, where I use a set to keep track of which letters are present in the string. However, the code just keeps running infinitely in the while loop below.

```<code>string pangrams(string s) {
    set<char> set{};
    int i=0;

    while (i!=s.length()) {
        if(s[i]!='\0') {
            set.insert(tolower(s[i]));
        }
    }

    if (set.size() == 27) {
        return "pangram";
    } else {
        return "not pangram";
    }

}
</code>```

答:
You're never incrementing i, so your code will run infinitely. I would recommend a for loop for (int i = 0; i < s.length(); i ++) or a for-each loop for (char c : s)

Instead of using a set, you could also try this, where each character corresponds to an index in a bool[]

```<code>bool exists[27];
for (char c : s) {
    if ('a' <= c && c <= 'z') {
        exists[c - 'a'] = true;
    } else if ('A' <= c && c <= 'A') {
        exists[c - 'A'] = true;
    } else if (c == ' ') {
        exists[26] = true;
    }
}
for (bool b : exists) {
    if (!b) return false;
}
return true;
</code>```

Body:
I found this question on Hackerrank where I have to write a method to say whether or not a given string is a pangram. A sentence is a pangram if it contains all 26 letters of the alphabet. The input will only contain characters that are alphabetical (uppercase or lowercase) and spaces.

Here's the code I've gotten so far, where I use a set to keep track of which letters are present in the string. However, the code just keeps running infinitely in the while loop below.

string pangrams(string s) {
    set<char> set{};
    int i=0;

    while (i!=s.length()) {
        if(s[i]!='\0') {
            set.insert(tolower(s[i]));
        }
    }

    if (set.size() == 27) {
        return "pangram";
    } else {
        return "not pangram";
    }

}

Body:
You're never incrementing i, so your code will run infinitely. I would recommend a for loop for (int i = 0; i < s.length(); i ++) or a for-each loop for (char c : s)

Instead of using a set, you could also try this, where each character corresponds to an index in a bool[]

bool exists[27];
for (char c : s) {
    if ('a' <= c && c <= 'z') {
        exists[c - 'a'] = true;
    } else if ('A' <= c && c <= 'A') {
        exists[c - 'A'] = true;
    } else if (c == ' ') {
        exists[26] = true;
    }
}
for (bool b : exists) {
    if (!b) return false;
}
return true;


问:
Flutter how to pass two arguments in route, parameters that have different classes?
This is object that needs to pass as argument in navigation.

```<code>Test test = Test(name:'name');
SecondTest testSecond = SecondTest(id:'dfdad');

//This is not working
//Navigator.pushNamed(context, "some-screen",arguments:{test , testSecond });

class SomeScreen extends StatefulWidget {

  final Test test;
  SecondTest testSecond;

  SomeScreen(this.test, this.testSecond);
</code>```

}

This is argument for that screen. How to send multiple values?

答:
Map values must be mapped to keys:

Navigator.pushNamed(context, "some-screen", arguments: { 'testClass': test, 'testSecondClass': testSecond });
```

Body:
This is object that needs to pass as argument in navigation.

Test test = Test(name:'name');
SecondTest testSecond = SecondTest(id:'dfdad');

//This is not working
//Navigator.pushNamed(context, "some-screen",arguments:{test , testSecond });

class SomeScreen extends StatefulWidget {

  final Test test;
  SecondTest testSecond;

  SomeScreen(this.test, this.testSecond);

}

This is argument for that screen. How to send multiple values?


答:
Your function needs a slight modification. Firstly, you aren't incrementing i which makes your function go into infinite loop. Other modification is explained in code below -

```<code>string pangrams(string s) {
set<char> set{};
int i=0;

  while (i!=s.length()) {
    if(s[i]!=' ') {           # if character is space, ignore it
        set.insert(tolower(s[i]));
    }
    i++;                      # Main reason of runtime error - you missed incrementing i
  }

   if (set.size() == 26) {    # 26 and not 27. There may be strings without space that are pangrams. So we wont add space into our set.
    return "pangram";
   } else {
    return "not pangram";
  }

}
</code>```

Also, you don't need to check s[i]!='\0' since a c++ string isn't terminated with \0 character. Only checking i!=s.length() will be enough.

Hope this clears your issue !

Title: Pangram String Error On My Hackerrank Code

Body:
Your function needs a slight modification. Firstly, you aren't incrementing i which makes your function go into infinite loop. Other modification is explained in code below -

string pangrams(string s) {
set<char> set{};
int i=0;

  while (i!=s.length()) {
    if(s[i]!=' ') {           # if character is space, ignore it
        set.insert(tolower(s[i]));
    }
    i++;                      # Main reason of runtime error - you missed incrementing i
  }

   if (set.size() == 26) {    # 26 and not 27. There may be strings without space that are pangrams. So we wont add space into our set.
    return "pangram";
   } else {
    return "not pangram";
  }

}

Also, you don't need to check s[i]!='\0' since a c++ string isn't terminated with \0 character. Only checking i!=s.length() will be enough.

Hope this clears your issue !


问:
How to input the image file from Django Admin to the html
if we don't use for, we can directly write the image address like '/img/1.jpg', but what if I already use for? what should i write?

here is my directory of my images

here is my django/admin, which is where my image has been uploaded on django / admin

i also already add MEDIA_URL, MEDIA_ROOT

here is my html file

```<code>{% for product in products %}
        <section id="card">
            <div class="container">
                <div class="row">
                    <div class="col">
                        <div class="card" style="width: 18rem;">
                            <img src= '(what should i write here?)' class="card-img-top" alt="...">
                            <div class="card-body">
                            <h5 class="card-title">{{ product.name }}</h5>
                            <p class="card-text">{{ product.Description }}</p>
                            <a href="#" class="btn btn-primary">Contact Us</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    {% endfor %}
</code>```

答:
Use src="{{ product.model_attribute_name.url }}" assuming you have added MEDIA_URL, MEDIA_ROOT in settings and urls of main project.
For more information plz take a look at https://docs.djangoproject.com/en/3.1/faq/usage/#why-do-i-get-an-error-about-importing-django-settings-module

urls.py file of main project should look like this:

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Body:
if we don't use for, we can directly write the image address like '/img/1.jpg', but what if I already use for? what should i write?

here is my directory of my images

here is my django/admin, which is where my image has been uploaded on django / admin

i also already add MEDIA_URL, MEDIA_ROOT

here is my html file

{% for product in products %}

{{ product.name }}

{{ product.Description }}

                            Contact Us

    {% endfor %}

Body:
Use src="{{ product.model_attribute_name.url }}" assuming you have added MEDIA_URL, MEDIA_ROOT in settings and urls of main project.
For more information plz take a look at https://docs.djangoproject.com/en/3.1/faq/usage/#why-do-i-get-an-error-about-importing-django-settings-module

urls.py file of main project should look like this:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


问:
How to bind the useState() in React to dynamically generated
 elements?
I am trying to create a widget in React which has a drop down in each block. I need to show a drop down on the click of a button in each respective list. But what is happening is, when i click the button all the drop down are showing up (of all the dynamically repeated elements).

```<code>class App extends Component {
  render() {
    return (
      <div className="wrapper">
        <div className="widget">
          <h2>whats happeing</h2>
          <Block data={mock} /> //sub component which has the dropdown
        </div>
      </div>
    );
  }
}

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState(false); //currently i am trying to get this done with useState()

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (
        <div key={item.id} className="block">
          <span
            className="dropdown-btn"
            onClick={() => setShowDropdown(!showDropdown)}
          >
            ▼
          </span>
          <div className="left-col">
            <p>{item.category}</p>
            <h3>
              <a href="#">{item.title}</a>
            </h3>
          </div>
          {showDropdown && <Dropdown />}
        </div>
      );
    });
  }
  return <div>{blocks}</div>;
};
</code>```

This is the sandbox link to the code. Could you please let me know how to handle this in React ?
https://codesandbox.io/s/widget-with-drodown-kjovc

答:
You have to make your state accordingly to the id of items than it will impact the particular block so just change your state accordingly. you can see in below code</p>

```<code>     return (
        <div key={item.id} className="block">
          <span
            className="dropdown-btn"
            onClick={() => setShowDropdown(item.id)}
          >
            ▼
          </span>
          <div className="left-col">
            <p>{item.category}</p>
            <h3>
              <a href="#">{item.title}</a>
            </h3>
          </div>
          {showDropdown === item.id && <Dropdown />}
        </div>
      );
</code>```

Title: How to bind the useState() in React to dynamically generated <div> elements?

Body:
I am trying to create a widget in React which has a drop down in each block. I need to show a drop down on the click of a button in each respective list. But what is happening is, when i click the button all the drop down are showing up (of all the dynamically repeated elements).

class App extends Component {
  render() {
    return (

whats happeing

          <Block data={mock} /> //sub component which has the dropdown

    );
  }
}

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState(false); //currently i am trying to get this done with useState()

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (

           setShowDropdown(!showDropdown)}
          >
            ▼

{item.category}

              {item.title}

          {showDropdown && <Dropdown />}

      );
    });
  }
  return
{blocks}
;
};

This is the sandbox link to the code. Could you please let me know how to handle this in React ?
https://codesandbox.io/s/widget-with-drodown-kjovc

Body:
You have to make your state accordingly to the id of items than it will impact the particular block so just change your state accordingly. you can see in below code

     return (
        <div key={item.id} className="block">
          <span
            className="dropdown-btn"
            onClick={() => setShowDropdown(item.id)}
          >
            ▼
          </span>
          <div className="left-col">
            <p>{item.category}</p>
            <h3>
              <a href="#">{item.title}</a>
            </h3>
          </div>
          {showDropdown === item.id && <Dropdown />}
        </div>
      );


问:
Receiving the error "undefined symbol" when loading C++ dynamic library from C executable
I am trying to write a plugin for a popular program whose code and compilation process I do not have control over. The program is written in C. However, I have written parts of my plugin in C++, since I use the QT5 library for graphics capabilities. The functions that the C program calls are written in C.

When the C program tries to load the plugin (shared library), it produces this error:

```<code>dlopen('build/libfoo.so') failed: build/libfoo.so: undefined symbol: _ZTV13JoystickPanel
</code>```

JoystickPanel is a class in the C++ part of the program.

I've tried rewriting parts of the program in C, but the error was unaffected. I know that I could rewrite the entire program in C, but I'd rather not have to switch to another, more C-friendly GUI framework. I've also opened up libfoo.so in a text editor and search for JoystickPanel, but it appears to be mangled as _ZN13JoystickPanel.

Are there any compiler options or solutions that I'm missing?

答:
I have no idea what _ZN13JoystickPanel means, since it's not apparently a valid mangled C++ name. It should perhaps be _ZN13JoystickPanelE, which would translate to JoystickPanel. That'd be symbol name for sure, but without much meaning anyway. You must have truncated something: I tried quite a bit and just can't generate an object file that would include _ZN13JoystickPanel as the complete symbol. It's just a prefix, there should be a "second half" attached to it - was there?

But _ZTV13JoystickPanel is the vtable for the JoystickPanel class. It's missing because you didn't provide implementations for all the virtual methods of the JoystickPanel class. Most likely, you didn't invoke moc properly, or forgot to compile and link its output.

You need to show a complete build script for your plugin at the very least (the .pro file, or CMakeLists.txt). You'll also need to provide a github link to your project (I presume it's open source).

The symbols you want to find in the compiled output are at least _ZTV13JoystickPanelD#Ev - virtual destructors, where # is a digit, _ZTV13JoystickPanel - the virtual method table,

Those symbols may be absent when compiled with optimization and/or LTCG, but also absent will be references to them.

You may wish to delete the build folder and rebuild your project, just to be sure. qmake is bad at dependency generation for the makefiles it produces, so if you use it, I suggest switching to cmake + ninja.

Body:
I am trying to write a plugin for a popular program whose code and compilation process I do not have control over. The program is written in C. However, I have written parts of my plugin in C++, since I use the QT5 library for graphics capabilities. The functions that the C program calls are written in C.

When the C program tries to load the plugin (shared library), it produces this error:

dlopen('build/libfoo.so') failed: build/libfoo.so: undefined symbol: _ZTV13JoystickPanel

JoystickPanel is a class in the C++ part of the program.

I've tried rewriting parts of the program in C, but the error was unaffected. I know that I could rewrite the entire program in C, but I'd rather not have to switch to another, more C-friendly GUI framework. I've also opened up libfoo.so in a text editor and search for JoystickPanel, but it appears to be mangled as _ZN13JoystickPanel.

Are there any compiler options or solutions that I'm missing?


问:
Why does flatten on nested Iterator not compile and why do I need type ascription?
```<code>(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}).flatten
</code>```

gives error:

```<code>value flatten is not a member of Iterator[List[Int]]
[error] possible cause: maybe a semicolon is missing before `value flatten'?
[error]     }.flatten
[error]       ^
[error] one error found
</code>```

But

```<code>(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}: Iterator[List[Int]]).flatten
</code>```

works.  Also storing the iterator in a val works.

Scala version: 2.11.8

答:
I believe this issue was addressed by Include the parts of a compound/refinement type in implicit scope. #5867. The problem was companion to anonymous classes used to not qualify for implicit search

I think aaf9198#diff-7c03397456d3b987549fd039d6b639c6R516 was the
  first to exclude refinement/anon classes from contributing to
  companion implicits. @odersky Can you remember the motivation?

Here is a minimal reproduction

```<code>trait A {
  def foo(): Int
}
class B {
  def bar(): String = "woohoo"
}
object A {
  implicit def aToB(a: A): B = new B
}

(new A {
  override def foo(): Int = 42
}).bar()

// Error:
// value bar is not a member of A$A12.this.A
// possible cause: maybe a semicolon is missing before `value bar'? }).bar();
</code>```

Therefore since in 2.11 and 2.12 flatten on Iterator was provided as an extension method via flattenTraversableOnce the issue would manifest for anonymous Iterator class.

The following is my answer prior to the edit above:

It seems to have something to do with implicit resolution in both 2.11 and 2.12. If you explicitly import flatten as an extension method via

```<code>import scala.collection.TraversableOnce.flattenTraversableOnce
</code>```

then it seems to work. The issue seems to be fixed since 2.13.0-M3 where typer phase gives

```<code>collection.this.TraversableOnce.flattenTraversableOnce[Int, List]({
  final class $anon extends AnyRef with Iterator[List[Int]] {
    def <init>(): <$anon: Iterator[List[Int]]> = {
      $anon.super.<init>();
      ()
    };
    def hasNext: Boolean = scala.Predef.???;
    def next(): List[Int] = scala.Predef.???
  };
  new $anon()
})(scala.Predef.$conforms[List[Int]]).flatten

</code>```

whilst in 2.13.0 release flatten no longer seem to be provided via extension method

```<code>{
  final class $anon extends AnyRef with Iterator[List[Int]] {
    def <init>(): <$anon: Iterator[List[Int]]> = {
      $anon.super.<init>();
      ()
    };
    def hasNext: Boolean = scala.Predef.???;
    def next(): List[Int] = scala.Predef.???
  };
  new $anon()
}.flatten[Int](scala.Predef.$conforms[List[Int]])
</code>```

The above expansion seems to be explained by SLS 6.4 Designators

.  is typed as if it was { val  = ; . }

Body:
(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}).flatten

gives error:

value flatten is not a member of Iterator[List[Int]]
[error] possible cause: maybe a semicolon is missing before `value flatten'?
[error]     }.flatten
[error]       ^
[error] one error found

But

(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}: Iterator[List[Int]]).flatten

works.  Also storing the iterator in a val works.

Scala version: 2.11.8

Body:
I believe this issue was addressed by Include the parts of a compound/refinement type in implicit scope. #5867. The problem was companion to anonymous classes used to not qualify for implicit search

I think aaf9198#diff-7c03397456d3b987549fd039d6b639c6R516 was the
  first to exclude refinement/anon classes from contributing to
  companion implicits. @odersky Can you remember the motivation?

Here is a minimal reproduction

trait A {
  def foo(): Int
}
class B {
  def bar(): String = "woohoo"
}
object A {
  implicit def aToB(a: A): B = new B
}

(new A {
  override def foo(): Int = 42
}).bar()

// Error:
// value bar is not a member of A$A12.this.A
// possible cause: maybe a semicolon is missing before `value bar'? }).bar();

Therefore since in 2.11 and 2.12 flatten on Iterator was provided as an extension method via flattenTraversableOnce the issue would manifest for anonymous Iterator class.

The following is my answer prior to the edit above:

It seems to have something to do with implicit resolution in both 2.11 and 2.12. If you explicitly import flatten as an extension method via

import scala.collection.TraversableOnce.flattenTraversableOnce

then it seems to work. The issue seems to be fixed since 2.13.0-M3 where typer phase gives

collection.this.TraversableOnce.flattenTraversableOnce[Int, List]({
  final class $anon extends AnyRef with Iterator[List[Int]] {
    def <init>(): <$anon: Iterator[List[Int]]> = {
      $anon.super.<init>();
      ()
    };
    def hasNext: Boolean = scala.Predef.???;
    def next(): List[Int] = scala.Predef.???
  };
  new $anon()
})(scala.Predef.$conforms[List[Int]]).flatten

whilst in 2.13.0 release flatten no longer seem to be provided via extension method

{
  final class $anon extends AnyRef with Iterator[List[Int]] {
    def <init>(): <$anon: Iterator[List[Int]]> = {
      $anon.super.<init>();
      ()
    };
    def hasNext: Boolean = scala.Predef.???;
    def next(): List[Int] = scala.Predef.???
  };
  new $anon()
}.flatten[Int](scala.Predef.$conforms[List[Int]])

The above expansion seems to be explained by SLS 6.4 Designators

.  is typed as if it was { val  = ; . }


问:
AS2: Mouse moves too fast messes up function
I am using the following code as part of a set of scrollable bars to change each bar in relation to another when one is dragged. It works until the user swipes the bar as fast as possible then the numbers go wrong... I'm sure this is the function unable to process as fast as the mouse but anyone know a way around this?</p>

```<code>onClipEvent (load) {
    Symptoms_sliders = new Array(this._parent.slider1.slider, this._parent.slider2.slider, this._parent.slider3.slider, this._parent.slider4.slider, this._parent.slider5.slider);
    Food_sliders = new Array(this._parent.slider6.slider, this._parent.slider7.slider, this._parent.slider8.slider, this._parent.slider9.slider);
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i]._y = 75;
    }
    is_scrolling = 0;
    function Food_scroll_ratio() {
        init_scroll_diff = init_scroll_num-init_scroll._y;
        Slider_ratio = new Array();
        totalLeft = init_scroll_num;
        while (_global.init_moved != init_scroll._y) {
            for (i=0; i<Food_sliders.length; i++) {
                if (Food_sliders[i] != init_scroll) {
                    slider_pos = Food_sliders[i]._y;
                    percentageOf = ((100-init_slider_pos[i])/totalLeft)*100;
                    percentageMultiplier = 100/percentageOf;
                    trace(percentageMultiplier);
                    if (init_scroll_num == 0) {
                        scroll_change = Math.round(Math.abs(init_scroll_diff/3));
                    } else {
                        scroll_change = Math.round(Math.abs(init_scroll_diff)/percentageMultiplier);
                    }
                    if (percentageOf == Infinity) {
                        Food_sliders[i]._y = 100;
                    } else if (init_scroll_diff>0) {
                        Food_sliders[i]._y = init_slider_pos[i]+scroll_change;
                    } else if (init_scroll_diff<0) {
                        Food_sliders[i]._y = init_slider_pos[i]-scroll_change;
                    }

                }
            }
            _global.init_moved = init_scroll._y;

        }
    }
}
onClipEvent (mouseMove) {
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i].onPress = function() {
            startDrag(this, false, 0, 100, 0, 0);
            init_scroll_num = this._y;
            init_scroll = this;
            is_scrolling = 1;
            init_slider_pos = new Array();
            init_slider_pos.push(Food_sliders[0]._y);
            init_slider_pos.push(Food_sliders[1]._y);
            init_slider_pos.push(Food_sliders[2]._y);
            init_slider_pos.push(Food_sliders[3]._y);
        };
        Food_sliders[i].onRelease = Food_sliders[i].onReleaseOutside=function () {
            stopDrag();
            is_scrolling = 0;
        };
    }
    if (is_scrolling == 1) {
        Food_scroll_ratio();
    }
}
</code>```

答:
This problem still occurs and I don't think it can be avoided but I use another function  (Slider_checker) that runs once 20ms after the mouse is idle everytime the mouse scrolls a scrollbar (the 20ms allows it to ensure that all loops of Food_Scroll_ratio are finished so nothing interferes with it and saves some cpu cycles).

Here is my final code:

```<code>onClipEvent (load) {
    Symptoms_sliders = new Array(this._parent.slider1.slider, this._parent.slider2.slider, this._parent.slider3.slider, this._parent.slider4.slider, this._parent.slider5.slider);
    Food_sliders = new Array(this._parent.slider6.slider, this._parent.slider7.slider, this._parent.slider8.slider, this._parent.slider9.slider);
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i]._y = 75;
    }
    is_scrolling = 0;
    Slider_check_interval = 0;
    var mouseTimerID:Number;
    var delay:Number = 50;
    var mouseMoveListener = new Object();
    mouseMoveListener.onMouseMove = function() {
        clearInterval(mouseTimerID);
        mouseTimerID = setInterval(Slider_checker, delay);
    };
    Slider_checker = function () {
        while (Slider_check_interval == 1) {
            count = 0;
            for (i=0; i<Food_sliders.length; i++) {
                count += 100-Food_sliders[i]._y;
            }
            if (count != 100 && count != 0) {
                mxm = Food_sliders[0];
                for (i=0; i<Food_sliders.length; i++) {
                    if (Food_sliders[i]._y<mxm._y) {
                        mxm = Food_sliders[i];
                    }
                }
                if (count>100) {
                    mxm._y += count-100;
                }
                if (count<100) {
                    mxm._y -= 100-count;
                }
            }
            Slider_check_interval = 0;
        }
    };

    Mouse.addListener(mouseMoveListener);
    function Food_scroll_ratio() {
        init_scroll_diff = init_scroll_num-init_scroll._y;
        totalLeft = init_scroll_num;
        Slider_check = new Array();
        for (i=0; i<Food_sliders.length; i++) {
            if (Food_sliders[i] != init_scroll) {
                slider_pos = Food_sliders[i]._y;
                percentageOf = ((100-init_slider_pos[i])/totalLeft)*100;
                percentageMultiplier = 100/percentageOf;
                if (init_scroll_num == 0) {
                    scroll_change = Math.round(Math.abs(init_scroll_diff/3));
                } else {
                    scroll_change = Math.round(Math.abs(init_scroll_diff)/percentageMultiplier);
                }
                if (percentageOf == Infinity) {
                    Food_sliders[i]._y = 100;
                } else if (init_scroll_diff>0) {
                    Food_sliders[i]._y = init_slider_pos[i]+scroll_change;
                } else if (init_scroll_diff<0) {
                    Food_sliders[i]._y = init_slider_pos[i]-scroll_change;
                }
            }
        }
        Slider_check_interval = 1;
    }
}
onClipEvent (mouseMove) {
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i].onPress = function() {
            startDrag(this, false, 0, 100, 0, 0);
            init_scroll_num = this._y;
            init_scroll = this;
            is_scrolling = 1;
            init_slider_pos = new Array();
            init_slider_pos.push(Food_sliders[0]._y);
            init_slider_pos.push(Food_sliders[1]._y);
            init_slider_pos.push(Food_sliders[2]._y);
            init_slider_pos.push(Food_sliders[3]._y);
        };
        Food_sliders[i].onRelease = Food_sliders[i].onReleaseOutside=function () {
            stopDrag();
            is_scrolling = 0;
        };

    }
    if (is_scrolling == 1) {
        Food_scroll_ratio();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using the following code as part of a set of scrollable bars to change each bar in relation to another when one is dragged. It works until the user swipes the bar as fast as possible then the numbers go wrong... I'm sure this is the function unable to process as fast as the mouse but anyone know a way around this?

onClipEvent (load) {
    Symptoms_sliders = new Array(this._parent.slider1.slider, this._parent.slider2.slider, this._parent.slider3.slider, this._parent.slider4.slider, this._parent.slider5.slider);
    Food_sliders = new Array(this._parent.slider6.slider, this._parent.slider7.slider, this._parent.slider8.slider, this._parent.slider9.slider);
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i]._y = 75;
    }
    is_scrolling = 0;
    function Food_scroll_ratio() {
        init_scroll_diff = init_scroll_num-init_scroll._y;
        Slider_ratio = new Array();
        totalLeft = init_scroll_num;
        while (_global.init_moved != init_scroll._y) {
            for (i=0; i<Food_sliders.length; i++) {
                if (Food_sliders[i] != init_scroll) {
                    slider_pos = Food_sliders[i]._y;
                    percentageOf = ((100-init_slider_pos[i])/totalLeft)*100;
                    percentageMultiplier = 100/percentageOf;
                    trace(percentageMultiplier);
                    if (init_scroll_num == 0) {
                        scroll_change = Math.round(Math.abs(init_scroll_diff/3));
                    } else {
                        scroll_change = Math.round(Math.abs(init_scroll_diff)/percentageMultiplier);
                    }
                    if (percentageOf == Infinity) {
                        Food_sliders[i]._y = 100;
                    } else if (init_scroll_diff>0) {
                        Food_sliders[i]._y = init_slider_pos[i]+scroll_change;
                    } else if (init_scroll_diff<0) {
                        Food_sliders[i]._y = init_slider_pos[i]-scroll_change;
                    }

                }
            }
            _global.init_moved = init_scroll._y;

        }
    }
}
onClipEvent (mouseMove) {
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i].onPress = function() {
            startDrag(this, false, 0, 100, 0, 0);
            init_scroll_num = this._y;
            init_scroll = this;
            is_scrolling = 1;
            init_slider_pos = new Array();
            init_slider_pos.push(Food_sliders[0]._y);
            init_slider_pos.push(Food_sliders[1]._y);
            init_slider_pos.push(Food_sliders[2]._y);
            init_slider_pos.push(Food_sliders[3]._y);
        };
        Food_sliders[i].onRelease = Food_sliders[i].onReleaseOutside=function () {
            stopDrag();
            is_scrolling = 0;
        };
    }
    if (is_scrolling == 1) {
        Food_scroll_ratio();
    }
}

Body:
This problem still occurs and I don't think it can be avoided but I use another function  (Slider_checker) that runs once 20ms after the mouse is idle everytime the mouse scrolls a scrollbar (the 20ms allows it to ensure that all loops of Food_Scroll_ratio are finished so nothing interferes with it and saves some cpu cycles).

Here is my final code:

onClipEvent (load) {
    Symptoms_sliders = new Array(this._parent.slider1.slider, this._parent.slider2.slider, this._parent.slider3.slider, this._parent.slider4.slider, this._parent.slider5.slider);
    Food_sliders = new Array(this._parent.slider6.slider, this._parent.slider7.slider, this._parent.slider8.slider, this._parent.slider9.slider);
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i]._y = 75;
    }
    is_scrolling = 0;
    Slider_check_interval = 0;
    var mouseTimerID:Number;
    var delay:Number = 50;
    var mouseMoveListener = new Object();
    mouseMoveListener.onMouseMove = function() {
        clearInterval(mouseTimerID);
        mouseTimerID = setInterval(Slider_checker, delay);
    };
    Slider_checker = function () {
        while (Slider_check_interval == 1) {
            count = 0;
            for (i=0; i<Food_sliders.length; i++) {
                count += 100-Food_sliders[i]._y;
            }
            if (count != 100 && count != 0) {
                mxm = Food_sliders[0];
                for (i=0; i<Food_sliders.length; i++) {
                    if (Food_sliders[i]._y<mxm._y) {
                        mxm = Food_sliders[i];
                    }
                }
                if (count>100) {
                    mxm._y += count-100;
                }
                if (count<100) {
                    mxm._y -= 100-count;
                }
            }
            Slider_check_interval = 0;
        }
    };

    Mouse.addListener(mouseMoveListener);
    function Food_scroll_ratio() {
        init_scroll_diff = init_scroll_num-init_scroll._y;
        totalLeft = init_scroll_num;
        Slider_check = new Array();
        for (i=0; i<Food_sliders.length; i++) {
            if (Food_sliders[i] != init_scroll) {
                slider_pos = Food_sliders[i]._y;
                percentageOf = ((100-init_slider_pos[i])/totalLeft)*100;
                percentageMultiplier = 100/percentageOf;
                if (init_scroll_num == 0) {
                    scroll_change = Math.round(Math.abs(init_scroll_diff/3));
                } else {
                    scroll_change = Math.round(Math.abs(init_scroll_diff)/percentageMultiplier);
                }
                if (percentageOf == Infinity) {
                    Food_sliders[i]._y = 100;
                } else if (init_scroll_diff>0) {
                    Food_sliders[i]._y = init_slider_pos[i]+scroll_change;
                } else if (init_scroll_diff<0) {
                    Food_sliders[i]._y = init_slider_pos[i]-scroll_change;
                }
            }
        }
        Slider_check_interval = 1;
    }
}
onClipEvent (mouseMove) {
    for (i=0; i<Food_sliders.length; i++) {
        Food_sliders[i].onPress = function() {
            startDrag(this, false, 0, 100, 0, 0);
            init_scroll_num = this._y;
            init_scroll = this;
            is_scrolling = 1;
            init_slider_pos = new Array();
            init_slider_pos.push(Food_sliders[0]._y);
            init_slider_pos.push(Food_sliders[1]._y);
            init_slider_pos.push(Food_sliders[2]._y);
            init_slider_pos.push(Food_sliders[3]._y);
        };
        Food_sliders[i].onRelease = Food_sliders[i].onReleaseOutside=function () {
            stopDrag();
            is_scrolling = 0;
        };

    }
    if (is_scrolling == 1) {
        Food_scroll_ratio();
    }
}


问:
How to extract the last digits of strings using regular expressions?
I have a bunch of colnames

```<code>L_1_3
L_2_23
L_3_91
L_3_16
</code>```

I want to replace these colnames with new names using the last digits following the _ like this:

```<code>3
23
91
16
</code>```

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

答:
Here's an option with positive lookahead:</p>

```<code>gsub(".+_(?=\\d+$)", "", X, perl = TRUE)
[1] "3"  "23" "91" "16"
</code>```

Body:
I have a bunch of colnames

L_1_3
L_2_23
L_3_91
L_3_16

I want to replace these colnames with new names using the last digits following the _ like this:

3
23
91
16

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

Body:
Here's an option with positive lookahead:

gsub(".+_(?=\\d+$)", "", X, perl = TRUE)
[1] "3"  "23" "91" "16"


问:
How do I pivot over date in pandas?
I have a df that looks like this

```<code>date     lat long
1/2/12   30   30
2/2/12   31   12
2/2/12   30   29
2/2/12   30   30
3/2/12   31   21
3/2/12   31   10
3/2/12   nan  nan
      ....
5/15/20  31   21
5/16/20  21   05
5/18/20  nan nan
</code>```

I want to get a table that looks like the following. Basically, each date column now contains the total count of a matching lat/long until that specific date

```<code> lat long 1/2/12  2/2/12 3/2/12 ... 5/15/20 5/16/20 5/17/20 ...
  30   30   1       2      2          11      55      67
  31   12   0       1      1          1        1      3
  30   29   0       1      1          17      22     25
  30   30   0       1      2          100     130    145
</code>```

and so on.

How would I do it?

Title: How do I pivot over date in pandas?

Body:
I have a df that looks like this

date     lat long
1/2/12   30   30
2/2/12   31   12
2/2/12   30   29
2/2/12   30   30
3/2/12   31   21
3/2/12   31   10
3/2/12   nan  nan
      ....
5/15/20  31   21
5/16/20  21   05
5/18/20  nan nan

I want to get a table that looks like the following. Basically, each date column now contains the total count of a matching lat/long until that specific date

 lat long 1/2/12  2/2/12 3/2/12 ... 5/15/20 5/16/20 5/17/20 ...
  30   30   1       2      2          11      55      67
  31   12   0       1      1          1        1      3
  30   29   0       1      1          17      22     25
  30   30   0       1      2          100     130    145

and so on.

How would I do it?

Body:
Looks like a crosstab:

pd.crosstab([df['lat'],df['long']], df.date).reset_index()

Output:

date   lat  long  1/2/12  2/2/12  3/2/12  5/15/20  5/16/20
0     21.0   5.0       0       0       0        0        1
1     30.0  29.0       0       1       0        0        0
2     30.0  30.0       1       1       0        0        0
3     31.0  10.0       0       0       1        0        0
4     31.0  12.0       0       1       0        0        0
5     31.0  21.0       0       0       1        1        0


问:
Pandas: astype error string to float (could not convert string to float: '7,50')
I am trying to convert a dataframe field from string to float in Pandas.

This is the field:

```<code>In:

print(merged['platnosc_total'].head(100))

Out:

0     0,00
1     4,50
2     0,00
3     0,00
4     0,00
5     4,50
6     6,10
7     7,99
8     4,00
9     7,69
10    7,50
</code>```

Note the 7,50, in the last row, which seems to cause the error:

```<code>In:

merged['platnosc_total'].astype(float)

Out:

ValueError: could not convert string to float: '7,50'
</code>```

Does this mean that the rest got converted, and only the row with 7,50 is the cause?

How can I actually cast this field/column to float?

答:
If you have nan or empty rows in your column, astype(float) won't work.

You should try

```<code>merged.replace('', np.nan).dropna(subset=['platnosc_total'], inplace=True)
merged['platnosc_total'].astype(float)
</code>```

Body:
I am trying to convert a dataframe field from string to float in Pandas.

This is the field:

In:

print(merged['platnosc_total'].head(100))

Out:

0     0,00
1     4,50
2     0,00
3     0,00
4     0,00
5     4,50
6     6,10
7     7,99
8     4,00
9     7,69
10    7,50

Note the 7,50, in the last row, which seems to cause the error:

In:

merged['platnosc_total'].astype(float)

Out:

ValueError: could not convert string to float: '7,50'

Does this mean that the rest got converted, and only the row with 7,50 is the cause?

How can I actually cast this field/column to float?

Body:
If you have nan or empty rows in your column, astype(float) won't work.

You should try

merged.replace('', np.nan).dropna(subset=['platnosc_total'], inplace=True)
merged['platnosc_total'].astype(float)


问:
How to obtain commit list between tags with JGit?
Suppose that given two tags as input, like "v5.8.0.202005061305-m2" and "v5.7.0.202003090808-r".

Is there a way to obtain the commit list between two tags with JGit?

I know GitHub has that functionality as you can compare two tags and see all the commits in between but can we do the same with JGit?

答:
The LogCommand has an addRange method to specify the commits you are interested in.

This is an example that resolves the tag names to commit IDs and then uses the LogCommand to list all commits in that range.

Git git = ...
Ref tag1 = git.getRepository().exactRef("refs/tags/tag1");
Ref tag2 = git.getRepository().exactRef("refs/tags/tag2");
Iterable<RevCommit> commits = git.log().addRange(tag1.getPeeledObjectId(), tag2.getPeeledObjectId());
for(RevCommit : commits ) {
  ...
}
```


问:
How to get multiple S3 objects asynchronously into memory
I am attempting to pull multiple S3 objects asynchronously into memory.

For single objects I can use the AmazonS3:

```<code>s3Object = s3Client.getObject(bucketName, String key)
S3ObjectInputStream stream = s3Object.getObjectContent();
byte[] byteArray  IOUtils.toByteArray(s3InputStream);
stream.close()
</code>```

For objects in directory downloads, AWS offers TransferManager, but the problem is that I do not want it to write to File/disk. I want all objects to be return to me in memory.

How do I achieve asynchronously pulling multiple objects at a time from S3 and return it in memory?

答:
I have not done it myself in Java yet, but in theory you should be able to achieve this by using CompletableFuture.

The second example in this AWS documentation shows how to get one object asynchronously from S3: Asynchronous Programming. To get the object as a byte-array instead of a file you will need to replace the AsyncResponseTransformer.toFile with AsyncResponseTransformer.toBytes.

You then need to do that for every file you want to load, and then use CompletableFuture.allOf() to wait on all the CompletableFutures to complete loading the files.

Body:
I am attempting to pull multiple S3 objects asynchronously into memory.

For single objects I can use the AmazonS3:

s3Object = s3Client.getObject(bucketName, String key)
S3ObjectInputStream stream = s3Object.getObjectContent();
byte[] byteArray  IOUtils.toByteArray(s3InputStream);
stream.close()

For objects in directory downloads, AWS offers TransferManager, but the problem is that I do not want it to write to File/disk. I want all objects to be return to me in memory.

How do I achieve asynchronously pulling multiple objects at a time from S3 and return it in memory?


问:
How to get the ForeColor associated with the BackColor of the skin?
When you set a SimpleButton.Appearance.BackColor property to a DX Skin color (@Danger, @Question, @Success, @Primary or @Info as shown in the image):

The SimpleButton.Appearance.ForeColor property is evaluated at run-time with the appropriate color (if the skin color is too dark, Color.White would be used; if the skin color is too bright, Color.Black would be used):

Dark @Success:

Light @Success:

How do I get this ForeColor that is evaluated in run-time?

I have tried getting SimpleButton.ForeColor, SimpleButton.Appearance.ForeColor and SimpleButton.Appearance.GetForeColor(e.GraphicsCache) (I'm trying to get this color inside a CustomDraw event) but it's always Color.Black

答:
I ended up with this extension method according to this implementation of the W3C standard, making some modifications per Miral's tests:</p>

```<code>public static Color GetContrastColor(this Color color)
{
    return (color.R * 0.299M) + (color.G * 0.587M) + (color.B * 0.114M) > 149 ?
        Color.Black :
        Color.White;
}
</code>```

Body:
I ended up with this extension method according to this implementation of the W3C standard, making some modifications per Miral's tests:

public static Color GetContrastColor(this Color color)
{
    return (color.R * 0.299M) + (color.G * 0.587M) + (color.B * 0.114M) > 149 ?
        Color.Black :
        Color.White;
}


问:
Build condition comparison for if statement
Is this possible?

```<code>$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}
</code>```

The syntax right now is not valid but is there a way to do this?

答:
It is possible with

```<code>if (eval("{$var_1} {$comparison} {$var_2}")) {
</code>```

But eval is strongly discouraged, so do this only if you can't achieve desired result otherwise

EDIT
As @mario noted, until PHP 5.3 this doesn't work. In 5.3 it does. So for older versions it should be

```<code>if (eval("return {$var_1} {$comparison} {$var_2};")) {
</code>```

Body:
Is this possible?

$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}

The syntax right now is not valid but is there a way to do this?

Body:
It is possible with

if (eval("{$var_1} {$comparison} {$var_2}")) {

But eval is strongly discouraged, so do this only if you can't achieve desired result otherwise

EDIT
As @mario noted, until PHP 5.3 this doesn't work. In 5.3 it does. So for older versions it should be

if (eval("return {$var_1} {$comparison} {$var_2};")) {


问:
WIX - Build a setup.exe bundle which hold both 32 bit and 64 bit MSI
I was able to create a 32 bit and 64 bit msi of an application. Now i need to include these MSIs to a bundle like setup.exe. What is the best way to create a bundle like setup.exe that will extract the 32 bit msi in 32 bit machine and extract 64 bit msi in 64 bit machine.</p>

答: Just put 2 MsiPackage elements in your bundle with mutually exclusive conditions.  VersionNT64 and Not VersionNT64.</p>


问:
Why can my fields not be bound in a T-SQL join?
So I have the following SQL statement:

```<code>SELECT
    CASE
    WHEN table1.Recommendation = 1 THEN 'Condition1'
    WHEN table1.Recommendation = 2 THEN 'Condition2'
    WHEN table1.Recommendation = 3 THEN 'Condition3'
    ELSE ' '
    END
    AS Recommendation,
    table2.Notes,
    table3.ItemDescription AS Item,
    table4.Description AS Concern
FROM Job
RIGHT JOIN table2 ON Job.JobId = table2.JobId
LEFT JOIN table1 ON table2.table2Id = table1.table2Id
INNER JOIN table3 ON table2.table3Id = table3.table3Id
LEFT JOIN table1 customName ON table4.table4Id = customName.table4Id
WHERE Job.JobId = @JobId AND table1.Condition = 3
</code>```

This is for a telerik report, and the JobId variable will be input with an actual job id. table2 holds the JobId, as well as the table1 id. I am trying to get the table4.Description, but everytime I get the errors:

```<code>The multi-part identifier table4.table4Id could not be bound.
The multi-part identifier table4.Description could not be bound.
</code>```

At this point I don't know what to try from here. Any help would be appreciated! I will gladly add any more information as possible to try to figure out this issue

答:
Basically you are missing a JOIN. You just add your join condition.

```<code>SELECT
    CASE
    WHEN table1.Recommendation = 1 THEN 'Condition1'
    WHEN table1.Recommendation = 2 THEN 'Condition2'
    WHEN table1.Recommendation = 3 THEN 'Condition3'
    ELSE ' '
    END
    AS Recommendation,
    table2.Notes,
    table3.ItemDescription AS Item,
    table4.Description AS Concern
FROM Job
RIGHT JOIN table2 ON Job.JobId = table2.JobId
LEFT JOIN table1 ON table2.table2Id = table1.table2Id
INNER JOIN table3 ON table2.table3Id = table3.table3Id
INNER JOIN table4 ON <I don't what what to join on>
LEFT JOIN table1 customName ON table4.table4Id = customName.table4Id
WHERE Job.JobId = @JobId AND table1.Condition = 3
</code>```

Body:
So I have the following SQL statement:

SELECT
    CASE
    WHEN table1.Recommendation = 1 THEN 'Condition1'
    WHEN table1.Recommendation = 2 THEN 'Condition2'
    WHEN table1.Recommendation = 3 THEN 'Condition3'
    ELSE ' '
    END
    AS Recommendation,
    table2.Notes,
    table3.ItemDescription AS Item,
    table4.Description AS Concern
FROM Job
RIGHT JOIN table2 ON Job.JobId = table2.JobId
LEFT JOIN table1 ON table2.table2Id = table1.table2Id
INNER JOIN table3 ON table2.table3Id = table3.table3Id
LEFT JOIN table1 customName ON table4.table4Id = customName.table4Id
WHERE Job.JobId = @JobId AND table1.Condition = 3

This is for a telerik report, and the JobId variable will be input with an actual job id. table2 holds the JobId, as well as the table1 id. I am trying to get the table4.Description, but everytime I get the errors:

The multi-part identifier table4.table4Id could not be bound.
The multi-part identifier table4.Description could not be bound.

At this point I don't know what to try from here. Any help would be appreciated! I will gladly add any more information as possible to try to figure out this issue

Body:
Basically you are missing a JOIN. You just add your join condition.

SELECT
    CASE
    WHEN table1.Recommendation = 1 THEN 'Condition1'
    WHEN table1.Recommendation = 2 THEN 'Condition2'
    WHEN table1.Recommendation = 3 THEN 'Condition3'
    ELSE ' '
    END
    AS Recommendation,
    table2.Notes,
    table3.ItemDescription AS Item,
    table4.Description AS Concern
FROM Job
RIGHT JOIN table2 ON Job.JobId = table2.JobId
LEFT JOIN table1 ON table2.table2Id = table1.table2Id
INNER JOIN table3 ON table2.table3Id = table3.table3Id
INNER JOIN table4 ON <I don't what what to join on>
LEFT JOIN table1 customName ON table4.table4Id = customName.table4Id
WHERE Job.JobId = @JobId AND table1.Condition = 3


问:
How to solve A facade root has not been set. In Facade.php line 236: Laravel 5.8?
I am receiving
In Facade.php line 236: A facade root has not been set.
in a Laravel 5.8 project I am cloning from GitLab.
here is the log output

```<code>[stacktrace]
#0 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\config\\seotools.php(14): Illuminate\\Support\\Facades\\Facade::__callStatic('get', Array)
#1 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Bootstrap\\LoadConfiguration.php(72): require('C:\\\\Users\\\\Abdell...')
#2 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Bootstrap\\LoadConfiguration.php(39): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->loadConfigurationFiles(Object(Illuminate\\Foundation\\Application), Object(Illuminate\\Config\\Repository))
#3 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Application.php(210): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->bootstrap(Object(Illuminate\\Foundation\\Application))
#4 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php(322): Illuminate\\Foundation\\Application->bootstrapWith(Array)
#5 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php(131): Illuminate\\Foundation\\Console\\Kernel->bootstrap()
#6 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#7 {main}
"} ```

```

答: Did you run composer install ?? composer install

Body:
I am receiving
In Facade.php line 236: A facade root has not been set.
in a Laravel 5.8 project I am cloning from GitLab.
here is the log output

[stacktrace]
#0 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\config\\seotools.php(14): Illuminate\\Support\\Facades\\Facade::__callStatic('get', Array)
#1 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Bootstrap\\LoadConfiguration.php(72): require('C:\\\\Users\\\\Abdell...')
#2 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Bootstrap\\LoadConfiguration.php(39): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->loadConfigurationFiles(Object(Illuminate\\Foundation\\Application), Object(Illuminate\\Config\\Repository))
#3 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Application.php(210): Illuminate\\Foundation\\Bootstrap\\LoadConfiguration->bootstrap(Object(Illuminate\\Foundation\\Application))
#4 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php(322): Illuminate\\Foundation\\Application->bootstrapWith(Array)
#5 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Console\\Kernel.php(131): Illuminate\\Foundation\\Console\\Kernel->bootstrap()
#6 C:\\Users\\Abdellah Ramadan\\Desktop\\COMPANY\\poblysh\\artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#7 {main}
"} ```


问:
Instagram API giving "Invalid platform app" error when I am trying to fetch the access token
I am trying to fetch the access token using this API: https://api.instagram.com/oauth/access_token. I have made sure to use the instagram app ID only and have also taken care of the content type to be "x-www-form-urlencoded" as suggested in the following answers: Authenticate the Test User { "error_type": "OAuthException", "code": 400, "error_message": "Invalid platform app" }. The API works perfectly fine in postman though but gives the following error response through my code:

{"error_type": "OAuthException", "code": 400, "error_message": "Invalid platform app"}

Here is my peice of code:

```<code>-(void)fetchAccessTokenForInsta{

NSString *targetUrl = [NSString stringWithFormat:@"%@", @"https://api.instagram.com/oauth/access_token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

NSDictionary *tmp = @{@"client_id":@"126.....", @"client_secret":@"c79c.....", @"grant_type":@"authorization_code", @"redirect_uri":@"https://firebase.google.com/", @"code":_codeStr};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];

[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:targetUrl]];

NSDictionary *headers = @{@"Content-Type": @"application/x-www-form-urlencoded" };
[request setAllHTTPHeaderFields:headers];

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
  ^(NSData * _Nullable data,
    NSURLResponse * _Nullable response,
    NSError * _Nullable error) {

      NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
      NSLog(@"Data received: %@", responseStr);
}] resume];
}
</code>```

Where _codeStr is the string after removing # from the code received in the earlier step. Any help is appreciated.

答: The only solution that worked so far is that you ask your server or backend team to develop an API for you that fetches the access token using the instagram API and gives it to you as a response.</p>

Body:
I am trying to fetch the access token using this API: https://api.instagram.com/oauth/access_token. I have made sure to use the instagram app ID only and have also taken care of the content type to be "x-www-form-urlencoded" as suggested in the following answers: Authenticate the Test User { "error_type": "OAuthException", "code": 400, "error_message": "Invalid platform app" }. The API works perfectly fine in postman though but gives the following error response through my code:

{"error_type": "OAuthException", "code": 400, "error_message": "Invalid platform app"}

Here is my peice of code:

-(void)fetchAccessTokenForInsta{

NSString *targetUrl = [NSString stringWithFormat:@"%@", @"https://api.instagram.com/oauth/access_token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

NSDictionary *tmp = @{@"client_id":@"126.....", @"client_secret":@"c79c.....", @"grant_type":@"authorization_code", @"redirect_uri":@"https://firebase.google.com/", @"code":_codeStr};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];

[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:targetUrl]];

NSDictionary *headers = @{@"Content-Type": @"application/x-www-form-urlencoded" };
[request setAllHTTPHeaderFields:headers];

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
  ^(NSData * _Nullable data,
    NSURLResponse * _Nullable response,
    NSError * _Nullable error) {

      NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
      NSLog(@"Data received: %@", responseStr);
}] resume];
}

Where _codeStr is the string after removing # from the code received in the earlier step. Any help is appreciated.


问:
Which JCE providers are FIPS 140-2 compliant?
What Java Cryptography Extension (JCE) providers are FIPS 140-2 compliant? More specifically, does the Sun/Oracle provider qualify?</p>

答: According to  this page, java 6 can be made FIPS 140 compliant via either NSS or SunJSSE.</p>

ContentLicense: CC BY-SA 2.5


问:
Retrieving from a database table a value only if the record does not contain duplicates
I have a table with the following three values without any other constraints imposed via Schema

```<code>id_a
id_b
id_c
</code>```

so, there could be more than one row with the same id_b

Now, I want to write a query, that will give me only the rows where id_b is unique and matches a given value.

something like:

```<code>select * where id_b = ? and (id_b is unique)
</code>```

I know it is simple, but my brain in not working as it should, so any help pls.

答:
This may be simpler, assuming you have a primary key.
And you can then add " AND t2.id_b = ..."

```<code>SELECT t1.*
FROM tablename as t1
  LEFT JOIN tablename as t2
      ON t1.id_b = t2.id_b AND t1.primarykey <> t2.primarykey
WHERE t2.primarykey IS NULL
</code>```

or this syntax:

```<code>SELECT t1.*
FROM tablename as t1
WHERE NOT EXISTS (SELECT 'x'
                  FROM tablename as t2
                  WHERE t1.id_b = t2.id_b AND t1.primarykey <> t2.primarykey)
</code>```

Body:
I have a table with the following three values without any other constraints imposed via Schema

id_a
id_b
id_c

so, there could be more than one row with the same id_b

Now, I want to write a query, that will give me only the rows where id_b is unique and matches a given value.

something like:

select * where id_b = ? and (id_b is unique)

I know it is simple, but my brain in not working as it should, so any help pls.

Body:
This may be simpler, assuming you have a primary key.
And you can then add " AND t2.id_b = ..."

SELECT t1.*
FROM tablename as t1
  LEFT JOIN tablename as t2
      ON t1.id_b = t2.id_b AND t1.primarykey <> t2.primarykey
WHERE t2.primarykey IS NULL

or this syntax:

SELECT t1.*
FROM tablename as t1
WHERE NOT EXISTS (SELECT 'x'
                  FROM tablename as t2
                  WHERE t1.id_b = t2.id_b AND t1.primarykey <> t2.primarykey)


问:
Unit test passes when in debug but fails when run
A search method returns any matching Articles and the most recent Non-matching articles up to a specified number.

Prior to being returned, the IsMatch property of the matching articles is set to true as follows:

articles = matchingArticles.Select(c => { c.IsMatch = true; return c; }).ToList();

In a test of this method,

```<code>    [Test]
    public void SearchForArticle1Returns1MatchingArticleFirstInTheList()
    {
        using (var session = _sessionFactory.OpenSession())
        {
            var maxResults = 10;
            var searchPhrase = "Article1";
            IArticleRepository articleRepository = new ArticleRepository(session);
            var articles = articleRepository.GetSearchResultSet(searchPhrase, maxResults);
            Assert.AreEqual(10, articles.Count);
            Assert.AreEqual(1, articles.Where(a => a.Title.Contains(searchPhrase)).Count());
            var article = articles[0];
            Assert.IsTrue(article.Title.Contains(searchPhrase));
            Assert.IsTrue(article.IsMatch);
        }
    }
</code>```

All assertions pass when the test is run in debug, however the final assertion fails when the test is run in release:

Expected: True
  But was:  False

In the app itself the response is correct.

Any ideas as to why this is happening?

Edit:

I figured out what the problem is. It's essentially a race condition. When I am setting up the tests, I am dropping the db table, recreating it and populating it with the test data. Since the search relies on Full Text search, I am creating a text index on the relevant columns and setting it to auto populate. When this is run in debug, there appears to be sufficient time to populate the text index and the search query returns matches. When I run the test I don't think the index has been populated in time, no matches are returned and the test fails. It's similar to issues with datetimes. If I put a delay between creating the catalog and running the test the test passes.

答:
try to print out the actual result that you are comparing them with expected on debug and normal run

in my case, I created entities (JBA) in the test method

in debug mode, the generated ids were 1, 2 and 3

but in the normal running mode, they ware different

that caused my hard-coded values to make the test fail, so I changed them to get id from entity instead of the hard-coded way

hope this helps

Body:
A search method returns any matching Articles and the most recent Non-matching articles up to a specified number.

Prior to being returned, the IsMatch property of the matching articles is set to true as follows:

articles = matchingArticles.Select(c => { c.IsMatch = true; return c; }).ToList();

In a test of this method,

    [Test]
    public void SearchForArticle1Returns1MatchingArticleFirstInTheList()
    {
        using (var session = _sessionFactory.OpenSession())
        {
            var maxResults = 10;
            var searchPhrase = "Article1";
            IArticleRepository articleRepository = new ArticleRepository(session);
            var articles = articleRepository.GetSearchResultSet(searchPhrase, maxResults);
            Assert.AreEqual(10, articles.Count);
            Assert.AreEqual(1, articles.Where(a => a.Title.Contains(searchPhrase)).Count());
            var article = articles[0];
            Assert.IsTrue(article.Title.Contains(searchPhrase));
            Assert.IsTrue(article.IsMatch);
        }
    }

All assertions pass when the test is run in debug, however the final assertion fails when the test is run in release:

Expected: True
  But was:  False

In the app itself the response is correct.

Any ideas as to why this is happening?

Edit:

I figured out what the problem is. It's essentially a race condition. When I am setting up the tests, I am dropping the db table, recreating it and populating it with the test data. Since the search relies on Full Text search, I am creating a text index on the relevant columns and setting it to auto populate. When this is run in debug, there appears to be sufficient time to populate the text index and the search query returns matches. When I run the test I don't think the index has been populated in time, no matches are returned and the test fails. It's similar to issues with datetimes. If I put a delay between creating the catalog and running the test the test passes.


问:
Setting up a docker registry on EC2 instance
I want to set up a private registry on an AWS ec2 instance, in such a way that I could securely push images, and our clients could securely pull them (but not push).

Right now I tried to do so with a self-signed certificate but I'm really confused about how it's supposed to work, and how to separate the push of images by me and the pull by the customers.

It would really help me if someone that has done something like that before could elaborate on how he did this.

答:
For achieving this you should deploy your registry behind a web server with authentication.

I can point you to an example that I followed long back for the same.
This is that example

Since you are in AWS infrastructure, I think you can go with ECR and easily handle access control.


问:
Quickest way to migrate win application to web - .NET
I have one win application with presentation layer done as windows forms.
Now I have request to transfer it whole to the web. Of course, this is a lot of work, so I'm wondering is it maybe somehow possible to achieve this without rewriting whole presentation layer to the web forms? I've heard that SAP has some technology to expose same forms in both win and web, so I'm wondering now how did they do it, and is it possible to somehow do this with C#?

I'm in a delicate situation where I have to transfer win client application to web as quickly as possible, disregarding performance or other issues, with as little effort as possible.

I'm using .NET framework (C#), and I should transfer this to ASP.NET.

EDIT: If I transform my win forms to win controls, can I then host them in IE? Maybe this could be fastest way to achieve my goals?

答:
In addition to the obvious technical problems and limitations, there are a whole host of other reasons that applications designed for the desktop need to be completely re-written as web applications. Rich client applications simply should not and cannot work the same way as web applications.

Or, to put things another way: You can put wheels on your mama, but that doesn't make her a bus.

You're not doing anyone any favors by trying to "port" the app over as quickly as possible. It's going to be somewhere between "difficult" and "downright infuriating" to use, not the position anyone wants their software to fall into. Yes, it's a lot of work. But no, it's not optional.


问:
Overriding update( ) Django rest framework
I have a model which contains a foreign key. When I my models all fields are updated except the foreign key.

My models:

```<code>class Produit (models.Model):
   titre=models.CharField(max_length=100)
   description=models.TextField()
   photo_principal=models.ImageField(upload_to='produits/',default='image.jpg')
   photo_1 = models.ImageField(upload_to='produits/', default='image.jpg')
   photo_2 = models.ImageField(upload_to='produits/', default='image.jpg')
   photo_3 = models.ImageField(upload_to='produits/', default='image.jpg')
   prix=models.FloatField()
   new_prix=models.FloatField()
   categorie=models.ForeignKey(Categorie,related_name= 'produit', on_delete=models.CASCADE)
</code>```

serializers.py

```<code>class ProduitUpdateSerializer(serializers.ModelSerializer):
categorie_id = serializers.PrimaryKeyRelatedField(queryset=Categorie.objects.all(),source='categorie.id')

class Meta:
    model = Produit
    fields = ['titre', 'description', 'photo_principal', 'photo_1', 'photo_2', 'photo_3', 'prix', 'new_prix',
              'categorie_id', ]

def update(self, instance, validated_data):
    print(validated_data)
    instance.categorie_id = validated_data.get('categorie_id',instance.categorie_id)
    instance.titre = validated_data.get('titre', instance.titre)
    instance.description = validated_data.get('description', instance.description)
    instance.photo_principal = validated_data.get('photo_principal', instance.photo_principal)
    instance.photo_1 = validated_data.get('photo_1', instance.photo_1)
    instance.photo_2 = validated_data.get('photo_2', instance.photo_2)
    instance.photo_3 = validated_data.get('photo_3', instance.photo_3)
    instance.prix = validated_data.get('prix', instance.prix)
    instance.new_prix = validated_data.get('new_prix', instance.new_prix)
    instance.save()

    return instance
</code>```

答:
why not call super like so as the modelserialiser has additional iteration for m2m db.</p>

```<code>def update(self, instance, validated_data):
    # MANIPULATE DATA HERE BEFORE INSERTION

    instance = super(ProduitUpdateSerializer,self).update(instance, validated_data)
    # ADD CODE HERE THAT YOU WANT TO VIEW
    return instance
</code>```

Body:
I have a model which contains a foreign key. When I my models all fields are updated except the foreign key.

My models:

class Produit (models.Model):
   titre=models.CharField(max_length=100)
   description=models.TextField()
   photo_principal=models.ImageField(upload_to='produits/',default='image.jpg')
   photo_1 = models.ImageField(upload_to='produits/', default='image.jpg')
   photo_2 = models.ImageField(upload_to='produits/', default='image.jpg')
   photo_3 = models.ImageField(upload_to='produits/', default='image.jpg')
   prix=models.FloatField()
   new_prix=models.FloatField()
   categorie=models.ForeignKey(Categorie,related_name= 'produit', on_delete=models.CASCADE)

serializers.py

class ProduitUpdateSerializer(serializers.ModelSerializer):
categorie_id = serializers.PrimaryKeyRelatedField(queryset=Categorie.objects.all(),source='categorie.id')

class Meta:
    model = Produit
    fields = ['titre', 'description', 'photo_principal', 'photo_1', 'photo_2', 'photo_3', 'prix', 'new_prix',
              'categorie_id', ]

def update(self, instance, validated_data):
    print(validated_data)
    instance.categorie_id = validated_data.get('categorie_id',instance.categorie_id)
    instance.titre = validated_data.get('titre', instance.titre)
    instance.description = validated_data.get('description', instance.description)
    instance.photo_principal = validated_data.get('photo_principal', instance.photo_principal)
    instance.photo_1 = validated_data.get('photo_1', instance.photo_1)
    instance.photo_2 = validated_data.get('photo_2', instance.photo_2)
    instance.photo_3 = validated_data.get('photo_3', instance.photo_3)
    instance.prix = validated_data.get('prix', instance.prix)
    instance.new_prix = validated_data.get('new_prix', instance.new_prix)
    instance.save()

    return instance

Body:
why not call super like so as the modelserialiser has additional iteration for m2m db.

def update(self, instance, validated_data):
    # MANIPULATE DATA HERE BEFORE INSERTION

    instance = super(ProduitUpdateSerializer,self).update(instance, validated_data)
    # ADD CODE HERE THAT YOU WANT TO VIEW
    return instance


问:
Unable to start kurento media server with docker
I'm trying to run kurent-media-server, by following the instructions found here:

https://hub.docker.com/r/kurento/kurento-media-server

I've followed them, but I am still unable to connect to the server.

After running

```<code>$ docker run --name kms -d -p 8888:8888 \
    kurento/kurento-media-server
</code>```

```<code>$ curl -i -N \
    -H "Connection: Upgrade" \
    -H "Upgrade: websocket" \
    -H "Host: 127.0.0.1:8888" \
    -H "Origin: 127.0.0.1" \
    http://127.0.0.1:8888/kurento
</code>```

I get curl: (56) Recv failure: Connection reset by peer, instead of

```<code>HTTP/1.1 500 Internal Server Error
Server: WebSocket++/0.7.0
</code>```

How can I fix this? I seem to have done done everything properly.

答: Try using latest image of kurento-media-server docker. I am using version 6.13.2 and it works fine for me.

Body:
I'm trying to run kurent-media-server, by following the instructions found here:

https://hub.docker.com/r/kurento/kurento-media-server

I've followed them, but I am still unable to connect to the server.

After running

$ docker run --name kms -d -p 8888:8888 \
    kurento/kurento-media-server

$ curl -i -N \
    -H "Connection: Upgrade" \
    -H "Upgrade: websocket" \
    -H "Host: 127.0.0.1:8888" \
    -H "Origin: 127.0.0.1" \
    http://127.0.0.1:8888/kurento

I get curl: (56) Recv failure: Connection reset by peer, instead of

HTTP/1.1 500 Internal Server Error
Server: WebSocket++/0.7.0

How can I fix this? I seem to have done done everything properly.