text:
Q: JasperReports: spliting string value with delimiter I have a problem with JasperReports.  I am passing string values to a report. A specific code has included to each and every value that I'm passing, like "pre: 001", "ab: 002", "lv: 003".
Codes - "pre","ab","lv"
As I mentioned above, each code and value can separately identify by ":" notation.
In Java I used following code to separate the code and value;
a = "pre:001";
String[] b = a.Split(":",2);
System.out.println(b[0]);  // code
System.out.println(b[1]);  // value

Problem
I need to pass combined value (code+value) to the report but the text field should only appear the value portion.
Ex:
Input – "pre:010"
Output-"010"

A: That should be in the text field expression for field A:
$F{A}.split(":",2)[1].trim()

A: To split a field 'fieldname' with '|' delimiter and get first element
$F{fieldname}.toString().split("\\|")[0]

A: If you are using irport add expression to your text field like {fieldName}.substring() from property menu.


text:
Q: Как спарсить данные с сайта, если есть определенное кол-во ссылок? (python) Есть код на Python, я взял его с интернета, чуть-чуть допилил для себя, но сейчас возник один вопрос.
У меня есть ссылки с которых нужно спарсить данные, я в питоне совсем зеленый, не знаю как задавать вопросы в гугле, чтобы правильно получить ответы...
Так вот: имеем сейчас код, который парсит данные с одной ссылки, а надо чтобы он парсил данные со всех ссылок, которые я вставлю, но пока не знаю как это реализовать..(
"""Парсинг сайтов"""

import requests  # для работы с запросами.
from bs4 import BeautifulSoup  # разбирает HTML страницу, делает из неё объект.
import csv  # для создания файла, который можно потом открыть в EXEL или OpenOffice.

FILE_NAME = 'toys.csv'
HOST = 'https://www.miele.ru'  # сайт, который мы будем пастить.
URL = 'https://www.miele.ru/domestic/oven-1451.htm?mat=11124400&name=H_7164_BP' # url страницы,которую будем пастить.

# Прописываем заголовки, чтобы сайт не подумал, что мы бот.
HEADERS = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,'
              '*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/87.0.4280.141 Safari/537.36'
}

# обращение к странице, чтобы получить HTML.
def get_html(url, params=''):
    r = requests.get(url, headers=HEADERS, params=params)  # запрашиваем данные со страницы.
    return r

# получаем контент со страницы (c одной).
def get_content(html):
    soup = BeautifulSoup(html, 'html.parser')  # сохраняем объект страницы.
    items = soup.find_all('div', class_='cc-productDetailHead')
    toys = []
    for item in items:
        toys.append(
            {
                'title': item.find('div').text,
                'model': item.find('strong').text,
                'price': item.find('div', class_='priceWrapper').text,
                #'linc': HOST + item.find('div', class_='cc-product-tile__button-wrapper').find('a').get('href'),
                'photo': item.find('a', class_='cloud-zoom-gallery active main').get('href'),
                'othphoto': item.find_all('a', class_='cloud-zoom-gallery')[1].get('href')
            }
        )
    return toys

# Промежуточный тест:
# html = get_html(URL)
# print(get_content(html.text))

""" Функция записи данных """

def save_doc(items, path):
    with open(path, 'w', newline='') as file:
        writer = csv.writer(file, delimiter=';', dialect='excel')
        writer.writerow(['name : Название', 'product_model', 'price : Цена', 'image : Иллюстрация', 'othphoto'])  # Первая строка.
        for item in items:
            writer.writerow([item['title'], item['model'], item['price'], item['photo'], item['othphoto']])

""" Основная функция парсинга """

def pars():
    page_count = int(input('Укажите количество страниц для парсинга: '))
    html = get_html(URL)
    if html.status_code == 200:  # Проверям приходят ли к нам данные со страницы.
        toys = []
        for page in range(1, page_count + 1):
            print(f'Парсим {page} страницу')
            params = '?count=9&PAGEN_3=' + str(page)
            html = get_html(URL + params)
            toys.extend(get_content(html.text))
        print('Парсинг закончен.')
        save_doc(toys, FILE_NAME)
    else:
        print('ERROR !')

pars()

""" Функция чтения csv файла в консоль """
with open("toys.csv") as r_file:
    # Создаем объект словарь, указываем символ-разделитель ","
    file_reader = csv.DictReader(r_file, delimiter=";")
    # Счетчик для подсчета количества строк и вывода заголовков столбцов
    count = 0
    # Считывание данных из CSV файла
    for row in file_reader:
        if count == 0:
            # Вывод строки, содержащей заголовки для столбцов.
            print('             ', "                               \
                             ".join(row))
        # Вывод содержимого строки по ключу.
        print(f' {row["name : Название"]} -- {row["product_model"]} -- {row["price : Цена"]}\
         -- {row["image : Иллюстрация"]} -- {row["othphoto"]}')
        count += 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to deal with anonymous variables in your dataset to get better predication i have data-set where i am having 4 anonymous variables as shown below and also target variable is kind of anonymous:

can someone please tell me how to deal with anonymous feature in machine learning ,what is best approach for feature engineering from this anonymous variables , how i can improve my predication from this feature

A: You should do multiple steps :
1- scale the numeric features and one-hot encode the categorical ones (you can also encode your categorical variables with their number of appearances = replace each value with it's count)
2- study correlation between your target and other variables
3- Use different plots to know your data better
4- Use variable selection methods while modeling


text:
Q: Excel pass url with parameters to browser How is it possible to open local HTML file passing parameters from Excel sheet? It seems that passing the parameters works just for URL not for the file protocol.
does not work:
=HYPERLINK("file:///C:/temp/html/new2017.htm?test=123","Search")

works:
=HYPERLINK("http://localhost/html/new2017.htm?test=123","Search")

What would be a way around it?


text:
Q: Apply table classes on ajax response I have applied classes on my
 and I am creating my rows from AJAX response in JSON. My issue is, listing is shown for 3 different radios selection, but the table classes are not being applied on the inserted rows so it escapes the pagination classes data. How can I rectify this? I searched a lot, and asked a lot many forums but could not get any outcome.

Any help or advice will be welcomed and appreciated.
<?php include 'blocks/headerInc.php' ; ?>
<?php
ob_start();

$errmsg         =   "" ;
$module_id      =   '';
$query          =   '';
$date_from      =   '';
$date_to        =   '';
$status ='';
$check ='';
$disabled='';
$row='';

$sqlQuery = "SELECT * FROM tbl_user WHERE type = 3 AND status = 0 AND registration_type = 0";
?>

         <?php include 'blocks/leftnavInc.php' ; ?>

Candidate Approval

                    <form id="selection" method="GET" >
                        <input type='radio'  name='users' value='unapproved' checked /> Unapproved Candidates
                        <input type='radio'  name='users' value='approved' /> Approved Candidates
                        <input type='radio' id='show' name='users' value='all'  /> All Candidates

                  S.No.
                  Email ID
                   Reference ID
                  Name
                  Mobile No.
                  Registration Date
                  Check for Approval
                  <input type="checkbox" id="select_all" name="all_check[]" <?php echo $disabled ;?> class="checkbox" value= "<?php //echo $row['id']; ?>">

                        <input type="submit" name ="all_send" value="Approve" style="display: none; float: right;"  id="one" class="btn btn-success">

                    </form>

report_ajax.php
<?php
  session_start();

  require("../includes/config.php");
  require("../classes/Database.class.php");
  $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

  $return_arr = array();
  $status='';

  if($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $value = filter_input(INPUT_POST, "selected_value");
    if (isset($value))
    {
      $users = $value;
    }
    else
    {
      $users='';
    }

  switch ($users)
  {
    case "all":
      $sqlQuery = "SELECT * FROM tbl_user WHERE type =3";
      break;
    case "approved":
      $sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";
      break;
  }

  $sq = $db->query($sqlQuery);

  if ($db->affected_rows > 0)
  {
    while ($row = mysql_fetch_array($sq))
    {
      $disabled = '';
      if ($status == '1')
      {
        $disabled = "disabled = 'disabled' checked='checked' ";
      }

      $id = $row['id'];
      $email = $row['email'];
      $employee_id = $row['employee_id'];
      $first_name = $row['first_name'];
      $middle_name = $row['middle_name'];
      $last_name = $row['last_name'];
      $mobile = $row['mobile'];
      $created_on1 = $row['created_on'];
      $created_on = date("d-m-Y", strtotime($created_on1));

      $return_arr[] = array("id" => $id,
        "email" => $email,
        "employee_id" => $employee_id,
        "first_name" => $first_name,
        "middle_name" => $middle_name,
        "last_name" => $last_name,
        "mobile" => $mobile,
        "created_on" => $created_on
        "disabled" => $disabled
      );
    }
  }
  header('Content-Type: application/json', true, 200);
  echo json_encode($return_arr);
}

A: I am not sure exactly what your issue is, but what I was saying was instead of this:
Your PHP code:
while ($row = mysql_fetch_array($sq))
    {
      $disabled = '';
      if ($status == '1')
      {
        $disabled = "disabled = 'disabled' checked='checked' ";
      }

      $id = $row['id'];
      $email = $row['email'];
      $employee_id = $row['employee_id'];
      $first_name = $row['first_name'];
      $middle_name = $row['middle_name'];
      $last_name = $row['last_name'];
      $mobile = $row['mobile'];
      $created_on1 = $row['created_on'];
      $created_on = date("d-m-Y", strtotime($created_on1));

      $return_arr[] = array("id" => $id,
        "email" => $email,
        "employee_id" => $employee_id,
        "first_name" => $first_name,
        "middle_name" => $middle_name,
        "last_name" => $last_name,
        "mobile" => $mobile,
        "created_on" => $created_on
        "disabled" => $disabled
      );
    }
  }

Your JS code:
success: function(response)
    {
    console.log(response);

    var len = response.length;
    $("#datashow").empty();
        for(var i=0; i<len; i++){
        var id = response[i].id;
        var email = response[i].email;
        var employee_id = response[i].employee_id;
        var first_name = response[i].first_name;
        var middle_name = response[i].middle_name;
        var last_name = response[i].last_name;
        var mobile = response[i].mobile;
        var created_on = response[i].created_on;
        var disabled = response[i].disabled;
        var users = response[i].users;

        var tr_str =
            "
" +
            "" + (i+1) + "	" +
            "" + email + "	" +
            "" + employee_id + "	" +
            "" + first_name + " " + middle_name + " " + last_name + "	" +
            "" + mobile + "	" +
            "" + created_on + "	" +
            "<input type='checkbox' name='check[]'"  + disabled +  "value= '"  + id +  "' class='checkbox' id='select_all' >	" +
            "<input type='hidden' value='"  + id +  "' name='user_id' id='user_id' >" +
            "
" ;

        $("#datashow").append(tr_str);
   }
}

Minimized PHP code:
$i = 1; //start at one, why not.
$html = '';
while ($row = mysql_fetch_array($sq)) {
    $disabled = '';
    if ($status == '1')
    {
        $disabled = "disabled = 'disabled' checked='checked' ";
    }

    $created_on = date("d-m-Y", strtotime($row['created_on']));

    $html .= "
";
    $html .=  "{$i}	";
    $html .= "{$row['email']}	";
    $html .= "{$row['employee_id']}	";
    $html .= "{$row['first_name']} {$row['middle_name']} {$row['last_name']}	";
    $html .= "{$row['mobile']}	";
    $html .= "{$created_on}	";
    $html .= "<input type='checkbox' name='check[]' value='{$row['id']}' class='checkbox' id='select_all' {$disabled}>	";
    $html .= "<input type='hidden' value='{$row['id']}' name='user_id' id='user_id' >"; //why is this same value as above
    $html .= "
" ;
    ++$i; //increment counter
}
echo $html;

Minimized JS code:
success: function(response){
    $("#datashow").append(response);
}

Just because it's AJAX doesn't  mean you have to return JSON, you can return plain old HTML if that is all you need. And as best I can tell, that is all you need.
If it's not all you need, you can return a combination of Data and HTML
JSON example:
   {
       "foo" : "bar",
       "html" : "
 ....
"
   }

Then you just pull the HTML out, etc.
Having so much redundant variable assignment (localization) can make you code very hard if not impossible to read, harder to write, harder to maintain, harder to debug, harder to understand and perform worse.  None of which is good.
Be lazy and do as little work as you need to.
If you don't like it all on one line in the source code, then you can change html to an array, add the items and then implode it with a line ending
$html = [];
while( ... ){
  $html[] = "
";
  ...
}

echo implode(PHP_EOL, $html);

This can make it a bit easier to read and debug the source code.
My rule is Readability is King.  This is a reduction of 66 lines of code, down to 28 lines (over 50%) that do basically the same thing.
UPDATE
Reducing the lines, will help you see things like this

Where you have HTML syntax errors, like missing " around your id, which probably prevents your selectors Javascript from finding your HTML elements.  And it should go without saying you should fix this.

UPDATE2
Also, the "id" attribute is supposed to be unique per page/request, so your repeated use of id='select_all' will have undesirable effects.


text:
Q: probability of random birthday I am very new to programming in general and Javascript in particular (a couple of weeks) and i am trying to create a program to tell me how many people have to be in a room that it should be probable (more than fifty percent) that one person has the same birthday that I picked beforehand.
the equation in math comes out about 253 people. However after running my program 10000 times it keeps on giving me about 367.I'm wondering if something is wrong with my program or the random number generator on javascript.

//sorry if the code is messy and unprofesional for i am very new
//functions for specific tasks

const functions = {
        randomGenerator (finish){
            const num = Math.floor(Math.random()*(finish))
            return num;
    } ,
        pickNum () {
        if(check){return}
        check = true;
        chosenTrials = +(prompt("PLEASE ENTER THE AMOUNT OF TRIALS YOU WANT TO RUN."))
        return chosenTrials;
    }
    }
    //The probability of having a person with a specific borthday
    const birthdayBtn = document.getElementById("bdBtn")
    const count = [];
    const dateArray = [];
    let rand;
    let check = false;
    let chosenTrials;
    const date = () =>{

        functions.pickNum();
        for(e =0;e<chosenTrials;e++){
            for (let b = 1;b<2000;b++){
                rand =functions.randomGenerator(366);
                if(dateArray.includes(59)){//59 is a random number
                    dateArray.push(rand);
                    break
                }
            dateArray.push(rand)
               }
               count.push(dateArray.length)
               dateArray.length = 0;
            }
            let avg =  0;
            count.forEach(el => avg+=el)

            const final = avg/count.length
            console.log(final)
           // console.log(count)

        }
    birthdayBtn.addEventListener('click',date)
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <script src="scripts/statistics.js" defer></script>
        <button id = bdBtn>The birthday problem</button>

      </head>
      <body>
      </body>
    </html>


text:
Q: How to make sidebar close when any link is clicked? I'm creating a Sidenav bar show when clicked on it but when it's showed I want to make it whenever any link is clicked it will close
Here is how I create a Side Navbar Open:
const App = (props) => {
    const [ menuOpen, setMenuOpen ] = useState(false);

    return (
        <HamburgerUlityItem>
            <InputNavbar type="checkbox" onClick={() => setMenuOpen(!menuOpen)} />
            <HamburgerLine />
        </HamburgerUlityItem>
           ...)

const SideNav = (props) => {
    return (
        <Wrapper>
            {props.menuOpen ? (
                <HamburgerSize>
                    <AllItems>
                        <ListItems to="/product-category/top"> TOPS </ListItems>
                        <Item to="/product-category/top/t-shirt"> T - Shirts </Item>
                        <Item to="product-category/top/shirts"> Shirts </Item>
                        <Item to="product-category/top/hoodies"> Hoodies </Item>
                        <Item to="product-category/top/coats"> Jackets & Coats </Item>
                        <ListItems to="/product-category/bottom"> BOTTOMS </ListItems>
                        <Item to="product-category/bottom/pants"> Pants </Item>
                        <Item to="product-category/bottom/shorts"> Shorts </Item>
                        <ListItems to="/product-category/bag"> BAGS & BACKPACKS </ListItems>
                        <ListItems to="/about-us"> ABOUT US </ListItems> <ListItems to="/contact"> CONTACT </ListItems>
                    </AllItems>
                </HamburgerSize>
            ) : null})

How can I close the sidebar when click to any link ?

A: According to the comments section, SideNav is a child of App component. So therefore, just pass down the state and state setter to SideNav and from there, when an Item is clicked, just set menuOpen to false or simply negate the state.
const App = (props) => {
    return(
        ...
        <SideNav menuOpen={menuOpen} setMenuOpen={setMenuOpen }/>
    )
}

On SideNav:
<Item to="/product-category/top/t-shirt" onClick={()=>{props.setMenuOpen(!props.menuOpen)}}> T - Shirts </Item>


text:
Q: Permission Not Granted by Manifest (Api Level 22) I am trying to log some actions to /sdcard. My AndroidManifest.xml specifies android:targetSdkVersion="22" and includes
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="<REDACTED-MYPACKAGENAME>"
          android:versionCode="100"
          android:versionName="1.00">
        <uses-sdk android:targetSdkVersion="22"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"   />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"   />
       More...

Unfortunately, my writes to /sdcard/events.txt cause exception
java.io.FileNotFoundException: /sdcard/events.txt: open failed: EACCESS (Permission denied)
Notes:

*

*Since the API level is <23, I believe run-time-permissions are not required.

*If I manually enable "Storage" using "Settings"->"Apps->MyApp->"Permissions", it works just fine.

*I am running on a Samsung S-9 running Android V10.

What am I missing?


text:
Q: java - How to set jtextfield can be filled by numbers only and popup a message dialog on jbutton So, I'm trying to make a simple program. I want to fill the jtextfield with anything (symbols,number or words) but when I click on jubutton there's a message dialog appears
This is my code,but it's not working as I want,because when I enter a character after a number the message dialog didn't shown up
if (!txtphone.getText().contains("1")&&!txtphone.getText().contains("2")&&!txtphone.getText().contains("3")&&!txtphone.getText().contains("4")&&!txtphone.getText().contains("5")&&!txtphone.getText().contains("6")&&!txtphone.getText().contains("7")&&!txtphone.getText().contains("8")&&!txtphone.getText().contains("9")&&!txtphone.getText().contains("0"))
{
    JOptionPane.showMessageDialog(rootPane, "Input must number");
    txtphone.setText("");
}

A: DocumentFilter is a better choice for what you want. You have a lot of examples in SO. Check this one.

A: Currently you check if there are numbers in the JTextfield, but you want to know if there are ONLY numbers in it:
if (!txtphone.getText().matches("[0-9]+"))
{
    JOptionPane.showMessageDialog(rootPane, "Input must number");
    txtphone.setText("");
}

A: Use regex
if(!txtphone.getText().matches("\\d+")){
    JOptionPane.showMessageDialog(rootPane, "Input must number");
    txtphone.setText("");
}


text:
Q: Google map: openInfoWindowHtml with jquery problem I've added ability for users to add new point on my google map. My code:
GEvent.addListener(map, "click", function(overlay,point) {
    if (point) {
        var myHtml = '
<form id="formadd" name="formadd_point" enctype="multipart/form-data" method="post" action="pointadd.php">

Place:	' + point + '

Name:	<input name="name" type="text" size="32" maxlength="200" />

Photo (jpg,png:2Mb):	<input type="file" name="image" size="20" accept="image/png,image/jpeg" />

	<input name="pcoord" type="hidden" value="'+point+'" /><input type="hidden" name="MAX_FILE_SIZE" value="2000000" /><input name="subpoint" type="submit" value="Add" />

</form>
';
        map.openInfoWindowHtml(point, myHtml);
        $('#formadd').ajaxForm({ beforeSubmit: validate, target:'#addpoint' });
    }
});

It should be AJAX post without reloading. But It is not working! I don't know why. Maybe there is some conflict jquery.js and google api?  How to submit form without reloading page?

A: Maybe you try to add eventListener to form before form html successfully added dom. Try this:
GEvent.addListener(map, "click", function(overlay,point) {
    if (point) {
        $('#formadd').live("load", function(){
            $(this).ajaxForm({ beforeSubmit: validate, target:'#addpoint' });
        });

        var myHtml = '
<form id="formadd" name="formadd_point" enctype="multipart/form-data" method="post" action="pointadd.php">

Place:	' + point + '

Name:	<input name="name" type="text" size="32" maxlength="200" />

Photo (jpg,png:2Mb):	<input type="file" name="image" size="20" accept="image/png,image/jpeg" />

	<input name="pcoord" type="hidden" value="'+point+'" /><input type="hidden" name="MAX_FILE_SIZE" value="2000000" /><input name="subpoint" type="submit" value="Add" />

</form>
';
        map.openInfoWindowHtml(point, myHtml);

    }
});


text:
Q: Given just a unary predicate symbol, find a formula F that is true just for some x, in all interpretations.
You are given the signagure $σ = 〈 ; ; P〉$ in which P is a unary predicate
  symbol. Find a formula F such that $\forall x F = 0$ and $\exists x$
  $F = 1$. Prove that it meets these requirements.

From what I understand, we need to assume that the domain of discourse D may be any non-empty set. Also we need to assume that the predicate P may be either true for all $x \in D$ (1), for some $x \in D$ (2) or for no $x \in D$ (3).
I tried to solve it in 3 parts. In case (1) the appropriate formula F would just be P(x). But then once I tried to do the other cases, I got stuck since if all of your values are 0 or 1, how can you change only some of them around by only using the symbols we have $(\neg, \land, \lor, \rightarrow, \leftrightarrow, \forall, \exists)$? Therefore, help would be much appreciated.

A: This seems to be impossible ...  When the domain contains exactly one object, $\forall x \phi$ and $\exists x \phi$ should always have the same truth-value, no matter what $\phi$ is.


text:
Q: Pandas While Loop Based On Condition - Truth Value Of A Series Is Ambiguous I have two dataframes. They both contain the same columns.
data = pd.DataFrame({'old_name': [2, 1], 'new_name': [2, 3], 'start':['2021-05-20', '2008-08-01'], 'end': ['2021-08-08', '2021-05-20']})
old_name  new_name  start      end
2         2         2021-05-20 2021-08-08
1         3         2008-08-01 2022-05-20
base = pd.DataFrame({'old_name': [3], 'new_name': [3], 'start':['2021-05-19'], 'end': ['2022-12-31'})
old_name  new_name  start      end
3         3         2021-05-19 2022-12-31
I am trying to create a new df that takes a new name df "base" and goes back in time finding all the old names and linking them together in descending date order while having the old name's end date >= the start date of the new name. There can be more than one match between old and new name and I have to follow the trail for all of them until start < '2008-08-01'.
The final result should be:
old_name  new_name  start      end
3         3         2021-05-19 2022-12-31
1         3         2008-08-01 2022-05-20
data['start'] = pd.to_datetime(data['start'])
base['start'] = pd.to_datetime(base['start'])
data['start'] = pd.to_datetime(data['start'])
base['start'] = pd.to_datetime(base['start'])

begin_date = datetime.datetime(2008, 8, 1)
list = pd.DataFrame(columns=base.columns)
for index, row in base.iterrows():
     start_date = row['start']
     base_name = row['name']

     while start_date > begin_date:
          temp = data[(data['new_name'] == base_name) & (data['end'] >= start_date)].copy().reset_index(drop=True)
          start_date = data['start']

     list = pd.concat([list, temp], ignore_index=True, sort=False)
     del temp

I get a "Truth value of a series is ambiguous" but I can't seem to find where I can correct my code. The condition evaluates to True so I'm stuck. Can someone please help me get back on track? Please let me know if my question isn't clear. Thank you!!!

A: Your code might be erroring out at the line,
 while start_date > begin_date:

In this line, you are trying to compare a pandas series(start_date) with begin_date which is not a series, it is a scalar value.
An easy fix would be,
while start_date.values[index] > begin_date:

A: In first row under the while you access a DataFrame column which is a Series, then you compare it with something. For example data['new_name'] is a Series.


text:
Q: Populating a C struct I would like to assign value fetched from sqlite database to a c-struct so I do that as follows:
typedef struct
{
    uint16_t    shortID;
    double       temp;
    unsigned long timestamp;
} location_t;

static uint8_t prv_set_value(lwm2m_data_t* dataP,
                           location_t* tempData)
{
    uint8_t ret = COAP_205_CONTENT;
    sqlite3 *db;
    sqlite3_stmt *res;

    // connect to sqlite
    int rc = sqlite3_open("test.sqlite3", &db);

    if (rc != SQLITE_OK) {
        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }
    else {
        fprintf(stderr, "Connection to SQLITE established!.\n" );
    }
    rc = sqlite3_prepare_v2(db, "SELECT temp FROM envirment ORDER BY ID DESC LIMIT 1", -1, &res, 0);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "Failed to fetch data: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;
    }
    rc = sqlite3_step(res);
    if (rc == SQLITE_ROW) {
        fprintf(stdout, "Temperature value ==== : %s\n", sqlite3_column_double(res, 0));

         tempData->temp = sqlite3_column_double(res, 0);
        fprintf(stdout, "Temp value from temperature_data_t: %s\n", tempData->temp);

        }

        sqlite3_finalize(res);
        sqlite3_close(db);

         }
    return ret;
}

Data is fetched from the sqlite database. I'm doing a check to see if the function behaves as intended so I display the value before and after the assignment. The output from the struct assignment tempData->temp = sqlite3_column_double(res, 0);as displayed in next line fprintf(stdout, " Temp value from temperature_data_t: %s\n", tempData->temp); is null. Following is the function output:
Connection to SQLITE established!.
Temperature value ==== : 29.1
Temp value from temperature_data_t:  (null)

What is the correct way to assign fetched to tempData->temp?

A: tempData->temp = sqlite3_column_double(res, 0); is correct but because tempData->temp is a double, not a char*, replace
fprintf(stdout, "Temp value from temperature_data_t: %s\n", tempData->temp) ;

by
fprintf(stdout, "Temp value from temperature_data_t: %f\n", tempData->temp);

I suppose the line
fprintf(stdout, "Temperature value ==== : %s\n", sqlite3_column_double(res, 0));

is in fact
fprintf(stdout, "Temperature value ==== : %s\n", sqlite3_column_text(res, 0));

because sqlite3_column_double doesn't return a char*

May be see also : retrieving float values using sqlite3_column_double


text:
Q: Unit testing complex logic What is the best way to unit test a relatively complex method where the test for each post-condition is very similar to the tests for the other post-conditions?  The pre-conditions are easy to test in isolation, but a lot of setup goes into making sure that they all hold so that the post-conditions can be tested.  The three ways that I've thought up are:

*

*Create a general function that can test everything at once, but defaults to the simplest possible scenario.  This function would take flag parameters indicating the deviations from the simplest scenario.  Then, create a unit test for each post-condition (or combination) that calls that function with the appropriate flags to get coverage of that post-condition.  The benefits here are that there is almost no code duplication, so if the code being tested changes, only one test function needs to be rewritten; and that it is trivial to write the test to cover groups of post-conditions, but the drawback is that the general test function is very complex

*Make a unit test for the simplest scenario, then copy, paste, and modify.  The benefit is that each test is very simple.  The drawback is that a problem with the original test will need to be fixed as many times as it is pasted.

*Write a general function that allows the various bits and pieces to be overridden by taking functions as parameters, but by default tests the simplest scenario.  The benefits are similar to those for the general function with flags, but I think it might be more complicated to make it all mesh together.

The fourth option would be "you're doing it wrong; break the method being tested down into bits that are simpler to test!"
Any ideas?

A: My earlier comment was somewhat in jest.
What I would actually advocate, broadly speaking, is to do what you list as option 2, but then refactor your test code to eliminate the duplication that you created by the copy-modify work.
Once you have this all tested, you might then look for ways to refactor the production code to break it down into smaller and more manageable pieces and make those pieces reusable.  But it's always healthy to have tests before making big changes.


text:
Q: How to concatenate cells in a row until the first blank cell I'm currently diving into code/VBA coding for the first time. I have a file that I dump into a worksheet that currently I'm manually organizing and pushing out. When put into the worksheet, it delimits itself across the cells. The first 2-4 cells are always parts of a name. This dump file will have varying row and column lengths every time I get it in a given day and dump into a work sheet. For example, one day it may be twenty rows and one day it may be thirty.
This is a rough illustration of what the data looks like, but my code probably doesn't match with the example below - I just wanted to provide a visual:

So, I'm wanting to make code that will start at A1 and concatenate the cells following it until it runs into a blank cell in that row. Then it places the concatenated data into cell A1 and removes the values it pulled the name pieces from and slides all the data to the left. After that, it continues the same operation on the next row until it meets the final row. As you can see in the image, I don't want any of the data after the blank cell to be affected.
This is my first time programming in general, so when you provide assistance, would you please explain your code so I can learn the concepts? Here's what I think will work so far... I'm just stuck on how to go about concatenating.
The code I currently have:
Sub DN_ERROR_ORGANIZER()
  Dim row As Integer
  NumRows = Range("A1", Range("A1").End(xldown)).Rows.Count
  Range("A1").Select
  For row = 1 To NumRows
      Do Until IsEmpty(ActiveCell)
          ' Code to concatenate
          ActiveCell.Offset(1, 0).Select
      Loop
      ActiveCell.Offset(1, 0).Select
  Next
End sub

A: Can you try this and let me know how you get on? It may need some tweaks depending on your precise layout. My approach is slightly different.
 Sub x()

Dim n As Long, r1 As Range, r2 As Range, v

For n = 1 To Range("A" & Rows.Count).End(xlUp).Row
    On Error Resume Next
    Set r1 = Cells(n, 1).EntireRow.SpecialCells(xlCellTypeConstants).Areas(1)
    Set r2 = Cells(n, 1).EntireRow.SpecialCells(xlCellTypeConstants).Areas(2)
    If Not r1 Is Nothing And Not r2 Is Nothing Then
        v = Join(Application.Transpose(Application.Transpose(r1)), ", ")
        Cells(n, 1) = WorksheetFunction.Proper(v)
        Cells(n, 2).Resize(, r1.Count).Clear
        r2.Cut Cells(n, 3)
    End If
Next n

End Sub

A: Here's another way to look at your problem: Suppose you have your table on Sheet2, and the result is reflected on Sheet1.
Sub PutInOrder()
  filledcells = 0
  '''lastrow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row

  For i = 1 To 100
     If Sheet2.Cells(i, 1) = "" Then Exit For
     For a = 1 To 4
        If Sheet2.Cells(i, a) = "" Then Exit For
          If Sheet2.Cells(i, a) <> "" Then
             filledcells = filledcells + 1
        End If
    Next

Select Case filledcells
    Case Is = 2

        Sheet1.Cells(i, 1) = Sheet2.Cells(i, 1) + ", " + Sheet2.Cells(i, 2)
        Sheet1.Cells(i, 3) = Sheet2.Cells(i, 4)
        Sheet1.Cells(i, 4) = Sheet2.Cells(i, 5)
        Sheet1.Cells(i, 5) = Sheet2.Cells(i, 6)
        Sheet1.Cells(i, 6) = Sheet2.Cells(i, 7)

    Case Is = 3

        Sheet1.Cells(i, 1) = Sheet2.Cells(i, 1) + ", " + Sheet2.Cells(i, 2) + " " + Sheet2.Cells(i, 3)
        Sheet1.Cells(i, 3) = Sheet2.Cells(i, 5)
        Sheet1.Cells(i, 4) = Sheet2.Cells(i, 6)
        Sheet1.Cells(i, 5) = Sheet2.Cells(i, 7)
        Sheet1.Cells(i, 6) = Sheet2.Cells(i, 8)

    Case Is = 4

        Sheet1.Cells(i, 1) = Sheet2.Cells(i, 1) + ", " + Sheet2.Cells(i, 2) + " " + Sheet2.Cells(i, 3) + " " + Sheet2.Cells(i, 4)
        Sheet1.Cells(i, 3) = Sheet2.Cells(i, 6)
        Sheet1.Cells(i, 4) = Sheet2.Cells(i, 7)
        Sheet1.Cells(i, 5) = Sheet2.Cells(i, 8)
        Sheet1.Cells(i, 6) = Sheet2.Cells(i, 9)

   End Select
   filledcells = 0
 Next
 End Sub


text:
Q: Force svn:eol-style=native on the server? Currently, in order to ensure the subversion property eol-style is set to native for each new file added to our project, we have to add this to the ~/.subversion/config file on each of our developers machines:
[miscellany]
enable-auto-props = yes

[auto-props]
*.java = svn:eol-style=native

Is there a way to do the equivalent on the svn server?

A: No there is not.
You can use a hook scripts to look for the property to be set or not, but apart from that it's not possible. Subversion, differently than CVS, cannot change the content of the code coming from a commit.
The SVN book includes a note about this question:

Warning
Do not attempt to modify the transaction using hook scripts. A common example of this would be to automatically set properties such as svn:eol-style or svn:mime-type during the commit. While this might seem like a good idea, it causes problems. The main problem is that the client does not know about the change made by the hook script, and there is no way to inform the client that it is out-of-date. This inconsistency can lead to surprising and unexpected behavior.
Instead of attempting to modify the transaction, it is much better to check the transaction in the pre-commit hook and reject the commit if it does not meet the desired requirements.

A: Just because answer of Fausto now is outdated after release Subversion 1.8

In case of Subversion 1.8 or later you can use at the repository level (not globally for all repositories on server) repository dictated configuration (see also topic in Collab's blog), namely - svn:auto-props in the root of trunk of every repository

A: I couldn't find an example of how to check for svn:eol-style property for source code in the pre-commit hook script directly. The closest is the check-mime-type.pl which uses mime-type properties to determine if a file is a text file.
The following script inserted into the pre-commit script file will check that all the .cpp/.h files added in a commit have the svn:eol-style property set. (It can easily be extended to check additional file extensions). It will also provide messages to indicate which files are missing the svn:eol-style property.
REPOS="$1"
TXN="$2"

# Get new cpp/h files
ADDFILES=$(${SVNLOOK} changed "$REPOS" -t "$TXN" | sed -n -e '/^A.*\(\.cpp\|\.h\)$/s/^A *//p')
#echo "ADDFILES=$ADDFILES" >&2

# Check files for svn:eol-style property
ESMISSING=''
for f in ${ADDFILES}
do
  if [[ "$(${SVNLOOK} pl ${REPOS} -t ${TXN} ${f})" != *svn:eol-style* ]]
  then
    # output to stderr to include message in svn commit ouput
    echo "No svn:eol-style property set on file $f" >&2
    ESMISSING=1
  fi
done

if [[ -n "$ESMISSING" ]]
then
  exit 1
fi


text:
Q: How to add registery key-value in Visual Stadio Setup Project to another program? I have c# program that needed to be in
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run

To run at startup after installation.
I use Visual Studio 2017 Setup Project but in it's Registry tab goes as far as :
HKEY_LOCAL_MACHINE\Software\

I know a program should not change others registry but in my case, I couldn't find any other way to do it.
I wrote a program to send it's ping or beacon or heart beat and authenticate to a server every N minutes and it should run after reboot.
I tried to wrote a service but as far as i understand i could not send string to service programmatically, it has custom command which it revise only integers. after that i tried to use WCF but it is too complicated for such simple task after that i realize if i could put my program in registry and it run after reboot, it will do the job.

A: You can right-click on the key name and select New key, and keep doing that until you need to create an actual name-value pair. That's when you right-click and add New string value.


text:
Q: what is mono project what is mono project , can this help me to run my winform software on macosx . is it secure ?
can I install mono instead of .netframework ?

A: Mono is an open source implementation of .NET framework. Yes it can run winform apps on both mac and linux. But to get the native look and feel of Mac you should probably use  cocoa# bindings on Mac rather than the winforms gui library. With Monotouch it can also let your C# application run on iPhone. With Monodroid it can run your C# app on Android ... etc etc
See the following for more info:
1)  for general information http://www.mono-project.com/Main_Page
2)  for iPhone development with mono http://monotouch.net/
3)  for Mac download http://www.go-mono.com/mono-downloads/download.html
Monodevelop is the Visual Studio equivalent for Mono development. Get it from http://monodevelop.com/

A: Mono project is targeting to run .NET Framework on Linux and MacOS.
But there are a lot of problem and the project proceeds slowly.
I don't know the current state but I know you can create WinForms on Linux and with MonoLight you can create Silverlight applications.
You can get more information from Mono-Project

A: Mono Rocks!
What can I say, I simply LOVE IT... It brings the .NET framework to all *nix machines, including Mac OSX.
and all this, includes the fantastic MonoTouch (though it requires a license from Novel) to develop Native iPhone apps in... .NET language!
there are 3 things you need to know to start developing your "winforms" under Mac.

*

*Install Mono Framework (kinda like you need to install .NET 3.5)

*Install MonoDevelop (it's the Mono IDE, kinda like Visual Studio)

added 3rd thingy that you should be aware of

*

*You can easily convert winforms to osx forms, the code behind it's a simple copy paste of all your methods, but the GUI is a little tricky and you should know how the Interface Builder works so you can understand the linkage between GUI and Code.

if you want to take a deeper look without starting and installing nothing, take a look at the Session EX02 that Miguel presented at MIX 2010, intitled The Mono Project

A: The home page of the Mono project has most of the information you need. I'll quote some relevant bits:

An open source, cross-platform, implementation of C# and the CLR that is binary compatible with Microsoft.NET
Mono is a software platform designed to allow developers to easily create cross platform applications. Sponsored by Novell, Mono is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime. A growing family of solutions and an active and enthusiastic contributing community is helping position Mono to become the leading choice for development of Linux applications

A: Mono is

An open source, cross-platform,
  implementation of C# and the CLR that
  is binary compatible with
  Microsoft.NET

Therefore, you use mono instead of .net framework on not-windows native machine like Ubuntu, OSX.
You can use MonoDevelop to build your application with C# code. refer: http://monodevelop.com/


text:
Q: Issue with capturing image from camera on iPhone How to use navigator.mediaDevices.getUserMedia() correctly? How to deal with portrait and landscape mode on mobile devices?
Demo code from tutorial website fails for iPhone 8.
I want to write my own barcode reader in JavaScript to be used on an iPhone. I have coded lots of other JavaScript projects before, so I'm quite experienced with HTML + JavaScript + CSS, but I'm not familiar with accessing the camera via JavaScript. But I found a nice tutorial and hoped to learn from it. But there seems to be an error in this tutorial.
Here is the tutorial: https://usefulangle.com/post/352/javascript-capture-image-from-camera
Here is the demo: https://usefulangle.com/demos/352/camera-capture-photo.html
And here is the complete source code of this demo, as available today, at 2022-05-21 (HTML, CSS and JavaScript are all included in one file):
<!DOCTYPE html>

<title>Demo - Capture Photo From Webcam Using Javascript</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">

<button id="start-camera">Start Camera</button>
<video id="video" width="320" height="240" autoplay=""></video>
<button id="click-photo">Click Photo</button>

    <canvas id="canvas" width="320" height="240"></canvas>

Image Data URL

    <textarea id="dataurl" readonly=""></textarea>

The problem is, that this demo works well on some of my devices, but fails on others. Among the failing devices it performs worst on iPhone 8, but this is the device I need most to work perfect, because I want to use my iPhone as barcode scanner.

This demo works fine on these platforms:
Computer: do-it-yourself Hackintosh (MacOS Catalina 10.15.7 on non-Apple hardware)
Camera: logitech HD Webcam C525
The demo works fine on all of these browsers:

*

*Safari Version 15.4

*Firefox 100.0.2 (64-Bit)

*Google Chrome Version 101.0.4951.64

*Opera Version:65.0.3467.78

12 years old Macbook Pro (13 inch, Mid 2010)
MacOS Catalina Version 10.15.7 (unsupported version installed with Catalina Patcher)
The demo works fine on all of these browsers:

*

*Safari Version 15.4

*Firefox 96.0.1 (64-Bit)

*Firefox 100.0.2 (64-Bit)

*Google Chrome Version 101.0.4951.64

Notebook "hp Elitebook"
Windows 10 Enterprise version 21H2
The demo works fine on all of these browsers:

*

*Microsoft Edge Version 101.0.1210.53

*Firefox 97.0.2 (64-Bit)

*Google Chrome Version 101.0.4951.67

iPad Pro, 12.9 inch, 3rd generation
iPadOS Version 15.4.1
The demo works fine on all of these browsers, but only in portrait mode!

*

*Safari 15

*Google Chrome Version 101.0.4951.58

It works with errors on these platforms:
iPad Pro, 12.9", 3rd generation
iPadOS Version 15.4.1
in landscape mode
Same error in all browsers: Distorted captured image: The live image is in portrait mode, the captured image is landscape, showing my face double as wide as it really is.

*

*Safari 15

*Google Chrome Version 101.0.4951.58

iPhone 8
iOS Version 15.4.1
The live image is black on all browsers. You see just a black rectangle
In landscape mode: The captured image is ok (user's face is visible and not distorted)
In portrait mode: Distorted captured image (as described for iPad in portrait mode)

*

*Safari 15

*Google Chrome Version 101.0.4951.58

summary:
Failing does not depend on the browser but on the device. The demo works even on exotic machines like a Hackintosh or a 12 years old Macbook Pro but fails with two different errors on an iPhone 8.
There are two errors:

*

*Black rectangle instead of live video image
Only on my iPhone 8. The live video image is visible on all other devices

*Distorted captured still image
On both mobile devices, but only in portrait mode. It works fine on stationary computer, laptop and Macbook, works also fine in landcape mode on mobile devices.

My question
Please, I need a correction of the demo code, so that it shows the live video image on all devices, including iPhone 8. The corrected code please also shall not show any distorted captured image in portrait mode of mobile devices.

Optional additional question: (An answer would be nice, but more important is an answer to the issue described above)
I have written a barcode scanner for iPhone 3 and iPhone 4 about 10 years ago in native Objective-C. It was no problem to have a video image 320 pixels wide and only 80 pixels high (to scan EAN-13 and other linear barcodes). Is it possible to have such a 4:1 video window also when using HTML + JavaScript?


text:
Q: WP media attachment location vs permalink Yesterday I moved my sites from http://www.example.com to  (secure site and removed the www).  Now when I look at an attachment page I see the File URL as the old http://www ... but the page permalink at https://.
I have even deleted the original photos and re-uploaded new ones, thinking that might solve it, but it does not.  The domain is properly set (https://) in Wordpress Settings/General.  The site works fine ... and the switch to https went much more smoothly than I had anticipated ... except for this issue.
Has anyone encountered similar?  Or know what/where I need to change something?
Thank you for any info/advice.

A: I think a possible solution could be following codesnippet from Mark Kaplun.
To solve issues with this you could remove the http part and Wordpress will/should use https instead.
Because the rest of your website is working correctly I assume that further settings are correct and will do their job as wished.
add_filter('the_content','wpse_217012',1000,1);
// remove 'http:' part from any mention of the site url
function wpse_217012($content) {
    return str_replace(siteurl(),str_replace('http:','',siteurl()),$content);
}

Please add the snippet to functions.php (make a copy first) or to a plugin.

Note: Of course is this a solution to achieve a positive result and actually
  not pointing on the cause of your problem as it.
  I personally would not use a redirect done by code in .htaccess because, as mentioned by yourself already, the rest is working.
  Maybe there is a plugin or own code somewhere in functions.php which is causing the problem? Please take also a look at these possibilities.

If I am totally wrong, please let me know and I will remove the answer to prevent other users here on wpse will use the (incorrect)code for an equal problem.


text:
Q: fixing date shape in pandas dataset in question
Hello, I have been trying to standardize the date in the year column to get rid of the decimals and and the random format and keep only the years.
Is there an efficient way to do this in Pandas?

A: Setup
import pandas as pd  # 1.5.1

so = pd.DataFrame({
    "Countries": [*["Canada"]*5, *["Brazil"]*5],
    "Year": [1990.0, 1991.0, 1992.0, 1993.0, 1994.0, 2020.0, 2021.0, 2021.0, "2011-21", 2021.0],
    "Value": 1  # placeholder
})

print(so)

  Countries     Year  Value
0    Canada   1990.0      1
1    Canada   1991.0      1
2    Canada   1992.0      1
3    Canada   1993.0      1
4    Canada   1994.0      1
5    Brazil   2020.0      1
6    Brazil   2021.0      1
7    Brazil   2021.0      1
8    Brazil  2011-21      1
9    Brazil   2021.0      1

Explanation
Inspecting the .dtype of so.Year we get object
print(so.Year.dtype)

object

I'm making an assumption that all years in so.Year will be 4-digit, so I convert to str and limit to the first four characters
so["NewYear"] = so.Year.astype(str).str[:4]

print(so)

  Countries     Year  Value NewYear
0    Canada   1990.0      1    1990
1    Canada   1991.0      1    1991
2    Canada   1992.0      1    1992
3    Canada   1993.0      1    1993
4    Canada   1994.0      1    1994
5    Brazil   2020.0      1    2020
6    Brazil   2021.0      1    2021
7    Brazil   2021.0      1    2021
8    Brazil  2011-21      1    2011
9    Brazil   2021.0      1    2021

Now you can either use the NewYear column as-is, or convert to some other dtype.


text:
Q: What is the best way to modify the class for an input nested inside an ember component? So I have a simple ember component that looks something like this

  {{input value=password type="password" class="text-input"}}

The component itself is dead simple - something like this
import Ember from 'ember';

export default Ember.Component.extend({
    didInsertElement: function() {
        //do stuff here
    }
});

Instead of "hard coding" the text-input class as I did above ... how can I instead "pass this in" when I use the component in my ember application?

A: Any parameters you pass into the component become properties on the component that are available to component's template.
So, you can do

Now, textClass is available to your component, so you can do

Working example here


text:
Q: Setting JRuby properties within Java code I use the JRuby complete JAR to interpret Ruby scripts in my Java program.
Looking for improving its performance, I found some properties: https://github.com/jruby/jruby/wiki/PerformanceTuning#compiler_rt_props
But those are properties for the command line JRuby. How can I set them within my Java code?

A: Use System.setProperty(String key, String value) to set the properties you provide in command line. e.g.
System.setProperty("jruby.compat.version","RUBY1_8");

You have to set these properties during start up of your application.so,that there will not be any problem of properties missing


text:
Q: WebDriver exception on using Winiumdriver I have started learning Winium tool. When running using the below code getting:
public class CalcDemo {

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

        DesktopOptions options=new DesktopOptions();
        options.setApplicationPath("C:\\Windows\\System32\\notepad.exe");
        WiniumDriver driver=new WiniumDriver(new URL("http://localhost:9999"), options);
        driver.findElementByClassName("Edit").sendKeys("This is sample test");
        driver.close();
    }
}

I'm getting the bellow error:
"org.openqa.selenium.WebDriverException: The given path's format is not supported"

Can anyone help me out.
Thanks.

A: I think you need to find the window before trying to access the Edit class.
Here's my C# example:
        var dc = new DesiredCapabilities();
        dc.SetCapability("app", @"C:/windows/system32/Notepad.exe");
        var driver = new RemoteWebDriver(new Uri("http://localhost:9999"), dc);

        var window = driver.FindElementByClassName("Notepad");
        var edit = window.FindElement(By.Name("Text Editor"));


text:
Q: Adding many checkboxes in R Manipulate as a list/vector I'm using {manipulate} to add a number of check-boxes to the plot - one for each line that is being drawn. Since the number required is not pre-defined I'm trying to figure a way out to pass all checkboxes as a vector or a list to the manipulate function.
The documentation seems to hint something :

manipulate(_expr, ...)
_expr : Expression to evalulate.
...  : One or more named control arguments (i.e. slider, picker, checkbox, or button), or a list containing named controls.

I think the way out would be to pass a list of as many checkboxes as is required. But how exactly should that be carried out?

A: The following example should do what you want:
# Define function for ploting
example <- function(...){
  plot(cars)
  i <- 1
  for (my.control in list(...)) {
    if (my.control) abline(0, i)
    i <- i+1
  }
}

# Define your controls
custom.args <- list()
for (i in 1:5) {
  custom.args <- append(custom.args, list(checkbox(FALSE, paste("Ceckbox", i))))
}
names(custom.args) <- paste("checkbox", 1:5, sep="")

# Pass everything to manipulate
library(manipulate)
manipulate(
  eval(parse(text=sprintf('example(%s)',
                          paste(names(custom.args), collapse=","))
             )),
  custom.args)

I don't know if there is a cleaner way to pass control values to plotting function, but at least this works.


text:
Q: Markers in react-google-map doesnt render after change in props I cant deal with that problem.
I got object locations. there are objects with info about position, function and icon color.
I send it to Map. At start it shows ok but then when i filter the array and send new ones to show it doesnt render new ones.
I add state to class and setState it- after check i see in console that everything is ok with changes- but markers are still the same.
Please help
locations is also a state in parent stateless component.
Map Component
import React, {Component} from 'react'
import GoogleMapReact from 'google-map-react'
import MarkerClusterer from '@google/markerclusterer'

export default class GoogleMapContainer extends Component {

state = {
locationsToShow:  null
}

componentDidMount () {
const script = document.createElement('script')
script.src = 'https://developers.google.com/maps/documentation/javascript/examples     /markerclusterer/markerclusterer.js'
script.async = true
document.body.appendChild(script)
}
componentDidUpdate(prevProps) {
if (this.props.locations !== prevProps.locations) {
 this.setState({locationsToShow: this.props.locations})
}
}

static defaultProps = {
center: {
  lat: 59.95,
  lng: 30.33
 },
 zoom: 11
}

render () {
const setGoogleMapRef = (map, maps) => {
  this.googleMapRef = map
  this.googleRef = maps
  let locations = this.props.locations
    console.log('locations w propsie')

  let markers = this.state.locationsToShow &&   this.state.locationsToShow.map((location) => {
    let item = new this.googleRef.Marker({position: location.position, icon:  location.icon })
    google.maps.event.addListener(item, 'click', location.fn)
    return item
  })
  console.log('markerow jest')
  let markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
    gridSize: 60,
    minimumClusterSize: 2
  })
}

return (
  <GoogleMapReact
    bootstrapURLKeys={{key: `apiKey`}}
    yesIWantToUseGoogleMapApiInternals
    onGoogleApiLoaded={({map, maps}) => setGoogleMapRef(map, maps)}
    defaultCenter={{lat: 52.193275, lng: 20.930372}}
    defaultZoom={7}
    options={{streetViewControl: true}}
  />
)
 }
}

parent comp element
let locationsList = filteredData.map((el) => {
            const lati = Number(el.location.latitude).toFixed(6)
        const longi = Number(el.location.longitude).toFixed(6)
            return {position: { lat: Number(lati), lng: Number(longi) }, icon: typeOfIcon(el.status), fn: ()=>{
                setIsOpen(true)
                setData(el)
                } }
          })
         setLocations(locationsList)

A: setGoogleMapRef is only called when the map component is instantiated I am guessing (you want this). so you need to access the map and update your locations in your render function outside of the setGoogleMapRef callback.
something like the following:
render () {
  const setGoogleMapRef = (map, maps) => {
    this.googleMapRef = map
    this.googleRef = maps
    this.markerCluster = //...
  };

  if (this.googleMapRef) {
    let locations = this.props.locations
    console.log('locations w propsie')

    let markers = this.state.locationsToShow &&
    this.state.locationsToShow.map((location) => {
    let item = new this.googleRef.Marker({position: location.position, icon:  location.icon })
    google.maps.event.addListener(item, 'click', location.fn)
    return item
    })
    console.log('markerow jest')
    // update marker cluster
   }

  return //...;
}


text:
Q: SugarORM not working So, I'm new to this and I'm trying to implement SugarORM to create a database because it's suppose to be easier.
I've followed every step of the tutorial and adapted it to what I want to do in my app but whenever I try to save something into the database, the app crashes and goes back to the previous activity.
Can anyone tell me what I'm doing wrong? I want to save 5 inputs into the database and be able to delete by inputing their name (which will also be stored in the database).
Here is the logcat:
09-25 15:00:29.909 18121-18121/com.example.cabr.teste E/SQLiteLog: (1)
09-25 15:00:29.911 18121-18121/com.example.cabr.teste E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.cabr.teste, PID: 18121
  android.database.sqlite.SQLiteException: no such table: SUGAR_ORM (Sqlite code 1): ,
  while compiling: INSERT OR REPLACE  INTO SUGAR_ORM(ID,SIMULT,POTENCIA,QUANTIDADE,EQUIPAMENTO,HORAS) VALUES (?,?,?,?,?,?),
  (OS error - 2:No such file or directory)
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:925)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:536)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1725)
      at com.orm.SugarRecord.save(SugarRecord.java:266)
      at com.orm.SugarRecord.save(SugarRecord.java:360)
      at com.example.cabr.teste.Main14Activity$16.onClick(Main14Activity.java:417)
      at android.view.View.performClick(View.java:5647)
      at android.view.View$PerformClick.run(View.java:22465)
      at android.os.Handler.handleCallback(Handler.java:761)
      at android.os.Handler.dispatchMessage(Handler.java:98)
      at android.os.Looper.loop(Looper.java:156)
      at android.app.ActivityThread.main(ActivityThread.java:6577)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
09-25 15:00:29.919 512-893/? E/logserver: imonitor_add_dynamic_path, path:/data/system/dropbox/data_app_crash@1506348029917.txt
09-25 15:00:29.923 1374-11353/? E/ReportTools: This is not beta user build
09-25 15:00:30.082 1374-11624/? E/HsmCoreServiceImpl: onTransact in code is: 102
09-25 15:00:30.132 1374-11619/? E/Process: isHighLoadProcess: get cpu failed
09-25 15:00:30.736 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 0
09-25 15:00:30.741 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 34359738371
09-25 15:00:30.742 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 240518168576
09-25 15:00:30.743 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 68719476736
09-25 15:00:30.745 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 1

And my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main14);

    final TextView textView12 = (TextView) findViewById(R.id.textView12);

    final Button button1 = (Button) findViewById(R.id.button1);
    final Button button2 = (Button) findViewById(R.id.button2);

    final EditText editText1 = (EditText) findViewById(R.id.editText1);
    final EditText editText2 = (EditText) findViewById(R.id.editText2);
    final EditText editText3 = (EditText) findViewById(R.id.editText3);

    final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
    final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);

    final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkbox1);

    final ImageView imageView1 = (ImageView) findViewById(R.id.imageview1);
    ImageView imageView2 = (ImageView) findViewById(R.id.imageview2);
    ImageView imageView3 = (ImageView) findViewById(R.id.imageview3);
    ImageView imageView4 = (ImageView) findViewById(R.id.imageview4);
    ImageView imageView5 = (ImageView) findViewById(R.id.imageview5);
    ImageView imageView6 = (ImageView) findViewById(R.id.imageview6);
    ImageView imageView7 = (ImageView) findViewById(R.id.imageview7);
    ImageView imageView8 = (ImageView) findViewById(R.id.imageview8);
    ImageView imageView9 = (ImageView) findViewById(R.id.imageview9);
    ImageView imageView10 = (ImageView) findViewById(R.id.imageview10);
    ImageView imageView11 = (ImageView) findViewById(R.id.imageview11);
    ImageView imageView12 = (ImageView) findViewById(R.id.imageview12);
    ImageView imageView13 = (ImageView) findViewById(R.id.imageview13);
    ImageView imageView14 = (ImageView) findViewById(R.id.imageview14);
    ImageView imageView15 = (ImageView) findViewById(R.id.imageview15);
    ImageView imageView16 = (ImageView) findViewById(R.id.imageview16);

    final TableLayout tableLayout1 = (TableLayout) findViewById(R.id.tablelayout1);

    final ScrollView scrollView1 = (ScrollView) findViewById(R.id.scrollView);

    imageView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    imageView3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), Main9Activity.class);
            startActivity(i);
        }
    });

    imageView4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.televisao2);
            textView12.setText(getString(R.string.televisor));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.sistemasom2);
            textView12.setText(getString(R.string.sistemasom));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.leitordedvd2);
            textView12.setText(getString(R.string.leitordvd));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.consoladejogos2);
            textView12.setText(getString(R.string.consolajogos));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.aspirador2);
            textView12.setText(getString(R.string.aspirador));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.arcondicionado2);
            textView12.setText(getString(R.string.arcondicionado));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.lampada2);
            textView12.setText(getString(R.string.lampadas));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView11.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.computadorportatil2);
            textView12.setText(getString(R.string.computadorportatil));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView12.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.aquecedoraoleo2);
            textView12.setText(getString(R.string.aquecedoreletr));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView13.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.ventoinha2);
            textView12.setText(getString(R.string.ventoinha));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView14.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.desumidificador2);
            textView12.setText(getString(R.string.desumificador));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView15.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.ferroeletrico2);
            textView12.setText(getString(R.string.ferroeletrico));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView16.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context context = getApplicationContext();
            CharSequence text = "Marque a caixa se utiliza este equipamento em simultâneo com outros equipamentos.";
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    });

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String equipamento, tipohoras, periodo;
            Integer potencia, quantidade, simult;
            Double quanthoras;
            Double horas = 0.0;

            button2.setVisibility(View.VISIBLE);
            button1.setVisibility(View.GONE);

            equipamento = textView12.getText().toString();
            potencia = Integer.parseInt(editText1.getText().toString());
            quantidade = Integer.parseInt(editText2.getText().toString());
            quanthoras = Double.parseDouble(editText3.getText().toString());
            tipohoras = spinner1.getSelectedItem().toString();
            periodo = spinner2.getSelectedItem().toString();
            simult = 0;

            if (potencia==0){
                if (equipamento.equals("Televisor")){
                    potencia = 90;
                }
                if (equipamento.equals("Sistema de Som")){
                    potencia = 150;
                }
                if (equipamento.equals("Leitor de DVD")){
                    potencia = 195;
                }
                if (equipamento.equals("Consola de Jogos")){
                    potencia = 140;
                }
                if (equipamento.equals("Aspirador")){
                    potencia = 600;
                }
                if (equipamento.equals("Ar Condicionado")){
                    potencia = 1400;
                }
                if (equipamento.equals("Lâmpadas")){
                    potencia = 10;
                }
                if (equipamento.equals("Computador Portátil")){
                    potencia = 65;
                }
                if (equipamento.equals("Aquecedor Elétrico")){
                    potencia = 1500;
                }
                if (equipamento.equals("Ventoinha")){
                    potencia = 80;
                }
                if (equipamento.equals("Desumidificador")){
                    potencia = 150;
                }
                if (equipamento.equals("Ferro Elétrico")){
                    potencia = 1000;
                }
            }

            if (quanthoras==0){
                if (equipamento.equals("Televisor")){
                    horas = 5.0;
                }
                if (equipamento.equals("Sistema de Som")){
                    horas = 8.0;
                }
                if (equipamento.equals("Leitor de DVD")){
                    horas = 3.0;
                }
                if (equipamento.equals("Consola de Jogos")){
                    horas = 3.0;
                }
                if (equipamento.equals("Aspirador")){
                    horas = 1.04;
                }
                if (equipamento.equals("Ar Condicionado")){
                    horas = 8.0;
                }
                if (equipamento.equals("Lâmpadas")){
                    horas = 5.0;
                }
                if (equipamento.equals("Computador Portátil")){
                    horas = 8.0;
                }
                if (equipamento.equals("Aquecedor Elétrico")){
                    horas = 4.0;
                }
                if (equipamento.equals("Ventoinha")){
                    horas = 6.0;
                }
                if (equipamento.equals("Desumidificador")){
                    horas = 4.0;
                }
                if (equipamento.equals("Ferro Elétrico")){
                    horas = 1.0;
                }
            } else {
                if (periodo.equals("dia")){
                    if (tipohoras.equals("min")){
                        horas = quanthoras/60;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras;
                    }
                }

                if (periodo.equals("semana")){
                    if (tipohoras.equals("min")){
                        horas = (quanthoras/60)/7;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras/7;
                    }
                }

                if (periodo.equals("mês")){
                    if (tipohoras.equals("min")){
                        horas = (quanthoras/60)/30.42;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras/30.42;
                    }
                }
            }

            SugarORM sugarORM = new SugarORM(equipamento, potencia, quantidade, horas, simult);
            sugarORM.save();

            Toast.makeText(getBaseContext(),"O equipamento foi adicionado com sucesso.", Toast.LENGTH_LONG).show();

        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            button2.setVisibility(View.GONE);
            tableLayout1.setVisibility(View.GONE);
            imageView1.setVisibility(View.GONE);
            textView12.setVisibility(View.GONE);

            String equipamento;
            equipamento = textView12.getText().toString();

            SugarORM sugarORM = SugarORM.findById(SugarORM.class, 1);
            sugarORM.delete();

            Toast.makeText(getBaseContext(),"O equipamento foi removido com sucesso.", Toast.LENGTH_LONG).show();

        }
    });

}

}
And the SugarORM class:
public class SugarORM extends SugarRecord {
String equipamento;
Integer potencia;
Integer quantidade;
Double horas;
Integer simult;

public SugarORM(){

}

public SugarORM(String equipamento, Integer potencia, Integer quantidade, Double horas, Integer simult){
    this.equipamento = equipamento;
    this.potencia = potencia;
    this.quantidade = quantidade;
    this.horas = horas;
    this.simult = simult;
}

}
And the manifest:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme.NoActionBar"
    android:name="com.orm.SugarApp">
    <meta-data
        android:name="DATABASE"
        android:value="notes.db" />
    <meta-data
        android:name="VERSION"
        android:value="1" />
    <meta-data
        android:name="QUERY_LOG"
        android:value="true" />
    <meta-data
        android:name="DOMAIN_PACKAGE_NAME"
        android:value="com.example.cabr.teste" />
    <activity android:name=".Main10Activity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Main2Activity" />
    <activity android:name=".Main3Activity" />
    <activity android:name=".Main4Activity" />
    <activity android:name=".Main5Activity" />
    <activity android:name=".Main6Activity" />
    <activity android:name=".Main7Activity" />
    <activity android:name=".Main8Activity" />
    <activity android:name=".MainActivity" />
    <activity android:name=".Main9Activity" />
    <activity android:name=".Main11Activity" />
    <activity android:name=".Main12Activity" />
    <activity android:name=".Main13Activity" />
    <activity android:name=".Main14Activity" />
    <activity android:name=".Main15Activity" />
    <activity android:name=".Main16Activity" />
    <activity android:name=".Main17Activity" />
    <activity android:name=".Main18Activity" />
    <activity android:name=".Main19Activity" />
    <activity android:name=".Main20Activity"></activity>
</application>

A: Try changing your declaration line from:
public class SugarORM extends SugarRecord

to
public class SugarORM extends SugarRecord<SugarORM>

If all else fails, increment your VERSION setting in your manifest

A: Your problem is that SugarORM can't find the table as mentioned at your log no such table:. Try to delete the application and rerun it or try to call the sugarDB.onCreate() at the launch activity.

A: The problem is that you do not change the version of your database in the AndroidManifest.xml. Every time you change something in your code (SugarORM in this case) you need to update the version in your Manifest. Otherwise it wil not update your database and you will get this error.
The same goes for changing names of attributes, then the error will be: no such column.
<meta-data  android:name="VERSION"  android:value="2" />


text:
Q: Are angle brackets allowed in html 5 data attribute? If so how to find it with jQuery? I wondered whether it is allowed to store angle brackets inside a html 5 data attribute. In my example I need to store email addresses inside this attribute. This looks like:
<input class="email" data-email="Name <a@z.com>">
<input class="email" data-email="Name <b@z.com>">

There was no problem in the browser until I tried to find the element with a certain email address with jQuery.
$('.email[data-email="Name <a@z.com>"]')

This didn't work. So I asked myself whether it is allowed and if so how to select it with jQuery. If not - is there another way how to solve this problem?

A: You need to do
$('.email[data-email*="a@z.com"]')

Here * is a wildcard saying that select element whose atttibute contains a@z.com

A: I don't know what is wrong with jQuery, but pure JS seems to be working:
document.querySelector('.email[data-email="Name <a@z.com>"]');

A: If you are not matching the full value of the field, you can't use the = operator; *= is substring comparison:

$('.email[data-email*="<a@z.com>"]').val("This one is a@z.com");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="email" data-email="Name <a@z.com>">
<input class="email" data-email="Name <b@z.com>">


text:
Q: find ode with a given solution $y=(1-y_0)t+y_o$ I want to find a first order ode, an initial value problem, that has the solution
$$y=(1-y_0)t+y_0$$
where $y_0$ is the initial value.The ode has to be of first order, that is:
$$y'=f(y).$$
I need this to test a special solver I am building.
The main objective is to find an ode that has the property that the end-value goes into the reverse direction of the initial value. My thought is, that the function above is the most simple one that fulfills that requirement. However, any other idea that produces my desired result is welcome.
I came so far: since
$$y'=1-y_0=f((1-y_0)+y_0)$$
$f$ should be something like
$$f(z)=\frac{z-y_0}{t}$$
so we get:
$$y'=\frac{y-y_0}{t}$$
However, I don't know how to properly get the initial condition into the equation, the $y_0$ part in the ode itself doesn't seem right, since the initial value can't be put into the ode itself but is a special constrained outside the ode. Can anyone help me get this clear?

A: Solve for $y_0$:
$$ y_0 = \frac{t-y}{t-1} $$
Then differentiate:
$$ 0 = \frac{(t-1)(1-y') - (t-y)}{(t-1)^2} = - \frac{y'}{t-1} + \frac{y-1}{(t-1)^2}$$
i.e.
$$ y' = \frac{y-1}{t-1}$$

A: This is maybe not what you intended.
Note that you want a differential equation of the form $y'=f(y)$, and at the same time the proposed solution has constant derivative with respect to $t$. This implies that $f$ is necessarily of the form $f(y)=c$ for some constant $c$. Given $y_0$ an IVP satisfying your requirements therefore could be
$$y'=1-y_0,\qquad y(0)=y_0\ .$$


text:
Q: Gulp - difference between function done() vs gulp.series I have two questions about Foundation's gulpfile.
By default gulp launches all the tasks at once and waits for nothing. To run tasks in a particular order we need to give a hint to tell gulp when the task is done (read more):
function reload(done) {
  browser.reload();
  done();
}

But why since later there's gulp.series:
function watch() {
  gulp.watch('src/assets/scss/**/*.scss').on('all', gulp.series(sass,browser.reload));
}

My questions are:

*

*Why using function done() and gulp.series simultaneously?

*What on('all') does? I can't find anything in docs about it.

A: It's all about new Gulp 4. Helpful links:

*

*The Complete-Ish Guide to Upgrading to Gulp 4

*Gulp 4 docs


text:
Q: QGIS - Transfer feature selection with new attributes to PostGIS I have three shapefiles which represent a conduit network with valves and hydrants. The pipe grid consists of line features in a shapefile and the valves and hydrant each are a point layer in a shapefile.

For the planning of flushing proceedings I need to select some of the pipe elements (the line features) in a certain order which are to be flushed. The underlying attribute table of the pipe elements is also important for the planning process.
Ideally there is a way to create many different flushing selections (e.g. pipe no. 1-5, pipe no. 18-45, etc.) and save them in another layer, let's call it flushings. It is essential that the selection of pipes is assigned a new identifier the flushing ID.
So the flushing layer would contain flushing no. 1,2,3... with each flushing itself containing or refering to a previos made selection of pipe elements.
I then would like to export the generated information of a pipe selection and an assigned flushing ID to either a shapefile or any other way which I can use in my PostGIS database.
Example:
pipe elements attribute table:
id  material  diameter
1   PE        80
2   PE        80
3   PE        100
4   PE        100

I need something like this in my database:
flushings
flushing_id   pipe_id  order
f1            2        1
f1            3        2
f1            4        3
f2            1        1
f2            2        2
f2            3        3

Is there an easy workflow for pipe selection and assigning a flushing id to the selection to import it in a database later? It would also be helpful if each selection could be colored differently to make it easier to work with.

A: The workflow in vanilla QGIS would probably be something like this:

*

*Set up your attribute tables as you have done - with pipeIDs, with two new columns flushing_id and ord (I would avoid using order as that is a database keywork)

*Manually click on each point in turn, and assign it a new flushing_id and ord manually, record by record, saving as you go.

The only possible improvement to this would to to write a script / add-in in QGIS that could speed this up, for instance by recording the order of selection of points, and writing them out automatically in that order to the database.
The issue with the workflow you have described is there is not generally a mechanism in GIS for recording the order of selection - the selection will remain in the order of the original table when you export it out or do anything with it, so you will probably have to write something custom - I haven't seen a tool that will do that or could be adapted to do that.


text:
Q: Hide add to cart button in WooCommerce but show stock status I want to hide the add to cart button in WooCommerce but still show the stock status message... It's easy in CSS but i am looking for a solution in php.
For now i've been using this code below but it hide all the shop functionnality, I just need to hide the add to cart button and show the out of stock message if the product is out of stock.
  // Remove add to cart on single product pages
  add_action( 'woocommerce_single_product_summary', 'hide_single_product_prices', 1 );

  function hide_single_product_prices(){

global $product;

  if ( has_term( array('category1', 'category2', 'category3', 'category4'), 'product_cat', $product->get_id() ) ) :

  //Hide add-to-cart button, quantity buttons (and attributes dorpdowns for variable products)
if( ! $product->is_type('variable') ){

  remove_action('woocommerce_single_product_summary','woocommerce_template_single_add_to_cart', 30 );
  } else {

  remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
  }

  endif;
  }```

A: So the issue is that when you remove the function 'woocommerce_template_single_add_to_cart' from 'woocommerce_single_product_summary' what you're actually doing is telling woocommerce not to load the template at all, located in: templates/single-product/add-to-cart. Which template loads there depends on the product type, but I'll assume simple for now.
If you look at that template, its not ACTUALLY just the add to cart button. It contains the call to wc_get_stock_html() that displays what you're looking for. So there isn't actually a good way just with removing a hook, to hide ONLY the button.
Instead what you'll have to do is one of two things: You can copy the add-to-cart/simple.php template into your theme, and edit it there with your logic. You'll likely want to wrap the button like this:
<?php if( ! your_custom_function( $product ) : ?>
    <div class='buttons-container'>
        <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button btn btn--pink"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>
    </div>
<?php endif; ?>

The downside to that is that if you want this to work for all product types, you'd have to copy each template and do something similar.
So alternatively, what you could do is remove the action - as you have in your code above, and then Re-add the stock display wherever you'd like it. I would lean this direction for the reason above. Something like this:
remove_action( 'woocommerce_single_product_summary','woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', function(){
    global $product;
    if( $product->is_purchasable() ){
        echo wc_get_stock_html( $product );
    }
}, 30 );


text:
Q: Youtube API Uncaught (in promise) Error: Request failed with status code 403 I am attempting to integrate the YouTube API into a new Vuejs application and I am testing it in the browser and continuing to get a 404 error.
I did have a www missing, but I continue to get this same error when I make the request. Is there something I am not seeing in my code that is wrong? Is it a cors issue? If so, what is the standard practice for resolving this in Vuejs? I have made a similar application in Reactjs and did not run into this issue.
<template>
  <div>
    <SearchBar @termChange="onTermChange"></SearchBar>
  </div>
</template>

<script>
import axios from "axios";
import SearchBar from "./components/SearchBar";
const API_KEY = "<api_key>";

export default {
  name: "App",
  components: {
    SearchBar
  },
  methods: {
    onTermChange(searchTerm) {
      axios
        .get("https://www.googleapis.com/youtube/v3/search", {
          params: {
            keys: API_KEY,
            type: "video",
            part: "snippet",
            q: searchTerm
          }
        })
        .then(response => console.log(response));
    }
  }
};
</script>

I did notice in the response I got this message:
"code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

I am not sure what this means.

A: Put your Api key in url like
"https://www.googleapis.com/youtube/v3/search?key=YOUR_API_KEY"
axios.get("https://www.googleapis.com/youtube/v3/search?key=Your_Api_Key", {
          params: {
            type: "video",
            part: "snippet",
            q: searchTerm
          }
        })
        .then(response => console.log(response));

You will find an example as well here

A: "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

This means that you have exceeded your limit to serve videos from youtube.
You need to create an account to be able to show more videos.
If you're sure you haven't exceeded your limit/ have an account double check your developer console that the API is turned on.
Developer Console.
What I would suggest is to add a catch to your call to handle errors in the future.
axios
  .get("https://www.googleapis.com/youtube/v3/search", {
    params: {
      keys: API_KEY,
      type: "video",
      part: "snippet",
      q: searchTerm
    }
  })
  .then(response => console.log(response));
  .catch(err => { console.log(err); }

A: Solved this by configure/updating/enabling the settings.
The api key worked in the past for me. When returning to use it again, i received a 403 error.
The server understood my request, but denied me access to the info.
Just go into developers console, go to enable apis, search youtube, and enable it, your key will now work as expected.

A: for some users, this error might be because of cause sanctions. so try to run your project using a DNS or VPN.


text:
Q: ScrollListener for RecyclerView inside NestedScrollView? I am using RecyclerView inside NestedScrollView. For smooth scrolling
nestedScrollView.setNestedScrollingEnabled(true);
recyclerView.setNestedScrollingEnabled(false);

And this RecyclerView is dynamic, dynamically adding rows on the scroll. But scroll listener is not working NestedScrollingEnabled is false.

A:         scroller.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (scrollY > oldScrollY) {
                    Log.i(TAG, "Scroll DOWN");
                }
                if (scrollY < oldScrollY) {
                    Log.i(TAG, "Scroll UP");
                }

                if (scrollY == 0) {
                    Log.i(TAG, "TOP SCROLL");
                }

                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    Log.i(TAG, "BOTTOM SCROLL");
    f (viewGroup1.getChildAt(viewGroup1.getChildCount() - 1) instanceof RecyclerView){
//add code here }

                }
           }
        });


text:
Q: How to improve poor performance of EF Core SQL query that sorts on a child collection My issue is with the queries that EF Core generates for fetching ordered items from a child collection of a parent.
I have a parent class which has a collection of child objects. I'm using Entity Framework Core 5.0.5 (code first) against a SQL Server database. I've tried to boil down the scenario, so let's call it an Owner with a collection of Pets.
I often want a list of owners with their oldest pet, so I'll do something like
Context.Owners
.Select(owner =>
    new {
       Owner = owner,
       OldPet = owner.Pets.OrderBy(pet => pet.Age).LastOrDefault()
    })
.Where(owner.Id == 1);

This worked fine before (on ef6) and works functionally now. However, the issue I have is that now EF Core translates these sub collection queries into something apparently cleverer, something like
 SELECT *
  FROM [Owners] AS [c]
  LEFT JOIN (
      SELECT *
      FROM (
          SELECT [c0].[Id] ... , ROW_NUMBER() OVER(PARTITION BY [c0].[OwnerId] ORDER BY [c0].[Age] DESC) AS [row]
          FROM [Pets] AS [c0]
      ) AS [t]
      WHERE [t].[row] <= 1
  ) AS [t0] ON [c].[Id] = [t0].[OwnerId]

The problem I'm having is that it seems to perform terribly. Looking at the execution plan it's doing a clustered index seek on the pets table, then sorting them. The 'number of rows read' is massive and the 'sorting' takes tens or hundreds of milliseconds.
The way EF6 does the same functionality seemed way more performant in this sort of scenario.
Is there a way to change the behaviour so I can choose? Or a way to rewrite this type of query such that I don't have this problem? I've tried many variations of using GroupBy etc and still have the same result.

A: If you are doing FirstOrDefault in projection, EF Core has to create such join, which uses Window Function ROW_NUMBER. To get desired SQL it is better to rewrite your query to be more predictable for LINQ translator:
var query =
    from owner in Context.Owners
    from pet in owner.Pets
    where owner.Id == 1
    orderby pet.Age descending
    select new
    {
        Owner = owner,
        OldPet = pet
    }

var result = query.FirstOrDefault();


text:
Q: Google Chrome failed to print preview issue (Out of memory/ page not responding) Hi please help me out for this issue.
If I print less then 100 page it is working fine, but when I try to print 100/100+ pages it is throwing print preview issue.
All the 100 pages have the one image in each. Image size is around 70KB or more.
If I print 50/60 it will work fine.
Please do help me with this issue.


text:
Q: Bottom Border CSS Transition not Stretching across Playing some more with pseudo elements and I wanted to simulate the bottom border of a list-item element growing from the left on a hover over.  Unfortunately, I can manage to get the line to grow the length of the text, just not the length of the border of the full list item.
I've put a border on the list items so you know what I mean
HTML:

Home

Products

Company

Contact

CSS:
body
{
margin: 0;
}

*
{
margin: 0;
padding: 0;
}

#orangeNavBar
{
height: 45px;
width: 627px;
background-color: #E87966;
margin-left: auto;
margin-right: auto;
margin-top: 15px;
}

ul
{
list-style:none;
}

ul li
{
float: left;
display: inline-block;
font-family: verdana;
font-size: .9em;
font-weight: bold;
color: white;
height: 45px;
box-sizing: border-box;
padding: 13.5px 20px;
transition: color .3s;
border: 1px solid black;

}

ul li::after
{
display: block;
content: "";
background: black;
height: 2px;
width: 0px;
transition: width 0.2s ease;
}

ul li:hover::after
{
width: 100%;
}

ul li:hover
{
color: black;
}

Link to Codepen

A: If you add the following CSS, it should work as you expect:
ul li {
    position: relative;
}

ul li:after {
    position: absolute;
    bottom: 0;
    left: 0;
}

The position: relative is required to make sure the pseudo element is constrained by the width and height of the
 instead of the entire .
The position: absolute; for the pseudo element allows you to anchor the element to the bottom left (bottom: 0; left: 0;) of the
 element.

A: *

*You should wrap the text with  tag.

*Then assign position:relative to it and move the ::after values of li to span. so that the border-bottom applies under the text only .

*And have to alter few css properties to perfect the alignment .

Here is my working codepen snippet of your project
HTML:

Home

Products

Company

Contact

CSS:
ul li span {
    display:block;
    padding: 13.5px 0;
    position: relative;
}
ul li span::after {
    display: block;
    content: "";
    background: black;
    height: 3px;
    width: 0px;
    transition: width 0.2s ease;
    position: absolute;
    bottom: 0;
    left: 0;
}
ul li:nth-child(n+1)::before {
    top: 20px;
}
ul li:hover span::after {
    width: 100%;
}


text:
Q: Aurelia compose element: childContainer is not defined I want to leverage the <compose> custom element in my application using the view property exclusively. Here is my markup/code:
app.html
<template>
    <main>
        <compose view="views/start.html"></compose>
    </main>
</template>

app.js
import { Metadata } from 'aurelia-framework';

export class App {
    static metadata() { return Metadata.singleton(); }
    constructor() { }
}

/views/start.html
<template>
    <section>
        <button>New game</button>
    </section>
</template>

However, I get the following error:

Potentially unhandled rejection [1] ReferenceError: childContainer is not defined

A: This was a bug that has been resolved. See here:
https://github.com/aurelia/templating/issues/6