text:
Q: window.onload not called using ajax loadXMLDoc I use JavaScript and AJAX's XMLHttpRequest to load content from different *.html in order to advance from my initial top page index.html through other html page.
To add some dynamic behaviour (not yet added) I desire to automatically call a JavaScript function setSelected() via window.onload=setSelected(); (please see below how I do it precisely).
This works very well when I load from my top page index.html the content of my first html page introduction.html. To check if setSelected() is called I put an alert message and a log-print to the console.
In index.html:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="css/base.css" rel="stylesheet" type="text/css"/>

In introduction.html:

<link href="../css/base.css" rel="stylesheet" type="text/css" />

    <button value="Next" onclick="loadXMLDoc('instructions.html',
    'id_intro')" class="button_blue">Next</button>

In my_js_lib.js:
function loadXMLDoc(url, id)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {   // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {   // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById(id).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}

function setSelected()
{
    alert('I am setSelected');
    console.log('I am setSelected');
}

However, utilizing the same syntax at the 2nd loaded html content page instructions.html does not invoke again setSelected() via window.onload.
I do not receive the alert message nor the log print at the console.
In instructions.html:

<button value="Intro" onclick="loadXMLDoc('introduction.html', 'id_instru')" class="button_blue">Introduction</button>
<button value="Next"  onclick="loadXMLDoc('speakers_inauguration.html', 'id_instru')" class="button_blue">Next</button>

Moreover, when going back to introduction.html (by clicking on the first button with value="Intro"), again neither the alert message nor the log print at the console appear.
I imagine 2 possible sources of error:
a) The window.onload=setSelected(); is only set once at the html header when the initial top page index.html gets loaded, but it may not be added to the html  section when I load further content via AJAX, right?
b) The onload event handler of the HTML5 element  doesn't get triggered when I load it the way I do via AJAX.
Best,


text:
Q: How to get values from mixed type json? I have string in JSON format. For example:
{
   "blockedStatus":true,
   "cars":[
      "RAW:123",
      "TVU:123"
   ],
   "phones":[
      "370665566",
      "3706324231"
   ]
}

This is output from server. I need to get seperate values but I don't know how to do it.
Tried this:
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
}

JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
Log.e("IO-OUTPUT", builder.toString());  //prints json output
Log.e("finalResult (1)", finalResult.getString(1));

But I get ant exception:
W/System.err(31249): org.json.JSONException: Value {"blockedStatus":true,"cars":["RAW"],"phones":["65431"]} of type org.json.JSONObject cannot be converted to JSONArray

Is there another way to get values? Because calculating symbols and getting values from it will be too hard

A: change
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);

to
JSONObject jsonObject = new JSONObject(builder.toString());
JSONArray carsResult = jsonObject.getJSONArray("cars");
JSONArray phoneResult = jsonObject.getJSONArray("phones");

your string rapresent a JSONObject which contains two JSONArray's, cars and phones, and a pair key/value blockedStatus .
Also, if you read the logcat, it says:
type org.json.JSONObject cannot be converted to JSONArray

You can not convert a JSONObject to a JSONArray, which means the you have a JSONObject

A: Try this
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips  = response.getEntity().getContent();
responseString = response.toString();
responseString = intputStreamToStringConvertor(ips);
JSONObject object = new JSONObject(responseString);
Boolean status = object.getBoolean("blockedStatus");
JsonArray cars = object.getJSONArray("cars");
JsonArray phones = object.getJSONArray("phones");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring scheduler with multiple profiles I have number of scheduler jobs but one job should only run for specific profile .So below code i am trying but not working, i cant use shedlock quickly as per company restrictions.
@Component
@Profile("emp")
public class CreateEmpJob{

At the startup I am setting -Dspring.profiles.active=sit,emp but I am getting below error
FileNotFoundException application-sit,emp.properties.


text:
Q: Mysql picking row when it shoudn't? I was confused, when I figured out that setting value to 0 actually picks some row. O_o
0 is number, not a string...
It's something i didn't knew? Some specific feature of mysql or i'm doing something wrong?
Here is query:
SELECT * FROM contacts WHERE owner=0

The result is:
contact_id,owner,contact
10,d9659deb29f21dcf468783f1e7f52aa2b2ab6b48,7d1d00cd5cc06c27b3bcbefa8b4aeeb16bdec14e

Here is test dump:
-- --------------------------------------------------------
-- Host:                         127.0.0.1
-- Server version:               5.5.8 - Source distribution
-- Server OS:                    Linux
-- HeidiSQL version:             7.0.0.4053
-- Date/time:                    2012-08-02 11:05:48
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;

-- Dumping database structure for test
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `test`;

-- Dumping structure for table test.contacts
CREATE TABLE IF NOT EXISTS `contacts` (
  `contact_id` int(10) NOT NULL AUTO_INCREMENT,
  `owner` varchar(40) DEFAULT '',
  `contact` varchar(40) DEFAULT '',
  PRIMARY KEY (`contact_id`),
  KEY `owner` (`owner`),
  KEY `contact` (`contact`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- Dumping data for table test.contacts: ~2 rows (approximately)
/*!40000 ALTER TABLE `contacts` DISABLE KEYS */;
REPLACE INTO `contacts` (`contact_id`, `owner`, `contact`) VALUES
    (9, '7d1d00cd5cc06c27b3bcbefa8b4aeeb16bdec14e', 'd9659deb29f21dcf468783f1e7f52aa2b2ab6b48'),
    (10, 'd9659deb29f21dcf468783f1e7f52aa2b2ab6b48', '7d1d00cd5cc06c27b3bcbefa8b4aeeb16bdec14e');
/*!40000 ALTER TABLE `contacts` ENABLE KEYS */;
/*!40014 SET FOREIGN_KEY_CHECKS=1 */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

A: My bet: OWNER is a reserved keyword. Change your select to
SELECT * FROM contacts WHERE contacts.owner=0

A: Use quotes for comparing numbers with character data type column:
SELECT * FROM contacts WHERE owner = '0';

or typecast using CAST function as:
SELECT * FROM contacts WHERE owner = CAST(0 AS CHAR);

A: The owner '7d1d00cd5cc06c27b3bcbefa8b4aeeb16bdec14e' is started with a number '7...', MySQL converts this value to 7, we have 7 = 0 - FALSE.
The owner 'd9659deb29f21dcf468783f1e7f52aa2b2ab6b48' is started with a char  'd...', MySQL converts this value to 0, so 0 = 0 - TRUE.
This is how MySQL converts strings to numbers.


text:
Q: Magento2 Admin Panel crashes after making any configuration change or even flushing cache I am encountering issue with Magento stability.
Version 2.2.5. It is only a month old installation.
When I login to Admin Panel, I can navigate to any screen/page/configuration. However, if I make any configuration changes and save, or even click on 'flush cache management', the admin panel screen closes and then I can not access Admin Panel because I get 404 page not found error. Additionally my website loses all its images, and the web content formatting changes.
I keep a copy of Magento folder, that I use to overwrite the exisitng Magento folder to recover from the above crashes.

A: I did go down the Git local repository path but abandoned it for couple of reasons. I did not share the entire background of what caused the crashes. We had implemented magento as subfolder under the root. I wanted to remove magento from our URL path.  Reading through different forums, it seemed pretty common request, and how to resolve it seemed pretty straight forward. I changed the Web URL configuration in Magento 2. Since then the Admin Panel had been crashing, and I had been restoring it as described here. I knew there was correlation between what we changed in the URL and Admin Panel crashes, but could not pin point. Yesterday, I did regression tweaking and  back tracking everything that we changed in Web URL. The key was that I had changed not just the Web Base URL (secure/unsecure) but also Web Base Link URL (secure/unsecure), and had unchecked 'Use system Value'.
Also the core_config_data table entries reflected the URLs without the word magento, but the Admin Panel always had the word magento in its URL path, with the settings as stated above.
I checked the 'Use System Value', and saved the configuration. The Admin Panel came up like it used to. The system automatically deleted the entries for Web Base Link URL (secure/unsecure) in core_config_data table. Since then both the application and Admin Panel are stable. It resolved this issue, although the other posted issue remains: Redirect Magento2 from subfolder to root folder.
I belive that I can resolve it by simply editing the Web Base URL (secure/unsecure), and not touch the Base Link URL (secure/unsecure), or the 'use system value' checkbox.
What I am not clear is the significance of these fields Base Link URL and Use System Value .


text:
Q: Как в Linux Mint Cinnamon создать ярлык для Juputer Notebook? Два вопроса есть.

*

*Как в Linux Mint Cinnamon создать ярлык для Juputer Notebook? Желательно, чтобы обходиться вообще без терминала. В меню или на рабочем столе - хоть где-нибудь.

*Если уже ярлык создать никак нельзя или Juputer Notebook был запущен через терминал. То как хотя бы терминал закрыть, чтобы Juputer Notebook продолжал работать?
Сейчас пишу в терминале "jupyter notebook" - он открывается и работает пока терминал открыт. Если терминал закрываю - Jupyter Notebook перестает работать. Причем без разницы, как его вызвать "jupyter notebook" или "jupyter notebook &".
Если нажать Ctrl + Z, после этого ввести bg и закрыть терминал - Jupyter Notebook перестает работать.

A: Качем иконку:
sudo wget https://raw.githubusercontent.com/jupyter/jupyter/master/docs/source/_static/_images/favicon.png -O /usr/share/icons/jupyter.png

Создаём ярлык запуска:
cat > $HOME/Рабочий стол/jupyter.desktop << EOF
[Desktop Entry]
Version=1.0
Type=Application
Exec=jupyter-notebook
Icon=jupyter.png
StartupNotify=true
Terminal=false
Name=Jupyter Notebook
# Name[ru]=Юпитер Ноутбук
Comment=The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text.
Comment[ru]=Jupyter Notebook - это веб-приложение с открытым исходным кодом, позволяющее создавать документы, содержащие живой код, уравнения, визуализации и повествовательный текст, и обмениваться ими.

EOF

Даём права на запуск:
chmod +x "$HOME/Рабочий стол/jupyter.desktop"

A:
Как в Linux Mint Cinnamon создать ярлык для Juputer Notebook?

А в чём собственно проблема?
У меня Fedora, не Cinnamon, но идея (я думаю) одна:

*

*Создаю файл  /home/<Мой логин>/bin/Jupyter.sh

*В этот файл записываю строку jupyter notebook и сохраняю

*Делаю файл исполнимым chmod 0755 /home/<Мой логин>/bin/Jupyter.sh

*С помощью стандартного редактора меню (в Fedora это AppEditor) вставляю этот файл в меню

Ну, разумеется, каталог /home/<Мой логин>/bin/ надо создать заранее.


text:
Q: Add Dynamic Row Table Not Displaying The Right Row I'm trying to add dynamic row of table in my code. And when I click on the add button it displays the incorrect row. It suppose to display the checkbox, dropdown and input text row instead of the header row. Below are the javascript and html code together with the incorrect output. Do I have to change the javascript code? I've also tried looking for the answer inside the web but I found nothing. Please help me thanks.
Javascript code:

HTML Code :
<input type="button" value="Add More" onClick="addRow('dataTable')">
<input type="button" value="Delete" onClick="deleteRow('dataTable')">

    ✓
     Relationship
     Name
     Occupation
     Phone Number

    <input type="checkbox" name="chk">

      <select name="fam_relationship[]" id="fam_relationship">
        <option value="">Select one</option>
        <option value="Spouse">Spouse</option>
        <option value="Father">Father</option>
        <option value="Mother">Mother</option>
      </select>

    <input type="text" name="fam_name[]" id="fam_name">
    <input type="text" name="fam_occupation[]" id="fam_occupation">
    <input type="text" name="fam_phone[]" id="fam_phone">

Output:

A: Replace 0 into 1 at the following line:
newcell.innerHTML=table.rows[1].cells[i].innerHTML;

up here rows[1] instead rows[0]

function addRow(tableID) {

  var table = document.getElementById(tableID);
  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var colCount = table.rows[0].cells.length;
  for (var i = 0; i < colCount; i++) {
    var newcell = row.insertCell(i);
    newcell.innerHTML = table.rows[1].cells[i].innerHTML;
    switch (newcell.childNodes[0].type) {
      case "select-one":
        newcell.childNodes[0].selectedIndex = 0;
        break;
      case "checkbox":
        newcell.childNodes[0].checked = false;
        break;
      case "text":
        newcell.childNodes[0].value = "";
        break;
    }
  }
}

function deleteRow(tableID) {
  try {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    for (var i = 0; i < rowCount; i++) {
      var row = table.rows[i];
      var chkbox = row.cells[0].childNodes[0];
      if (null != chkbox && true === chkbox.checked) {
        if (rowCount <= 1) {
          alert("Cannot delete all the rows.");
          break;
        }

        table.deleteRow(i);
        rowCount--;
        i--;
      }
    }
  } catch (e) {
    alert(e);
  }
}
<input type="button" value="Add More" onClick="addRow('dataTable')">
<input type="button" value="Delete" onClick="deleteRow('dataTable')">

    ✓
    Relationship
    Name
    Occupation
    Phone Number

      <input type="checkbox" name="chk">

      <select name="fam_relationship[]" id="fam_relationship">
        <option value="">Select one</option>
        <option value="Spouse">Spouse</option>
        <option value="Father">Father</option>
        <option value="Mother">Mother</option>
      </select>

      <input type="text" name="fam_name[]" id="fam_name">

      <input type="text" name="fam_occupation[]" id="fam_occupation">

      <input type="text" name="fam_phone[]" id="fam_phone">


text:
Q: HTML/CSS line break when text overflows container On my website, the Lorem Ipsum text overflows the container. How can I automatically add a line break when the text reaches its container's borders.
I have created this JSFiddle to demonstrate my issue.
HTML:

                       Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.

CSS
body,html {
  background: #fff;
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

#wrapper{
  background: #ccc;
  height: 100%;
}

.flex {
  width: 100%;
  height: 340px;
  display: -webkit-box;
  display: flex;
}

.flexchild {
  -webkit-flex: 1 0 auto;
  flex: 1 0 auto;
  overflow: auto;
  display: block;
}

A: You need to use 0 instead of auto:
.flexchild {
  -webkit-flex: 1 0 0;
  flex: 1 0 0;
  overflow: auto;
  display: block;
}

See this JSFiddle, or run the code snippet below.

body,
html {
  background: #fff;
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}
#wrapper {
  background: #ccc;
  height: 100%;
}
.flex {
  width: 100%;
  height: 340px;
  display: -webkit-box;
  display: flex;
}
.flexchild {
  -webkit-flex: 1 0 0;
  flex: 1 0 0;
  overflow: auto;
  display: block;
}

Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.

Further Reading:
MDN Documentation for flex-basis, the third parameter of flex

A: I'm not familiar with the css flex bits but removing these 2 lines makes the text flow as you want.
-webkit-flex: 1 0 auto;
flex: 1 0 auto;


text:
Q: Fulltext search throws "The bucket doesn't exist" Reopening this discussion, as none of the found solutions worked.
I have about 60 categories and subcategories, going down 4 levels deep. Number of products is irrelevant, this bug reproduces with 10 products, as well as with 4000.
What I've tried

*

*Setting the Root Category to not-anchored, and then to anchored back again

*Just having one root category

*Setting all categories to is_anchor=false, then back to is_anchor=true in a bulk fashion straight in the database (UPDATE catalog_category_entity_int set value = 1 where attribute_id = 54;)

*Flushing caches and reindexing in the meantime

*Commenting out the exception, but then the search simply does not work (returns a bunch of non-related products)

Versions

*

*Magento 2.3.5-p1

*Theme "Infortis Ultimo Modif"

*PHP 7.3.24

*No ElasticSearch

References

*

*Magento 2 - Filter through non anchor categories throws "The bucket doesn't exist." exception

*Bucket does not exist in Magento 2 error

*Exception when filtering by category in Layered Navigation (Bucket does not exist

*when i click on category filter on Category List page Category filter getting error "Bucket does not exist"

*How to Set Anchor to YES in all Categories in Magento 2
Stacktrace
Exception #0 (Magento\Framework\Exception\StateException): The bucket doesn't exist.
<pre>#1 Manadev\ProductCollection\Resources\Collections\FullTextProductCollection->getFacetedData('category') called at [generated/code/Manadev/ProductCollection/Resources/Collections/FullTextProductCollection/Interceptor.php:63]
#2 Manadev\ProductCollection\Resources\Collections\FullTextProductCollection\Interceptor->getFacetedData('category') called at [vendor/magento/module-catalog-search/Model/Layer/Filter/Category.php:113]
#3 Magento\CatalogSearch\Model\Layer\Filter\Category->_getItemsData() called at [vendor/magento/module-catalog/Model/Layer/Filter/AbstractFilter.php:202]
#4 Magento\Catalog\Model\Layer\Filter\AbstractFilter->_initItems() called at [vendor/magento/module-catalog/Model/Layer/Filter/AbstractFilter.php:159]
#5 Magento\Catalog\Model\Layer\Filter\AbstractFilter->getItems() called at [vendor/magento/module-catalog/Model/Layer/Filter/AbstractFilter.php:148]
#6 Magento\Catalog\Model\Layer\Filter\AbstractFilter->getItemsCount() called at [vendor/magento/module-catalog/Model/Layer/Category/AvailabilityFlag.php:33]
#7 Magento\Catalog\Model\Layer\Category\AvailabilityFlag->canShowOptions(array(&Magento\CatalogSearch\Model\Layer\Filter\Category#00000000261d0415000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d041d000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0419000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d041a000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0466000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0410000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0413000000006d43a070#)) called at [vendor/magento/module-catalog/Model/Layer/Category/AvailabilityFlag.php:23]
#8 Magento\Catalog\Model\Layer\Category\AvailabilityFlag->isEnabled(&Magento\Catalog\Model\Layer\Search#00000000261d0597000000006d43a070#, array(&Magento\CatalogSearch\Model\Layer\Filter\Category#00000000261d0415000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d041d000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0419000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d041a000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0466000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0410000000006d43a070#, &Magento\CatalogSearch\Model\Layer\Filter\Attribute#00000000261d0413000000006d43a070#)) called at [vendor/magento/module-layered-navigation/Block/Navigation.php:126]
#9 Magento\LayeredNavigation\Block\Navigation->canShowBlock() called at [app/design/frontend/Infortis/base/Magento_LayeredNavigation/templates/layer/view.phtml:18]

A: TL;DR
Uninstall Manadev's Layered Navigation (Filters) with Multiple Select for Magento 2 extensions.
Long version
For debug purposes, I removed the thrown exception just to see what happens. After that, search by any string showed all products each time. So fulltext search wasn't working at all.
My final and successful thought was to check for buggy extensions, and encountered Manadev. Disabling it wasn't enough, it had to go forever. I'm not even in the mood to search for a working version of it.
Steps as described in the link above:

*

*Delete folder app/code/Manadev

*Delete the file bin/mana

*Drop tables from DB (make sure "Enable foreign key check" is disabled, if you're running the script from phpmyadmin)

SET @@foreign_key_checks = 0;
DROP TABLE IF EXISTS mana_config_history;
DROP TABLE IF EXISTS mana_extension;
DROP TABLE IF EXISTS mana_filter;
DROP TABLE IF EXISTS mana_filter_edit;
DROP TABLE IF EXISTS mana_url_key;
DROP TABLE IF EXISTS mana_url_key_conflict_resolution;
SET @@foreign_key_checks = 1;
DELETE FROM setup_module WHERE module LIKE 'Manadev_%';

*Execute php bin/magento setup:upgrade
Your fulltext search will now work properly.

A: For me the problem occurred when trying to load the layered navigation, and the solution was really simple: Make sure that the "is_visible_on_front" option is set to "Yes" for all products that you want to use in the layered navigation.


text:
Q: Determinate the joint probability marginal distribution I have a random vector $(X,Y,Z,W)$ with the following Probability Mass Function:

Which steps should I follow to determinate the joint probability marginal distribution of $(X,Y)$ in a similar table with its own marginals?

A: From the table, you can determine the joint marginal distribution of $(X,Y)$ as follows:-
$$p_{(X,Y)}(x,y)=\sum_{z}\sum_{w}p_{(X,Y,Z,W)}(x,y,z,w)$$
Practically, this means that for each of the $4$ possible values of $(x,y)$ i.e. $(0,0),(0,1),(1,0),(1,1)$ you need to add up the relevant entries of $p_{(X,Y,Z,W)}(x,y,z,w)$.


text:
Q: Change FAB background color when disabled I'm trying to figure out how I can change the background color of the floating action button when it is disabled for a duration of 2 seconds after being pressed. I would also like it to return to its original color when the 2 second duration is over.
This is the code for the 2 second delay when pressed. This code is in a fragment within the MainActivity.
 appBar.setExpanded(true, true);
 fab.setVisibility(View.VISIBLE);
 fab.setImageResource(R.drawable.ic_phone_white_18dp);

 fab.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
     fab.setClickable(false);
     Timer buttonTimer = new Timer();
     buttonTimer.schedule(new TimerTask() {
       @Override
       public void run() {
         runOnUiThread(new Runnable() {
           @Override
           public void run() {
             fab.setClickable(true);
           }
         });
       }
     }, 2000);

I've tried playing around with the StateListDrawable methods in the documentation but have not come across anything that works.
This is the XML for the color themes of the FAB
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/themeColorPressed" android:state_pressed="true"/>
    <item android:color="@color/themeColorPressed" android:state_checked="true"/>
    <item android:color="@color/themeColorPressed" android:state_selected="true"/>
    <item android:color="@color/themeColorPressed" android:state_enabled="false"/>
    <item android:color="@color/themeColor" android:state_enabled="true"/>
</selector>

A: Just call fab.setBackgroundColor(Color.GRAY); (or whatever color) when you disable it. Also you can use fab.setBackgroundColor(getResources().getColor(R.color.colorAccent0)); to use a resource color.

A: Just use as app:backgroundTint a selector as:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="...." android:state_enabled="true"/>
  <item android:alpha="..." android:color="...."/>
</selector>

And then just use in your code:
fab.isEnabled = true
fab.isEnabled = false

A: I just found something that works well...
Firstly I moved the setEnabled() method in the selector XML of the button theme atleast above the color declaration like so.
<?xml version="1.0" encoding="utf-8"?>

<item android:color="@color/themeColorPressed" android:state_pressed="true"/>
<item android:color="@color/themeColorPressed" android:state_checked="true"/>
<item android:color="@color/themeColorPressed" android:state_selected="true"/>
<item android:color="@color/grey" android:state_enabled="false"/>
<item android:color="@color/themeColor"/>

Setting it initially to false for that respected color it's assigned to.
Then in the Java code, just call the setEnabled method on the button you're targerting (fab in this case) and use a boolean value to dictate whether its activated or deactivated in the onClick method:
                                fab.setClickable(false);
                                fab.setEnabled(false);
                                Timer buttonTimer = new Timer();
                                buttonTimer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                fab.setClickable(true);
                                                fab.setEnabled(true);
                                            }
                                        });
                                    }
                                }, 2000);

A: Looking at the implementation of the FloatingActionButton, the fab.setBackgroundColor(int color) method is not supported.
I managed to change the color of the FAB with the following method (in Kotlin):
private fun toggleFabEnabled(enabled: Boolean){
    fab.isEnabled = enabled
    if (enabled){
        fab.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.colorAccent, null))
    } else {
        fab.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.disabled, null))
    }
}

For API < 23 get the color with the following method resources.getColor(R.color.disabled)
How I handle the different API methods is I create an extension function in Kotlin that handles all APIs.


text:
Q: Irda + vb.net express Not sure that this is a valid programming question ... but is it possible to program infa red using vb.net express (iRDA) Got a programming project in my mind, but none of the coding examples work, IrDAClient never gets recognised
Cheers

A: It's a valid question but it needs to be a bit more specific.   VB.Net can certainly be used to program against IRDA.  There is nothing preventing you from using IrDAClient with VB.Net.
We do need to know though what problems you are having?  Can you post the samples that are giving you trouble or tell us what errors you are seeing?
EDIT Update to comments
There is nothing that will prevent you from writing a program targeting IRDA from VB Express.  What you appear to be missing is a reference to the DLL that contains the IrDA libraries.  You'll neeed to add a reference to System.Net.Irda.dll.  It will be in the following directory (assuming your programming to Windows CE)

C:\Program Files\Microsoft.NET\SDK\CompactFramework\v2.0\WindowsCE

EDIT2
I may be wrong about the ability of VB express to program against a device project.  I don't have any 2008 express builds on my machine to verify right now.

A: The IrDAClient class is part of the .Net Compact framework. I'm not sure if it's possible to use it on a desktop machine.
You can at least add the reference by searching for the file System.Net.IrDA.dll. On my system it was under: Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE
If it's not present you may be able to download it here: http://msdn.microsoft.com/en-us/netframework/aa497280.aspx


text:
Q: Google Drive API - Error: disabled_client When I follow the Quickstart Tutorial: https://developers.google.com/drive/web/quickstart/quickstart-python
Entering the URL for authentication shows the following error on the website:

Error: disabled_client
The OAuth client was disabled. Request Details
cookie_policy_enforce=false
scope=https://www.googleapis.com/auth/drive
response_type=code
redirect_uri=urn:ietf:wg:oauth:2.0:oob
access_type=offline
client_id=1086226639551-hgv3m4atq7jmsdgie1d5t92qbo8k9b1g.apps.googleusercontent.com

I created id and secret for an "Installed Application" in the developer console:
https://console.developers.google.com/project
And selected "Other" as application type.
Any idea what causes the problem might help.
[EDIT] I just used PyDrive for authentication without problems:
https://github.com/googledrive/PyDrive
So I will settle for PyDrive.


text:
Q: Good way to maintain Qt labels and text on UI What is the best way/common practice for maintaining all string resources found on a UI in Qt, especially the textual input/text in combo boxes etc. (since these are the once that are frequently used in the code itself)?
I know that Android has this string resources thing such that resources only have to be modified at one position.
Does Qt have something like that too or do I have to initialize string resources in code instead of in the UI's XML itself...

A: AFAIK, there is no built-in mechanism for string resources in Qt. If you want to maintain strings at build time you can define them in one .h/.cpp file as global variables and reuse them in your code.
Otherwise you can use Qt's translator files (binary) and load them along with your application. If you need to change a string, you simply will need to edit the translation file (xml) and "recompile" it with lrelease utility without building the application again.

A: There is a mechanism to dynamically translate texts in application, but it works a bit different than Android string resources, but achieves the same goals.
Qt uses i18n system modelled after standard, well known unix gettext. It works in a very similar way to iOS NSLocalizedString, if that rings a bell.
http://doc.qt.io/qt-5/qobject.html#tr
This is worth reading too:

*

*http://en.wikipedia.org/wiki/Gettext

*http://doc.qt.io/qt-5/internationalization.html
Android approach is a bit unique and you should not expect it to be a "standard everywhere". It works, it's ok, but it's not a standard way of doing things on desktop.


text:
Q: Why is this float conversion made I have this dataframe
Python 3.9.0 (v3.9.0:9cf6752276, Oct  5 2020, 11:29:23)
[Clang 6.0 (clang-600.0.57)] on darwin
>>> import pandas as pd
>>> import datetime as datetime
>>> pd.__version__
'1.3.5'
>>> dates = [datetime.datetime(2012, 2, 3) , datetime.datetime(2012, 2, 4)]
>>> x = pd.DataFrame({'Time': dates, 'Selected': [0, 0], 'Nr': [123.4, 25.2]})
>>> x.set_index('Time', inplace=True)
>>> x
            Selected     Nr
Time
2012-02-03         0  123.4
2012-02-04         0   25.2

An integer value from an integer column is converted to a float in the example but I do not see the reason for this conversion. In both cases I assume I pick the value from the 'Selected' column from the first row. What is going on?
>>> x['Selected'].iloc[0]
0
>>> x.iloc[0]['Selected']
0.0
>>> x['Selected'].dtype
dtype('int64')

A: x.iloc[0] selects a single "row". A new series object is actually created. When it decides on the dtype of that row, a pd.Series, it uses a floating point type, since that would not lose information in the "Nr" column.
On the other hand, x['Selected'].iloc[0] first selects a column, which will always preserve the dtype.
pandas is fundamentally "column oriented". You can think of a dataframe as a dictionary of columns (it isn't, although I believe it used to essentially have that under the hood, but now it uses a more complex "block manager" approach, but these are internal implementation details)


text:
Q: Fragment Back button pressed which method is called or how to call user defined function I have one ActionbarSherlock Activity and 3 Actionbar Tab.The second tab having two Fragments(A and B). The Fragment "A" having the list calendar and Fragment "B" having the Task adding functionalities.When i click the Fragment "A" list calendar items it will be go to the Fragment "B". Then I add some task in fragment "B" and then press back button to redirect Fragment "A" fine.My problem is when i back to the Fragment "A" from Fragment "B" which method is called and also i update the task details when back to the Fragment "A".Thanks...
ActionbarActivityclass:

When i select the second Actionbar Tab that having two fragments ListCalendarFragment and TaskFragment.First I add both fragments.Then I hide the TaskFragment and show only ListCalendarFragmnet.

        TaskFragment()fragmentTask = new TaskFragment();
        ListCalendarFragment fragmentListCalendar = new ListCalendarFragment();
        fragmentrans = getSupportFragmentManager().beginTransaction();
        fragmentrans.add(R.id.content_frame, fragmentListCalendar);
        fragmentrans.add(R.id.content_frame, fragmentTask);
        fragmentrans.hide(fragmentTask);
        fragmentrans.commit();

When i click the list calendar item it will call one listener that can be used to show Task Fragment as well as hide the List Calendar Fragment.

SherlockFragmentActivity activity = getSherlockActivity();
                if (activity instanceof ListItemClickListener) {

                    ((ListItemClickListener)activity).onListClick();
                }

ListItemClickListener: Interface

public interface ListItemClickListener {
public void onListClick();
}

ActionbarActivityclass implements ListItemClickListener.
This functionality show the Task calendar and hide the List Calendar.
@Override
public void onListClick() {

    fragmanager = getSupportFragmentManager();
    fragmentrans = fragmanager.beginTransaction();
    fragmentrans.hide(fragmentListCalendar);
    fragmentrans.show(fragmentTask);
    fragmentrans.addToBackStack(null);
    fragmentrans.commit();

}

My problem is when i back to the List Calendar by clicking the back button at that time which lifecycle method is called or how to call the user defined method in the List Calendar Fragment.Because i need to refresh the List Calendar Adapter in ListCalendar Fragment.Thanks

A: I hope I'm understanding your question correctly. Here's how I solved a similar problem:
Make an interface for Fragment B like this:
public interface FragmentBListener {
    public void onBackButtonPressed();
}

Then, instantiate it in Fragment B (up above onCreateView where you instantiate widgets, etc):
FragmentBListener mCallback;

Then, in your Fragment B, whenever you want to go back, or cancel or whatever, you call:
mCallback.onBackButtonPressed();

The interface is, of course, implemented in your main activity (or whichever activity you choose), so there should be a method there like this:
@Override
public void onBackButtonPressed() {
    Log.i(TAG, "onBackButtonPressed()");

    // Do something, e.g. reload Fragment A
}

Hope this helps.


text:
Q: Why does Nokogiri to_html URL escape differently then URI.escape? Example:
URI.escape 'http://www.pmlive.com/pharma_news/mylan_buys_abbotts_non-us_generics_in_$5.3bn_deal_585883'
=> "http://www.pmlive.com/pharma_news/mylan_buys_abbotts_non-us_generics_in_$5.3bn_deal_585883"

Nokogiri::HTML.fragment('test').to_html
=> "test"

As you can see Nokogiri encodes '$' to '%24' where URI.escape does not.

A: Since to_xhtml does what you need, why not use it?
require 'nokogiri'

Nokogiri::HTML.fragment('test').to_html
# => "test"

Nokogiri::HTML.fragment('test').to_xhtml
# => "test"


text:
Q: How do I maintain the 'correct' scope in javascript even listeners? I'm writing a geometry engine in Typescript, and I'm trying to implement drag&drop. I have a point object that inherets from a geometry object, and it has control of a circle element inside an svg element. I have a mousedown even listener attached to the circle element that calls a function belonging to the point object, a little like this:
class point extends geometry {
    htmlNode:any;
    constructor() {
        this.htmlNode = makeTheThing();
        addItToTheDom();
        this.htmlNode.addEventListener("mmousedown",this.onClick);
        onClick();
    }

    onClick() {
        console.log(this);
    }
}

When the page loads it outputs the point object to the console, but when I click it outputs the html element, rather than the javascript object. Previously I got around this like this:
class point extends geometry {
    htmlNode:any;
    constructor() {
        this.htmlNode = makeTheThing();
        addItToTheDom();
        var blah = this;
        var f = function() {
            console.log(blah);
        }
        this.htmlNode.addEventListener("mmousedown",f);
        f();
    }

    onClick() {
        console.log(this);
    }
}

That will give the javascript object when it loads and when I click, but it's ugly and I'd like to do it more cleanly.
UPDATE: For anyone who cares, I did end up just rewriting this, much prettier now.

A: In pure JavaScript (ES5), you can use bind to create a new function that will have function context (this) forever bound:
this.htmlNode.addEventListener("mmousedown",this.onClick.bind(this));

In TypeScript (and shortly in ES6) we have arrow functions:
this.htmlNode.addEventListener("mmousedown", event => this.onClick(event));

Arrow functions maintain a lexical this, that is, the take this from surrounding context.

A: in pure js i would do it this way (of course without 'class'^^):
class point extends geometry {
var parent = this;
var htmlNode = null;
this.constructor = function() {
    parent.htmlNode = makeTheThing();
    parent.htmlNode.addEventListener(yourStuff);
}

this.onClick = function() {
    console.log(parent);
}

}
maybe there is a better way in ts, but this should work


text:
Q: Python tutorial code from RabbitMQ failing to run Edit: I had the wrong version of the pika package installed on my device. It works fine after I updated from pip.
I just started learning the usage of RabbitMQ (using Python) by following their tutorial. The send.py code works works fine but when I try to run receive.py, I see this error:
Traceback (most recent call last):
  File "receive.py", line 15, in <module>
    no_ack=True)
TypeError: basic_consume() got multiple values for keyword argument 'queue'

Here's the code inside receive.py:
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

Any idea what I am doing wrong?

A: I can't reproduce your error, but I want to be as concise as possible, when trying to.
At first I set up a rabbitmq server as docker container on my computer, not to pollute my system:
$ docker run -d --hostname localhost --name some-rabbit rabbitmq:3

Then I use inspect to find about the IPAddress my rabbitmq container is running actually:
$ docker inspect some-rabbit --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'
172.17.0.2

Next I use pipenv to create a virtual environment in python3 that contains at least pika and dependencies to follow the example:
$ mkdir example && cd example && pipenv --three install pika
Creating a virtualenv for this project…
Using /usr/bin/python3 (3.6.5) to create virtualenv…

Note, that you can also use python 2.7 here if you say pipenv --two when installing pika.
Then jump into the environment using pipenv shell:
~/example$ pipenv shell
Spawning environment shell (/bin/bash). Use 'exit' to leave.

There I create the two files send.py and receive.py as proposed by the example documentation of pika, but I'll replace the localhost by the docker containers IP from above:
$ cat send.py
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='172.17.0.2'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

And receive.py:
$ cat receive.py
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='172.17.0.2'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

Having receive.py running in one terminal and running send.py in another works as expected:
 $ python receive.py
 [*] Waiting for messages. To exit press CTRL+C

 $ python send.py
 [x] Sent 'Hello World!'

 $ python receive.py
 [*] Waiting for messages. To exit press CTRL+C
 [x] Received b'Hello World!

HTH,
f3rdy

A: You probably don't need it anymore, but I had exactly the same problem as You and this is what I figured out.
For me it turned out that RabbitMQ documentation must've been using a different version of pika. I found out that in pika 1.0.0 basic_consume function has different order of arguments. This is how it looks on my machine:
    def basic_consume(self,
                  queue,
                  on_message_callback,
                  auto_ack=False,
                  exclusive=False,
                  consumer_tag=None,
                  arguments=None):

Once I changed the order of arguments passed, or added keyword 'on_message_callback=callback' it all worked. I hope it helps!

A: just change
channel.basic_consume(callback, queue='hello', no_ack=True)

to
channel.basic_consume('hello', callback, auto_ack=True)

A: I got the same issue on Ubuntu 18.04 with the in-stock python-pika package version 0.11.0-1, after I remove the in-stock version and installed a newer version pika (1.0.1) by pip, this issue disappeared.

A: just change
channel.basic_consume(callback, queue='hello', no_ack=True)

to
channel.basic_consume(queue='hello', callback, no_ack=True)

because i found the code in lib is.

A: This code might help:
channel.basic_consume(on_message_callback=callback, queue='hello')

or
channel.basic_consume(on_message_callback=callback, queue='hello', auto_ack=True)


text:
Q: SSL Certificate on Apache Not Working on iPhone and iPad I am having a strange problem.  I have installed a new certificate from RapidSSL onto Apache on an Ubuntu server for the website http://www.radflek.com/shop/.
It seems to work absolutely fine on all PC browsers I try, but when I try on iPhone or iPad I receive the error: "Safari cannot open the page because it could not establish a secure connection to the server.".
Can anyone advise as to what might be wrong?!
UPDATE: I was unable to solve this issue, but when iOS 5.1 was released this issue resolved itself entirely so it appears to be related to iOS5.0 only.

A: They gave you an incomplete certificate chain; mobile browsers tend to be a little more sensitive to chain issues than others.  The intermediate issuer certificate with a thumbprint of c039a3269ee4b8e82d00c53fa797b5a19e836f47 is being presented correctly, but the "root" certificate that your server is presenting isn't a root certificate at all; it's an intermediate.
The real root cert (de28f4a4ffe5b92fa3c503d1a349a7f9962a8212, which most browsers will figure out), and the presented root-that-isn't (7359755c6df9a0abc3060bce369564c8ec4542a3) share the same cryptographic key, so their signing relationship with the issuing CA works either way - but the presented root's not a root at all, its trust chain relies on a root certificate (d23209ad23d314232174e40d7f9d62139786633a) that isn't being sent.

Either they gave you a certificate bundle to point to with an SSLCertificateChainFile directive, or rolled the roots into the public key file that's pointed at with SSLCertificateFile - figure out which, then you'll be modifying that file.
Copy the file as a backup before modifying it.  Then, find this section:
-----BEGIN CERTIFICATE-----
MIIDfTCCAuagAwIBAgIDErvmMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT
MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0
aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDIwNTIxMDQwMDAwWhcNMTgwODIxMDQwMDAw
WjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UE
AxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9m
OSm9BXiLnTjoBbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIu
T8rxh0PBFpVXLVDviS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6c
JmTM386DGXHKTubU1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmR
Cw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5asz
PeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo4HwMIHtMB8GA1UdIwQYMBaAFEjm
aPkr0rKV10fYIyAQTzOYkJ/UMB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrM
TjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjA6BgNVHR8EMzAxMC+g
LaArhilodHRwOi8vY3JsLmdlb3RydXN0LmNvbS9jcmxzL3NlY3VyZWNhLmNybDBO
BgNVHSAERzBFMEMGBFUdIAAwOzA5BggrBgEFBQcCARYtaHR0cHM6Ly93d3cuZ2Vv
dHJ1c3QuY29tL3Jlc291cmNlcy9yZXBvc2l0b3J5MA0GCSqGSIb3DQEBBQUAA4GB
AHbhEm5OSxYShjAGsoEIz/AIx8dxfmbuwu3UOx//8PDITtZDOLC5MH0Y0FWDomrL
NhGc6Ehmo21/uBPUR/6LWlxz/K7ZGzIZOKuXNBSqltLroxwUCEm2u+WR74M26x1W
b8ravHNjkOR/ez4iyz0H7V84dJzjA1BOoa+Y7mHyhD8S
-----END CERTIFICATE-----

And replace it with this, to present the version of the root that's actually a root certificate:
-----BEGIN CERTIFICATE-----
MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG
EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg
R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9
9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq
fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv
iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU
1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+
bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW
MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA
ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l
uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn
Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS
tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF
PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un
hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV
5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw==
-----END CERTIFICATE-----

Or, as option B if that causes issues for some reason, you could instead leave the current "root" in place then add its root certificate to the chain, at the bottom of the file:
-----BEGIN CERTIFICATE-----
MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV
UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy
dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1
MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx
dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B
AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f
BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A
cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC
AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ
MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm
aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw
ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj
IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF
MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA
A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y
7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh
1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4
-----END CERTIFICATE-----

Restart Apache fully after making changes - a graceful restart or "reload" doesn't pick up the changed certificate files correctly.

A: Here's a StackOverflow posting related to RapidSSL intermediate certs on mobile devices:
https://stackoverflow.com/questions/7203857/rapidssl-certificate-not-trusted-on-android-tablet

A: A certificate can contain a special Authority Information Access extension (RFC-3280) with URL to issuer's certificate. Most browsers can use the AIA extension to download missing intermediate certificate to complete the certificate chain. But some clients (mobile browsers, OpenSSL) don't support this extension, so they report such certificate as untrusted.
You can solve the incomplete certificate chain issue manually by concatenating all certificates from the certificate to the trusted root certificate (exclusive, in this order), to prevent such issues. Note, the trusted root certificate should not be there, as it is already included in the system's root certificate store.
You should be able to fetch intermediate certificates from the issuer and concat them together by yourself. I have written a script to automate the procedure, it loops over the AIA extension to produce output of correctly chained certificates. https://github.com/zakjan/cert-chain-resolver


text:
Q: Problem with file stream/fstream in Xcode C++ Here is a simple program to output to a text file:
#include <iostream>
#include <fstream>

using namespace std;

int main() {
double myNumber = 42.5;
fstream outfile("test.txt", fstream::out);
outfile << "The answer is almost " << myNumber << endl;
outfile.close();
}

All that ends up being wrote to my text file is, "The answer is almost " and the data is not displayed at all. What am I doing wrong? or could it be a problem with Xcode since I am using that as an IDE.

A: There is no problem with your code. It could be a problem with Xcode.

A: I'm not sure what the problem is. Is it that it's never executed or that it's writing to the wrong path. To shed light on this try include unistd.h and insert this snippet.
char* s = getcwd(NULL, 256);
printf("im running and pwd is: %s\n", s);

Inside xcode hit CMD-SHIFT-R to open the console and see if it prints anything.


text:
Q: BitmapFactory decodeByteArray SkImageDecoder Factory returned null - image from JSON I have a program with can login into the server throught PHP form (he fill the form with username and password) and then the PHP script generate a very simple JSON file:

{
 "success":1,
 "message":"PHP Login successful!",
 "userid":"1",
 "data":
 [
  {
   "id_data":"1",
   "data_name":"Mona Lisa",
   "data_date":"29.9. 2015",
   "pic_user_id_user":"1",
   "data_picture":‰PNG

IHDR         ľ‹   sRGB ®Îé   gAMA  ±üa    pHYs  Ä  Ä•+   TIDAT(S]NÙ  b"FqtGqòªgýB °"¶"¨Ž5—ŽxB¼ædzA»ar
SHÞMÞÐæ5š7Ž†ÿÈ
Œ*Qæ92V¸pRϪü(Ü
…üZI÷Í    IEND®B`'"
  },
 ]
}

thats all working, set TextView with name and date of image too. But when I want to draw image, logCat write error SkImageDecoder::Factory returned null. I dont want download image from any url, I just want draw image from JSON.
There is public method, when the login has been sucessfull and then set the public variables where are JSON data. Then in the next Fragment (list_of_files.java) use public variables (main.java) and write data on screen.
// main.java
public static void login_success(JSONObject login_json) throws JSONException, UnsupportedEncodingException {
    status.setText("Login successful.");
    JSONArray data = login_json.getJSONArray("data");   // get array data witch contains all information about image
    int count_of_images = data.length();                // get count, how many images user have
    img_name = new String[count_of_images];             // then, create an array, with contains name of each image
    img_date = new String[count_of_images];             // and the date of image

    // {...} - JSONObject (work with normal methods getting value of coll, f.e. getString( "name of coll" )
    // [...] - JSONArray (work with index - numbers)
    for (int i = 0; i < count_of_images; i++){
        JSONObject under_data = data.getJSONObject(i);
        img_name[i] = under_data.getString("data_name");
        img_date[i] = under_data.getString("data_date");
        if ( i == 0 )
            img_img = under_data.getString("data_picture").getBytes();
    }
    Log.d("== IMAGE SIZE ==", String.valueOf(img_img.length) + " B");
}

// list_of_files.java
    // Update listView list_of_files
    if (list_of_files_str != null) {
        adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, list_of_files_str);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            private FragmentManager supportFragmentManager;

            public FragmentManager getSupportFragmentManager() {
                return supportFragmentManager;
            }

            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // set image name and date in textView
                TextView image_name = (TextView)getView().findViewById(R.id.image_name);
                image_name.setText(list_of_files_str[position] + " // " + date_str[position]);

                // draw image with char array from main class Red Orchestra
                ImageView img = (ImageView)getView().findViewById(R.id.imageView);

                Bitmap image_to_draw;
                byte[] data;
                String str = "";
                try {
                    data = str.getBytes("UTF-8");
                    String base64 = Base64.encodeToString(data, Base64.DEFAULT);
                    byte[] imageAsBytes = Base64.decode(base64.getBytes(), Base64.URL_SAFE);
                    image_to_draw = BitmapFactory.decodeByteArray(data, 0, data.length);
                    img.setImageBitmap( image_to_draw );
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        });

    } else { // if the user is not login, write him message
        String[] must_login = new String[] {"You must be sign in."};
        adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, must_login);
        list.setAdapter(adapter);
    }

    // Inflate the layout for this fragment
    return rootView;
}

I dont really know, how to save this problem. I searched throught different forums and websites, but nothing work.
PHP file:
//load and connect to MySQL database stuff

require("config.inc.php");
$login_ok = false;
if (!empty($_POST)) {
    $query_1 = "SELECT * FROM pic_user WHERE user_name = :username";
$query_params = array(
    ':username' => $_POST['username']
);

try {
    $stmt   = $db->prepare($query_1);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "PHP Database Error1. Please Try Again!";
    die(json_encode($response));
}

$validated_info = false;

$row = $stmt->fetch();
if ($row) {
    if ($_POST['password'] === $row['user_password']) {
        $login_ok = true;
    }
}

if ($login_ok) {
    $query_2   = "SELECT * FROM pic_data WHERE pic_user_id_user = :userid";

    $user_id   = $row['id_user'];
    $user_name = $row['user_name'];

    $query_params_2 = array( ':userid' => $user_id );
    $stmt         = $db->prepare($query_2);
    $result       = $stmt->execute($query_params_2);
    $row          = $stmt->fetchAll();

    $response["success"] = 1;
    $response["message"] = "PHP Login successful!";
    $response["userid"]  = $user_id;
    $response['data']    = $row;

    die(json_encode($response));

} else {
    $response["success"] = 0;
    $response["message"] = "PHP Invalid Credentials!";
    die(json_encode($response));
}

A: I´ve got it! There´s just wrong base64 convert. When I delete convertion in code and convert image to base64 (http://www.motobit.com/util/base64-decoder-encoder.asp) and add base64 string into database and than download it throught JSON, it works.


text:
Q: Why don't three R, G and B circles blend correctly? I am trying to represent the RGB color model using python + pygame.
I wanted to get the following:

So then, I wrote the following code:
import pygame, sys
from pygame.locals import *

ALPHA = 100

TRANSPARENT = (255,0,255)
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0,100)
GREEN = (0,255,0,100)
BLUE = (0,0,255,100)

pygame.init()

size=(800,500)
screen= pygame.display.set_mode(size)

surf1 = pygame.Surface(size)
surf1.fill(TRANSPARENT)
surf1.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf1, BLUE, (430, 280), 60 )

surf2 = pygame.Surface(size)
surf2.fill(TRANSPARENT)
surf2.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf2, GREEN, (370, 280), 60 )

surf3 = pygame.Surface(size)
surf3.fill(TRANSPARENT)
surf3.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf3, RED, (400, 220), 60 )

surf1.set_alpha(ALPHA)
surf2.set_alpha(ALPHA)
surf3.set_alpha(ALPHA)

while True :
    screen.fill(WHITE)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.blit(surf1, (0,0))
    screen.blit(surf2, (0,0))
    screen.blit(surf3, (0,0))
    pygame.display.flip()

But instead of getting the RGB color model, I got this, with colors incorrectly blended:
Does anybody know what it could be? Thanks!

A: This should work:
import pygame, sys
from pygame.locals import *

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0, 100)
GREEN = (0, 255, 0, 100)
BLUE = (0, 0, 255, 100)

pygame.init()

size = (800, 500)
screen = pygame.display.set_mode(size)

surf1 = pygame.Surface(size)
surf1.fill(BLACK)
surf1.set_colorkey(BLACK)
pygame.draw.circle(surf1, BLUE, (430, 280), 60)

surf2 = pygame.Surface(size)
surf2.fill(BLACK)

surf2.set_colorkey(BLACK)
pygame.draw.circle(surf2, GREEN, (370, 280), 60)

surf3 = pygame.Surface(size)
surf3.fill(BLACK)

surf3.set_colorkey(BLACK)
pygame.draw.circle(surf3, RED, (400, 220), 60)

surf4 = pygame.Surface(size)
surf4.set_colorkey(BLACK)
surf4.blit(surf1, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
surf4.blit(surf2, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
surf4.blit(surf3, (0, 0), special_flags=pygame.BLEND_RGB_ADD)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(WHITE)
    screen.blit(surf4, (0, 0))

    pygame.display.flip()

You want to add the colors at the intersections of the circles, hence use the BLEND_RGB_ADD flag.
I created a fourth surface since you wanted a white background.


text:
Q: Qt C++ include winsock2.h I am currently trying to get WebSocket++ to work in my Qt project. The problem is that WebSocket++ can not find "winsock2.h".
I added these lines to my .pro file:
INCLUDEPATH += "C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86"
win32:LIBS += -lWS2_32

I tried different variations of the lib name, which I found in some previous questions here on stackoverflow, without any success. What am I doing wrong? All help is very much appreciated. Thanks.

A: Make sure you install the appropriate Windows SDK (8.1 as it implies in path).
winsock2.h, no such file or directory


text:
Q: Entroware laptop with Ubuntu 17.04 stopped outputting to HDMI HDMI used to work on my laptop, but now neither the Sound nor the Display programs can see that my HDMI cable is connected. My sound card is HDA Intel PCH according to alsamixer, and my GPU is an nVidia GTX. The cable still works on my PS3. This has happened once before.

Just tried out different GPU drivers. I think I started with 378.13 from nVidia (which it falsely claims is open source, wtf!) and then tried the later version 381.22, and then tried the open source Nouveau driver. Rebooted each time and it didn't fix it.
Since the sound part of HDMI isn't working either, I'm thinking that it's not a problem with the GPU.

Tried installing a different nVidia driver (375.82), and when I rebooted, it was outputting to my TV until I logged in. Now I can't get it to output to my TV.

A: The main thing I did was install a different driver (the nVidia 375.82 one), and then I toggled some things in the Display Settings program, and it worked.
General advice is try different drivers.


text:
Q: How to use Material UI theme (pre-defined colours etc), with the react-select component? I am trying to pull out all of the common styles used throughout an application and storing them in a stylesheet and material ui theme file - this way I can update the base styling of all input fields for example in one place.
I am using the react-select element in a component as a dropdown for a country code picker, although I cannot seem to use material ui's useStyle/makeStyles feature to call the theme's styling within the custom react-select's styling block.
Does anyone have any idea of how to use mui theme elements within the react-selects custom styling block?


text:
Q: Linked Lists and Trees Final Question/Post on this! I'm pretty close now I think!
Basically, A Tree, where each node contains a List of numbers, where the tree is sorted by the name (data contained within the tree node). Essentially, at the moment, I have so my name is added to my tree, and that tree's list, is given the number, but I am trying to work towards the ability of each name having multiple numbers, thus the linked list expands if two of the same names are entered with different numbers. I have the compare code in place to check for the same name, but at that point, I am unsure how to modify my pointers, so that I add another element to my list, and add the new number there.
Cheers, any help/tips/clues etc are much appreciated
Below is my current code:
EDIT: The question is really, how I now, take the code I have, and allow the list of each TreeNode to contain multiple numbers, when the same name of a previous treenode is entered, thus building a list of numbers for that name.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

typedef struct ListNode {
    char            *number;
    struct ListNode *next;
}ListNode;

typedef struct TreeNode {
    char            *name;
    ListNode        *numbers;
    struct TreeNode *left;
    struct TreeNode *right;
}TreeNode;

TreeNode* AddNode(TreeNode *, char *, char *);
TreeNode* SearchTree(TreeNode *root, char *search);
int N_Print(TreeNode *root);

int main(void) {
    char my_string[50], name[25], number[25];
    TreeNode *root = NULL;
    while ((fgets(my_string, 50, stdin)) != NULL) {
        if (my_string[0] == '.')
            break;
        sscanf(my_string, "%s %s", name, number);
        root = AddNode(root, name, number);
    }
    N_Print(root);
    return 0;
}

TreeNode* AddNode(TreeNode *root, char *name, char *number) {
    int comparison;
    if ( root == NULL) {
        root = (TreeNode *)malloc(sizeof(TreeNode));
        root->numbers = (ListNode *)malloc(sizeof(ListNode));
        root->name = strdup(name); root->numbers->number = strdup(number);
        root->left = root->right = NULL;
        root->numbers->next = NULL;
    }else if (( comparison = strcmp(name, root->name)) < 0 )
        root->left = AddNode(root->left, name, number);
    else if (comparison > 0) {
        root->right = AddNode(root->right, name, number);
    } else if (comparison == 0 ) {
        root->numbers->number = strdup(number);
        root->numbers->next = NULL;
    }
    return root;
}

TreeNode* SearchTree(TreeNode *root, char *search) {
    int comparison;
    if (root == NULL) {
        printf("NOT FOUND\n");
        return NULL;
    } else if ((comparison = stricmp(search, root->name)) == 0) {
        return root;
    } else if ((comparison = stricmp(search, root->name)) < 0) {
        return SearchTree(root->left, search);
    } else if ((comparison = stricmp(search, root->name)) > 0)
        return SearchTree(root->right, search);
}

int N_Print(TreeNode *root) {
    TreeNode *search_val;
    char search[25];
    while(1) {
        printf("Type a name please: ");
        scanf("%24s", search);
        if (search[0] == '.')
            break;
        search_val = SearchTree(root, search);
        if (search_val == NULL) {
            N_Print(root);
        }
        printf("%s\n", search_val->numbers->number);
    }
    return 0;
}

My first guess is that the code I need to add, needs to be placed within my compare IF statement when the result of compare == 0, thus increment the list, and add the number there. But this is where I'm stuck!

A: I didn't read entirely through your code as it made my eyes glaze...
This is your struct that holds the numbers.
typedef struct ListNode {
    char            *number;
    struct ListNode *next;
}ListNode;

If a name is to have multiple numbers, you should declare it like this.
char            **number;

So that the first pointer *(*number+0) is the first number for that name, and then *(*number+0) is the next. This would look neater as a linked list so i suggest structuring it like that, and then iterating through the list until you hit null to get all the possible numbers for that name.

A: As this thread contains most of your code, I thought it was best to respond here.
To make your code work, you need to change the code within the "IF statement" of your function AddNode when comparison == 0, which you have already pointed out.
TreeNode* AddNode(TreeNode *root, char *name, char *number) {
int comparison;
if ( root == NULL) {
    root = (TreeNode *)malloc(sizeof(TreeNode));
    root->numbers = (ListNode *)malloc(sizeof(ListNode));
    root->name = strdup(name); root->numbers->number = strdup(number);
    root->left = root->right = NULL;
    root->numbers->next = NULL;
}else if (( comparison = strcmp(name, root->name)) < 0 )
    root->left = AddNode(root->left, name, number);
else if (comparison > 0) {
    root->right = AddNode(root->right, name, number);
} else if (comparison == 0 ) {

    // Create a new ListNode
    newListNode = (ListNode *)malloc(sizeof(ListNode));

    newListNode -> number = strdup(number);

    // Add newListNode to existing list
    newListNode -> next = root -> numbers;
    root -> numbers = newListNode;
}
return root;
}

You should probably also adjust your SearchTree function, so that it returns the list of phone numbers.


text:
Q: UNet Caffe patch installation I have installed caffe successfully. Have someone tried to install U-Net caffe patch which is including 2D and 3D UNet? Could you please guide if you have installed? Thank you.

A: I could install it by following the instructions in the ReadMe file of the caffe_unet_3D_patch. after running all the commands successfully, I installed the Caffe by following the Caffe installation instructions.


text:
Q: How to check what Filebeat is sending to Logstash? I already have Logstash configured to directly pick up files (Gatling logs), process them using custom logic, and send to Elasticsearch. And it's working fine. I'm now trying to setup Filebeat to send the files to it instead.
The basics seem to work as I see the new entires ending up in Elasticsearch, but they look all wrong. My theory is that Logstash is configured to parse Gatling logs, but Filebeat doesn't send the logs directly, but some JSON or other format containing the metadata as well, and Logstash needs to be reconfigured to parse this instead.
But... how do I find out what Filebeat is sending? Is the format documented somewhere?

A: add the setting to filebeat.yml
you could see the output log as file in your path to see what happened.
output.file:
# Boolean flag to enable or disable the output module.
enabled: true

# Path to the directory where to save the generated files. The option is
# mandatory.
path: "your path"

# Name of the generated files. The default is `filebeat` and it generates
# files: `filebeat`, `filebeat.1`, `filebeat.2`, etc.
filename: filebeat

# Maximum size in kilobytes of each file. When this size is reached, and on
# every filebeat restart, the files are rotated. The default value is 10240
# kB.
#rotate_every_kb: 10000

# Maximum number of files under path. When this number of files is reached,
# the oldest file is deleted and the rest are shifted from last to first. The
# default is 7 files.
number_of_files: 7

if you want to see the network setting
please add the setting to see the log.
logging.level: warning
logging.to_files: true
logging.to_syslog: false
logging.files:
  path: /var/log/mybeat
  name: mybeat.log
  keepfiles: 7


text:
Q: Misleading warning from BibTeX Accidentally, I discovered a misleading warning. By mistake, I left the citation argument empty, compiled and run BibTeX. BibTeX warned that 'RealCitation' was not found in the database. After I remove the \cite{}, it compiles fine. I guess this issue would be better fixed (or maybe message changed)
\cite{RealCitation}
\cite{}

A: If you make a test file such as
\documentclass{article}

\begin{document}

\cite{RealCitation}
\cite{}
\cite{zz}
\end{document}

Then you see the generated aux file is
\relax
\citation{RealCitation}
\citation{zz}

and LaTeX has silently ignored the \cite{} so BiBTeX has no information that it was ever there, and it can not affect the bibtex output. If it is affecting the generated warnings there is additional code that you have not shown.


text:
Q: How to write a mongoDB query to match any element in an array of subdocuments against any element in a Typescipt Array? I have a mongoDB database containing Events. Each event is defined by a number of fields, including an array of genres (which are subdocuments consisting of a {genre and subGenre}).
For example: an event could be of {genre: "music", subGenre: "jazz"}, and {genre: "music", subGenre: "blues"}. See event.js - the model. In this case, 2 "genre" sub documents are added to the "genres" array in the Event document in the database.
Back in my node application - see query.ts - I am trying to work out how to run a query that lets the user search for all events that match their genre preferences.
So:

*

*the Event is defined by an array of genres (in the database), and

*the user's preferences are defined by an array of genres (in the
application).

I am looking to define a mongoDB query that returns all Events where there is a match of any 1 {genre, subGenre} combination between the 2 arrays.
I looked into $in Query Selector in the mongoDB documentation and suspect it might need to be used... but programmatically, how do I write a query that expands to include all the values in the variable "searchGenres" in query.ts?
Thanks a lot in advance for your thoughts.

event.js: mongoDB Model for 'Events" defined using Mongoose - snippet:
let mongoose    = require('mongoose');

let EventSchema = new mongoose.Schema({

genres: [
          {
            genre:      String,
            subGenre:   String
          }
       ]
)};

module.exports =  mongoose.model('Event', EventSchema);

query.ts:
import mongoose   = require('mongoose');
let Event         = require ('../models/event');

class Genre {
    genre:      string;
    subGenre:   string;

    constructor (gen: string, sub: string) {
        this.genre      = gen;
        this.subGenre   = sub;
    }
}

async function runQuery()
{
    let searchGenres : Array<Genre> = new Array<Genre>();

    // populate searchGenres with some data here... e.g.
    const searchGenre1 : Genre = new Genre ('music', 'jazz');
    const searchGenre2 : Genre = new Genre ('music', 'rock');

    searchGenres.push(searchGenre1);
    searchGenres.push(searchGenre2);

    // Query logic here:
    // Return all events from the database, if the 'genres' array
    // in the document matches any element in the searchGenres array
    // defined above..

    const events = await Event.find ({
                                       'genres': {?help? }

                                    });

}
```

A: After some self-education today, I have come up with a solution, which I am happy with - to append to end of query.ts:
type GenreQuerySelector = { genres: { $elemMatch: { 'genre': string; 'subGenre': string; }; }; };

let querySelectors : Array< GenreQuerySelector > = new Array< GenreQuerySelector >();

for (let genre of searchGenres) {

    const genreQuery : GenreQuerySelector = {
        genres: {
                    $elemMatch: {
                                    'genre':    genre.genre,
                                    'subGenre': genre.subGenre
                                }
                }
     };
     querySelectors.push(genreQuery);
};

const events = await Event.find  ({ $or: querySelectors }).exec();


text:
Q: Why doesn't lldb forward my environment variable anymore? I'm working on a patch for FFmpeg and need to debug my code. I'm loading an external library, and in order to test different library versions, I have them in different folders. To select which one I want to use, I've been using DYLD_LIBRARY_PATH=/path/to/lib/dir ./ffmpeg and that works okay. But when I try it within lldb, it crashes saying dyld: Library not loaded and Reason: image not found. This used to work pre-Xcode 7.1, but I just recently upgraded and it stopped working.

Here's my MVCE:
#include <stdio.h>
#include <stdlib.h>

int main() {
  char* str = getenv("DYLD_LIBRARY_PATH");
  if (str) puts(str);
  else     puts("(null)");
  return 0;
}

Running this program as follows produces the output:
$ ./a.out
(null)
$ DYLD_LIBRARY_PATH=/tmp ./a.out
/tmp

That looks okay. But when I try to use lldb it fails:
$ DYLD_LIBRARY_PATH=/tmp lldb ./a.out
(lldb) target create "./a.out"
Current executable set to './a.out' (x86_64).
(lldb) run
Process 54255 launched: './a.out' (x86_64)
(null)
Process 54255 exited with status = 0 (0x00000000)

Trying to set the environment variable inside lldb works:
lldb ./a.out
(lldb) target create "./a.out"
Current executable set to './a.out' (x86_64).
(lldb) env DYLD_LIBRARY_PATH=/tmp
(lldb) run
Process 54331 launched: './a.out' (x86_64)
/tmp
Process 54331 exited with status = 0 (0x00000000)

lldb version (it's from Xcode 7.1):
$ lldb --version
lldb-340.4.110

Question: Is this an intended new "feature," or is this a new bug in lldb (or am I totally crazy and this never used to work)? I'm quite positive lldb used to forward the DYLD_LIBRARY_PATH environment variable, so how come it isn't anymore?

Edit: This is on OS X 10.11.1.

A: If this is on El Capitan (OS X 10.11), then it's almost certainly a side effect of System Integrity Protection. From the System Integrity Protection Guide: Runtime Protections article:

When a process is started, the kernel checks to see whether the main
  executable is protected on disk or is signed with an special system
  entitlement. If either is true, then a flag is set to denote that it
  is protected against modification. …
… Any dynamic linker (dyld)
  environment variables, such as DYLD_LIBRARY_PATH, are purged when
  launching protected processes.

Everything in /usr/bin is protected in this fashion. Therefore, when you invoke /usr/bin/lldb, all DYLD_* environment variables are purged.
It should work to run lldb from within Xcode.app or the Command Line Tools, like so:
DYLD_LIBRARY_PATH=whatever /Applications/Xcode.app/Contents/Developer/usr/bin/lldb <whatever else>

I don't believe that copy of lldb is protected. /usr/bin/lldb is actually just a trampoline that executes the version in Xcode or the Command Line Tools, so you're ultimately running the same thing. But /usr/bin/lldb is protected so the DYLD_* environment variables are purged when running that.
Otherwise, you will have to set the environment variable inside lldb as shown in this thread:
(lldb) process launch --environment DYLD_LIBRARY_PATH=<mydylibpath> -- arg1 arg2 arg3

or using the short -v option:
(lldb) process launch -v DYLD_LIBRARY_PATH=<mydylibpath> -- arg1 arg2 arg3

Or, you can disable System Integrity Protection, although it serves a good purpose.

A: You can set an environment variable inside lldb once it is started.
$ lldb
(lldb) help env
Shorthand for viewing and setting environment variables.  Expects 'raw' input (see 'help raw-input'.)

Syntax:
_regexp-env                  // Show environment
_regexp-env <name>=<value>   // Set an environment variable

'env' is an abbreviation for '_regexp-env'
(lldb)

So that
lldb ./a.out
(lldb) env DYLD_LIBRARY_PATH=/path/to/lib/dir
(lldb) r

should work.
Tested with
$ lldb --version
lldb-1400.0.38.17
Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)


text:
Q: Son of a superhero is stashed at the Antarctica base, which is attacked by a villain. Escapes, and uses wits to survive, learns dark history I read this in the last five years, I'm pretty sure, probably more than two years ago. I believe it was a complete book, not a short story. I don't remember if it was a paper book or an ebook. I'm pretty sure it was a published book, not an online story. The protagonist is a teenage boy who is the son of the Superman analogue of the setting. No powers, but it is a fairly intelligent young man with an interest in computers. Since the death of his mother, years ago, his father has kept him isolated from society for his own protection. In this case, he's at their Antarctica base. I remember there being a scene where he was discussing how he periodically had to go outside to do something (base maintenance?) and that, even with heavy gear, he couldn't be out there for long due to the low temperature. His father would leave him there for weeks at a time, if not months. I believe he'd cannibalized bits of the base to build his own communications network to give himself some internet access, which had been forbidden, again ostensibly for his safety. He thinks his father is overly paranoid since the death of his mother (which, I think, was unexplained by that point in the book). The base comes under attack by a robot, and he manages to board an escape pod, but only after doing something in the base that resulted in the robot being destroyed (although I think whatever he did messed up the base's systems such that he knew he wouldn't be able to stay and survive).
The escape pod is essentially a missile with a descent system, and he winds up in a park, where a young woman (I want to say the protagonist is high school age and she's around college age) finds him and brings him back to her home. It seems that his father saved her at some point in the past and so she agreed to monitor a particular frequency, retrieve the escape pod, keep him safe, etc. I want to say that she's either a doctor, or studying to be one, and that she has a steady boyfriend or fiancee (the protagonist doesn't really show any romantic interest in her, but she establishes that she's taken early on with the assumption that otherwise he'd assume something romantic). After that, my memory is hazy other than that the protagonist winds up being attacked by more robots, including I think a spider-based one that he manages to take out by virtue of coating its sensors in paint while climbing on shelves in a hardware shop to escape it. Eventually, he learns that the villain who is after him has an origin with direct ties to his father — I think that either the villain was a scripted opponent sponsored by the government to prop up the hero or was a former hero turned bad — and that his mother died at the villain's hands, possibly in front of him, refusing to tell the villain where to find her husband. I don't remember if this was something he'd blocked out, that had been wiped from his memory, or simply not revealed to the reader until then.
I also don't remember exactly how it ends, although I think he does reunite with his father, and they reconcile. The protagonist is still bitter about having been mewed up for so long but also understands the danger, and the father realizes that hiding so much from his son, and barring him from resources, has put him in danger. I don't know if the villain was defeated at the end, and I got the impression that the series would continue, although I don't think I read any other books.

A: Crimson Son (2014) by Russ Linton...?
It's the first book in the Crimson Son series.
From Goodreads:

His mother kidnapped, his superhero father absent, powerless Spencer launches into a world of battle robots and weaponized humans to uncover the truth.
Armed with only a multi-tool and an arsenal of weapons-grade snark, Spencer takes on his superpowered father's robotic nemesis to try and uncover the fate of his mother. Along the way he rallies a team of retiree superheroes and everyday people living in the shadow of a weapons program gone wrong.
Before the dust settles every superhero and supervillain will come together for a Jerry Springer style Ragnarok. On the brink of Armageddon, with his mother's very existence at stake, Spencer stumbles into the true mastermind's web and discovers he's been the prey all along.
Crimson Son isn't your typical superhero novel. Fast-paced, engaging, with all the action you'd expect but set in a believable world helmed by a vulnerable hero with an unmistakable voice. Mr. Robot meets the Winter Soldier in this unique superhero series you'll love.

From a Goodreads user review:

19-year-old Spencer Harrington is the powerless son of the world's strongest Augment (a superpowered being) known as Crimson Mask. Two years prior, Spencer's mom was abducted by the supervillain Black Beetle, and ever since her abduction, his father has kept him hidden away in an ice bunker located in Antarctica. Spencer's dad is a hero, but they have a complex, almost antagonistic relationship with each other. Spencer blames his father for his mother's disappearance and for never being there. Spencer's dad has control issues and believes that he has to micromanage every bit of Spencer's life when he is around for his safety. When his dad leaves the ice bunker for more supplies, Spencer comes under attack and is thrust into the world that his father has mostly tried to keep him safe from, and he has to learn to rely on his own wits to find out what happened to his mother and to make peace with his father.


text:
Q: Docker - Laravel App Not Running and Not Error The container stands up and doesn't give any error but also doesn't work. When I try another app that has the same sub-core of the app, I see that it works successfully. The problem is in this app, I'm sure now.
I am leaving some necessary files below. I have no idea what the problem is. Thank you if anyone can help.
supervisord.conf file
[supervisord]
nodaemon=true
user=root
logfile=/var/log/supervisor/supervisord.log
pidfile=/var/run/supervisord.pid

[program:php]
command=/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan octane:start --watch --server=swoole --host=0.0.0.0 --port=8000
user=sail
environment=LARAVEL_SAIL="1"
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

[program:laravel-horizon]
command=/usr/bin/php -d variables_order=EGPCS /var/www/html/artisan horizon
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=sail
numprocs=1
redirect_stderr=true
stopwaitsecs=3600

compose file
# For more information: https://laravel.com/docs/sail
version: '3'
services:
    laravel.test:
        build:
            context: ./docker/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        container_name: Laravel
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - '${APP_PORT:-8000}:8000'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis
    mysql:
        image: 'mysql:8.0'
        container_name: MySql
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_USER: '${DB_USERNAME}'
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
        volumes:
            - "/var/lib/mysql"
        networks:
            - sail
    phpmyadmin:
        image: 'phpmyadmin:latest'
        container_name: PhpMyAdmin
        ports:
            - 8081:80
        environment:
            PMA_HOST: mysql
            MYSQL_ROOT_USER: '${DB_USERNAME}'
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
        depends_on:
            - mysql
        networks:
            - sail
    redis:
        image: 'redis:alpine'
        container_name: Redis
        ports:
            - '${FORWARD_REDIS_PORT:-6379}:6379'
        volumes:
            - 'sailredis:/data'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "redis-cli", "ping"]
            retries: 3
            timeout: 5s
networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local
    sailredis:
        driver: local

Docker Desktop Image


text:
Q: Sitecore 7.2 | Drawbacks of using MVC and Web Forms in the same site built with MVC
Question : Downside of using Web forms and MVC in same sitecore instance.
Current Situation : We have a Sitecore 7.2 instance developed using MVC and Glass Mapper. We want to reuse existing component which is already developed in Web Forms using the same sitecore version that we are currently using. What we have done so far: To achieve this we did a small POC and were able to achieve the same. We referred below link at Git to achieve this POC We found few blogs where people have done this but always say that it may not work all the time (and not highlighted which scenarios they fail). What are the drawbacks or possible difficulties that we could face doing this ?.It will be helpful if you can highlight as For example :Workflow does not work or personalization does not work etc. Thanks

A: I am currently running a Sitecore 7.2 instance with both WebForms and MVC (we actually went the other way- our old code is Webform and with a recent redeisgn we moved to MVC) and its doable, but kind of messy.
The biggest issues we've run into have been when we want to display webform and mvc content on the same page, or have the two code bases communicate in any way. Attempting to have renderings calling both webform and mvc code on the same page was disaster. Likewise trying to have webform-only pages communicate with mvc-only pages (eg. building out submenues, getting field values, etc).
In a way, what ended up happening with us was we had essentially two sites - the webforms and mvc versions - and the two never really merged well together. Our project plan was to move off of Webforms to full MVC, so we accepted this as a reality. I'm not sure how well a permanent mvc-webform crossover solution would work, to be honest.
We had some good luck using the following resources: https://www.packtpub.com/books/content/mixing-aspnet-webforms-and-aspnet-mvc
http://www.sitecore.net/Learn/Blogs/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/06/Using-Web-Forms-and-MVC-in-a-Single-Solution-with-the-Sitecore-ASPNET-CMS.aspx
It's been messy for us, lots of time keeping pages and code apart, and we are planning on cutting out webforms completely in the near future and going full-mvc. But running both is very doable.


text:
Q: What exactly means that pointer on the struct into the same structure the was created? typedef struct secinfo_t {
    struct secinfo_t*   next; /* NULL for no next section */
    const char*     name; /* nul-terminated section name */
    void*       addr; /* Address of section in memory */
    uint32_t        size; /* length of section (bytes) */
    uint32_t        flags; /* flags, see below */
    struct secinfo_t*   romcopyof; /* this section is a ROM copy of 'romcopyof' */enter code here

 /* Future fields go here */
} *secinfo_ptr;

What is "next" and "romcopyof" members that are created with type pointer on the struct? My problem which I don't understand is the type of struct for that members is the same I created? Could someone explain me more detailed?

A: typedef struct secinfo_t {
struct secinfo_t*   next; /* NULL for no next section */
const char*     name; /* nul-terminated section name */
void*       addr; /* Address of section in memory */
uint32_t        size; /* length of section (bytes) */
uint32_t        flags; /* flags, see below */
struct secinfo_t*   romcopyof; /* this section is a ROM copy of     'romcopyof' */enter code here

} *secinfo_ptr;

the struct secinfo_t*   next; in the struct is a reference of the struct to itself, this is used when the struct object is associated to other 'instances' of itself, i.e. this is often used for nodes in (binary ) trees or linked lists :
typedef struct Node Node;

struct Node
{
  int value;
  Node *next;
  Node *prev;
};

source : How to define a typedef struct containing pointers to itself?
for examples how to use this coding structures see http://www.learn-c.org/en/Linked_lists and https://www.geeksforgeeks.org/binary-tree-set-1-introduction/
struct secinfo_t* romcopyof; is a pointer to a ROM copy of secinfo_t, ROM is i.e. in EEPROM or on hard disc not in RAM where the code is executed ...


text:
Q: How to prove part of exponential family We saw that in order to prove a distribution is a part of a exponential family we should be able to write it in this form:
f(y;θ)=exp(a(y)b(θ)+c(θ)+d(y)
And to prove that:

*

*All statistics T are linearly independent

*The interior of the parameter set is non empty.

For example I am working on the Beta family and I proved everything except the 2).
I can  not understand how one can prove that the interior of parameter set is non empty?

A: There is some confusion about the notion:
(i) For a density of the form
$$f(x;\theta) = \exp\{a(\theta)^\text{T}b(x)+c(\theta)+d(x)\}$$
to be an exponential family the only constraint is that the support of the density does not depend on $\theta$.
(ii) The representation of this density is minimal if

*

*the components of $b(\cdot)$ are linearly independent

*the components of $a(\cdot)$ are linearly independent

(iii) For a minimal representation, the exponential family is full-rank if the set of the $a(\theta)$'s (when $\theta$ varies in the original parameter set) contains an open set. Otherwise it is curved.


text:
Q: Fourier Transformation of $e^{-a|x|}$ The Fourier Transformation will be like this :
$$ F_\text{trans}= \int_{-\infty} ^{\infty} f(x) e^{-ikx} dx  =  \int_{-\infty} ^{\infty} e^{-a|x|} e^{-ikx} dx $$
I don't understand what to do after that line. How will I deal with the the modulus  x?

A: Split the integral into two regions and use the fact that $\vert x\vert = -x$ for $x \lt 0$ and $\vert x\vert = x$ for $x\gt 0$:
$$
F_\text{trans}= \int_{-\infty} ^{\infty} f(x) e^{-ikx}\,dx  =  \int_{-\infty} ^{\infty} e^{-a|x|} e^{-ikx}\,dx \\
= \int_{-\infty} ^{0} e^{ax} e^{-ikx}\,dx + \int_{0} ^{\infty} e^{-ax} e^{-ikx}\,dx \\
= \int_{-\infty} ^{0} e^{(a-ik)x}\,dx + \int_{0} ^{\infty} e^{-(a+ik)x}\,dx.
$$


text:
Q: Python Pig-Latin translator     import string
def main():
  filename = input("Enter the name of a file to translate into Pig Latin: ")
  vowels = ['a', 'e', 'i', 'o', 'u','A','E','I','O','U']
  regFile = open((filename), 'r')
  Output = open('Output.txt', 'w')
  for line in  regFile.readlines():
    pigList = line.split()
    t = translate(pigList, vowels)
    w = write(t, Output)
  regFile.close()
  input ("Press ENTER to continue: ")

def translate(pigList, vowels):
  PigList2 = []

  for word in pigList:
    if word[-1] in string.punctuation:
      actual_word = word[:-1]
      ending = word[-1]
    else:
      actual_word = word
      ending = ""

    if word[0] in vowels:
      PigList2.append(actual_word + "-yay" + ending)
    else:
      PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
  return PigList2

def write(pigList, Output):
  print(" ".join(pigList))

main()

I believe this has fixed my errors. Thank you for the help. I know have the translator working correctly and translating all the lines at once instead of one line at a time.

A: You're almost there. I just used used the punctuation check to split up your word into the actual word and the punctuation and then append the '-' before the first letter rather than with the "ay".
def translate(pigList, vowels):
  PigList2 = []

  for word in pigList:
    if word[-1] in string.punctuation:
      actual_word = word[:-1]
      ending = word[-1]
    else:
      actual_word = word
      ending = ""

    if word[0] in vowels:
      PigList2.append(actual_word + "-yay" + ending)
    else:
      PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)

  return PigList2


text:
Q: GO: Serve static pages I'm trying to display a static page with GO.
GO:
package main

import "net/http"

func main() {
    fs := http.FileServer(http.Dir("static/home"))
    http.Handle("/", fs)
    http.ListenAndServe(":4747", nil)
}

Directory:
Project
    /static
        home.html
        edit.html
    project.go

When I run it, the web page displays the links to edit.html and home.html instead of displaying the static page from home.html. What am I doing wrong. Is this the best way to serve files? I know there are other ways eg. from the html/templates package but I'm not sure what the difference is and when to use each of these methods. Thanks!

A: func main() {
    http.Handle("/", http.FileServer(http.Dir("static")))
    http.ListenAndServe(":4747", nil)
}

You don't need static/home, just static.
FileServer is using directory listing and since you don't have an index.html in /static, the directory content is shown instead.
A quick fix would be to just rename home.html to index.html. This would allow you to access index.html through http://localhost:4747/ and edit.html with http://localhost:4747/edit.html.
There's no need to use html/template if you only need to serve static files.
But a clean solution depends on what you are actually trying to do.

A: If you're only interested in writing a simple server that serves static content and not just as a learning experience I'd take a look at Martini (http://martini.codegangsta.io/).
The quintessential Martini app to serve static files from a folder named 'public' would be:
package main

import (
    "github.com/go-martini/martini"
)

func main() {
    m := martini.Classic()
    m.Run()
}

to add a new static folder called 'static' to the list of static folders searched for content is also simple:
package main

import (
    "github.com/go-martini/martini"
)

func main() {
    m := martini.Classic()
    m.Use(martini.Static("static")) // serve from the "static" directory as well
    m.Run()
}

Martini provides lots more functionality as well, such as session, template rendering, route handlers etc...
We're using Martini in production here and have been more than happy with it and it's surrounding infrastructure.