text:
Q: Counting different values using Data.Map leaks memory The following program uses 100+ MB RAM when counting different line lengths in a 250 MB file. How do I fix it to use less RAM? I suppose I misused lazy IO, foldr and laziness of Data.Map in values.
import Control.Applicative
import qualified Data.Map as M
import Data.List

main = do
  content <- readFile "output.csv"
  print $ (foldr count M.empty . map length . lines) content

count a b = M.insertWith (+) a 1 b

A: The first big mistake in
main = do
  content <- readFile "output.csv"
  print $ (foldr count M.empty . map length . lines) content

count a b = M.insertWith (+) a 1 b

is using foldr. That constructs an expression of the form
length firstLine `count` length secondLine `count` ... `count` length lastLine `count` M.empty

traversing the entire list of lines constructing the thunk - at that time not even evaluating the length calls due to laziness - before it is then evaluated right to left. So the entire file contents is in memory in addition to the thunk for building the Map.
If you build up a map from a list of things, always use a strict left fold (well, if the list is short, and the things not huge, it doesn't matter) unless the semantics require a right fold (if you're combining values using a non-commutative function, that might be the case, but even then it is often preferable to use a left fold and reverse the list before building the map).
Data.Maps (or Data.IntMaps) are spine-strict, that alone makes it impossible to generate partial output before the entire list has been traversed, so the strengths of foldr cannot be used here.
The next (possible) problem is (again laziness) that you don't evaluate the mapped-to values when putting them in the Map, so if there is a line length that occurs particularly often, that value becomes a huge thunk
((...((1+1)+1)...+1)+1)

Make it
main = do
  content <- readFile "output.csv"
  print $ (foldl' count M.empty . map length . lines) content

count mp a = M.insertWith' (+) a 1 mp

so that the lines can be garbage collected as soon as they have been read in, and no thunks can build up in the values. That way you never need more than one line of the file in memory at once, and even that need not be in memory entirely, since the length is evaluated before it is recorded in the Map.
If your containers package is recent enough, you could also
import Data.Map.Strict

and leave count using insertWith (without prime, the Data.Map.Strict module always evaluates values put into the map).

A: One way to get max residency down is to use IntMap instead of Map, which is a specialized version of the Map data structure for Int keys. It's a simple change:
import Control.Applicative
import qualified Data.IntMap as I
import Data.List

main = do
  content <- readFile "output.csv"
  print $ (foldr count I.empty . map length . lines) content

count a b = I.insertWith (+) a 1 b

Comparing this version against yours using /usr/share/dict/words saw max residency go from about 100MB to 60MB. Note that this was also without any optimization flags. If you crank those, max residency will very likely see further improvement.


text:
Q: How android ROMS based on TouchWiz work if TouchWiz source code is not available as opensource? Source code of samsung-touchwiz is not available to public to download and use. But there are custom roms which have touchwiz UI available .How do touch-wiz based roms like Salman rom work without having samsung touch-wiz code?

A: TouchWiz gets shipped as an *.APK on Samsung Smartphones. So  if you want to integrate the TouchWizUI, you just have to integrate the APK into your rom and voila, you got a touchWiz based android rom.
Edit: Maybe you'll need to integrate the framework-res.apk also to keep the style consistent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove islands smaller than a given radius and specify minimum gap between islands I have some data that I have segmented into a number of classes in Python 3.5. The resulting image is the following
Original image

There are a lot of small islands within the data that I want to remove. I've circled a few of them to give an idea below, but there are many.
Original image with some noise circled

The idea is that I want to be able to specify a minimum radius below which a noise island should be deleted.
I have tried a few different approaches using scikit-image morphology filters. I have tried combining grayscale closing and opening filters (shown in the image below), and I have also tried using the remove_small_objects filter and treating each pair of classes separately and combining them at the end. They do work at removing the noise islands (shown below), but this creates a new problem. There are thin boundaries between some of the islands, which I don't want either!
Image with grayscale opening applied and thin areas circled

So basically, I want to remove the noise islands but also have a minimum gap between each island.
Any help would be much appreciated.
EDIT:
Some clarification on the desired result:
The desired result is to obtain an image where there are no blobs smaller than a certain radius, and also that the thin boundaries between blobs below a certain thickness are filled in or removed. A mockup of what I'm looking for is shown here:
Desired result

A: Dilation and erosion (the processes that are performed by opening and closing) are the standard approach for filtering small noise patches, but for long and snaky regions they can cause the issues you are experiencing with the creation of thin regions and boundaries. Rather than dilation and erosion, you can instead try filtering based on explicit connected component size. Skimage has the function skimage.morphology.label which labels your connected components, and skimage.morphology.remove_small_objects which removes any connected components with size below a certain threshold.


text:
Q: How do I insert a JavaScript variable into a string containing Jinja markup? I have a javascript function that is trying to dynamically insert an anchor tag into a webpage, the href attr of which being a url for a flask route. This flask route accepts an argument username. I want to set username to the value of a javascript variable.
I have tried using template literals:
let username = 'user1';
let href = `{{ url_for("some.route", username=${username}) }}`

$("#elem").append('');

which throws a jinja2.exceptions.TemplateSyntaxError: unexpected char '$' error.
I've also tried string concatenation:
let username = 'user1';
let href = '{{ url_for("some.route", username=' + username + ')}}'

$("#elem").append('');

which results in the literal string + username + being passed to the route.
Any ideas on how to do this?


text:
Q: How to get FileId or OwnerId or CustomAttribut in Qbwc file in wsdl implementation I am thinking of how I can fetch fileId or ownerId or any custom attribute in any or all wsdl methods. I am thinking to create generic qbwc file.
    <?xml version="1.0"?>
<QBWCXML>
 <AppName>WCWebService1</AppName>
 <AppID></AppID>
 <AppURL>http://localhost:8000/wsdl </AppURL>
 <AppDescription>A short description for WCWebService1</AppDescription>
 <AppSupport>http://developer.intuit.com</AppSupport>
 <UserName>Admin</UserName>
 <OwnerID>{57F3B9B1-86F1-4fcc-B1EE-566DE1813D20}</OwnerID>
 <FileID>{90A 44FB5-33D9-4815-AC85-BC87A7E7D1EB}</FileID>
 <QBType>QBFS</QBType>
 <Scheduler>
 <RunEveryNMinutes>2</RunEveryNMinutes>
 </Scheduler>
</QBWCXML>

Not sure how to get those attribute. Was able to get ticketid in all of them but that is random uuid creating after auth.

A: Take a look at https://developer.intuit.com/app/developer/qbdesktop/docs/api-reference/qbdesktop/companyquery
You can add OwnerID to the Company Query and you should receive it on the DataExtRet key on the response
<CompanyQueryRq>
        <IncludeRetElement >STRTYPE</IncludeRetElement> <!-- optional, may repeat -->
        <OwnerID >GUIDTYPE</OwnerID> <!-- optional, may repeat -->
</CompanyQueryRq>

In my case, I opted to use a JWT for the password so I'm using that to identify the user and issue a session JWT (sent as ticket)


text:
Q: How exactly can I overload the '{' operator? To initialize an std::vector, I can directly use the initializer_list, like so:
std::vector<int> myVec = {1, 2, 3, 4};

If i create a custom List Class (which will hold a number of items), for example class customVector (for simplicity only with ints, I think I could figure out how to do it with templates myself, if necessary), can I overload the operator '{' in such a way that an instance of customVector can be initialized in the same matter? So that I could write
customVector myCustomVec = {1, 2, 3, 4}

A: You can accomplish what you ultimately want, but not by overloading any operators – { is not an operator.
vector does this by having a constructor that takes an initializer_list parameter, and you can do the same with your class.
Learning how to do it and implementing it left as an exercise.

A: You cannot, since { is not an operator. Up to C++20, the following operators were overridable:
+    -    *    /    %    ^    &    |    ~    !    =
<    >    +=   -=   *=   /=   %=   ^=   &=   |=   <<
>>   >>=  <<=  ==   !=   <=   >=   &&   ||   ++   --
,    ->*  ->   ()   []

C++20 added the spaceship operator <=> but I believe that's it.

A: As the others have pointed at, { is not an operator. However, you can still use the initializer list as you like. It's a part of the standard library.
#include <iostream>
#include <initializer_list>
using namespace std;

template <typename T>
struct customVector {
    customVector(std::initializer_list<T> list) : size(list.size()) {
        arr = new T[size];
        int count = 0;
        for(auto val: list) arr[count++] = val;
    }
    T* arr;
    std::size_t size;

    ~customVector() {
        for(int i = 0; i < size; i++)
            std::cout << arr[i] << std::endl;
        delete [] arr;
    }
};

int main() {
    customVector<int> myCustomVec = {1, 2, 3, 4};
}


text:
Q: Is it possible to call 2 dependent api's in one scenario of cucumber feature file I have a requirement to call 2 dependent api's in one scenario.
Below steps I have done.
Feature: Verify the output.
     Background: Generate the token
       Given I use the <token-endpoint> with <username> and <password>
       When I send "POST" request to get the token
       Then I should receive the token
Scenario: 1. <Statement>
    Given I use the <token> endpoint with token
    When I send a "POST" request to the <**first**> api
    And I store the response in file1.json
    Given I use the <token> endpoint with token
    When I send a "POST" request to the <**second**> api
    And I store the response in file2.json
    Then the status should be 200.

<first> api is able to read the token but <second> api is not able to read the token resulting into "Forbidden" error.
NOTE : <Second> api is dependent on <first> api and using the same token.


text:
Q: Variable input arguments in PHP I have an half PHP/half algorithmic question. I will have random inputs between 0 and 4. they will be used in the same query such as
  <?php  SELECT * FROM `table` WHERE inputs in (input0,input1,input2)  //for 3 inputs
          SELECT * FROM `table` WHERE inputs in (input0,input1)  //for 2 inputs
         //do nothing for zero inputs ?>

I believe this is the start point.
 <?php
 function myfunc(){
   $args = func_get_args();
  foreach ($args as $arg)
   echo $arg."/n";
 }
  myfunc('hello', 'world', '.');
      ?>

Now I think I can run the foreach loop n times for n individual inputs but I couldn't figure out how to use them in the query effectively. Can I create an array and pass it somehow to the query as inputs?
thanks
arda

A: You could also pass your function an array:
function myfunc(array('input2','input1'));

But to answer your question using func_get_args:
<?php
function buildQuery() {
    $args = func_get_args();

    $q = implode(', ',$args);

    return 'SELECT * FROM `table` WHERE inputs in ('.$q.');';
}

echo buildQuery('input0','input1');
?>

Outputs:

SELECT * FROM table WHERE inputs in (input0, input1);

A: Don't forget to sanitize your inputs first before you use them in a query. Try this
$i = impode(", ", array_map(function($a) {
   return '"' . mysql_real_escape_string($a) . '"';
}, func_get_args());

and then replace (input0,input1) with content of $i like this
$q = "SELECT * FROM `table` WHERE inputs in " . $i;


text:
Q: VBA No resultset from stored procedure that backups database I need to execute a stored procedure that make some changes to a specific database and back it up at the same time. For some reason, when the backup code is active, in VBA's recordset I don't get any row but the backup is effectively created.
The recordset comes closed and Err.Description is "Operation is not allowed when the object is closed." If I comment the backup code in the stored procedure, the recordset comes opened I get the 1 row with the results.
In the vb code I am calling the stored procedure with adAsyncExecute and waiting using the following code:
Any Idea why the recordset comes closed and does not return 1 row when executing successfully the sp?
Edit:
If I execute the sp in SSMS with exec, it works and I can see the row with the values.

12.01.2015

*

*I found exactly the same issue for another user but no solution
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/7e05bc02-4681-4d08-9c21-b90d5730c7e6/receiving-recordsetresultset-from-sql-server?forum=sqlexpress

*I tried to execute the sp  in synchronous mode and I face the same issue

*It is not a timeout problem. Currently command's timeout is 180 seconds  and the sp takes around 40 seconds to finish.
VB code:
             sDB = "master"
             TrustedConnection = True
             ReDim arrPara(1, 2)
             arrPara(0, 1) = sStandardDatabaseSTR: arrPara(1, 1) = "@DATABASE"
             arrPara(0, 2) = 1: arrPara(1, 2) = "@STEP"
             Set rs = ADO_OpenParameterQuerySTR("dbo.Frozen_Generation", adCmdStoredProc, arrPara, , True)
             Do While rs.ActiveCommand.State = adStateExecuting 'or 4
                'sleep 1000
                DoEvents
             Loop
             rs.MoveFirst <-- Here I got the closed recordset when using the backup block

ADO_OpenParameterQuerySTR code:
Function ADO_OpenParameterQuerySTR(ByVal sSQL As String, CommandType As CommandTypeEnum, Optional arrParameter As Variant, Optional iQueryTimeout As Variant, Optional async As Boolean = False) As ADODB.Recordset
   On Error GoTo errHandler
   LogToFile currentModule, "ADO_OpenParameterQuerySTR", "exec " & sSQL & " " & SerializeArray(arrParameter)
   Dim cmd As New ADODB.Command
   Dim para As ADODB.Parameter
   Dim blFound As Boolean
   Dim i As Variant, j As Variant, iType As Variant

Start:
    cmd.ActiveConnection = DBconnSTR

    cmd.CommandType = CommandType
    cmd.CommandText = sSQL
    cmd.CommandTimeout = 180

    If Not IsMissing(iQueryTimeout) Then
      cmd.CommandTimeout = iQueryTimeout
    End If

    If blDebugSTR Then Debug.Print sSQL

    If CommandType = 4 Then
        If Not IsMissing(arrParameter) Then
            blFound = False
            For i = 0 To cmd.Parameters.Count - 1
                If cmd.Parameters(i).Name <> "@RETURN_VALUE" Then
                    For j = 0 To UBound(arrParameter, 2)
                        If cmd.Parameters(i).Name = arrParameter(1, j) Then
                            cmd.Parameters(i) = IIf(arrParameter(0, j) = "", Null, arrParameter(0, j))

                            #If DEBUG_MODUS = 1 Then
                              Debug.Print cmd.Parameters(i).Name & " - " & cmd.Parameters(i).value
                           #End If
                            blFound = True
                        End If
                    Next
                End If

            Next
            If cmd.Parameters.Count = 0 And UBound(arrParameter, 2) >= 0 Then
                For i = 0 To UBound(arrParameter, 2)
                    If Not IsNumeric(arrParameter(0, i)) Then
                     'adVarBinary
                        If TypeName(arrParameter(0, i)) = "Byte()" Then
                           iType = adLongVarBinary
                        Else
                           iType = adVarChar
                        End If
                    Else
                        iType = adInteger
                    End If

                    Set para = cmd.CreateParameter(arrParameter(1, i), iType, adParamInput, 250)
                    cmd.Parameters.Append para
                    cmd.Parameters(arrParameter(1, i)) = arrParameter(0, i)
                Next
            End If
        End If
    End If
    If InStr(1, sSQL, "?", vbTextCompare) > 0 Then
        For i = 0 To UBound(arrParameter, 2)
            cmd.Parameters(i) = arrParameter(0, i)
        Next
    End If

    Set ADO_OpenParameterQuerySTR = New ADODB.Recordset
    If (async) Then
        ADO_OpenParameterQuerySTR.Open cmd, , adOpenStatic, adLockOptimistic, adAsyncExecute
    Else
        ADO_OpenParameterQuerySTR.Open cmd, , adOpenStatic, adLockOptimistic
    End If

exit_me:
   On Error GoTo 0
   Exit Function

errHandler:
   LogToFile currentModule, "ADO_OpenParameterQuerySTR", Err.Number & ", " & Err.Description
   Debug.Print Err.Number & ", " & Err.Description
   If Err.Number = -2147467259 Then
      Set m_ADO_STR = Nothing
      Application.Wait (Now + TimeValue("0:00:01"))
      Resume Start
   End If
   If Err.Number = 3709 Then Resume Start
   If Err.Number = -2147217911 Then
      'No Rights to Execute
      MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ADO_OpenParameterQuerySTR of Modul mdlDatabase"
   End If
   If Err.Number = -2147217871 Then
      MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ADO_OpenParameterQuerySTR of Modul mdlDatabase"
   End If

   Resume exit_me
   Resume

End Function

SP code:
ALTER PROCEDURE [dbo].[Frozen_Generation]
(
    @DATABASE as varchar(100),
    @STEP as int
)
AS
--general
DECLARE @ParmDefinition NVARCHAR(500);
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @now DateTime

DECLARE @resStep1_1 int
DECLARE @resStep1_2 int
DECLARE @resStep1_1_ERR varchar(200)
DECLARE @resStep1_2_ERR varchar(200)

--backup
DECLARE @fileName VARCHAR(90);
DECLARE @db_name VARCHAR(20);
DECLARE @fileDate VARCHAR(20);

BEGIN
    SET NOCOUNT ON;

    SET @now = GETDATE()

    if (@STEP=1) begin

        SET @ParmDefinition = N'@SettingsValueBIT int, @SettingsName varchar(100), @UpdatedOn smalldatetime';
        SET @SQLQuery =
        N'use ' + @DATABASE + ';
        UPDATE dbo.A_ConfigSettings set SettingsValueBIT=@SettingsValueBIT, UpdatedOn=@UpdatedOn  where SettingsName=@SettingsName'
        EXECUTE @resStep1_1 = sp_executesql @SQLQuery, @ParmDefinition, @SettingsValueBIT=0, @SettingsName='APP_Status',@UpdatedOn=@now;

        -- Make backup (If I comment this block, I got 1 row in the recordset)
        BEGIN TRY
            SET @fileName = 'E:\backups\'; -- change to the relevant path
            SET @db_name = 'frozenwizard';     -- change to the relevant database name
            SET @fileDate = CONVERT(VARCHAR(20), GETDATE(),112);
            SET @fileName = @fileName + @db_name + '_' + RTRIM(@fileDate) + '.bak';
            SET @SQLQuery = N'BACKUP DATABASE '+@DATABASE+' TO DISK = ''' + @fileName + ''''
            EXECUTE @resStep1_2 = sp_executesql @SQLQuery
        END TRY
        BEGIN CATCH
            SELECT @resStep1_2=ERROR_NUMBER(), @resStep1_2_ERR=ERROR_MESSAGE();
        END CATCH

        SELECT
         @resStep1_1 as resStep1_1, coalesce(@resStep1_1_ERR,'') as resStep1_1_ERR
         @resStep1_2 as resStep1_2, coalesce(@resStep1_2_ERR,'') as resStep1_2_ERR

    end

END


text:
Q: Typing a letter into a number array I have this simple project where I'm supposed to create 4 arrays and enter employee's data into, the arrays are: The employee's ID, their salary, the salary cuts, and the net salary. I am also supposed to print the average salary, the ID # of the employee with the highest salary, and the ID # of the employee with the lowest cut.
The code works fine, except if I enter a letter, then it just executes the whole program in a weird way (no formatting, random numbers).
Why is that? The letter gets converted to an integer, right? What causes it to stop working properly?
Also, would you mind looking at the coding style I used and telling me if there's a way I can improve it?
#include <stdio.h>

#define SIZE 100

int main(void){
    int n; /*Number of employees*/
    float average; /*Average of the employee's salary*/
    int max; /*Highest salary*/
    int min; /*Minimum cut*/
    int i;
    int employee_number = 1;; /*The number (index +1) of the employee*/
    float sum = 0; /*The sum of the employee's salary*/
    int num_highest; /*The number of the employee with the highest
    salary*/
    int num_lowest; /*The number of the employee with the lowest cut*/

int id_number[SIZE]; /*Array to hold employee's IDs in*/
float salary[SIZE]; /*Array for employee's salaries*/
float cuts[SIZE]; /*Array for salary cuts*/
float net_salary[SIZE]; /*Net salary after cuts*/

printf("Enter the number of employees\t");
scanf("%i", &n);

for(i = 0; i < n; i++){
    printf("Enter the ID of employee #%i\t", employee_number);
    scanf("%i", &id_number[i]);

    printf("Enter the salary of employee #%i\t", employee_number);
    scanf("%f", &salary[i]);

    printf("Enter the salary cut of employee #%i\t", employee_number);
    scanf("%f", &cuts[i]);

    employee_number++;
}

for(i = 0; i < n; i++){
    net_salary[i] = salary[i] - (salary[i] * cuts[i] * 1/100);
}

for(i = 0; i < n; i++){
    sum += net_salary[i];
}

average = sum/(float)n;
printf("The average salary is %.2f\n", average);

max = net_salary[0];
min = cuts[0];

for(i = 0; i < n; i++){
    if(net_salary[i] > max){
        max = net_salary[i];
        num_highest = i;
    }
    if(cuts[i] <= min){
        min = cuts[i];
        num_lowest = i;
    }
}

printf("Employee with ID # %i has the highest salary which is %i\n", id_number[num_highest], max);

printf("Employee with ID # %i has the lowest cut of %i and a base salary of %.2f", id_number[num_lowest], min, salary[num_lowest]);

}

A: You should check the value returned by every call to function scanf.
If this value is smaller than the number of input arguments that the function is supposed to obtain from the user, then it has failed and you should call it again.

A: In terms of coding style, you can use a struct to store information about each employee, and create an employees[] array of structs that way. This helps in organizing your code better, and avoids having to use 4 separate arrays to store information about the employees.
The struct can look like this:
typedef struct {
    int id_number;
    float salary;
    float cuts;
    float net_salary;
} employee_t;

And then you can create an array of structs like this:
employee_t employees[n]; /* n is number of employees */

It is also good to check the return of scanf().
So instead of doing simply:
scanf("%i", &n);

Be extra careful and change this to:
if (scanf("%i", &n) != 1) {
    /*exit program if true */
}

I wrote some code to demonstrate these points:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id_number;
    float salary;
    float cuts;
    float net_salary;
} employee_t;

void get_number_employees(int *n);
void get_user_input(employee_t employees[], int n, float *average);
void print_results(employee_t employees[], int n, float average);
int highest_salary(employee_t employees[], int n);
int lowest_cut(employee_t employees[], int n);

int
main(void) {
    int n;
    float average;

    get_number_employees(&n);

    employee_t employees[n];

    get_user_input(employees, n, &average);

    print_results(employees, n, average);;

    return 0;
}

void
get_number_employees(int *n) {
    printf("Enter number of employees: ");
    if (scanf("%d", n) != 1) {
        printf("Invalid number.\n");
        exit(EXIT_FAILURE);
    }
}

void
print_results(employee_t employees[], int n, float average) {
    int high_sal, low_cut;

    high_sal = highest_salary(employees, n);
    low_cut = lowest_cut(employees, n);

    printf("The average salary is %f\n", average);

    printf("Employee with ID # %d has the highest salary which is %f\n",
            employees[high_sal].id_number, employees[high_sal].net_salary);

    printf("Employee with ID # %d has the lowest cut of %f and a base salary of %f\n",
            employees[low_cut].id_number, employees[low_cut].cuts, employees[low_cut].salary);
}

void
get_user_input(employee_t employees[], int n, float *average) {
    int i, employee_number = 1, sum = 0;

    for (i = 0; i < n; i++) {

        printf("Enter the ID of employee #%d: ", employee_number);
        if (scanf("%d", &(employees[i].id_number)) != 1) {
            printf("Invalid number.\n");
            exit(EXIT_FAILURE);
        }

        printf("Enter the salary of employee #%d: ", employee_number);
        if (scanf("%f", &(employees[i].salary)) != 1) {
            printf("Invalid salary.\n");
            exit(EXIT_FAILURE);
        }

        printf("Enter the salary cut of employee #%d: ", employee_number);
        if (scanf("%f", &(employees[i].cuts)) != 1) {
            printf("Invalid cuts.\n");
            exit(EXIT_FAILURE);
        }

        employees[i].net_salary = employees[i].salary - (employees[i].salary * employees[i].cuts * 1/100);

        sum += employees[i].net_salary;

        employee_number++;
    }

    *average = (1.0f * sum)/n;
}

int
highest_salary(employee_t employees[], int n) {
    float max;
    int i, idx;

    max = employees[0].net_salary;
    for (i = 1; i < n; i++) {
        if (employees[i].net_salary > max) {
            max = employees[i].net_salary;
            idx = i;
        }
    }
    return idx;
}

int
lowest_cut(employee_t employees[], int n) {
    float min;
    int i, idx;

    min = employees[0].cuts;
    for (i = 1; i < n; i++) {
        if (employees[i].cuts < min) {
            min = employees[i].cuts;
            idx = i;
        }
    }
    return idx;
}

A: Letters are char or char* when taken as input for many C and C++ functions. char can generally be output to the console as an ASCII encoded digit or as an integer value.
char can be cast into int very easily in C because it's actually considered a numeric value. For example, A becomes 41, and B becomes 42.


text:
Q: Numpy array with the given values and the sum equal 1 I want to create random np.array with values including only [0.05, 0.1, 0.15, ... 0.9, 0.95, 1] with the sum of the values = 1
I know how to create a random array, for example, of 5 elements, so that the sum is equal to 1:
array = np.random.random(5)
array /= np.sum(array)

But how can I make that the values in this array are only from [0.05, 0.1, 0.15, ... 0.9, 0.95, 1]?
Upd. This method works, but maybe there are more pythonic ways. 100 arrays
sets = []
while len(sets) < 100:
    array = np.random.choice(np.arange(0, 1.05, 0.05), 5)
    if np.sum(array) == 1:
        sets.append(array)

A: Your problem is equivalent to the following problem:

*

*Choose 5 random integers in [1, 20] with a sum of 20, where the integers appear in random order.

*Divide the chosen integers by 20.

The Python code below shows how this can be implemented. It has the following advantages:

*

*It does not use rejection sampling.

*It chooses uniformly at random from among all combinations that meet the requirements.

It's based on an algorithm by John McClane, which he posted as an answer to another question.  I describe the algorithm in another answer.
import random # Or secrets

def _getSolTable(n, mn, mx, sum):
        t = [[0 for i in range(sum + 1)] for j in range(n + 1)]
        t[0][0] = 1
        for i in range(1, n + 1):
            for j in range(0, sum + 1):
                jm = max(j - (mx - mn), 0)
                v = 0
                for k in range(jm, j + 1):
                    v += t[i - 1][k]
                t[i][j] = v
        return t

def intsInRangeWithSum(numSamples, numPerSample, mn, mx, sum):
        """ Generates one or more combinations of
           'numPerSample' numbers each, where each
           combination's numbers sum to 'sum' and are listed
           in any order, and each
           number is in the interval '[mn, mx]'.
            The combinations are chosen uniformly at random.
               'mn', 'mx', and
           'sum' may not be negative.  Returns an empty
           list if 'numSamples' is zero.
            The algorithm is thanks to a _Stack Overflow_
          answer (`questions/61393463`) by John McClane.
          Raises an error if there is no solution for the given
          parameters.  """
        adjsum = sum - numPerSample * mn
        # Min, max, sum negative
        if mn < 0 or mx < 0 or sum < 0:
            raise ValueError
        # No solution
        if numPerSample * mx < sum:
            raise ValueError
        if numPerSample * mn > sum:
            raise ValueError
        if numSamples == 0:
            return []
        # One solution
        if numPerSample * mx == sum:
            return [[mx for i in range(numPerSample)] for i in range(numSamples)]
        if numPerSample * mn == sum:
            return [[mn for i in range(numPerSample)] for i in range(numSamples)]
        samples = [None for i in range(numSamples)]
        table = _getSolTable(numPerSample, mn, mx, adjsum)
        for sample in range(numSamples):
            s = adjsum
            ret = [0 for i in range(numPerSample)]
            for ib in range(numPerSample):
                i = numPerSample - 1 - ib
                # Or secrets.randbelow(table[i + 1][s])
                v = random.randint(0, table[i + 1][s] - 1)
                r = mn
                v -= table[i][s]
                while v >= 0:
                    s -= 1
                    r += 1
                    v -= table[i][s]
                ret[i] = r
            samples[sample] = ret
        return samples

Example:
weights=intsInRangeWithSum(
   # One sample
   1,
   # Count of numbers per sample
   5,
   # Range of the random numbers
   1, 20,
   # Sum of the numbers
   20)
# Divide by 100 to get weights that sum to 1
weights=[x/20.0 for x in weights[0]]

In any case, your code below:
array = np.random.random(5)
array /= np.sum(array)

...does not result in a uniform random combination of numbers with a sum of 1.  Instead, use the following instead of that code, noting that uniform arrivals are exponentially spaced, not uniformly spaced. (To be clear, this does not solve the problem in your question; this is only an observation.  Never mind the fact that numpy.random.* functions are now legacy functions since NumPy 1.17, in part because they use global state.)
array = np.random.exponential(5)
array /= np.sum(array)


text:
Q: Adding headers to ORION inquiries I'm currently working in an environment where several ORION Context Brokers (OCBs) are deployed and I'm guessing how to include headers in the enquiries.
I mean, when one of the OCBs communicates with other OCB and wants to add additional headers, how it should be handled (if there is a way to)?
Thanks!

A: If the comunication is done using notifications (i.e. OCB1 is subscribed to OCB2, so OCB1 receives notifications from OCB2), you could use the NGSIv2 custom notifications functionality in order to include custom headers.
See "Custom notifications" section in the NGSIv2 specification document. Pay special attention to the headers field within httpCustom.


text:
Q: pjsip pjsua USB SoundCard choopy the pjsua runs in openwrt, we use USB SoundCard.
When we answer a call, allways choopy, both the capture and the playback are not work well!
Tips:We have use auddemo tested my soundcard, recoreding/playing are good, and the capture id is 8, playback id is 1.
thank you~~
below is logs:
11:58:06.357    dlg0xdb687c  .Received Request msg ACK/cseq=103 (rdata0xdb3ecc)
11:58:06.360   strm0xe038dc !Start talksprut..
11:58:06.361          speex  warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:06.363     alsa_dev.c  pb_thread_func: underrun!
11:58:06.587   Master/sound !160 samples reduced, buf_cnt=1888
11:58:06.587   Master/sound  Buffer size adjusted from 2048 to 1888 (eff_cnt=1280)
11:58:06.588     alsa_dev.c  ca_thread_func: overrun!
11:58:06.756     alsa_dev.c  ca_thread_func: overrun!
11:58:06.968   Master/sound  228 samples reduced, buf_cnt=1980
11:58:06.968   Master/sound  Buffer size adjusted from 2208 to 1980 (eff_cnt=1280)
11:58:06.968     alsa_dev.c  ca_thread_func: overrun!
11:58:06.981          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:07.083   Master/sound  317 samples reduced, buf_cnt=1983
11:58:07.083     alsa_dev.c  ca_thread_func: overrun!
11:58:07.098          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:07.321   Master/sound !280 samples reduced, buf_cnt=1703
11:58:07.321   Master/sound  Buffer size adjusted from 1983 to 1703 (eff_cnt=1280)
11:58:07.321     alsa_dev.c  ca_thread_func: overrun!
11:58:07.493     alsa_dev.c  ca_thread_func: overrun!
11:58:07.505          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:07.707   Master/sound !182 samples reduced, buf_cnt=2161
11:58:07.711     alsa_dev.c  ca_thread_func: overrun!
11:58:07.506     alsa_dev.c !pb_thread_func: underrun!
11:58:07.936   Master/sound !376 samples reduced, buf_cnt=1785
11:58:07.937   Master/sound  Buffer size adjusted from 2161 to 1785 (eff_cnt=1280)
11:58:07.937     alsa_dev.c  ca_thread_func: overrun!
11:58:07.950          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:08.001          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:08.099   Master/sound  467 samples reduced, buf_cnt=1958
11:58:08.100     alsa_dev.c  ca_thread_func: overrun!
11:58:08.108          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:08.331   Master/sound !390 samples reduced, buf_cnt=1568
11:58:08.332   Master/sound  Buffer size adjusted from 1958 to 1568 (eff_cnt=1280)
11:58:08.332     alsa_dev.c  ca_thread_func: overrun!
11:58:08.508     alsa_dev.c  ca_thread_func: overrun!
11:58:08.521          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:08.574          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:08.677   Master/sound  320 samples reduced, buf_cnt=2208
11:58:08.677     alsa_dev.c  ca_thread_func: overrun!
11:58:08.688          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:08.915   Master/sound !499 samples reduced, buf_cnt=2029
11:58:08.915     alsa_dev.c  ca_thread_func: overrun!
11:58:09.128   Master/sound  193 samples reduced, buf_cnt=1836
11:58:09.128   Master/sound  Buffer size adjusted from 2029 to 1836 (eff_cnt=1280)
11:58:09.129     alsa_dev.c  ca_thread_func: overrun!
11:58:09.142          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:09.197          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:09.300   Master/sound  257 samples reduced, buf_cnt=2219
11:58:09.300     alsa_dev.c  ca_thread_func: overrun!
11:58:09.308          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:09.309     alsa_dev.c  pb_thread_func: underrun!
11:58:09.523   Master/sound !427 samples reduced, buf_cnt=1792
11:58:09.523   Master/sound  Buffer size adjusted from 2219 to 1792 (eff_cnt=1280)
11:58:09.523     alsa_dev.c  ca_thread_func: overrun!
11:58:09.718     alsa_dev.c  ca_thread_func: overrun!
11:58:09.731          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:09.832   Master/sound  297 samples reduced, buf_cnt=2135
11:58:09.833     alsa_dev.c  ca_thread_func: overrun!
11:58:09.845          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:10.080   Master/sound !160 samples reduced, buf_cnt=1975
11:58:10.080   Master/sound  Buffer size adjusted from 2135 to 1975 (eff_cnt=1280)
11:58:10.080     alsa_dev.c  ca_thread_func: overrun!
11:58:10.316   Master/sound  110 samples reduced, buf_cnt=2185
11:58:10.316     alsa_dev.c  ca_thread_func: overrun!
11:58:10.329          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:10.427   Master/sound  527 samples reduced, buf_cnt=1978
11:58:10.427          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:10.530   Master/sound  142 samples reduced, buf_cnt=2156
11:58:10.531     alsa_dev.c  ca_thread_func: overrun!
11:58:10.538          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:10.768   Master/sound !169 samples reduced, buf_cnt=1987
11:58:10.768   Master/sound  Buffer size adjusted from 2156 to 1987 (eff_cnt=1280)
11:58:10.769     alsa_dev.c  ca_thread_func: overrun!
11:58:11.004   Master/sound  67 samples reduced, buf_cnt=2240
11:58:11.005     alsa_dev.c  ca_thread_func: overrun!
11:58:11.017          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:11.117   Master/sound  439 samples reduced, buf_cnt=2121
11:58:11.118     alsa_dev.c  ca_thread_func: overrun!
11:58:11.124          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:11.125     alsa_dev.c  pb_thread_func: underrun!
11:58:11.349   Master/sound !162 samples reduced, buf_cnt=1959
11:58:11.349   Master/sound  Buffer size adjusted from 2121 to 1959 (eff_cnt=1280)
11:58:11.349     alsa_dev.c  ca_thread_func: overrun!
11:58:11.574   Master/sound  39 samples reduced, buf_cnt=2240
11:58:11.575     alsa_dev.c  ca_thread_func: overrun!
11:58:11.584          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:11.809   Master/sound !423 samples reduced, buf_cnt=1817
11:58:11.810   Master/sound  Buffer size adjusted from 2240 to 1817 (eff_cnt=1280)
11:58:11.810     alsa_dev.c  ca_thread_func: overrun!
11:58:11.984     alsa_dev.c  ca_thread_func: overrun!
11:58:11.998          speex  warning: No playback frame available (your application is buggy and/or got xruns)
11:58:12.106   Master/sound  224 samples reduced, buf_cnt=2233
11:58:12.106     alsa_dev.c  ca_thread_func: overrun!
11:58:12.115          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:12.328   Master/sound !295 samples reduced, buf_cnt=1938
11:58:12.329   Master/sound  Buffer size adjusted from 2233 to 1938 (eff_cnt=1280)
11:58:12.329     alsa_dev.c  ca_thread_func: overrun!
11:58:12.564   Master/sound  31 samples reduced, buf_cnt=2227
11:58:12.565     alsa_dev.c  ca_thread_func: overrun!
11:58:12.573          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:12.574     alsa_dev.c  pb_thread_func: underrun!
11:58:12.803   Master/sound !368 samples reduced, buf_cnt=1859
11:58:12.804   Master/sound  Buffer size adjusted from 2227 to 1859 (eff_cnt=1280)
11:58:12.804     alsa_dev.c  ca_thread_func: overrun!
11:58:12.990     alsa_dev.c  ca_thread_func: overrun!
11:58:13.002          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:13.223   Master/sound !568 samples reduced, buf_cnt=1931
11:58:13.223     alsa_dev.c  ca_thread_func: overrun!
11:58:13.469   Master/sound  416 samples reduced, buf_cnt=1515
11:58:13.469   Master/sound  Buffer size adjusted from 1931 to 1515 (eff_cnt=1280)
11:58:13.470     alsa_dev.c  ca_thread_func: overrun!
11:58:13.474          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:13.658     alsa_dev.c !ca_thread_func: overrun!
11:58:13.826     alsa_dev.c  ca_thread_func: overrun!
11:58:13.833          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:13.834     alsa_dev.c  pb_thread_func: underrun!
11:58:14.041   Master/sound !450 samples reduced, buf_cnt=1385
11:58:14.041   Master/sound  Buffer size adjusted from 1835 to 1385 (eff_cnt=1280)
11:58:14.041     alsa_dev.c  ca_thread_func: overrun!
11:58:14.216     alsa_dev.c  ca_thread_func: overrun!
11:58:14.223          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:14.433   Master/sound !169 samples reduced, buf_cnt=1536
11:58:14.434   Master/sound  Buffer size adjusted from 1705 to 1536 (eff_cnt=1280)
11:58:14.434     alsa_dev.c  ca_thread_func: overrun!
11:58:14.606     alsa_dev.c  ca_thread_func: overrun!
11:58:14.613          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:14.843   Master/sound !459 samples reduced, buf_cnt=1397
11:58:14.843   Master/sound  Buffer size adjusted from 1856 to 1397 (eff_cnt=1280)
11:58:14.844     alsa_dev.c  ca_thread_func: overrun!
11:58:15.023     alsa_dev.c  ca_thread_func: overrun!
11:58:15.032          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:15.033     alsa_dev.c  pb_thread_func: underrun!
11:58:15.254   Master/sound !454 samples reduced, buf_cnt=1263
11:58:15.254   Master/sound  Buffer size adjusted from 1717 to 1263 (eff_cnt=1280)
11:58:15.254     alsa_dev.c  ca_thread_func: overrun!
11:58:15.448     alsa_dev.c  ca_thread_func: overrun!
11:58:15.455          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:15.636     alsa_dev.c !ca_thread_func: overrun!
11:58:15.808     alsa_dev.c  ca_thread_func: overrun!
11:58:15.814          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:16.029   Master/sound !300 samples reduced, buf_cnt=1603
11:58:16.030   Master/sound  Buffer size adjusted from 1903 to 1603 (eff_cnt=1280)
11:58:16.030     alsa_dev.c  ca_thread_func: overrun!
11:58:16.195     alsa_dev.c  ca_thread_func: overrun!
11:58:16.204          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:16.205     alsa_dev.c  pb_thread_func: underrun!
11:58:16.429   Master/sound !369 samples reduced, buf_cnt=1554
11:58:16.430   Master/sound  Buffer size adjusted from 1923 to 1554 (eff_cnt=1280)
11:58:16.430     alsa_dev.c  ca_thread_func: overrun!
11:58:16.609     alsa_dev.c  ca_thread_func: overrun!
11:58:16.617          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:16.851   Master/sound !399 samples reduced, buf_cnt=1475
11:58:16.851   Master/sound  Buffer size adjusted from 1874 to 1475 (eff_cnt=1280)
11:58:16.852     alsa_dev.c  ca_thread_func: overrun!
11:58:17.037     alsa_dev.c  ca_thread_func: overrun!
11:58:17.047          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:17.268   Master/sound !461 samples reduced, buf_cnt=1334
11:58:17.268   Master/sound  Buffer size adjusted from 1795 to 1334 (eff_cnt=1280)
11:58:17.269     alsa_dev.c  ca_thread_func: overrun!
11:58:17.460     alsa_dev.c  ca_thread_func: overrun!
11:58:17.469          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:17.470     alsa_dev.c  pb_thread_func: underrun!
11:58:17.681   Master/sound !215 samples reduced, buf_cnt=1439
11:58:17.681   Master/sound  Buffer size adjusted from 1654 to 1439 (eff_cnt=1280)
11:58:17.682     alsa_dev.c  ca_thread_func: overrun!
11:58:17.859     alsa_dev.c  ca_thread_func: overrun!
11:58:17.867          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:18.089   Master/sound !350 samples reduced, buf_cnt=1409
11:58:18.089   Master/sound  Buffer size adjusted from 1759 to 1409 (eff_cnt=1280)
11:58:18.089     alsa_dev.c  ca_thread_func: overrun!
11:58:18.274     alsa_dev.c  ca_thread_func: overrun!
11:58:18.284          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:18.511   Master/sound !254 samples reduced, buf_cnt=1475
11:58:18.511   Master/sound  Buffer size adjusted from 1729 to 1475 (eff_cnt=1280)
11:58:18.512     alsa_dev.c  ca_thread_func: overrun!
11:58:18.514    pjsua_acc.c !Sending 2 bytes keep-alive packet for acc 1 to 211.149.184.241:5060
11:58:18.515   tdta0xe088f8  Destroying txdata raw
11:58:18.689     alsa_dev.c !ca_thread_func: overrun!
11:58:18.701          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:18.881     alsa_dev.c !ca_thread_func: overrun!
11:58:18.888     alsa_dev.c !pb_thread_func: underrun!
11:58:19.105   Master/sound !283 samples reduced, buf_cnt=1832
11:58:19.105   Master/sound  Buffer size adjusted from 2115 to 1832 (eff_cnt=1280)
11:58:19.105     alsa_dev.c  ca_thread_func: overrun!
11:58:19.114          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:19.342   Master/sound !414 samples reduced, buf_cnt=1418
11:58:19.343   Master/sound  Buffer size adjusted from 1832 to 1418 (eff_cnt=1280)
11:58:19.343     alsa_dev.c  ca_thread_func: overrun!
11:58:19.517     alsa_dev.c  ca_thread_func: overrun!
11:58:19.526          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:19.736   Master/sound !173 samples reduced, buf_cnt=1565
11:58:19.736   Master/sound  Buffer size adjusted from 1738 to 1565 (eff_cnt=1280)
11:58:19.736     alsa_dev.c  ca_thread_func: overrun!
11:58:19.924     alsa_dev.c  ca_thread_func: overrun!
11:58:19.935          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:19.936     alsa_dev.c  pb_thread_func: underrun!
11:58:20.115     alsa_dev.c !ca_thread_func: overrun!
11:58:20.132   strm0xe038dc !VAD re-enabled
11:58:20.331   Master/sound !460 samples reduced, buf_cnt=1745
11:58:20.337   Master/sound  Buffer size adjusted from 2205 to 1745 (eff_cnt=1280)
11:58:20.337     alsa_dev.c  ca_thread_func: overrun!
11:58:20.339   strm0xe038dc !Starting silence
11:58:20.340          speex  warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:20.574   Master/sound !387 samples reduced, buf_cnt=1358
11:58:20.574   Master/sound  Buffer size adjusted from 1745 to 1358 (eff_cnt=1280)
11:58:20.574     alsa_dev.c  ca_thread_func: overrun!
11:58:20.760     alsa_dev.c  ca_thread_func: overrun!
11:58:20.762    tsx0xdf545c !Timeout timer event
11:58:20.762    tsx0xdf545c  .State changed from Completed to Terminated, event=TIMER
11:58:20.765    tsx0xdf545c  Timeout timer event
11:58:20.765    tsx0xdf545c  .State changed from Terminated to Destroyed, event=TIMER
11:58:20.766   tdta0xdf43f0  ..Destroying txdata Response msg 200/NOTIFY/cseq=102 (tdta0xdf43f0)
11:58:20.766    tsx0xdf545c  Transaction destroyed!
11:58:20.948     alsa_dev.c !ca_thread_func: overrun!
11:58:20.958          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:20.960     alsa_dev.c  pb_thread_func: underrun!
11:58:21.187   Master/sound !295 samples reduced, buf_cnt=1383
11:58:21.187   Master/sound  Buffer size adjusted from 1678 to 1383 (eff_cnt=1280)
11:58:21.187     alsa_dev.c  ca_thread_func: overrun!
11:58:21.378     alsa_dev.c  ca_thread_func: overrun!
11:58:21.387          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:21.610   Master/sound !419 samples reduced, buf_cnt=1284
11:58:21.610   Master/sound  Buffer size adjusted from 1703 to 1284 (eff_cnt=1280)
11:58:21.612     alsa_dev.c  ca_thread_func: overrun!
11:58:21.804     alsa_dev.c  ca_thread_func: overrun!
11:58:21.810          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:22.040   Master/sound !168 samples reduced, buf_cnt=1436
11:58:22.040   Master/sound  Buffer size adjusted from 1604 to 1436 (eff_cnt=1280)
11:58:22.040     alsa_dev.c  ca_thread_func: overrun!
11:58:22.053     alsa_dev.c !pb_thread_func: underrun!
11:58:22.230     alsa_dev.c !ca_thread_func: overrun!
11:58:22.414          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:22.440     alsa_dev.c !ca_thread_func: overrun!
11:58:22.619     alsa_dev.c  ca_thread_func: overrun!
11:58:22.805     alsa_dev.c  ca_thread_func: overrun!
11:58:22.815     alsa_dev.c !pb_thread_func: underrun!
11:58:23.039   Master/sound !232 samples reduced, buf_cnt=1524
11:58:23.039   Master/sound  Buffer size adjusted from 1756 to 1524 (eff_cnt=1280)
11:58:23.039     alsa_dev.c  ca_thread_func: overrun!
11:58:23.229     alsa_dev.c  ca_thread_func: overrun!
11:58:23.237          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:23.470   Master/sound !341 samples reduced, buf_cnt=1503
11:58:23.470   Master/sound  Buffer size adjusted from 1844 to 1503 (eff_cnt=1280)
11:58:23.471     alsa_dev.c  ca_thread_func: overrun!
11:58:23.645     alsa_dev.c  ca_thread_func: overrun!
11:58:23.652          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:23.860   Master/sound !167 samples reduced, buf_cnt=1656
11:58:23.861   Master/sound  Buffer size adjusted from 1823 to 1656 (eff_cnt=1280)
11:58:23.861     alsa_dev.c  ca_thread_func: overrun!
11:58:24.049     alsa_dev.c  ca_thread_func: overrun!
11:58:24.056          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:24.057     alsa_dev.c  pb_thread_func: underrun!
11:58:24.267   Master/sound !166 samples reduced, buf_cnt=1810
11:58:24.267   Master/sound  Buffer size adjusted from 1976 to 1810 (eff_cnt=1280)
11:58:24.268     alsa_dev.c  ca_thread_func: overrun!
11:58:24.505   Master/sound  450 samples reduced, buf_cnt=1360
11:58:24.505   Master/sound  Buffer size adjusted from 1810 to 1360 (eff_cnt=1280)
11:58:24.505     alsa_dev.c  ca_thread_func: overrun!
11:58:24.697     alsa_dev.c  ca_thread_func: overrun!
11:58:24.708          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:24.883     alsa_dev.c !ca_thread_func: overrun!
11:58:25.121   Master/sound  209 samples reduced, buf_cnt=1791
11:58:25.121   Master/sound  Buffer size adjusted from 2000 to 1791 (eff_cnt=1280)
11:58:25.122     alsa_dev.c  ca_thread_func: overrun!
11:58:25.132          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:25.133     alsa_dev.c  pb_thread_func: underrun!
11:58:25.354   Master/sound !319 samples reduced, buf_cnt=1472
11:58:25.354   Master/sound  Buffer size adjusted from 1791 to 1472 (eff_cnt=1280)
11:58:25.354     alsa_dev.c  ca_thread_func: overrun!
11:58:25.547     alsa_dev.c  ca_thread_func: overrun!
11:58:25.557          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:25.790   Master/sound !320 samples reduced, buf_cnt=1472
11:58:25.791   Master/sound  Buffer size adjusted from 1792 to 1472 (eff_cnt=1280)
11:58:25.791     alsa_dev.c  ca_thread_func: overrun!
11:58:25.982     alsa_dev.c  ca_thread_func: overrun!
11:58:25.990          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:26.218   Master/sound !201 samples reduced, buf_cnt=1591
11:58:26.218   Master/sound  Buffer size adjusted from 1792 to 1591 (eff_cnt=1280)
11:58:26.218     alsa_dev.c  ca_thread_func: overrun!
11:58:26.419          speex !warning: Auto-filling the buffer (your application is buggy and/or got xruns)
11:58:26.422     alsa_dev.c !ca_thread_func: overrun!
11:58:26.424     alsa_dev.c !pb_thread_func: underrun!
11:58:26.643   Master/sound !275 samples reduced, buf_cnt=1636
11:58:26.644   Master/sound  Buffer size adjusted from 1911 to 1636 (eff_cnt=1280)
11:58:26.644     alsa_dev.c  ca_thread_func: overrun!
11:58:26.646 sip_endpoint.c !Processing incoming message: Request msg INVITE/cseq=104 (rdata0xdb3ecc)
11:58:26.646   pjsua_core.c  .RX 841 bytes Request msg INVITE/cseq=104 (rdata0xdb3ecc) from UDP 211.149.184.241:5060:
INVITE sip:192.168.199.246:30003 SIP/2.0
Via: SIP/2.0/UDP 211.149.184.241:5060;branch=z9hG4bK0ed27c3d;rport
Max-Forwards: 70
From: <sip:103009844960152@211.149.184.241>;tag=as47643774
To: <sip:8002@192.168.199.246:30003;ob>;tag=d7d7f583-6390-4a16-9b9c-2f35c8bef97f
Contact: <sip:103009844960152@211.149.184.241:5060>
Call-ID: 356bbaf75eabf6633e02135d7019b2e8@211.149.184.241:5060
CSeq: 104 INVITE
User-Agent: Asterisk PBX 11.7.0
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH
Supported: replaces, timer
Content-Type: application/sdp
Content-Length: 238

A: Beforte I compling simple_pjsua.c I set the log level frome 4 to 5.After complied and I run it, I fond the same warnging as you, but have no effect to the session.when I set the log level from 5 back to 4,the waring disappeared.I didn't know the reasion that cause the waring but I know it dosn't have effect to the session.


text:
Q: How to Find Class of + in Ruby The design philosophy of ruby is just amazing. So I did 1 + 2 and got 3. I managed to make this: 1.+(2) # => 3.
As cool as this was, I also wanted to test out the class method on the + method.
+.class
=> SyntaxError: (irb):14: syntax error, unexpected '.'
   +.class
     ^

And then:
+().class
=> NoMethodError: undefined method `+@' for NilClass:Class

While:
+(2).class
NoMethodError: undefined method `+@' for Fixnum:Class

Why was +(2).class a fixnum and not an integer? I try it again with +(2.to_i).class and the same error appears for +(2).class.
But back to the key question: How do I find the class of the + method?

A: 1 + 2 is calling the + method on 1 with 2 as an argument, which is the same as 1.+(2).
However, because of precedence, +(2).class is actually calling (2).class first, returning an instance of Class, then calling the nonexistent +@ method, which is the unary plus method that only exists for Numeric. You can test this by typing (+(2)).class, which returns Fixnum as one would expect. This is also the source of the error for +().class, because () returns nil, and the class of nil is NilClass, which also doesn't have a +@ method.
tl;dr: because precedence made the leading + evaluate last, as +@.
The + method on any object is of the class Method, as is any other method on any object. However, typing + calls the method instead of returning it, because Matz saw in a dream that a programming language that returns methods instead of calling them doesn't run. You can have the method returned to you by calling the method method with the method name, like so: 1.method(:+). Then you can make the method object tell you what its class is: 1.method(:+).class.

A:
How do I find the class of the + method?

You can do it as below using #owner and #method :
1.method(:+).owner # => Fixnum
'1'.method(:+).owner # => String

As above output clearly telling you, when you are doing 1 + 2 or 1.+(2), Fixnum#+ method is being called. Similar way While you would write '1' + '2' or '1'.+('2'). String#+ method is being called.

A: Simple :)
Try that :
m = 1.method("+")
m.class

A: Methods aren't objects in Ruby, therefore they don't have a class. You can use reflection to obtain a proxy object that represents a method, though, in which case the class will either be Method or UnboundMethod, depending on whether the method is bound to a receiver object or not.


text:
Q: Why is area expressed as unit^2? It is clear to me that area is measured in no of unit squares that are enough to cover the given shape's entire surface. So we should say that area of my roof is 50 (meter squares). But why does it equivalently translate into 50 m^2, is it simply an algebraic convenience so that area/length cancellation gives length, and power of 2 also represents the second dimension while unit^3 represents volume because 3 is third dimension?

A: This is because an area is measured by computing the product of two lengths. For example if those are defined in meters, you multiply some meters by some other meters. Therefore the way to say that the area is in square meters.
The same for volume: you multiply three lengths.

A: It's just notational convenience. We agreed that the basic unit for measurement of surfaces is the area of a square with side length of $1$ meter and we compare all surface areas we want to measure to that (exactly the same way we simply agreed, that the basic unit for measuring distance is equal to $1$ meter). We write $m^2$ for this concept because this way we can almost think of the $m$ as a variable and do the usual algebraic manipulations to it.


text:
Q: Shortcode display featured image and permalink from pages in Wordpress I am trying to make a shortcode that can display featured image and permalink from chosen pages on my front-page in Wordpress.
It works fine to display one page, but I want to be able to choose different pages. I cannot figure out how....

// Creating Shortcodes with parameter to display pages
function my_shortcode_display_pages($attr, $content = null){
//call global variable
    global $post;

// Defines Shortcode's Attributes
$shortcode_args = shortcode_atts(
                  array(
                    'type'     => '',
        'pagename' => '',
                    'num'     => '',
                    'order'  => ''
                    ), $attr);

// set an array with query arguments
$args = array(
        'post_type'        => $shortcode_args['type'],
'pagename'        => $shortcode_args['pagename'],
        'posts_per_page' => $shortcode_args['num'],
        'order'          => $shortcode_args['order']
         );

// get posts
$recent_posts = get_posts($args);
    $output = '
';
    $query = new WP_Query($args);

if($query->have_posts()) :

    while($query->have_posts()) :

        $query->the_post() ;

    $output .= '
' . ''.get_the_post_thumbnail() .'
'.get_the_title() .'
'.'
';

    endwhile;

    wp_reset_postdata();

endif;

//return the output.
return $output . '
';

}
// Register the shortcode.
add_shortcode( 'my_display_pages', 'my_shortcode_display_pages' );

[my_display_pages pagename="hotell"]


text:
Q: Programming PIC from USB using FT232 I have a PIC18F1330 which does not have native USB capabilities (see datasheet). I am planning to load it with a bootloader using my PICkit the first time and then programming from a USB port after that. I have a Micro-B USB jack and an FT232 (datasheet) to allow me to program it using the RX/TX pins on the PIC (RA3 and RA2 on the 28-pin QFN). However, I am not very familiar with this method of programming micros so I'm looking for some verification. Here's the schematic I have so far:

Is it as simple as connecting pins 24 and 25 on the FT232 to pins 7 and 8 on the PIC? Or must I use some of the other connections as well? I have not found much information for programming PICs through an FT232, mostly AVRs.
You can ignore some of the net labels that don't make much sense, they are used for other parts of my project.
EDIT: This post is asking about the connection between the FT232 and the PIC18F1330. I am NOT asking about the bootloader.

A: RX, TX would be enough to send out programming data and get back acknowledgements from the bootloader. Don't forget ground. Also, if you need to use USB only occasionally consider having it extermally (see ft232 basic breakout from Sparkfun,for example).
Edit: you may also want to connect vccio from ft232 to the vcc of the pic to have the same logic levels on both chips.

A: You will want to cross-connect the TX lead from the FT32 chip (pin 25) to the RX lead of the PIC (pin 8), and RX lead from the FT32 chip (pin 24) to the TX lead of the PIC (7).
I know you said you are not asking about the bootloader, but I'm going to address that anyway.
I'm a little confused by your question, you seem to know what a bootloader is, but then as Olin says you are asking basic questions about how to wire up the IC's.  Are you planning on writing your own bootloader (which is not trivial), or using one that you have found on the net?  As you stated in your question, you say you have not found much information re using bootloaders with PICs as they are much more common with AVRs because of the Arduino.
If you are planning on writing your own bootloader, you are going need to write two pieces of firmware -- parsing the contents of the hex file coming from the PC (presumably sent over a virtual COM port using still additional software), and then using the self-programming feature of the PIC (available on some, but certainly not all PICs) to update the portion of the flash not occupied by the bootloader.
Frankly, unless you are completely out of pins on the PIC, I would just include an interface for an ICD or PICkit using the PGEC/PGED pins.  Much, much easier.


text:
Q: How download Android build support for Unity manually? (without unity hub) I have a problem that does not allow me to compile for android, I have looked for solutions but it is always "untick and tick in unity hub" but I use the installer beacause unity hub uses much more internet, and I cannot download 15GB without having a crash that cancels the download
enter image description here
and apparently I have the folder but the subfolders mentioned by unity do not exist, I used a beta and downloaded the latest LTS but I have the same problem
enter image description here

A: Yes you can.

*

*Check which android sdk/ndk supported by your unity version.

*download from android google the necessary versions

*In unity preferences change path to your downloaded sdk/ndk.

Same to openjdk

A: I found the files before
NDK, SDK and JDK


text:
Q: Why are only some portions of the EM spectrum able to pass through a metal dog bowl?
In this photo you can see part of the bowl, which I turned upside down and placed on top of various electromagnetic sources to determine whether the waves could pass through it. The graph in the background illustrates my results.
For the shorter wavelengths, I had to guess. I knew that ultraviolet would be blocked, but I assumed that x-rays and gamma rays could  go through the bowl.
To me, is seems that wavelengths in the range of, say, 100nm to 900nm are more easily stopped by the bowl. Even though I used a metal bowl, I think a plastic or paper bowl would produce similar results.
So my question is: why are the waves in the middle of the spectrum  stopped by the bowl and not those at the ends?
Here are some of the items I used in my experiment:
a TV Remote, a Bluetooth device, an IPhone, our Home WiFi, a Cellular LTE, a Sprinkler Remote, and a Radio.
All of the items on my list were able to pass through the bowl except the TV remote, which I assume was infrared.

A: Long-wavelength and short-wavelength radiation passes for different reasons: long-wavelength does not actually pass, but bends around the bowl due to diffraction (or is reflected from the walls), as the wavelength is greater or of the order of the dimensions of the bowl, and short-wavelength radiation passes because its frequency is higher than the plasma frequency of the metal of the bowl. Plastic and paper can give very different results (for example, in the visible range, if the plastic is transparent).


text:
Q: How to list all running webjobs within an azure subscription using powershell I have an azure subscription that has upwards of 200 appServices where around about half of them have Continuous, always on webJobs attached, some also have slots which also have webJobs.
Is there a way to list all webJobs that are inside a subscription? I was originally tring to use powershell to do this but it was getting rather complex and was wondering if anyone knew of an easy way to achieve the above.
It seems like Get-AzureRmWebApp should be able to help but i cant find a way to list the jobs that reside inside the webapps.

A: I found the command Get-AzureWebsiteJob which is not in the AzureRM family of commandlets. The following script can get the data that I'm looking for:
$groups = get-AzureRmResourceGroup | where{$_.ResourceGroupName -like "*-prod-*"}

foreach($group in $groups){
    Write-Host -ForegroundColor Cyan "processing resourceGroup" $group.ResourceGroupName

    $webApps = Get-AzureRmWebApp -ResourceGroupName $group.ResourceGroupName

    foreach($webApp in $webApps){
        write-host -ForegroundColor Yellow $webApp.Name
        $job = Get-AzureWebsiteJob -Name $webApp.Name
        if($job){
            write-host -ForegroundColor DarkYellow $job.JobName
        }
        $job = Get-AzureWebsiteJob -Name $webApp.Name -Slot staging
        if($job){
            write-host -ForegroundColor DarkYellow $job.JobName " -staging"
        }
    }
}

The above does not filter out the running ones from the stopped, but that can be easily added if need be.
Of course you firstly need to be logged into AzureRM and Azure classic
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionId <<mySubscriptionId>>
Get-AzureRmContext

Add-AzureAccount
Select-AzureSubscription -SubscriptionId <<mySubscriptionId>>
Get-AzureSubscription -Current

Its a very slow script iterating over this number or AppServices though. Any ideas for speeding it up would be appreciated.

A: You can do it through the ARM APIs, though you still need to call it on each Web App.
You can get the WebJobs with a GET request to:
https://management.azure.com/subscriptions/subscription-id/resourceGroups/resource-group-name/providers/Microsoft.Web/sites/app-name/webjobs?api-version=2016-03-01

But I doubt this will be any more efficient than what you have since you still need to make a call for every Web App. And you will need to get the access token somehow.
Web Jobs are a property of App Service applications and can't be requested all at once from Azure.

A: I know it's too late but we can try with Azure CLI too these days.
az webapp webjob triggered list --name MyWebApp --resource-group MyResourceGroup

Additionally, you can query the above result and get the desired information you are looking for
az webapp webjob triggered list --name MyWebApp --resource-group MyResourceGroup  --query "[].{Name:name, Schedule:settings.schedule}"

A: I know it's too late but we can try with Azure CLI too these days.
az webapp webjob triggered list --name MyWebApp --resource-group MyResourceGroup

Additionally, you can query the above result and get the desired information you are looking for
az webapp webjob triggered list --name MyWebApp --resource-group MyResourceGroup  --query "[].{Name:name, Schedule:settings.schedule}"

But, again you have to run the above query in the for each loop to fetch the results from all resource groups in the subscription.


text:
Q: Show single post only if written by current logged in author Wordpress I have found some code which restricts a feed of posts to the current logged in author below, and it works great. Now I am looking for a way to apply the same restriction to a single post. What would I adjust in the code so it would work on single.php? If I use this code it as it is right now, it generates a feed rather than a single post.
<?php if (is_user_logged_in()):
        global $current_user;
        wp_get_current_user();
        $author_query = array('author' => $current_user->ID);
        $author_posts = new WP_Query($author_query);
        while($author_posts->have_posts()) : $author_posts->the_post(); ?>

A: You can pass the post id into WP_Query along with the author, e.g.
$args = array('author' => $current_user->ID,
              'p' => get_the_ID() );
$author_posts = new WP_Query( $args );

However this seems like you are doing extra work that you don't need - you are already on the post page so the loop is already set up to show the post details.
I assume what you are trying to do is check if it is the logged-in user's own post and only display it if it is. In that case, all you need to do is this:
$current_user = wp_get_current_user();
if (is_user_logged_in() && $current_user->ID == $post->post_author)  {
    /* the user is logged in and the current logged-in user is the post author */
    /* Show the post here....*/
}
else{

    /* Author is not the logged in user!
       Do whatever you want in this case...*/
}

Reference: Check if The Current User is The Post Author in WordPress (Updated to replace deprecated function)


text:
Q: check if day of month is between two months I want to check if a (month,day) is between two months regardless of the year. I am having a problem in modeling the month of january. I tried representing january by 13 but I got stuck.

return values

*

*3 = between 25JUN and 22AUG

*2 = between 01APR-24JUN or 22AUG-31OCT or 17DEC-01JAN

*1 = between 01SEP-31MAR or 01NOV-16DEC or 02JAN-31MAR

*0 = My program is not working and couldn't find the dates. I am screwed

source code
from datetime import date, datetime, timedelta

def get_season(date):
        month = date.month
        day   = date.day

        if month == 1:
            month = 13

        if (6,25) <= (month, day) <= (8,22):
            return 3

        elif (4, 1) <= (month, day) <= (6,24) or (8, 22) < (month, day) <= (10, 31) or (12,17) <= (month, day) <= (13,1):
            return 2

        elif  (9, 1) <= (month, day) <= (3, 31) or  (11,1) <= (month, day) <= (12, 16) or (13,2) <= (month, day) <= (3, 31):
            return 1
        else:
            return 0

if __name__ == "__main__":

    date = datetime.strptime("2016-02-01",'%Y-%m-%d').date()

    if get_season(date) == 0:
      print "WRONG DOES NOT EXIST THERE!!!!!!!!!!!!!!"

A: I would do all these comparisons directly between datetime.date objects, and re-write them as a single year.
from datetime import date

def get_season(d):

    d = date(year=1900, month=d.month, day=d.day)

    if date(1900, 6, 25) <= d <= date(1900, 8, 22):
        return 3

    elif date(1900, 4, 1) <= d <= date(1900, 6, 24) or \
         date(1900, 8, 22) <= d <= date(1900, 10, 31) or \
         date(1900, 12, 17) <= d <= date(1900 12, 31) or \
         date(1900, 1, 1) == d:
        return 2

    elif date(1900, 9, 1) <= d <= date(1900, 3, 31) or \
         date(1900, 11, 1) <= d <= date(1900, 12, 16) or \
         date(1900, 1, 2) <= d <= date(1900, 3, 31):
        return 1

This also makes it much easier to create boundary pairs.
def get_season(d):
    d = date(year=1900, month=d.month, day=d.day)

    boundarydict = {1: [(date(1900, 9, 1), date(1900, 3, 31)),
                        (date(1900, 11, 1), date(1900, 12, 16)),
                        (date(1900, 1, 2), date(1900, 3, 31))],
                    2: [(date(1900, 4, 1), date(1900, 6, 24)),
                        (date(1900, 8, 22), date(1900, 10, 31)),
                        (date(1900, 12, 17), date(1900, 12, 31)),
                        (date(1900, 1, 1), date(1900, 1, 1))], # note this one!
                    3: [(date(1900, 6, 25), date(1900, 8, 22))]}

    for retval, boundaries in boundarydict.values():
        if any(a <= d <= b for a, b in boundaries):
            return retval


text:
Q: Delphi Firemonkey ComboBox insert in AdoTable So, I've been using LiveBindings between two tables at a combobox to get the Id and Description of a foreign key(with the Item.LookupData and Item.text properties) and assign the key to a field in another table with the SelectedValue propertie. This is working fine i guess but i'm using custom dbnavigator controls to make a "register form".
I'm using methods like this to make the inserts: adotablealuno.FieldValues['Nome']:=editnomeAluno.Text;

But I'cant find how to use the combobox in this way, i've already tried the ItemIndex and Selected properties, but none of this work (I'm using a Access DB btw). How can I use my foreign key in ComboBox for this?

A: Actually I was already stating this question and there was no good answer for a long time. I found a way out that I am currently using. At least I know that I'll get reliable data.
You need to handle OnFillingListItem event of the LinkFillControlToField link in alike way and store id number in ComboBox Items. I use Tag property for this purpose though it is not actually good.
procedure TForm1.LinkFillControlToField1FillingListItem(Sender: TObject;
  const AEditor: IBindListEditorItem);
begin
  (AEditor.CurrentObject as TListBoxItem).Tag :=
    YourLookuptable.FieldByName('id').AsInteger;
end;

And then fetch the item id from ListBox1.Selected.Tag. The text value can be accessed via ComboBox1.Selected.Text.
Appended.
You make an alike LinkFillControlToField link.
Then you select this link and create an OnFillingListItem event handler to the link (select events tab in the Object Inspector and double click on OnFillingListItem ComboBox). The event handler (empty procedure) will appear. It will be given a name like TForm1.LinkFillControlToField1FillingListItem(... Then you write the code setting the id property to the items' Tags.


text:
Q: align time-lapse images to remove translation and rotation I have a sequence of images that you can get as a stack from here:
https://www.dropbox.com/s/8ds08klvq9irgz9/imagestack.tif?dl=0
Now i have the following image sequence where we can see that the white blob moves a lot

I want to align the images with each other such that the translation and rotation is minimized. I used the following code below:
(* masks are the sequence of images *)
FoldList[ImageAlign[#1, #2, Method -> "Fourier", TransformationClass -> "Rigid"] &,
First@masks, Rest@masks]

the result is:

I think there should be a way to improve it more such that translation and especially rotations are minimized. Would appreciate help !

A: This is only a partial answer.  (But I'm not convinced one can determine the rotation angle unless one knows more information about either the shape of the object or the rotation speed function.)
Edit:  While I'm still not convinced there is enough information to determine the rotation angle - in part because the shape sometimes looks very circular - I've included the use of the "Orientation" option that assumes the shape of an ellipse.
(* Import the images *)
images = Import["imagestack.tif"];

(* Find the centroid and possible rotation angle (assuming an ellipse) *)
centroids =
  Table[ComponentMeasurements[Binarize[images[[i]]], "Centroid"], {i, Length[images]}];
angles = Table[ComponentMeasurements[Binarize[images[[i]]], "Orientation"],
  {i, Length[images]}];
a = 1 /. # & /@ angles;

(* Center the graphic at the centroid, trim, and rotate *)
w = 150;
centeredImages = Table[ImageRotate[ImageTrim[images[[i]],
  {(1 /. centroids[[i]]) - w, (1 /. centroids[[i]]) + w}], -a[[i]]],
  {i, Length[centroids]}];

(* Export as an animated gif *)
Export["objects.gif", Flatten[{centeredImages[[1 ;; Length[centeredImages] - 1]],
   Reverse[centeredImages]}], "DisplayDurations" -> 0.5]


text:
Q: NSOutlineView reloadItem/reloadData not working when replacing an item I have a view-based NSOutlineView with a dataSource/delegate model instead of binding to a tree controller (I want control over the insert/update animations).
I'm replacing an item in my model and would like to update that specific row in the outline view without having to call reloadData().
I cannot get this to work. Either the item does not update at all or the item's expanded state doesn't update. There seems to be some caching being done inside of NSOutlineView according to this, but even with these suggestions, I could not get it to work.
What I have:
(1) The outline view represents a folder structure
(2) At first, there is a singe file:

(3) The file is then replaced with a folder item:
 // Model update
 let oldFileItem = rootItem.children.first!
 rootItem.children.remove(at: 0)
 rootItem.children.append(Item(title: "Folder", children:[], isExpandable:true))

Expected result:

Actual result (reloadItem):
outlineView.reloadItem(oldFileItem) // I kept a reference

Icon and title reloaded, but note that the expansion triangle is missing.
I can somewhat understand that reloadItem() might not work in this case, because the old item is not part of the data model anymore. Strangely enough, the item's title and icon update, but not the expansion state.
Actual result (reloadData(forRowIndexes:columnIndexes:):
outlineView.reloadData(forRowIndexes: IndexSet(integer:0), columnIndexes: IndexSet(integer:0))

No effect whatsoever. This is the one that I would have expected to work.
Actual result (remove/insert):
outlineView.removeItems(at: IndexSet(integer:0), inParent: rootItem, withAnimation: [])
outlineView.insertItems(at: IndexSet(integer:0), inParent: rootItem, withAnimation: [])

No effect whatsoever.
The docs say about removeItems(): "The method does nothing if parent is not expanded." and isExpanded does indeed return false for the root node, although its children are visible. Is this special behavior for items that are direct children of the root node? What am I missing here?
For reference, my data model:
class Item:NSObject {
    var title:String
    var children:[Item]
    var isExpandable:Bool

    init(title:String, children:[Item], isExpandable:Bool) {
        self.title = title
        self.children = children
        self.isExpandable = isExpandable
    }
}

A: For reference:
It turned out to be an issue with how I used the API. NSOutlineView.removeItems/insertItems expect nil for the inParent parameter for the root item. I was handing in the actual root item. Using nil instead of the root item solved the problem.


text:
Q: Inserting node at the end of LinkList in C I don't have any problems to insert nodes in the middle or at the beginning of a LinkedList. However, at the end is different. When I try to print the values, it gives me the address:
Now, here is how I build the LinkedList:
employeeData ed[4];

node *head = NULL, *list = NULL;

for (int i = 0; i < 4; i++)
    fscanf(file, "%d %s %d %d %lf", &ed[i].EMP_ID, ed[i].name, &ed[i].dept, &ed[i].rank, &ed[i].salary);

head = (node *)malloc(sizeof(node));

head->employee = ed[0];
head->next = NULL;

list = head;

for (int i = 1; i < 5; i++){

    node *ptr = (node *)malloc(sizeof(node));

    ptr->employee = ed[i];
    ptr->next = NULL;

    head->next = ptr;

    head = head->next;
}

Here is how I add nodes to it:
node *newNode = (node *)malloc(sizeof(node)), *temptr = list, *endNode = list;

newNode->employee.EMP_ID = id;
strcpy(newNode->employee.name, name);
newNode->employee.dept = dept;
newNode->employee.rank = rank;
newNode->employee.salary = salary;
newNode->next = NULL;

while (endNode->next != NULL) endNode = endNode->next;

if (id < temptr->employee.EMP_ID){
    newNode->next = list;
    list = newNode;
}
else if (id > endNode->employee.EMP_ID){
    endNode->next = newNode;
}
else{

    while ((temptr->next != NULL) && (temptr->next->employee.EMP_ID < newNode->employee.EMP_ID))
        temptr = temptr->next;

    newNode->next = temptr->next;

    temptr->next = newNode;
}

When I try to remove the value, It will remove it. However, it does not display the value.
What am I doing wrong?
Thanks

A: As BLUEPIXY stated, the problem was during the building.
the index needed to be in 4 for (int i = 1; i < 4; i++)
And also, I changed how I printed the list.
from
while (temp->next != NULL){
    printf("");
    temp = temp->next;
}

to
while (temp != NULL){
    printf("");
    temp = temp->next;
}


text:
Q: Should I use Releases or YAML Pipelines for app deployment? In Azure DevOps we have Pipeline and Releases.
Which one should I use for deploying application ?
Will Releases be deprecated ?
Will YAML pipeline be one and primary way to build and publish apps ?

A: Both Release pipeline and YAML pipeline can be used to deploy application.
Yaml pipeline is defined in YAML file and can be versioned with your code.
Release pipeline in Releases section is in classic UI view and would be easier to start with. Please check here for more information.
There is no official announcement that Classic UI pipeline will be deprecated. You can easily move from Classic Release pipeline to Yaml pipelines even if classic UI pipeline is deprecated. And you can check the Tasks yaml format definition in classic UI pipeline by clicking VIEW YAML.
However Yaml pipeline currently do not support manual triggerring for multi-stages. This is on the road map. You can check this thread for more information.
And Yaml pipeline support Template yaml pipeline, while classic release pipeline donot have this feature.
You can choose either of them according to your requirements.

A: I heared that rumors that multi stage pipelines (with deployments) will replace Releases. There is plenty of actions taken to close the gap between YAML pipelines and Releases. But I would recommend you to pick solution which is raight for you. This may help you with this: Azure Devops multistage pipeline or release, when to use what?
Tis is a great conclusion (Taken from the question above)

When this or other feature which haven't added in YAML is necessary in
  your team, at this time, you'd better use Release pipeline with
  classic UI for your product security.


text:
Q: Big multidimensional vector initializaton C++ I am trying to load simulation results from a file into a vector. The code works well for small and medium amount of data. When I try do load big files I get an exception. The array that makes my program crash is about 17000*7*3000 elements. I've tried splitting initialization into few steps but it has crashed as well. Could you please tell me if I can do something to make it work?
//////////////////////////////////////////////////////////
//Import of surface receivers file
    for(int freq=0;freq<7;freq++)
    {
        filePath=filePath_old;

        filePath.Replace(wxT("125 Hz"),wxString::Format(wxT("%i"), freqSTI[freq])+wxT(" Hz"));
        if(importer.ImportBIN(filePath,mainData))
        {
            if(timeTable.size()==0){
                for(int idstep=0;idstep<mainData.nbTimeStep;idstep++)
                {
                    timeTable.push_back(mainData.timeStep*(idstep+1)*1000);
                }
            }
            for(wxInt32 idrs=0;idrs<mainData.tabRsSize;idrs++)
            {
                for(wxInt32 idface=0;idface<mainData.tabRs[idrs].dataRec.quantFaces;idface++)
                {
                    if(tab_wj.size()<idrs+1){
                        tab_wj.push_back(std::vector<std::vector<std::vector<wxFloat32> > > (mainData.tabRs[idrs].dataRec.quantFaces,std::vector<std::vector<wxFloat32> >(7,std::vector<wxFloat32>(mainData.nbTimeStep,0.f))));
                    }
                    //Pour chaque enregistrement de cette face
                    int tmp=mainData.tabRs[idrs].dataFaces[idface].dataFace.nbRecords;
                    for(wxInt32 idenr=0;idenr<mainData.tabRs[idrs].dataFaces[idface].dataFace.nbRecords;idenr++)
                    {
                        t_faceValue* faceval=&mainData.tabRs[idrs].dataFaces[idface].tabTimeStep[idenr];
                        tab_wj[idrs][idface][freq][faceval->timeStep]=faceval->energy;
                    }
                }
            }
        }

    }

The place where an exception occures is tab_wj.push_back...
When I tried to split initialization into more than one step I wrote:
std::vector<wxFloat32> t1(mainData.nbTimeStep,0.f);
std::vector<std::vector<wxFloat32> > t2(7,t1);
std::vector<std::vector<std::vector<wxFloat32> > > t3(mainData.tabRs[idrs].dataRec.quantFaces,t2);

Then it crashed at last one of these lines.
Thanks for any help!

A: Looks like it is getting an exception while allocating memory.
std::vector<> must reallocate its storage as you add new items to it.
It doesn't do this for each push_back() because it allocates more than it needs.
A vector<> of size 5 might actually have space for 8 items (size() vs. capacity()). When you insert the 9th item it must reallocate, and typically it will double its capacity (from 8 to 16 (*)).
This reallocation can fragment your heap.
To improve you can preallocate the vector to the size it will eventually need, so it will never need to reallocate. vector::reserve()
So, if you know you will eventually need 17000*7*3000, reserve this up front.
Also, if you have a lot of small vectors, allocating those at a small size can reduce your memory requirements. Usually vector<> has a default size which could be 8 or 16. If you only ever insert 3 items, then you are wasting a lot of storage. During allocation of the vector I believe you can specify its initial capacity.
Since you are using nested vectors, each of these will in turn have their own allocations. Depending on your version of C++, pushing a vector onto a vector can cause a number of allocations.
You might try restructuring the code to not require nested vectors.
(*): a naive vector implementation will double the allocation size when it needs more space, but a factor of 1.6 is better for a number of reasons (its just as big-O efficient and leads to much less memory fragmentation). See "The golden ratio": https://en.wikipedia.org/wiki/Golden_ratio


text:
Q: Reallocating array size using type of its element I have a class attribute which is an Anytype built-in array. At some point I need to reallocate it's memory to double it, but since it is Anytype, I can't do:
myArray = new Anytype[myArray.length * 2];

Since the array is already defined, I can access to it's elements class:
myArray[0].getClass();

My question is: Can I use the fact that I know the class of my array to reallocate it? I know I could use Arrays.copyOf from Java utils, but I want to know if it is possible to reallocate knowing the size your object need, kind of a C-way:
myArray = new myArray[0].getAllocationNeeded()[myArray.length * 2];

P.S: I'm not sure if the title is relevant, please indicate me if you have something more clear

A: Yes, something like this (assume source is not null or empty):
   public <T> T[] resizeArray(T[] source, int multiplier) {
    T[] newArray = (T[]) Array.newInstance(source.getClass().getComponentType(), source.length * multiplier);
    System.arraycopy(source, 0, newArray, 0, source.length);
    return newArray;
}

Both:

*

*source.getClass().getComponentType()

*myArray[0].getClass()

Return the element class.


text:
Q: Using "angels of mercy" to refer to nurses I wonder if "angels of mercy" by itself (not in context) will be understood to mean "nurses."
I have googled this term, but the results I got referred to the angels from religions.

A: The association of nurses with "angels of mercy" goes back more than 175 years, and in at least some early accounts may involve the overtly religious inspiration of the nurses. Lucy Hamilton, "The Sister of Charity," in the [Clearfield, Pennsylvania] Democratic Banner (July 9, 1852) tells a story that seems likely to have historical underpinnings, especially with regard to the nursing staff at a hospital in Boston:

I chanced while making a tour of the Northern States, during the year 1820, to be taken suddenly ill in the city of Boston, and, in consequence, had myself removed from my hotel to the sick hospital, Sisters of Charity were among the regular attendants, numbers having volunteered their assistance on account of the difficulty of procuring nurses.

In the paragraph immediately before the one just cited, the writer gives a sense of the support that these nurses provided:

Reader, if, like me, you can recall the time when religious consolations breathed into your ear tenderly and spiritually, first penetrated a heart petrified by long sufferings, you know how to value those angels of mercy and kindness, who hover around the sick and dying, to minister support and sympathy in the dark hour of mortal despair.

Twenty years earlier, an item headed "Brothers of Charity" in the [Lawrenceburg, Indiana] Western Statesman (November 16, 1832) describes similar ministrations provided by male volunteers:

Brothers of Charity.—There is a society in this city, which for distinction's sake, we will call the Brothers of Charity. It is a part of their creed to hold themselves in readiness for every good work. Many of them are wealthy, and being so, possess the means of far more extensive usefulness than if otherwise circumstanced. Thy do not coop themselves up in solitary establishments, but mingle in society like other men—assume its relations, and perform its duties. Whenever distress befalls the community, you will be sure to find them, like angels of mercy, administering relief to the suffering. During the prevalence of the late epidemic, no place inhabited by human beings, was so dark and dreary, that they did not penetrate it; no atmosphere so loaded with pestilence that they did not breath it; no wretchedness so revoking that they did not relieve it. The sick and the dying were soothed by their kindness, the abodes of pollution were cleansed by their instrumentality, and at their expense; whatever humanity could suggest, was cheerfully rendered, at the sacrifice of every personal comfort; and all this was done day after day, week after week, by men who had thousands and tens of thousands at their command, and might, instead, have been rolling in the magnificence of earthly splendor, with no sight or sound of wo[e] to annoy them. ... The Brothers of Charity have no peculiar organization; they are simply good men and good citizens, carrying their principles into practice, and fulfilling their obligations, to themselves, their families, the community, and their Maker, in all the relations in which Providence has placed them.

And from "Sisters of Charity" in The Catholic Telegraph (May 25, 1833):

These Angels of Mercy, hearing that the city authorities of Philadelphia were about to present each of them with a piece of plate, with appropriate inscriptions, for their labors in the Cholera Hospitals, during the spread of the pestilence, have addressed a letter to the Mayor, informing him that they are unwilling to receive any guerdon for the perils which they voluntarily braved. They remark, in their letter, that they are 'aware that the offering was not to be presented as a recompense for their services, but as a mark of public approbation of their conduct. If their exertions have been useful to their suffering fellow beings, and satisfactory to the public authorities, they deem it a satisfactory reward, and indeed the only one which it would be consistent with their vocation to receive.' Here we perceive that mercy, which droppeth like the gentle dew from Heaven upon the Earth beneath.

Medical nursing seems not to have been viewed as a profession prior to 1850 or so. Rather, it was a do-gooder volunteer activity performed by relatives, the saintly, or (in times of war) the ultra-patriotic. This born out by the first paragraph of Encyclopædia Britannica's discussion of the history of nursing:

History of Nursing
Although the origins of nursing predate the mid-19th century, the history of professional nursing traditionally begins with Florence Nightingale. Nightingale, the well-educated daughter of wealthy British parents, defied social conventions and decided to become a nurse. The nursing of strangers, either in hospitals or in their homes, was not then seen as a respectable career for well-bred ladies, who, if they wished to nurse, were expected to do so only for sick family and intimate friends. In a radical departure from these views, Nightingale believed that well-educated women, using scientific principles and informed education about healthy lifestyles, could dramatically improve the care of sick patients. Moreover, she believed that nursing provided an ideal independent calling full of intellectual and social freedom for women, who at that time had few other career options.

But if Florence Nightingale—the lady with a lamp—marks the origin of the professional nurse, she carries the "angel of mercy" description into the new profession with her, as this illustration titled "Florence Nightingale, an Angel of Mercy. Scutari Hospital 1855" indicates.
To some extent, whether people will recognize the phrase "angels of mercy" as an allusion to nurses depends on the context in which it appears. But the phrase has been applied to nurses since the days when nursing was often viewed as a kind of ministry to the sick that might or might not include any training or scientific competence. The connection is thus firm and of long duration.


text:
Q: C# - Windows Service - Remote WMI query throws error: RPC not found I am developing a WMI query windows service to query network servers.
If I run the application in console, it works as expected but the service fails to complete the WMI query. Is there any way I can setup the service so the RPC doesn't fail due to insufficient privileges? I am using credentials in the WMI query to connect to the remote PC so that should not be a problem.
Thanks

A: Probable reason:

*

*Firewall configuration (RPC connections blockage)

*You don't have enough permission to run WMI queries.
Second point is valid if you are trying to run queries on remote machines. You can use wbemtest to verify.

*

*Windows+R (run command)

*Type wbemtest
You have to connect ManagementScope and check for it's validity scope.IsConnected. It is just a snippet of code, you might have to provide a structure to it.
ConnectionOptions cOption = new ConnectionOptions();
    ManagementScope scope = new ManagementScope("\\\\" + machine + "\\" + nameSpaceRoot + "\\" + managementScope, cOption);
           scope.Options.Username = UserName;
            scope.Options.Password = passWord;
            scope.Options.EnablePrivileges = true;
            scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
            //scope.Options.Timeout = TimeSpan.FromSeconds(180);
            //cOption.Timeout = TimeSpan.FromSeconds(180);
            scope.Options.Impersonation = ImpersonationLevel.Impersonate;
            scope.Connect();
            return scope;

    if (scope.IsConnected && scope != null)
    {
    query = new ObjectQuery(@"Select * from Win32_SCSIController");
                            searcher = new ManagementObjectSearcher(scope, query); searcher.Options.Timeout = new TimeSpan(0, 0, wbemConnectFlagUseMaxWait);
                            ManagementObjectCollection qWin32_SCSIController = searcher.Get();
    foreach (ManagementObject item in qWin32_SCSIController)
    {
    <Some code here>
    }


text:
Q: How to find on what ranges one sorting algorithm is better than other? I'm reading the book "Introduction to algorithms" and want to solve one task from it. But don't know the best way how to find solution.
The task is:
We have 2 sorting algorithms. Сomplexity of first one is $8 n^2$, the second is $64 n \lg n$. I want to find the range of $n$ when first algorithm is better than second.
I understand different ways how to solve it:

*

*I can take numbers one by one from range $[2..n]$ an find both values. According to them find a place when values of first algorithm become greater than second.

*I understand that I can solve $8 n ^2$ < $64 n \lg n$. But have no idea how to do it. Maybe someone can assist with it or give a link where to read.

*I can build graphics and find intersection point. But I had a problem with it. I don't want to build them on the paper. I found such online programm as Sage. But I can't find how to build graphic for logarithm. I'm trying:
a=plot(8*n^2)
b=plot(64*n*log(10, n), rgbcolor='red')
(a+b).show()
But it's not working. Maybe somebody can help with it? And what is the most popular     programm for such mathematics tasks?

A: To get the graphics, put:
8*x**2, 64*x*log x

in google. You will get the graph of the two functions and "see" the interval requested.

A: In Maple 16:
solve(8*n^2<64*n*log[2](n));

$$\text {RealRange} \left( \text {Open} \left( -{\frac {8\; \text {LambertW}
 \left( -\frac{\ln  \left( 2 \right)}{8}  \right) }{\ln  \left( 2 \right) }
} \right) ,{\it Open} \left( -{\frac {8\;\text{ LambertW} \left( -1,-
\frac{\ln  \left( 2 \right)}{8}  \right) }{\ln  \left( 2 \right) }} \right)
 \right)
$$
evalf(%);

$$ \text{RealRange}(\text{Open}(1.099997030),\text{Open}(43.55926044))$$
So for integers $n$ the answer is $2 \le n \le 43$.


text:
Q: Show image using OpenCV in Python on a Raspberry Pi terminal I get a gtk-WARNING when trying:
cv2.imshow("WindowName", image)
I'm using this to watch a live stream one frame at a time. Are there any alternative libraries I could use? I tried several other options like PIL and Tkinter as well as wand, but could get none of them to work for various different reason.

A: You need to use a windowing system to display images using imshow.
(That can be enabled in settings running sudo raspi-config)
If you absolutely, positively need to display images without using a windowing system, consider providing an html/web interface. Two options that come to mind when serving a web interface are:

*

*Creating an HTTP video stream (serve the output image as if it's an IP camera, kind of)

*Stream the output matrix as a jpg blob via websockets


text:
Q: Are there other Linux-to-Linux network mount method besides NFS? In Linux,
specifically RHEL/CentOS 7.9, but anything equivalent or of a later version...
if I wanted to mount a folder/directory from another Linux system across a network,
all I am aware of is NFS, either NFSv3 or NFSv4.
Is there any other mount method, that is functionally comparable to NFS,
for mounting some exported (shared) folder/directory
from another Linux system on the network?

A: The two best options are going to be CIFS and NFS. On Linux, most likely you will experience much better reliability in NFSv4.
Yes, it has been a couple decades of NFS. There just doesn't look like anyone is interested in starting over on an alternative. Many storage providers (e.g. NetApp) use NFS or iSCSI over 10gbe.