Por que ao inserir um valor em uma lista ele se torna None?

Question: valores = []

valor1 = valores.append(int(input('Valor 1: ')))
valor2 = valores.append(int(input('Valor 2: ')))

if valor1 in valores > 0:
  print(valor1, 'é positivo')
else:
  print(valor1, 'é negativo')

if valor2 in valores > 0:
  print(valor2, 'é positivo')
else:
  print(valor2, 'é negativo')

Ao executar o código, inserimos os dois valores e no final ambos são negativos pois são "none":
Valor 1: 10
Valor 2: 20
None é negativo
None é negativo

Queria entender por que os valores estão retornando none, o que está errado.
Comment: Você está fazendo `valor1 = valores.append(...)`; o retorno da função `append` é `None`.
Comment: Sobre a sua condição `valor1 in valores > 0`, leia essa discussão: https://pt.stackoverflow.com/q/241769/5878
Answer: Isso acontece porque append retorna None.
Se quer ler os valores e guardá-los na lista, faça esses passos separadamente:
valores = []

# primeiro lê os valores
valor1 = int(input('Valor 1: '))
valor2 = int(input('Valor 2: '))

# depois insere na lista
valores.append(valor1)
valores.append(valor2)

# ou, se quiser, crie a lista diretamente com os valores
valores = [ valor1, valor2 ]

Outro ponto é que isso não faz sentido:
if valor2 in valores > 0:

Como o valor já foi inserido na lista, não precisaria verificar se ele está na lista. E de qualquer forma, não é assim que verifica se o valor é maior que zero (na verdade, esta expressão não faz o que você está imaginando). Bastaria fazer apenas:
if valor1 > 0:
  print(valor1, 'é positivo')
else:
  print(valor1, 'é negativo')

if valor2 > 0:
  print(valor2, 'é positivo')
else:
  print(valor2, 'é negativo')

Comment: valeu amigo!! realmente foi falta de atenção minha, muito obrigado
Answer: Oi, sua atribuição em:
valor1 = valores.append(int(input('Valor 1: ')))
valor2 = valores.append(int(input('Valor 2: ')))

Está errada, nas variavéis valor1 e valor2 não há nada, logo o Python trata como None. A sua lógica na condicional (if/else) também tá estranha.
Versão "corrigida"
valor1 = int(input('Valor 1: '))
valor2 = int(input('Valor 2: '))

if valor1 > 0:
  print(valor1, 'é positivo')
else:
  print(valor1, 'é negativo')

if valor2 > 0:
  print(valor2, 'é positivo')
else:
  print(valor2, 'é negativo')

Se precisar mesmo usar listas:
arr = []
arr.append(int(input('Valor 1: ')))
arr.append(int(input('Valor 2: ')))

for i in arr:
   if i > 0:  # como pode ver, não há tratamento para valor == 0
      print(f'{i} é positivo.')
   else:
      print(f'{i} é negativo.')

Comment: valeu amigo!! falta de atenção minha, muito obrigado


curl POST format for CURLOPT_POSTFIELDS

Question: When I use curl via POST and set CURLOPT_POSTFIELD do I have to urlencode or any special format?
for example: If I want to post 2 fields, first and last:
first=John&last=Smith

what is the exact code/format that should be used with curl?
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reply=curl_exec($ch);
curl_close($ch);

Answer: In case you are sending a string, urlencode() it. Otherwise if array, it should be key=>value paired and the Content-type header is automatically set to multipart/form-data.
Also, you don't have to create extra functions to build the query for your arrays, you already have that:
$query = http_build_query($data, '', '&');

Comment: You can just use `http_build_query($data)` since `&` is the default separator.
Comment: Of course you can skip them. This is to illustrate the other two arguments that you may (or may not) change (ex. the default separator) to suit your specific needs.
Answer: EDIT: From php5 upwards, usage of http_build_query is recommended:
string http_build_query ( mixed $query_data [, string $numeric_prefix [,
                          string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Simple example from the manual:
<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";

/* output:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/

?>

before php5:
From the manual:

CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

So something like this should work perfectly (with parameters passed in a associative array):
function preparePostFields($array) {
  $params = array();

  foreach ($array as $key => $value) {
    $params[] = $key . '=' . urlencode($value);
  }

  return implode('&', $params);
}

Comment: Why would you pass a string if you can pass an array...?
Comment: @barius, I agree with you. And I think http_build_query() actually is better than the function defined above.
Comment: I think $key should be encoded too, just in case you have it like "name&surname" etc. Especially if data is given by the end user
Comment: @skyfree I agree! That function was added in php5 though which was still far from standard in 2011.
Comment: why http_build_query is required when you could just pass array?
Comment: You're right, I'm just somehow used to this because it's the same as GET - a matter of habit so that you won't "forget" to escape next time you're doing GET.
Comment: @Offenso - without `http_build_query`, what is sent, for an array, is a *multi-part form*. This may or may not be what you want, but it requires different code at the receiving end.  See [curl examples in PHP manual](https://www.php.net/manual/en/curl.examples-basic.php#117009) -- Roberto Braga's example "when using curl to post form data and you use an array for CURLOPT_POSTFIELDS option, the post will be in multipart format". Wrapping array with `http_build_query` instead sends the traditional `key1=value1&key2=value2`.
Answer: Do not pass a string at all!
You can pass an array and let php/curl do the dirty work of encoding etc.
Comment: passing an array will be a different Content-type than a string, so there is a good reason to do so.  Took me a while to figure that out.
Comment: Nested arrays won't work. cURL will try to convert them to string and a PHP _Array to string conversion_ notice will follow
Comment: I have no idea why, but I find that on my win dev pc passing an array takes about a second longer (1.029s using array vs. 0.016s using `http_build_query()` on that same array)
Comment: This is a **dangerous** answer in many situations where it isn't just a basic key-based, single dimension array.
Answer: It depends on the content-type
url-encoded or multipart/form-data
To send data the standard way, as a browser would with a form, just pass an associative array. As stated by PHP's manual:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

JSON encoding
Neverthless, when communicating with JSON APIs, content must be JSON encoded for the API to understand our POST data.
In such cases, content must be explicitely encoded as JSON :
CURLOPT_POSTFIELDS => json_encode(['param1' => $param1, 'param2' => $param2]),

When communicating in JSON, we also usually set accept and content-type headers accordingly:
CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'content-type: application/json'
]

Answer: For CURLOPT_POSTFIELDS, the parameters can either be passed as a urlencoded string like para1=val1&para2=val2&.. or as an array with the field name as key and field data as value
Try the following format :
$data = json_encode(array(
"first"  => "John",
"last" => "Smith"
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);

Comment: Hi Shraddha, `json_encode()` will give you something really different of a valid parameter string as `first=John&last=Smith`. `json_encode()` will output: `{"first":"John","last":"Smith"}` which will then become the raw body of your POST request.
Comment: To add to @7ochem's comment:  Unless the recipient is expecting *a single parameter containing a json-encoded string*, instead of `json_encode(...)` do `http_build_query(...)`. This will create the expected "url-encoded string" containing the parameters separated by "&".
Answer: One other major difference that is not yet mentioned here is that CURLOPT_POSTFIELDS can't handle nested arrays.
If we take the nested array ['a' => 1, 'b' => [2, 3, 4]] then this should be be parameterized as a=1&b[]=2&b[]=3&b[]=4 (the [ and ] will be/should be URL encoded). This will be converted back automatically into a nested array on the other end (assuming here the other end is also PHP).
This will work:
var_dump(http_build_query(['a' => 1, 'b' => [2, 3, 4]]));
// output: string(36) "a=1&b%5B0%5D=2&b%5B1%5D=3&b%5B2%5D=4"

This won't work:
curl_setopt($ch, CURLOPT_POSTFIELDS, ['a' => 1, 'b' => [2, 3, 4]]);

This will give you a notice. Code execution will continue and your endpoint will receive parameter b as string "Array":

PHP Notice:  Array to string conversion in ... on line ...
Answer: According to the PHP manual, data passed to cURL as a string should be URLencoded.  See the page for curl_setopt() and search for CURLOPT_POSTFIELDS.
Answer: We were looking for the same solution when we wrote a test for CMS Effcore. The solution turned out to be quite simple and it is shown below:
$data = [
  'name[0]' => 'value 1',
  'name[1]' => 'value 2',
  'name[2]' => 'value 3',
  'id'      => 'value 4'
];

$data = array(
  'name[0]' => 'value 1',
  'name[1]' => 'value 2',
  'name[2]' => 'value 3',
  'id'      => 'value 4'
);

Answer: Interestingly the way Postman does POST is a complete GET operation with these 2 additional options:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');

Just another way, and it works very well.
Comment: Excellent, simple and worked for me aswell!! thank you Klompenrunner!
Answer: This answer took me forever to find as well. I discovered that all you have to do is concatenate the URL ('?' after the file name and extension) with the URL-encoded query string. It doesn't even look like you have to set the POST cURL options. See the fake example below:
//create URL
$exampleURL = 'http://www.example.com/example.php?';

// create curl resource
$ch = curl_init();

// build URL-encoded query string
$data = http_build_query(
    array('first' => 'John', 'last' => 'Smith', '&'); // set url
curl_setopt($ch, CURLOPT_URL, $exampleURL . $data);

// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources

curl_close($ch);

You can also use file_get_contents():
// read entire webpage file into a string
$output = file_get_contents($exampleURL . $data);

Comment: It seems like you are doing a GET rather than a POST.

curl POST format for CURLOPT_POSTFIELDS


How to make full calendar month and year in dropdown selectable

Question: I have a full calendar and I need to show its month and year in dropdown list, I know this question is already asked but still not answered there. I am new to full calendar and as per as i know it is updated now hope there is some easiest way to achieve rather than giving it gotodate option. I have created code pen for the calendar if anyone has done this before then please update my codepen and give me link thank you so much...
 demoToEdit
Below is my code I have added some of the functions of full calendar as you see I am not able to get on which event I should right dropdown year and month so I have not done it.
<code>$(window).load(function(){

  $('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    editable: true,
    eventRender: function(event, element, view) {
        for (var i = 0; i<= event.products.length - 1; i++) {
            element.append('<span>'+event.products[i].name+'<span>');
        };

    },

    events: [
                {
                    title: 'EventName',
                    start: '2016-05-02',
                    products:[
                                {

                                    name:'ProductName'
                                }
                            ]
                },
                {
                    title: 'Event',
                    start: '2016-05-03',
                    products:[
                                {

                                    name:'ProductName1'
                                },
                                {

                                    name:'ProductName2'
                                },
                                {

                                    name:'ProductName3'
                                },
                            ]
                },
                {
                    title: 'EventName',
                    start: '2016-05-13',
                    products:[
                                {

                                    name:'ProductName1'
                                },
                                {

                                    name:'ProductName2'
                                }
                            ]
                },
                {
                    title: 'Event',
                    start: '2016-05-15',
                    products:[
                                {

                                    name:'ProductName'
                                }
                            ]
                },
                {
                    title: 'EventNAme',
                    start: '2016-05-21',
                    products:[
                                {

                                    name:'ProductName1'
                                },
                                {

                                    name:'ProductName2'
                                }
                            ]
                },
                {
                    title: 'Event',
                    start: '2016-05-23',
                    products:[
                                {

                                    name:'ProductName1'
                                },
                                {

                                    name:'ProductName2'
                                }
                            ]
                },
                {
                    title: 'Eventname',
                    start: '2016-05-25',
                    products:[
                                {

                                    name:'ProductName'
                                }
                            ]
                },
                {
                    title: 'Event',
                    start: '2016-05-29',
                    products:[
                                {

                                    name:'ProductName'
                                }
                            ]
                }
            ],
            dayClick: function(date, allDay, jsEvent, view) {
           console.log('date'+date.format('DD/MMM/YYYY')+"allDay"+allDay.title+"jsEvent"+jsEvent+"view"+view)
    }

});
})

[1]: http://codepen.io/sud/pen/LNvZmv
</code>
Comment: a fiddle, bin, pen is nice, but try always to add the code right within your question - only the bugging part - (so we don't have to do it for you)
Comment: thank you for the suggestion I will do it now wait
Comment: You want to change your date according to 2 dropdowns? year and month?
Answer: It is hard to insert drop downs using fullcalendar custom buttons. I simply make header option to false and created custom header myself. Then you can insert any thing to header part and bind events to  those buttons and call appropriate fullcalendar function. example functions that available are
prev (),
next (),
prevYear (),
nextYear (),
today (),
gotoDate ()
Comment: U have create any demo or useble link


how to make coturn run as user coturn

Question: I have coturn running on a server and it runs as usual systemd process as user root.
Can someone tell me how I could make coturn run as user coturn ?
p.s. could someone modify the Tags and add coturn , turn and sturn because I need 300 reputation for this, and I have only 225-
Comment: (after checking): coturn on debian 9, available as a sysv init start script, starts as root (even if there appears to be some preliminary settings for user turnserver). coturn on Debian 10 runs as user turnserver. So does that mean you are running Debian 9 rather than Debian 10?
Comment: Just noticed there's a coturn in stretch-backports already
Comment: I run a Debian 9 but I'l check if I can upgrade coturn.
Comment: Don't try to mix a package from Debian 10 on Debian 9. I could see two options: backport the package(s) from buster to stretch, or just steal the coturn.service from buster and adapt it to stretch (if any needed at all). Oh and of course a 3rd option: upgrade the system to Debian 10.
Answer: OP is running Debian 9. On Debian 9, the coturn package has a start script (only) available as sysv init script, and while the start scripts already takes some actions in relation to user turnserver, coturn is still run as root.
On Debian 10, while the same sysv script will probably behave the same, there's also a coturn.service file, which starts coturn with User=turnserver and Group=turnserver, so systemd will use it.
The good news is that there's already a stretch-backport version of this package, currently version 188.8.131.52-1~bpo9+1. So one just has to add the stretch-backports repository and upgrade the coturn package, as documented there: https://backports.debian.org/Instructions/ (but using stretch-backports rather than buster-backports).
The service will then run as the dedicated user turnserver.
Comment: excellent, added backport version, everything rocks now
Comment: could you please add "coturn" and "turn" to the question tags, I do not have enough reputation to do it.

how to make coturn run as user coturn


Regular expression for checking

Question: I am facing a problem with regular expression in Python.
The problem is that "Have to check a list and have to find out space containing strings."
The code is:
def testFunction(self, func):
        a = re.findall(r'\w+[\ ]*\(.*?\)', func)
        j = len(a)
        print j
        if j<=1:
            return True

        else:
           s = re.findall(r"function *()", func) # cheking
            t = len(s) # calculating the lenth
            if t<=0:
                return True
            else:
                return False

It returns all time true whether there is a gap or nor.
Example:it detects both "test()" & "test ()"
With in a word i am searching for a regular expression it will search for the gap inside a string.It will detect only "test ()" not "test()"
I tried with regex = r'\w+[\ ](.?)'
              regex = r'^\s*'
but unfortunately does not work.
The work can be done by a regular expression that will differ between test(arg1) &
test (arg1).
Thanks.
Comment: If "space" and not "white space", why not `l = ["a b", "c", "d e"]; [x for a in l if a.find(" ") != -1]` ?
Answer: if all you care about is whether there are any spaces, why not just do something like
return " " in func

Answer: how about this r'.*\s+.*'
Answer: [\ ]* matches zero or more occurrences of space. Try [\ ]+ instead
Comment: What the heck is `[\ ]` supposed to be? Couldn't you obfuscate that any further??? ☹
Answer: re.findall(r"function\ *\(\)", func)

Answer: HI,
I have done this by
 def testFunction(self, func):
       #this function looks for a "function",looks for "function"  both with and without parameter & with parameter
        a = re.findall(r'\s', func)
        j = len(a)
        if j<=1:
            return True
        else:
                return False

Thanks a lot :)

Regular expression for checking


How to set DataTemplate element during initialization - 'System.Reflection.TargetInvocationException'

Question: I have got this part of XAML code with DataTemplate:
<Grid Grid.Row="1" Visibility="Collapsed" x:Name="licenseGrid">
 <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
 </Grid.RowDefinitions>
 <ListBox x:Name="LicensesListBox" Grid.Row="0"
       Margin="12,10,12,0" Visibility="Visible"
       ItemsSource="{Binding Licenses}">
   <ListBox.ItemContainerStyle>

   </ListBox.ItemContainerStyle>
   <ListBox.ItemTemplate>
      <DataTemplate x:Name="dt">
             <toolkit:ToggleSwitch x:Name="ts" Header="{Binding Header}"/>
      </DataTemplate>
  </ListBox.ItemTemplate>
 </ListBox>
</Grid>

During initialization of the page I want to set some value to ToggleSwitch elements but in this part of code 'library' is null and I got 'System.Reflection.TargetInvocationException'.
public Page1()
{
    InitializeComponent();

    LicenseViewModel licenseViewModel = new LicenseViewModel();
    licenseViewModel.GetLicenses();
    this.DataContext = licenseViewModel;

    SetLicenseData();
}

private void SetLicenseData()
{
    // Code for other non DataTemplate XAML elements that works

    for (int i = 0; i < LicensesListBox.Items.Count; i++)
    {
        ListBoxItem library = (ListBoxItem)(LicensesListBox.ItemContainerGenerator.ContainerFromIndex(i));
        ToggleSwitch ts = FindFirstElementInVisualTree<ToggleSwitch>(library);
        // another lines with code...
    }
}

I guess it is because ListBox is not fully loaded in that moment but I don't know how to fix this. Thank you for any help.
Comment: You must wait LayoutUpdated Event
Comment: You should also consider that in some configuration the only elements that are generated are only those that fit in the view.
Comment: You mean add LayoutUpade event to ListBox and call SetLicenseData() there? That doesn't help.
Comment: it doesn't work for any element or just for some elements?
Comment: Every ListBoxItem element, 'library' is always null.
Comment: you have a problem in the code by the way `ListBoxItem library = (ListBoxItem)
                 LicensesListBox.ItemContainerGenerator.ContainerFromIndex(i));` you have )) at the end and there should be only one i think you fixed that
Comment: Yes, that is no problem anymore. I have these lines of code also in another method and there it works, but there is ListBox visibly loaded yet so I guess that's why.
Comment: Are you calling `SetLicenseData()` in your contructor?
Comment: Not anymore, now I call it in LayoutUpade method.
Answer: So I finally got it. I add Loaded event to ToggleSwitch element and there simply use cast
ToggleSwitch ts = sender as ToggleSwitch;
//another lines with code


use selected option as argument inside a function

Question: As a JS novice I need some help with the following:
I want to create a 3-steps little program:

let user choose list from a selectbox (fruit or vegetables)
let user choose the number of items (x) he wants to see
show x items of fruit or vegetables

As you can see, step 2 and 3 are working just fine,
My question is about step 1:
how can I pass the selected option in as an argument in the function, just as the second argument (number of elements) is set by the number from the users input.
All help is welcome. Thank you in advance.

// The arrays to choose
var fruit = ['Apple', 'Banana', 'Mango', 'Apricot'];
var vegetable = ['Brussels sprout', 'Broccoli', 'Potato', 'Tomato']

///////////////////// RANDOM ARRAY ELEMENT SELECTION

function getRandomArrayElements(arr, a) {
    var shuffled = arr.slice(0), i = arr.length, min = i - a, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}

// use an eventlistener for the click event
var genElementsdBtn = document.getElementById('genBtn');
genElementsdBtn.addEventListener('click', getElements, false);

function getElements() {
    document.getElementById('result').innerHTML =
    getRandomArrayElements(fruit, a.value).join("   ");
    /* document.getElementById('divalert').className = 'show'; */
}
.wrapper {width:320px; margin: 0 auto}
select, label, button, input, div  {
  width:100%;
  height:45px;
  margin:16px 0;
 }

<select id="selectList">
  <option value="">choose your array</option>
  <option value="fruit" id="fruit">fruit</option>
  <option value="vegetables" id="vegetables">vegetables</option>
</select>

select number of random elements from the chosen list

<input type="number" placeholder="set a number" id="a">

<button id='genBtn' type='button'>generate random array elements</button>

Comment: You are not using SelectList anywhere in your javascript, you need to get its selected value selectList[selectList.selectedIndex].value;
Answer:

var fruits = ['apple', 'banana', 'cherry', 'orange', 'watermelon', 'lemon'];
var veggies = ['carrots', 'eggplant', 'pumpkin', 'tomateos', 'potatoes'];

$('#btn').click(function() {
  var choice = $('#food').val();
  var count = $('#txt_number').val();

  get_food(choice, count);

});

function get_food(choice, count) {
  $('#result').html('');

  for (var i = 0; i < count; i++) {
    $('#result').append((choice == 'fruit') ? fruits[i] : veggies[i]).append(" ");
  }

}

<select id='food'>
  <option value='fruit'>Fruits</option>
  <option value='veggies'>Vegetables</option>
 </select>

<input type='text' id='txt_number' />

<button id='btn'>Get food</button>

Comment: Jquery is not used in the question while asking
Comment: Thank you Ahmad. This clearly works, accept I wish to acompliosh this using pure javascript. Do you see the chace to translate the jquery answer? thanks!!!
Comment: @Bee just give me a few minutes
Answer: You can get current value like this:

let selectList = document.getElementById("selectList");
let currentValue;
selectList.addEventListener("change", function(e){
    currentValue = e.target.value;
    console.log(currentValue);
});
<select id="selectList">
  <option value="">choose your array</option>
  <option value="fruit" id="fruit">fruit</option>
  <option value="vegetables" id="vegetables">vegetables</option>
</select>
Comment: This also helps a lot. Thank you Tapok.
Comment: I can't yet, to green :)
Answer: This should help:

// The arrays to choose
const types = {
  fruit: ['Apple', 'Banana', 'Mango', 'Apricot'],
  vegetables: ['Brussels sprout', 'Broccoli', 'Potato', 'Tomato'],
};
const output = document.getElementById('result');
const typeSelect = document.getElementById('selectList');
const number = document.getElementById('a');
const genElementsdBtn = document.getElementById('genBtn');
///////////////////// RANDOM ARRAY ELEMENT SELECTION

function getRandomArrayElements(arr, a) {
  console.log(arr, a);
  var shuffled = arr.slice(0),
    i = arr.length,
    min = i - a,
    temp, index;
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}

// use an eventlistener for the click event
genElementsdBtn.addEventListener('click', getElements, false);

function getElements() {
  const selected = typeSelect.options[typeSelect.selectedIndex].value;
  const quantity = number.value;
  if (selected && quantity) {
    output.innerHTML = getRandomArrayElements(types[selected], quantity).join("   ");
  }
}
.wrapper {
  width: 320px;
  margin: 0 auto
}

select,
label,
button,
input,
div {
  width: 100%;
  height: 45px;
  margin: 16px 0;
}

  <select id="selectList">
  <option value="">choose your array</option>
  <option value="fruit" id="fruit">fruit</option>
  <option value="vegetables" id="vegetables">vegetables</option>
</select>

  select number of random elements from the chosen list

  <input type="number" placeholder="set a number" id="a">

  <button id='genBtn' type='button'>generate random array elements</button>

Comment: Thank you Oniondomes. This realy helps very much!
Comment: @Bee, btw avoid accessing DOM elements directly by its id as a `document` property (here: `getRandomArrayElements(fruit, a.value)`). Use `getElementById()`-like functions. Read more: https://stackoverflow.com/questions/25325221/why-dont-we-just-use-element-ids-as-identifiers-in-javascript


Calling a function with va_list argument needs va_start() at the beggining?

Question: A function with the following header:
int max(int n, va_list vals)

Called inside the function:
int max_first(int n, ...)

Needs a va_start(vals, n) invocation at the body's beginning? I tried without and it works but I don't understand which is the correct way of doing it.
int max(int n, va_list vals)
{
    va_start(vals, n);
    // etc
}

Answer: The question is if

int max(int n, va_list vals)

Called inside the function:
int max_first(int n, ...)

Needs a va_start(vals, n) invocation at the body's beginning?

No, it does not and it must not, the correct pattern is as follows:
int max_first(int n, ...) {
    va_list vals;
    va_start(vals, n);
    int rv = max(n, vals);
    va_end(vals);
    return rv;
}

then
int max(int n, va_list vals) {
    for (int i = 0; i < n; i ++) {
        int val = va_arg(vals, int);
        ...
    }

    ...
}

i.e. you can call va_start only in a function that has ... and you need to pass in the argument immediately preceding the ..., and each call to va_start must be always followed by va_end for the same value, and if you pass it to a function then you must call va_end right afterwards without using it in the calling function; if you want to process the arguments again, you must then call va_start again.
Answer: You must initialize va_list with va_start in max_first. But you must not redo it in max, because that function doesn't have necessary callframe information.
Comment: _that function doesn't have necessary callframe information_. What do you mean ?
Comment: @CătălinaSîrbu You have to pass last non variable argument (`n` in `max_first`) to `va_start`, which it will use to calculate address of first possible variable argument. Your another function `max` doesn't have that variable (that `n` is different).
Answer: Let's start with some background: per the documentation, you need to call va_start before invoking va_arg on any va_list:

"va_start should be invoked with an instance to a valid va_list object ap before any calls to va_arg". (Source)

"Prior to calling va_arg, ap must be initialized by a call to either va_start or va_copy, with no intervening call to va_end". (Source)

I would imagine not calling va_start is undefined behavior, but I couldn't find a specific callout to state as such.
In your question, the function int max(int n, va_list vals) is not "really" variadic, since it accepts a fixed number of arguments: 2. These are int n and va_list vals.
Per the documentation "The declaration of a variadic function uses an ellipsis as the last parameter, e.g. int printf(const char* format, ...);"
So, it depends on how you implement it, but I would recommend documenting the int max(int n, va_list vals) to accept a va_list that is already initialized with a va_start call. The rationale being that it is not technically "variadic" and does not really "own" the va_list. It just accepts it as an input from some other source.
The actual variadic function int max_first(int n, ...) should be the one creating the va_list and priming it with the call to va_start before passing it anywhere.
Although, as far as I can tell, there's no way to check if a va_list already has va_start called on it or not. And there's no guarantee that it will be called before being passed to your function, so I suspect this would have to be enforced by documentation and convention.
Comment: A note on formatting: \` ≠ ". Backticks are there exclusively *to highlight code* (and other monospaced stuff, e.g. paths)
Comment: @CătălinaSîrbu - you should call `va_start` in `max_first` before passing it to `max`. And you should not call `va_start` twice without first having a call to `va_end`. This is called out in the C11 specification, as mentioned here https://stackoverflow.com/a/59608709/1366973. Otherwise it is undefined behavior.
Comment: Thank you! After reading your answer, some questions came into my mind: It is perfectly fine to call `int max` from `int max_first` before max_first calling va_start? also, calling twice va_start (once in `max` and second in `max_first`) is a problem ?
Comment: You can format quotes on separate paragraphs prefixing the lines with `>`


Comparador - PriorityQueue

Question: Estou a construir um comparador para depois usar dentro de uma PriorityQueue.
private PriorityQueue<Conta> listaOrdenada = new PriorityQueue<Conta>(new ComparadorConta());

O objeto que quero ordenar é a Conta.
 Conta conta = new Conta(String designação, int numero);

 new Conta("A",2);
 new Conta("B",3);
 new Conta("B",6);
 new Conta("A",1);
 new Conta("A",5);

O suposto é ordenar segundo o seguinte critério:

Tem de vir os que tem um numero inferior a 4
Tem de vir os que começam com a letra A
Ordem de inserção

Isto daria este ouput:
"A",2
"A",1
"B",3
"B",6
"A",5
Só que só sei ordenar por número.
public class ComparadorConta implements Comparator<Conta>{

 @Override
 public int compare(Conta a, Conta b) {

    return a.getNumero() - b.getNumero();
 }
}

Alguem me pode ajudar a ordenar por estes critérios? Obrigado!
Comment: Só uma coisa cara. Pra acessar o atributo `numero` você usa um método mesmo? `numero()`?
Comment: por acaso ate era get numero, ja mudei
Comment: Nesse teu exemplo a ordem correta final não seria: "A",2
"B",3
"A",1
"A",5
"B",6?
Answer: EDIT 1 - Com PriorityQueue
Caso realmente precise usar PriorityQueue para ordenar, sugiro a criação de uma variável de controle para saber a ordem de inserção.
Crie uma variável de classe para controlar o último inserido dentro da classe Conta:
private static int ultimo = 0;

Crie um atributo ordem que será utilizado internamente:
private final int ordem;

No construtor, instancie a ordem e atualize a variável ultimo:
this.ordem = ultimo + 1;
ultimo = this.ordem;

Adicione o get do campo ordem:
public int getOrdem() {
  return ordem;
}

Para fazer a comparação, você não precisa de um Comparator, apenas que a sua classe Conta implemente a interface Comparable da seguinte forma:
public class Conta implements Comparable<Conta> {

Você precisará implementar o método compareTo que ficará como o seguinte, respeitando as 3 regras impostas no tópico:
@Override
public int compareTo(Conta conta) {

  // 1. Tem de vir os que tem um numero inferior a 4
  if (this.numero < 4 && conta.getNumero() >= 4) {
    return -1;
  } else if (this.numero >= 4 && conta.getNumero() < 4) {
    return 1;
  }

  // 2. Tem de vir os que começam com a letra A
  if (this.designacao.toUpperCase().startsWith("A") && !conta.getDesignacao().toUpperCase().startsWith("A")) {
    return -1;
  } else if (!this.designacao.toUpperCase().startsWith("A") && conta.getDesignacao().toUpperCase().startsWith("A")) {
    return 1;
  }

  // 3. Ordem de inserção
  return Integer.valueOf(this.ordem).compareTo(conta.getOrdem());
}

Para testar utilize:
public static void main(String[] args) {
  PriorityQueue<Conta> listaOrdenada = new PriorityQueue<>();

  listaOrdenada.add(new Conta("A", 2));
  listaOrdenada.add(new Conta("B", 3));
  listaOrdenada.add(new Conta("B", 6));
  listaOrdenada.add(new Conta("A", 1));
  listaOrdenada.add(new Conta("A", 5));

  while(!listaOrdenada.isEmpty()) {
    System.out.println(listaOrdenada.poll());
  }
}

Lembrando que a estrutura que você está utilizando (PriorityQueue) reorganiza os itens após o poll.
Isso resultará em:

"A",2
"A",1
"B",3
"A",5
"B",6

Sem PriorityQueue
Acredito que usar o Collections.sort e PriorityQueue não seja a melhor escolha pelo fato de já existir uma estrutura com o requisito 3 que é a ordem de inserção. O LinkedHashSet.
Colocarei aqui duas implementações e o teste das duas é realizado com o seguinte código:
LinkedHashSet<Conta> lista = new LinkedHashSet<>();
LinkedHashSet<Conta> listaOrdenada;

lista.add(new Conta("A", 2));
lista.add(new Conta("B", 3));
lista.add(new Conta("B", 6));
lista.add(new Conta("A", 1));
lista.add(new Conta("A", 5));

listaOrdenada = this.ordenar(lista);

for (Conta conta : listaOrdenada) {
  System.out.println(conta);
}

Onde a classe conta possui o método toString seguinte:
@Override
public String toString() {
  return "\"" + this.designacao + "\"," + String.valueOf(this.numero);
}

A primeira considera apenas as 3 regras isoladas:
public LinkedHashSet<Conta> ordenar(LinkedHashSet<Conta> lista) {
  LinkedHashSet<Conta> prioridade1 = new LinkedHashSet<>(); // Números menores que 4
  LinkedHashSet<Conta> prioridade2 = new LinkedHashSet<>(); // Letra "A"
  LinkedHashSet<Conta> restante = new LinkedHashSet<>();
  LinkedHashSet<Conta> listaOrdenada = new LinkedHashSet<>();

  for (Conta conta : lista) {
    if (conta.getNumero() < 4) {
      prioridade1.add(conta);
    } else if (conta.getDesignacao().toUpperCase().startsWith("A")) {
      prioridade2.add(conta);
    } else {
      restante.add(conta);
    }
  }

  listaOrdenada.addAll(prioridade1);
  listaOrdenada.addAll(prioridade2);
  listaOrdenada.addAll(restante);

  return listaOrdenada;
}

Resultando em:

"A",2
"B",3
"A",1
"A",5
"B",6

A segunda considera que os números menores que 4 e com letra "A" tem prioridade máxima:
public LinkedHashSet<Conta> ordenar(LinkedHashSet<Conta> lista) {
  LinkedHashSet<Conta> prioridade1 = new LinkedHashSet<>(); // Números menores que 4 com letra "A"
  LinkedHashSet<Conta> prioridade2 = new LinkedHashSet<>(); // Números menores que 4
  LinkedHashSet<Conta> prioridade3 = new LinkedHashSet<>(); // Letra "A"
  LinkedHashSet<Conta> restante = new LinkedHashSet<>();
  LinkedHashSet<Conta> listaOrdenada = new LinkedHashSet<>();

  for (Conta conta : lista) {
    if (conta.getNumero() < 4
            && conta.getDesignacao().toUpperCase().startsWith("A")) {
      prioridade1.add(conta);
    } else if (conta.getNumero() < 4) {
      prioridade2.add(conta);
    } else if (conta.getDesignacao().toUpperCase().startsWith("A")) {
      prioridade3.add(conta);
    } else {
      restante.add(conta);
    }
  }

  listaOrdenada.addAll(prioridade1);
  listaOrdenada.addAll(prioridade2);
  listaOrdenada.addAll(prioridade3);
  listaOrdenada.addAll(restante);

  return listaOrdenada;
}

Resultando em:

"A",2
"A",1
"B",3
"A",5
"B",6

Caso seja necessário usar PriorityQueue você pode fazer a conversão a seguir:
PriorityQueue pq = new PriorityQueue();
pq.addAll(listaOrdenada);

Comment: Mas e quanto aos critérios 1 e 3? A comparação entre letras realmente funciona, porém a de números não parece se encaixar
Comment: Começa pelo número né? Fiz invertido. Mas ta ali o compareTo do numero também
Comment: pois é isso, eu preciso dos 3 critérios. E esse só dá as letras.
Comment: @Sorack Acontece que seu código não compara se é menor que 4, e também não compara os objetos pela ordem de inserção, como deveria.
Comment: Alterei para corresponder exatamente ao que foi perguntado
Comment: Obrigado! Mas tenho mesmo de resolver isto com priority queue
Comment: Você pode dar um PriorityQueue pq = new PriorityQueue();
pq.addAll(listaOrdernada); para transformar depois
Comment: sim, mas sem usar linkedhash é que é suposto.
Comment: Verifique o `Edit 1` com a implementação necessária para que seu problema seja resolvido com `PriorityQueue`
Answer: Para ordenar com uma ou mais campos funciona assim, supondo 3 campos no seu caso é dois.
Lição 1: conforme aumenta o numero de campos aumenta o numero e quando retorna zero é que ele não muda de posição, isso faz com que avance ou recue a posição do item na coleção
 1
 2
 3
 0
-1
-2
-3

Lição 2: Implementar a interface java.lang.Comparable
Fazendo a implementação conforme necessário, somente do methodo
@Override
public int compareTo(Object object)
{
    Conta bean = (Conta) object;
    int result=0;
    if (this.getId() < bean.getId())
    {
        result = -1;
    }
    else if (this.getNumero() < bean.getNumero)
    {
        result = -2;
    }
    else if (this.getDescricao() < bean.getDescricao())
    {
        result = -3;
    }else if (this.getId() > bean.getId())
    {
        result = 1;
    }
    else if (this.getNumero() > bean.getNumero)
    {
        result = 2;
    }
    else if (this.getDescricao() > bean.getDescricao())
    {
        result = 3;
    }
    return result;
}

Lição 3:  Trate as condições conforme sua necessidade. depois é só usar, clean code

Collections.sort(contas);

Comparador - PriorityQueue


SwiftUI Navigation Link Selection's Highlight Not Working

Question: In iOS, when you tap a row in a list to navigation to a page, the row gets highlighted to indicate which row is selected. This is not working for me when I have a NavigationStack(path:root:) that uses NavigationLink(_ titleKey:value:) and navigationDestination(for:destination).
Highlight doesn't work in the code below for me neither in Simulator nor device:
import SwiftUI

struct ExperimentView: View {
    @State private var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            List {
                NavigationLink("Page", value: 0)
                NavigationLink("Page", value: 1)
                NavigationLink("Page", value: 2)
            }
            .navigationTitle("List")
            .navigationDestination(for: Int.self) { int in
                Text(int.description)
            }
        }
    }
}

But it works just fine when I use NavigationStack(root:) that uses NavigationLink(_ titleKey:destination).
Comment: Can you describe more specifically how "the row gets highlighted"? I don't see any difference between using `.init(_:destination:)` and `.inti(_:value)`. The navigation links turn grey when I tap on them in both cases.
Answer: This is one of the core differences between NavigationStack and NavigationSplitView.
The selection only works with NavigationSplitView I assume it is because the List does not stay on the screen with NavigationStack
struct ExperimentView: View {
    @State private var selection: Int?
    var body: some View {
        NavigationSplitView {
            List(selection: $selection) {
                NavigationLink("Page", value: 0)
                NavigationLink("Page", value: 1)
                NavigationLink("Page", value: 2)
            }
        } detail: {
            if let selection {
                Text(selection.description)

            } else {
                Text("Please select page.")
            }
        }
    }
}

https://developer.apple.com/documentation/swiftui/migrating-to-new-navigation-types#Update-selection-based-navigation


PHP unique values from fetch_assoc()

Question: I have a product database and each product has 1 or more tags. For example, my query result is:
//Query results
product_id  tag
12345       Kitchen
12345       Mixer
12345       Baking

How can I display all the tags for a given product and only list the product once so that my output is something like:
Product ID: 12345
Tags: Kitchen Mixer Baking

Currently, I'm using fetch_assoc() and looping through the rows which just displays everything. What's the best way to accomplish this?
Below is my current code:
$sql = <<<SQL
    SELECT p.product_id, t.tag
    FROM products p
    JOIN tags t
    ON p.product_id = t.product_id
    WHERE p.product_id='12345'
SQL;

$db = new mysqli('localhost', 'user', 'password', 'dbname');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

while($row = $result->fetch_assoc()){
    echo $row['product_id'] . '
';
    echo $row['tag'] . '
';
}

Answer: Use GROUP_CONCAT() function:
SELECT p.product_id, GROUP_CONCAT(t.tag)
FROM products p
JOIN tags t
ON p.product_id = t.product_id
WHERE p.product_id='12345'
GROUP BY p.product_id

Comment: Thanks! That was simple enough.

PHP unique values from fetch_assoc()


Assign string from vector of strings

Question: vector<string> a;
string b;
a.push_back("1");
a.push_back("2");
b = a.back();

I would like to assign string b to a value from the vector of strings.
b = a.back() does not seem to work. b.assign(a.at(1)) does not seem to work.
Is there any way I can do this? gdb says there is error at raise.c:54.
Comment: Can you provide a backtrace from the gdb at the time you get the error?
Comment: How did you verify that `b = a.back();` doesn't work? http://coliru.stacked-crooked.com/a/56460bc0e3b818f0
Comment: `b = a.back()` *and* `b.assign(a.at(1))` work just fine. Could you post a [mcve] that demonstrates how they don't?
Comment: Cannot reproduce; `b` contains `"2"` in my test.
Comment: If we can't see line 54, we can't comment on the error at line 54.
Comment: If the error is in `raise.c`, are you sure that your code is compiled as C++ and not in language C?
Comment: Thank you for your comments!!! I will look further!
Answer:
I would like to assign string b to a value from the vector of strings.

The way to do it is exactly like in your code. Either version is correct.
If this program crashes, then possibly your compiler / runtime library is borked. You could try to solve that by reinstalling a fresh copy.
Comment: Thank you for your answer! I will try reinstalling!

Assign string from vector of strings


jquery and part-find names

Question: I have many INPUT tags with the following name structure:
name="menu:popSearch:chk0"
name="menu:popSearch:chk1"
name="menu:popSearch:chk2"
name="menu:popSearch:chk3"
and so on.
What jQuery will give me the INPUT 's that follow this structure.
(It's to run the sites http://BiblePro.BibleOcean.com and http://BahaiResearch.com)
Answer: do you mean find all the inputs with popSearch in the name,
you can use
<code>var list = $("input[name*='popSearch']")
</code>
that will get you an array of those elements that have popSearch in the name
Comment: You can also use `$("input[name*='menu\\:popSearch\\:chk'])` to match more strictly names. Colon has to be escaped if you want to include it in search pattern.
Comment: What about all those INPUTS where they are checked ?
Comment: answers in the other quetion you asked :)

jquery and part-find names


Small Business Server 2008 Standard vs Windows Server + Exchange

Question: As far as I can tell, the only compelling reasons to get SBS are Exchange and Remote Web Workplace.  Less interesting but useful features are Shared Fax and Backup.  Most of the other "features" of SBS are free products like WSUS and WSS, or trialware (Forefront).
I'm playing with pricing here, and it looks like I can get Windows Server 2008 Standard x2 plus Exchange Server 2010 (or 2007) for only $1500 more than SBS 2008.  (I only need Exchange CALs for a portion of the devices on the network)
I've running SBS since 4.0 and have always found it...annoying.  For instance, I just read that in SBS 2008 we're limited to one network connection....which sounds fine unless you have a legitimate use for a second connection, like iSCSI, etc.  Crap like this drives me up the wall.
So my question to you all is, what are the actual non-configuration-wizard features of SBS that I'm going to miss if I go with standalone Windows Server and Exchange products.  So far I've got:
1) Remote web workplace
2) Shard Fax
3) SBS Backup (it's sorta neat, but I hear Server 2008 will incorporate it eventually?)
What else is unique to SBS that I'm overlooking here?  Again, I'm only looking for usable features...not features that limit usability or supposedly make it easier to use.
Answer: Well from what I remember, Exchange CALs are included in your SBS 2008 CALs. And if you purchase the Premium edition of SBS 2008, you get a second Windows Server license so you can use it for either an edge firewall or anything else (SQL), except Exchange, since it must stay with the "PDC" (main SBS 2008 server.)
I had this question myself, I went ahead and chose SBS 2008 over separate purchases of each "server" software. For us it ended up coming out cheaper with a bunch more little pros than cons, such as the ones you mentioned.
I could be wrong, but you can use more than one NIC, however it isn't supported.
http://blogs.technet.com/sbs/archive/2008/09/26/can-i-use-terminal-services-in-sbs-2008.aspx
Multiple NICs in SBS 2008 Discussion
Comment: Thanks for your comments.  I'm considering virtualizing and if I do so I think I'm going to lose several of the smaller benefits of SBS, such as VSS backups and shared fax.  The premium version of SBS is very expensive if you've no need for SQL Server...it's cheaper to just buy another Windows 2008 license.
Comment: There are no "PDC" computers in Active Directory. All copies of an Active Directory database hosted by DCs in the same AD domain are equal. The SBS Server computer must hold the two forest-wide and three domain-wide FSMO roles, as well as being a global catalog server. One of those domain-wide FSMO roles is "PDC Emulator", but that doesn't make the copy of AD on the SBS Server some kind of special "primary" copy.
Comment: Correct and I am well aware of how Active Directory works. What I meant was misunderstood, PDCs were NT days, thus the "s. My apologies for using the term too loosely.
Answer: I think about a better approach for iSCSI.
You should install on your phisical box Windows Server 2008 Enterprise R2 x64 core edition. It is almost like the full version, but it lacks GUI. What is powerful is Hyper-v total support and iSCSI, so you can configure iscsi with one or two NICs and they become Hyper-v resources.
On the top of the virtual hypervisor, then you create a new VM and you may install on it SBS 2008. you wil configure it with only one NIC, but the underlying system is connected with other two NICs.
Comment: I forgot the funniest thing: Windows Server 2008 Enterprise x64 Core Edition IS TOTALLY FREEEEEEEE!


bijection of the sum of 3 variables

Question: I was doing an exercice and there is a sentence in the correction i didn't quite understand. I had three balanced dices and I had to find the probability that the sum gave an even result.
When I check my answer they just give a weird explanation : let $(i,j,k)$ be result of my 3 dices in $\{1,2,3,4,5,6\}$ and an application
$\omega \mapsto (7-i,7-j,7-k)$ is said to be the bijection of the $(i,j,k)$ giving an even sum over those over an uneven onesum.
I know what is a bijection but I just don't get it why it's a bijection in between : {sum of dice is even} and {sum of dice is uneven}
I'd just like to understand because it doesn't make sense to me.
Thank you for your help
Answer: If $i+j+k$ is even $(7-i)+(7-j)+(7-k)$ is odd.
Answer: It's one-to-one, each triple $(7-i,7-j,7-k)$ corresponds to a single input $(i,j,k)$. There's no way to have $(7-i_1,7-j_1,7-k_1)=(7-i_2,7-j_2,7-k_2)$ unles $(i_1,j_1,k_1) = (i_2,j_2,k_2)$. Furthermore, it is surjective (onto) since we have when $(7-1,7-1,7-1,)=(6,6,6)$ all the way to $(7-6,7-6,7-6)=(1,1,1)$, i.e. all the possible triples $(i,j,k)$ are accounted for. Does that make sense?
Comment: If $i+j+k = 2b$ for some $b\in\mathbb{N}$ then $7-i + 7-j + 7-k = 21 - (i+j+k) = 21-2b = 2(10) + 1 - 2b = 2(10-b)+1$ is odd since $10-b\in\mathbb{Z}$.
Comment: I understand for $(i,j,k) \mapsto (7-i,7-j,7-k)$ what I don't get is about having a bijection between "the sum of dices giving an even result" and "the sum of dices giving and uneven result"
Comment: Thank you very much for these clarifications !

bijection of the sum of 3 variables


Where should I store in app purchase 'Consumable' information

Question: I have an app where users purchase tokens in order to interact with the app.
So if the user purchases 100 tokens his 'token' count would equal 100, then if the user purchases another 100 tokens, it would equal 200 tokens, and so on and so forth.
Question is where should I store the 'token' count for the app!? I want the user to have access to his 'tokens' no matter what device he uses (iPhone, Android, website...) All the user needs to do is login to his account on the device.
Comment: As far as I know, consumables can not be restored (therefore, not shared among devices). You must implement your own, server-based sync logic to preserve the user's coins across sessions on different devices (and prevent them form e.g. using the same coin twice).
Answer: you need to store it in an database where you can access from iphone, android and website. it can be an self hosted database where you need to write your server side api or it can be a cloud service like FireBase.
my advice: add also an transaction log for each time the user uses the token or recharge the token. in case of trouble you can see where the tokens are gone or how he reloaded the tokens and you can show this log also to the user
Comment: if utilizing firebase, can you suggest the firebase rules to secure the token count so that the users can 'inflate' the actual tokens purchased?
Comment: yes - you should secure your data. how you restrict the access depends on your database.


Using dhcp and static ip on same nic on linux with systemd-networkd

Question: I have a portabel device that sometimes needs connection to internet(to update) but will mostly be used directly connected to a laptop via ethernet cable. I want my users to have the plug and play benefits from dhcp ip when connected to a router but still be able to reach the device when no dhcp server is involved.
I basically want to do this but with systemd-networkd:

auto lo
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
auto eth0:0
iface eth0:0 inet static
address 192.168.0.130
netmask 255.255.255.0

How do i achieve this with systemd-networkd and is there a better way to achieve same result?
Answer: You can enable DHCP on a network interface and also set additional IPv4/IPv6 addresses.
This is an example configuration: /etc/systemd/network/eth0.network
[Match]
Name=eth0

[Network]
DHCP=yes

[Address]
Address=192.168.0.130/24

It results in:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:8d:c0:32 brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.130/24 brd 192.168.0.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic eth0
       valid_lft 86357sec preferred_lft 86357sec
    inet6 fe80::a00:27ff:fe8d:c04d/64 scope link
       valid_lft forever preferred_lft forever

192.168.0.130 is the static IPv4, 10.0.2.15 the IPv4 from DHCP.
Answer: You can configure dhclient.conf as follows:
timeout 10;

lease {
interface "eth0";
fixed-address 10.0.0.10;
option subnet-mask 255.255.255.0;
}

interface "ep0" {
prepend domain-name-servers 10.0.0.1;
}

This will configure your dhcp to timeout after 10 seconds of not getting an IP address from a DHCP server and give the address 10.0.0.10 on a /24 network. You can also set DNS servers in the configuration as well. Here's a link to the man page that I got this configuration from

http://www.freebsd.org/cgi/man.cgi?query=dhclient.conf&sektion=5&n=1


Conflito RewriteRule no htaccess

Question: Já fiz várias pesquisas mas não achei a solução do meu problema.
Tenho um htaccess no seguinte formato:
RewriteEngine On
RewriteRule fotos$ arc_fotos.php
RewriteRule fotos/$ arc_fotos.php
RewriteRule minha-area/$ arc_minha_area.php
RewriteRule minha-area/fotos$ arc_minhas-fotos.php

Quando eu acesso o endereço meudominio.com.br/fotos -> página de fotos (arc_fotos) OK
Mas quando eu acesso o endereço meudominio.com.br/minha-area/fotos ele vai para arc_fotos.php sendo que eu quero que vá para arc_minhas_fotos.php
O mesmo caso acontece quando:
RewriteEngine On
RewriteRule blog/$ arc_blog.php
RewriteRule esqueci esqueci_senha.php

Quando o usuário acessa meudominio.com.br/blog/uma-pagina-com-url-inesquecivel ele interpreta inESQUECIvel e vai para a página esquece_senha.php
Alguém pode me auxiliar para evitar esse tipo de conflito?
Answer: Para resolver seu problema, você deve saber analisar o nível de especificação das suas regras.

As regras mais especificas devem ficar no topo.

Mas como assim nível de especificação?
O nível de especificação pode ser verificado de varias formar (se quiser saber mais peça depois, vou abordar apenas o seu caso)

Para saber se algo é mais especifico basta verificar se alguma outra regra engloba ela.

RewriteRule fotos$ arc_fotos.php # menos especifico
RewriteRule minha-area/fotos$ arc_minhas-fotos.php # mais especifico

A primeira regra engloba a segunda pois fotos$ também captura as sentença de minha-area/fotos$ ou seja a primeira regra é mais genérica tornando a segunda mais especifica, já que para a segunda ocorrer é necessário ter junto minha-area.
Seguindo a norma citada a cima a sua ordem então deveria ser :
RewriteRule minha-area/fotos$ arc_minhas-fotos.php # mais especifico
RewriteRule fotos$ arc_fotos.php # menos especifico

Conflito RewriteRule no htaccess


Draw two CAShapeLayer's intersection

Question: I'm trying to draw two CALayer intersection to UIImage using UIGraphicsImageRenderer and CGBlendModes with no success. I tried all blend modes with different layers position and I'm pretty much stuck.
Is this a good way to do this or there is other way?
What I want to achieve

Here is playground code sample
import UIKit
import PlaygroundSupport

func getDesignElementLayer(byElementID elementID : Int) -> CAShapeLayer
{
    let caShapeLayer = CAShapeLayer()
    caShapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
    caShapeLayer.fillColor = UIColor.black.cgColor

    switch elementID
    {
    case 1:
        let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
        caShapeLayer.path = ovalPath.cgPath
    case 2:
        let bezierPath = UIBezierPath()

        bezierPath.move(to: (CGPoint(x: 50, y: 0)))
        bezierPath.addLine(to: (CGPoint(x: 0, y: 100)))
        bezierPath.addLine(to: (CGPoint(x: 100, y: 100)))
        bezierPath.addLine(to: (CGPoint(x: 50, y: 0)))
        bezierPath.close()
        caShapeLayer.path = bezierPath.cgPath

    default:
        print("")
    }

    return caShapeLayer
}

class MyViewController : UIViewController
{

    var shape1 : CAShapeLayer!
    var shape2 : CAShapeLayer!

    var testView : UIView!

    override func loadView() {
        let view = UIView()

        view.backgroundColor = .white
        shape1 = getDesignElementLayer(byElementID: 1)
        shape1.fillColor = UIColor.green.cgColor
        shape2 = getDesignElementLayer(byElementID: 2)
        shape2.fillColor = UIColor.yellow.cgColor

        view.layer.addSublayer(shape1)
        view.layer.addSublayer(shape2)

        let imageView = UIImageView(frame: CGRect(x: 0.0, y: 150.0, width: 100.0, height: 100.0))
        imageView.image = render()
        view.addSubview(imageView)
        self.view = view
    }

    func render() -> UIImage
    {
        let resolution = CGSize(width: 100.0, height: 100.0)
        let imageRenderer = UIGraphicsImageRenderer(size: resolution)
        let image = imageRenderer.image { (context) in

            shape1.render(in: context.cgContext)
            context.cgContext.setBlendMode(.clear)
            shape2.render(in: context.cgContext)
        }
        return image
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

EDIT: CALayers can have image as content, so CAShapeLayers in example are just for example. I need to find intersection of any type of CALayers.
Answer: You can do this by clipping cgPaths instead of shape layers.
Here is a playground example:
import UIKit
import PlaygroundSupport

func getDesignElementPath(byElementID elementID : Int) -> CGPath
{
    var pth: CGPath!

    switch elementID
    {
    case 1:
        let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
        pth = ovalPath.cgPath
    case 2:
        let bezierPath = UIBezierPath()

        bezierPath.move(to: (CGPoint(x: 50, y: 0)))
        bezierPath.addLine(to: (CGPoint(x: 0, y: 100)))
        bezierPath.addLine(to: (CGPoint(x: 100, y: 100)))
        bezierPath.addLine(to: (CGPoint(x: 50, y: 0)))
        bezierPath.close()
        pth = bezierPath.cgPath

    default:
        print("")
    }

    return pth
}

class MyViewController : UIViewController
{
    override func loadView() {
        let view = UIView()

        view.backgroundColor = .white

        let img = renderTest()

        let imageView = UIImageView(image: img)
        imageView.frame.origin = CGPoint(x: 40, y: 40)
        view.addSubview(imageView)

        self.view = view
    }

    func renderTest() -> UIImage {

        let size = CGSize(width: 100.0, height: 100.0)

        UIGraphicsBeginImageContext(size)

        guard let ctx = UIGraphicsGetCurrentContext() else { return UIImage() }

        let circle = getDesignElementPath(byElementID: 1)
        let triangle = getDesignElementPath(byElementID: 2)

        ctx.addPath(circle)
        ctx.clip()

        ctx.addPath(triangle)
        ctx.clip()

        ctx.setFillColor(UIColor.yellow.cgColor)
        ctx.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

Result:

Edit:
If you want to get that shape to clip an image, you can use it as a mask.
Same code as above, but replace viewDidLoad() with:
override func loadView() {
    let view = UIView()

    view.backgroundColor = .white

    // load a 100x100 image (of a cat)
    let imgForLayer = UIImage(named: "cat100x100.jpg")

    // create a 100x100 UIView at x:40 y:40
    let testView = UIView(frame: CGRect(x: 40.0, y: 40.0, width: 100.0, height: 100.0))

    // create an "image layer"
    let imgLayer = CALayer()
    // set its frame to match the view
    imgLayer.frame = testView.bounds
    // set its contents to the "cat" image
    imgLayer.contents = imgForLayer?.cgImage
    // add it as an "image sub layer"
    testView.layer.addSublayer(imgLayer)

    // create image with triangle / oval clip path
    let img = renderTest()

    // create a UIImageView from the rendered image
    let maskImageView = UIImageView(image: img)

    // use that image view as a mask
    testView.mask = maskImageView

    // add testView to the view
    view.addSubview(testView)

    self.view = view
}

Cat image:

Result:
Comment: Thank you for response, but this is not what I need. Sometimes I will have two CALayers that have UIImage as content and I need to find their intersection so I can't achieve it with CGPath.
Comment: Hmmm... well, if I understand correctly... You have a view with an image as a sub layer, you could create this imageView and use it as a mask for your view. See my edited answer.
Comment: Good suggestion, but still doesn't work for me. I want to be able to make two shapes intersection, then make intersection with CATextLayer, maybe intersection with UIImage. All of this should happen offscreen on CGContext, not adding to UIImageView.

Draw two CAShapeLayer's intersection


selectOneMenu - a4j onchange do not work

Question: I'm trying to make the following code working using a4j update.
Here my souce code:
File communauteThematiques.xhtml:
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:s="http://jboss.com/products/seam/taglib"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:rich="http://richfaces.org/rich"
    xmlns:a4j="http://richfaces.org/a4j"
    template="../layout/template.xhtml">

    <ui:define name="containerCentral" >

            <h:messages globalOnly="true" />

        <s:div style="padding-top: 20px;" >
            <h:form id="frmList" >

Gestion des thématiques des communautés

                <h:outputText value="Sélectionner une communauté : "/>
                <h:selectOneMenu id="listeCommunaute" value="#{adminThesaurusThematiques.communauteSelected}" required="true" disabled="#{adminThesaurusThematiques.communauteSelected != null}" >
                    <s:selectItems value="#{adminThesaurusThematiques.listeCommunaute}"
                                   var="communaute"
                                   label="#{communaute.nom}"
                                   noSelectionLabel="Veuillez sélectionner une communauté ... " />
                    <a4j:support event="onchange" reRender="arbre" status="majTypeWaiting" ajaxSingle="true" />
                </h:selectOneMenu>

                <a4j:status id="majTypeWaiting" forceId="true">
                    <f:facet name="start">

                    </f:facet>
                </a4j:status>

                <rich:tree id="arbre" value="#{adminThesaurusThematiques.arbre}" var="node" switchType="client" toggleOnClick="true" >
                    <rich:treeNode>
                        <h:outputText value="#{node}" />
                    </rich:treeNode>
                </rich:tree>

                <h:commandButton id="saveNewOrder" value="Enregistrer les modifications" action="#{adminThesaurusThematiques.saveNewOrder}" style="display: none;" />
            </h:form>
        </s:div>

    </ui:define>
</ui:composition>

File AdminCommunauteThematiquesAction:
public class AdminCommunauteThematiquesAction {

    @Logger
    private Log log;

    @In(create = true)
    private GeneralMgr generalMgr;
    @In(create = true)
    private CommunauteMgr communauteMgr;
    @In(create = true)
    private MetadataMgr metadataMgr;
    @In
    private FacesMessages facesMessages;
    private Communaute communauteSelected;
    private List<Communaute> listeCommunaute;
    private TreeNodeImpl<String> arbre;

    @Create
    public void init() {
        //if (listeCommunaute == null) {
            log.debug("Listing des communautés");
            listeCommunaute = communauteMgr.getListeCommunautesByName();
        //}
    }

    public List<Communaute> getListeCommunaute() {
        return listeCommunaute;
    }

    public void setListeCommunaute(List<Communaute> listeCommunaute) {
        this.listeCommunaute=listeCommunaute;
    }

    public Communaute getCommunauteSelected() {
        return communauteSelected;
    }

    public void setCommunauteSelected(Communaute communaute) {
        this.communauteSelected=communaute;
    }

    private void buildTree() {
        try {
            arbre = new TreeNodeImpl<String>();
            Metadata thesaurus = metadataMgr.getApplicationMetadata();
            if (thesaurus.getThesaurus() != null) {
                for (MetadataValue metVal : thesaurus.getThesaurus()) {
                    arbre = ajoutNodeRecursif(arbre, metVal);
                }
            }
        } catch (Exception e) {
            log.error("Erreur pendant la génération de l'arbre de thématiques", e);
            facesMessages.add("Une erreur est survenue pendant la génération de l'arbre de thématiques");
        }
    }

    private TreeNodeImpl<String> ajoutNodeRecursif(TreeNodeImpl<String> node, MetadataValue val) {
        if (val != null) {
            TreeNodeImpl<String> child = new TreeNodeImpl<String>();
            child.setData(val.getLibelle());

            if (val.getSousElements() != null) {
                for (MetadataValue metVal : val.getSousElements()) {
                    child = ajoutNodeRecursif(child, metVal);
                }
            }

            node.addChild(val.getId(), child);
        }

        return node;
    }

    /* Getters & Setters */

    public TreeNodeImpl<String> getArbre() {
        if(communauteSelected!=null) {
            communauteSelected.getId();
            buildTree();
        }
        return arbre;
    }

    public void setArbre(TreeNodeImpl<String> arbre) {
        this.arbre = arbre;
    }
}

When trying to debug my code, I see that communauteSelected is never initialized. Any idea?
Here are the values in drop down combo:
org.cyo.diapason.model.Communaute@411 - Aspects postes de travail
org.cyo.diapason.model.Communaute@41e - BLOC 3
org.cyo.diapason.model.Communaute@419 - CCF

Any idea is very welcome.
Your help will be appreciated
Answer: You try to insert a rich:panel after form e reRender it:
<h:form id="frmList" >
<rich:panel id="panel">

...

<h:selectOneMenu id="listeCommunaute" value="#{adminThesaurusThematiques.communauteSelected}" required="true" disabled="#{adminThesaurusThematiques.communauteSelected != null}" >
                    <s:selectItems value="#{adminThesaurusThematiques.listeCommunaute}"
                                   var="communaute"
                                   label="#{communaute.nom}"
                                   noSelectionLabel="Veuillez sélectionner une communauté ... " />
                    <a4j:support event="onchange" reRender="panel" status="majTypeWaiting" ajaxSingle="true" />
                </h:selectOneMenu>
...

</rich:panel>


Why was the Asia Cup format changed from 50-over to Twenty20?

Question: I don't understand it. The Asia Cup tournament has been played as a 50 over tournament for a long time, but has suddenly been changed to 20 over format.
What is the reason for this?
Answer: While Joe's answer is correct, the Asia Cup will not permanently be a T20 tournament. This Wikipedia article tells us that the recently revived Asia Cup tournament will be played on rotation basis in One Day International (ODI) and Twenty20 International (T20I) format based on respective next world events under the ICC.
Answer: Everyone knew the format not changed suddenly.It changed for a quite a good reason. However, down to its timing and proximity to the World T20. Since it is scheduled to end a few days before that major event, it was felt to be convenient for every team to use it as a warm-up tournament. The conditions in Fatullah and Mirpur would be similar to what most of these teams would face in India during the World T20, and in any case most of these teams don't really play a lot of T20 internationals in Indian soil recently, so this would be a proper exercise to gear up ahead of a major tournament.
In my opinion people love to watch T20 these days anyhow and everyone wants one of the Asian team should be in the final T20 to spice up the game. So just  sit back and enjoy the new format of cricket and support your nation ahead of T20 WC...
Comment: Can you provide some documents to justify your reply?


Ckeditor how to change button text

Question: My django site uses the image upload feature. I want to change the send it to the server button text to upload
I have checked what seems like every source file but I cannot filed a reference to button.
How would I go about changing it.
I found this posts trying to do the same thing but it is very old

Update:
I dug through what seems like every file but I cannot find the reference to send it to the server not sure what to do at this point.
Answer: Probably too late for your situation, but posting anyway in case others needs a solution in the future (as I just did today):
I found a solution using CKEDITOR this way:
CKEDITOR.on('dialogDefinition', function(ev)
            {
                var dialogName = ev.data.name;
                var dialogDefinition = ev.data.definition;
                if (dialogName == 'image')
                {
                    //console.log(dialogDefinition);
                    dialogDefinition.contents[2].elements[1].label = 'upload';
                }
    });

You can use the commented out console.log(dialogDefinition) to see the array positions of everything in the dialog window. In short, the contents represents the tabs (in which [2] is the upload tab) and elements represents labels, buttons etc inside each tab.
Comment: Going to give this a try thank you!
Comment: No problem, hope it works for you! Let me know if you run into any issues and I'll be happy to follow up on it.
Comment: Did you put this code in the `config.js` file?
Comment: My project is a Laravel project and not Django, but ought to be the same.
I placed it inside the view in a
Comment: Hey, unfortunately couldn't get the code working, did you use this for the `send to server btn`?
Comment: I did. Also used it to change a few other things - can be used for anything in the window.
Make sure the event is triggered when opening the window. Can uncomment the console.log part, and see if it shows up in the console.
If it does not, you might've added the script in the wrong location in your project.

Ckeditor how to change button text


Alternative to Conditional probability tables (CPT) in Bayesian network with discrete random variables

Question: I am interested in modeling a decision support system with a bayesian network, consisting of discrete random variables. While I could use CPT, the requirements grow exponentially in size so I am curious about a more tractable  representation. I was suggested the multinomial Dirichlet distribution but decision support doesn't seem well represented as a multinomial Dirichlet distribution; that is viewing decision support as the number of successes for n number of trials seems odd. Are there any other discrete distributions commonly used in Bayesian networks proper for decision support? Am I incorrect to view multinomial Dirichlet as unsuited to decision support?
Answer: The more tractable representation is the CPT as opposed to the full joint distribution which it succinctly represents. Often the Dirichlet distribution is used for this kind of problem.


How would you draw tan value from an unit circle

Question: How would I draw to show the $tan$ value ?
Comment: https://www.mathsisfun.com/geometry/unit-circle.html
Comment: Did you try to google this? I think there are many resources online ...
Answer: By definition, we need to intersect the line passing throught $(-\sqrt 2/2,-\sqrt 2/2)$ and $(0,0)$ with the vertical line passing throught $(1,0)$.

(credits: Trigonometry/Geometric Definitions of Trig Functions)
Answer: Here is a way to draw all trig functions on the unit circle:


Angular Universal ssr - static prerender

Question: I recently update to latest angular version 10, i have a problem to running a static prerender, the error is:
Unhandled Promise rejection: Cannot read property 'moduleType' of undefined ;
I try different configuration but always the same error, under, you can find my configuration code.
Server.ts
<code>import 'zone.js/dist/zone-node';

//import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

//import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync, readFileSync } from 'fs';

//const { AppServerModule, LAZY_MODULE_MAP } = require('./dist/server/main');
//const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

const {AppServerModule, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap, renderModuleFactory} = require('./dist/server/main');

const server = express();
//const distFolder = join(process.cwd(), 'dist/browser');
const distFolder = join(process.cwd(), 'dist/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index.html';

// The Express app is exported so that it can be used by serverless Functions.
export function app() {

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // app.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

function run() {
  const port = process.env.PORT || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}
export * from './src/main.server';
</code>
Prerender.ts
<code>// Load zone.js for the server.
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';

import { enableProdMode } from '@angular/core';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
//import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import { renderModuleFactory } from '@angular/platform-server';

const ROUTES = ['/'];
//const PAGE_DIR = process.argv.slice(2, process.argv.length)[0];

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');

const BROWSER_FOLDER = join(process.cwd(), 'browser/theme-adventure/');

let previousRender = Promise.resolve();

// Iterate each route path
ROUTES.forEach(route => {

  var fullPath = join(BROWSER_FOLDER, route);
  var index = readFileSync(join(fullPath, 'index.html'), 'utf8');
//  console.log("FULL PATH", fullPath);
  // Make sure the directory structure is there
  if (!existsSync(fullPath)) {
    mkdirSync(fullPath);
  }

  // Writes rendered HTML to index.html, replacing the file if it already exists.
  previousRender = previousRender.then(_ => renderModuleFactory(AppServerModuleNgFactory, {
    document: index,
    url: route
  })).then(html => writeFileSync(join(fullPath, 'index.html'), html));

});
</code>
Thanks
Comment: I am having the same problem. Based on all factors out there, It seems the issue is related to Module Factory, I am suspecting that something about "forRoot" (whatever they replaced to it) mechanism somehow is not working properly. So the modules are not compiled correctly.
Answer: AppServerModuleNgFactory and LAZY_MODULE_MAP not used for ng9/ng10 universal, pls check installations guides


Manually calculating p-value for t-test: How to avoid values bigger than $1$?

Question: These two methods for calculating the p-value should be equivalent:
t.test(rats.drug,mu=1.2)$p.value
2*pt((mean(rats.drug)-1.2)*sqrt(n)/sd(rats.drug),df=n-1)

The problem with the second method is that there is the risk of getting values bigger than $1$ (in fact up to $2$):
2*pt((1.5-1.2)*sqrt(100)/.5,df=100-1)
[1] 2

This can of course be remedied by
2*pt((1.5-1.2)*sqrt(100)/.5,df=100-1,lower=F)
[1] 3.245916e-08

My question
Obviously the algorithm of the t-test function is intelligent enough to distinguish these two cases (whether the sample mean is bigger or smaller than the given mean). Is there an easy method to manually replicate the calculation of the p-value as it is done by the t-test function?
My solution at the moment is an if-statement which checks whether the resulting value is bigger than $1$ and in this case does the same calculation again with the lower=F option but perhaps there is a better way.
Comment: Look at the code: `getAnywhere(t.test.default)`. You'll find `pval <- 2 * pt(-abs(tstat), df)` there.
Answer: You can make use of abs in the numerator (so it's always >0) and keep the lower.tail=FALSE.
Answer: Glen_b is absolutely right about the abs, however, I have found that in certain data sets the values would require -abs to have the desired effect. I'm not able to explain why, but I'll leave these line of code here, incase anyone who is having a similar problem finds this thread.
  t.value <- betacoeff/standard error of the beta coefficients
  p.value <- 2 * pt(-abs(t.value), df = nrow(data)-2)

Expanded answer at the request of mdewey.
Comment: Can you expand on how you think this adds to the comment and answer that are already there?


Why my width: 100% wrapper doesn't work properly?

Question: I put all my content in wrapper that 100% width. my wrapper is not a child.

    <?php require_once("header.php"); ?>
    <?php require_once("content.php"); ?>
    <?php require_once("footer.php"); ?>

CSS:
#wrapper {
overflow-x: hidden;
height: 100%;
width: 100%;
background-color:#fff5e5;
}

But browser (chrome, moz) shows that:

Thanks for help.
Comment: localhost. auto height didn't help
Answer: An element in your page is rendering outside of  element. This can be the result of many causes (negative margins, large widths, large paddings) and guessing it is waste of time. Create a minimal, complete and verifiable example and I'll find it in minutes.
If you don't care what is the cause and only want to remove the effect, (which is clearly the wrong way to go about it and I strongly advise against), you can always apply
body {
  oveflow-x: hidden;
}

Comment: Thank you, you were right the problem was in a negative margin.
Answer: If it is main wrapper,Only adding
display:block;

must solve your issue.
Comment: The  information you provided is not enough to solve it
Comment: it is all on my machine. i use xampp. I share all related code, what kind of information do you want?
Comment: First can you add border:2px red solid; to your code
Comment: I guess it is not wrapper problem but content inside
Comment: Can you please add that border to body and see what happens. If it draw on correct place it means you have a wrong padding or margin on right hand side of wrapper
Comment: I also have that code there:
* {

 padding:0;
 margin:0;
 outline:none;
}
html {
 height:100%;
 width:100%;

}
Answer: You might want to check if your content inside of the wrapper takes up 100% of the space. If you hover over the element in the debug, a blue box will show up. If it is 100% of the width, then that means that the content inside probably only spans part of the screen width.


$\lVert x \rVert_1^k \leq C \left(|x_1|^k + \cdots + |x_n|^k \right)$

Question: I'm trying to prove that given $k \in \mathbb{N}$ there exists a constant $C >0$ such that for all $x \in \mathbb{R}^n$
$$\lVert x \rVert_1^k \leq C \left(|x_1|^k + \cdots +|x_n|^k \right)$$
where
$$\lVert x \rVert_1=|x_1|+ \cdots + |x_n|$$
Any ideas?
Comment: You can look up Minkowski's and Hölder's inequalities.
Answer: If your problem is to find a constant, it is direct, my friend.
$\Vert x\Vert_1^k \le n^k \Vert x \Vert_{\infty}^k \le n^k( |x_1|^k+...+|x_n|^k)$


Two Body/text areas for a multilingual site

Question: When creating a new node, I want 2 body text areas, each one for one language (one in English, and one in German ).
How can I have 2 body areas when create a node?
Comment: Since you seem to just want to show one language at time, is there any reason you could not create a node in German, and a node in English. With core modules, showing one of those nodes basing on the language set from the user or the site is possible.
Answer: Edit the content type that you are using or create a new one and add another field to it.
Comment: Yes but I want one field to appear when english are selected and the other one when the german language is selected.So I want eah field for each language.
Comment: Ok, if you want to write out two fields in two different languages I would suggest a view that displays your ct using an exposed filter. Possibly use [conditional fields](https://www.drupal.org/project/conditional_fields) to display one or the other dependent on a form item state (or write your own using [`#states`](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states)). This is all assuming that using Drupals [t()](https://www.drupal.org/node/1844980) is not sufficient. A little more info about your use case would help us help you.


Performance issue when extracting a subset from an immutable Map

Question: I wrote a function for my own needs taking a subset from an existing Map[String, List[Double]]. Here is the code :
object Myobj {
  val globalPointsByChannel = 5120
  val numberOfWindow = 125
  val numOfPoints2Remove = 41
  val recordFrequency = 1024
  val windowDuration = 3000
  val localWindowSize = 3072

  def subwindow
    (
      start : Long,
      m : Map[String, List[Double]],
      nxtWindow : Map[String, List[Double]],
      left : Int,
      right : Int
    ) : List[String] = {
    for {
      windowIndex <- (0 until numberOfWindow)
    } yield {
      // in microseconds
      val startime = (start * 1000) + (math round ((windowIndex * (numOfPoints2Remove / recordFrequency) * 10e6))).toLong
      // in microseconds
      val endtime = startime + (windowDuration * 10e3).toLong
      val data : Map[String, List[Double]] = {
        for ((key, values) <- m) yield {
          // the number of points to remove at the left side from the window
          val from = windowIndex * numOfPoints2Remove
          // the number of points to remove at the right side from the window
          val until = localWindowSize + from
          val t0 = System.currentTimeMillis
          val channelData : List[Double] = values.drop(from).take(globalPointsByChannel - until - 1)
          val t1 = System.currentTimeMillis
          channelData match {
            case cd if cd.size >= localWindowSize =>
              (key -> channelData)
            case _ =>
              val numOfMissingPts = localWindowSize - channelData.size
              val missingPoints  = nxtWindow(key) take numOfMissingPts
              val completePoints : List[Double] = List(channelData,missingPoints).flatten
              (key -> completePoints)
          }
        }
      }
      val strData = data.values map (values => "[" + (values mkString(",")) + "]") mkString(",")
      strData
    }
  }.toList
}

I think there is two parts in my code taking time. The first part :
val channelData : List[Double] = values.drop(from).take(globalPointsByChannel - until - 1)

I'm doing this for every values in the Map for every window
The second part :
val numOfMissingPts = localWindowSize - channelData.size
          val missingPoints  = nxtWindow(key) take numOfMissingPts
          val completePoints : List[Double] = List(channelData,missingPoints).flatten
          (key -> completePoints)

This case is matched less often than the first case but again, it takes time.
For example, when I execute this code 10 times, it takes (talking in average) 9 000 msecs. Can I have some advice on how to change this two pieces of codes to make more faster than now ?
Comment: Have you considered `slice` instead of the combo of `drop` and then `take`?  That's one operation vs two and will result in one less intermediary List for each time you call it.
Comment: At the first, I use `slice` instead of the combination of `drop` and `take`. But it does't change anything :/
Answer: Depending on you hardware using a ParallelCollection may work for you:
http://docs.scala-lang.org/overviews/parallel-collections/overview.html
The nice thing is that you can quite easily add this to you code. Just call the .par-method on Map.
Map(1 -> "a", 2 -> "b").par
res0: scala.collection.parallel.immutable.ParMap[Int,String] = ParMap(1 -> a, 2 -> b)

Comment: Thank you for the suggestions. Using scala parallel collections, my code takes 2000 msecs in average but when I deploy it on server, it's too slow (12000 msecs in average).


Problem implementing sorting algorithm in C with an array of structs

Question: Well here is my little problem, first my code:

struct alumn {
    char name[100];
    char lastname[100];
    int par;
    int nota;
};
typedef struct alumn alumn;
int bubble(alumn **arr, int length)
{
    int i,j;
    alumn *temp;
for (i=0; i<=length-2; i++) {
    for (j=i+1; j<=length-1;j++) {
        if ((*arr)[i].nota > (*arr)[j].nota) {
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
}

}
int main(int argc, char **argv)
{
    alumn *alumns;
... here goes some other code ...

bubble(&alumns,totalAlumns);

return 0;

}

My problem is that this algorith is not sorting anything. I'm having a hard time doing the swap, i tried everything but nothing works :( . Any help???
Answer: Apparently you're confusing an array of alumn structs with an array of pointers to alumm struct.
The Bubble logic expexts the array of pointers,  whereby the main function seems to call it with an array of structs.
Because of the size of the alumn struct, it is probably more efficient to perform the bubble sort on pointers, since each swap will require much less moving around of data (3 copies of one pointer a few bytes each, vs. 3 copies of alumn struct, 200+ bytes each!).
I suggest you modify the logic (not shown in snippet of question) of the main() function to introduce such an array of pointers to the actual alumn structs.  (Of course this array of pointers won't spare you from also allocating the structs themselves, en block (in an array of structs) or individually.

Upon your insistence I'm hinting here how main could look like to produce an array of pointer usable by bubble (bubble stays unchanged).
BTW, I declare alumns as  alumn *alumns[] which shows the intent use more readily. this is the same thing as alumn **alumns.
int main(int argc, char **argv)
{
    alumn *alumns[];   // changed to array of pointers [to alumn structs]
                       // was pointer to alumn struct, likely to be used as an array thereof

    int MaxNbOfAlumns = some_limit;
    alumns = malloc(sizeof(*alumn) * MaxNbOfAlumns);

    // Load the alumn records (from file or whereever)
    // pseudo code:
    // int i_alumns = 0;  // points to the next free slot in alumns array
    // for each record (in file or whereever...)
    //     alumms[i_alums] = malloc(sizeof(struct alumn));
    //     strcpy(alumms[i_alums]->lastname,  whatever_data);
    //     strcpy(alumms[i_alums]->name,  whatever_otherdata);
    //     alumms[i_alums]->par = some_int_data;
    //     alumms[i_alums]->nota = some_other_int_data;
    //     i_alums++;

... here goes some other code ...

  bubble(alumns, totalAlumns);   // alumns now being an array can be passed as is.

  return 0;
}

Alternatively if you wish to keep the original alumns variable as previously, all that may be needed is something like that, just before the call to bubble()
  int i;
  alumn *ap_alumns[];   // new variable
  ap_alumns = malloc(sizeof(*alumn) * totalAlumns);
  for (i = 0; i < totalAlumns; i++)
      ap_alums[i] = &alumns[i];
  bubble(ap_alumns, totalAlumns);

One thing that should be stressed is that regardless of its genesis, the array passed to bubble() gets sorted ok, but to use it you need to dereference the individual pointers.
Whereby with the old array you intended to use as in say alumns[123].lastname,  you'll now need alumns[123]->lastname  (or ap_alumns[123]->lastname if you use the second version).
Comment: I can, but won't.  For one it is readily implemented as such (in bubble() function) and second, this seriously looks like homework, hence worthy of hints but _you_ will be the better for figuring things for yourself.  I think you'll agree ;-)
Comment: ok i'm understand. Look only i need a little help, the only thing that is failing to me is the swap method, i want to change the pointers, so *arr points to alumn but the thing tha i can't figure its how in terms of arr reference a member of the alumn array. Any help?
Comment: @dilog: see edit. With two versions on how to create the array of pointers needed.
Answer: Your code does not work because you have an array of structs instead of an array of pointers.
When you try to swap two structs, the = operator does not know what to do. You have to copy the fields of the struct one by one for that to work.
If you had an array of pointers to instances of the alumn struct instead. THen the code would work, since you are assigning pointers. A pointer is basically a number and = knows how to copy a number.
Comment: buddy i'm swapping pointers not the structs himself. The parameters of the function contain a pointer to the array structs.
Comment: alumn **arr means that arr points to a array of structs not array of pointers to structs, as was already pointed out above.
Answer: Your code is written as if you have an array of pointers, but have left out an important part of your code (i.e., ... here goes some other code ...) so we can't see how you've set up the thing to be sorted.  If you have an array of pointers, this line of code:
if ((*arr)[i].nota > (*arr)[j].nota) {

should be:
if (arr[i]->nota > arr[j]->nota) {

The reason is, (*arr) gets the first pointer in the list, then (*arr)[i] gets the i'th item in memory after that pointer (meaningless since each pointer should point to one item).  The 2nd syntax goes to the i'th pointer in the pointer array, and dereferences it to get that value.
Maybe this illustration will help:
arr points to an array of two pointers, each pointing to a struct.
(*arr)[1].nota refers to an item in ??????.
arr[1]->nota refers to an item in struct 2.

       +---+                   +----------+
arr -> | * | ----------------> | struct 1 |
       +---+    +----------+   +----------+
       | * | -> | struct 2 |   :  ??????  :
       +---+    +----------+   +..........+


How to place some text over the DIV without breaking hover area of this DIV?

Question: I'm total noob with CSS and it looks like hell =/
I have absolute positioned DIV and I handle mouse events over this DIV with JS like this:

SOME TEXT

I need to place some text over this DIV and over the few same DIVs, but if I place any element over this DIV onMouseOut event is firing when mouse cursor switch to text. Tag with text can't be inside the DIV. Playing with z-index didn`t help. My browser is IE8.
UPDATE:
I can't place text into the div because text must go beyond bounds of DIV. In other words I want handle mouse events over arbitrary area in any text. I can do this if I set backgroundColor of DIV, but I need handle events of transparent area.
Comment: If your mouse strays in to another DIV, then it is out, and the event will fire.  If the overlaying element was a child of the parent, then you might be alright.
Comment: Why can't the tag with text be inside the div??
Answer: If you're trying to do this purely with mouseover events, then the only way to achieve what you're after is to place the second div inside of the first.
On the other hand, if you want to dive into some scripting, here's a basic algorithm for how you can handle this:

Set up a function to fire when you mouseover the trigger divs.  This function will show the "SOME TEXT" div, if its display is set to "none".
Set up a function to fire when you mouseout of the trigger divs.  This function will be a little more complex.  First you have to check to see what the event.currentTarget is; if event.currentTarget is the "SOME TEXT" div, return false.  If it's anything else, then you set the display of "SOME TEXT" to "none".

This might be a little beyond where you are with CSS and JS, but it's pretty much the only way to get it done, since CSS alone won't do what you need.
Comment: moving  'some text' into the empty div
Answer: tried {cursor: pointer} on the text div?
Comment: I know, but he mentioned the dumb bell cursor. Wasn't positive he was purely talking about an  hover problem or simply an aesthetic problem with the event triggers.