text:
Q: MinionPro is not displaying Cyrillic (and other) characters I am following the directions in the README at the CTAN entry for MinionPro. I am using the Minion Pro fonts from the Adobe Font Folio 11. I'm running a fully-updated TeX Live 2011 distribution on OS X Lion 10.7.2.
Please note that I'm entirely aware this can be solved by using XeLaTeX (with fontspec), but I wish to use LaTeX in this case.
Running otfinfo -v on any one of the 64 Minion Pro fonts yields,
Version 2.030;PS 2.000;hotconv 1.0.51;makeotf.lib2.0.18671

so naturally I'm using the enc-2.000.zip encoding files.
After unzipping metrics-base.zip, metrics-full.zip, metrics-opticals.zip, and enc-2.000.zip into my /usr/local/texlive/texmf-local directory, I ran sudo mktexlsr, then sudo updmap-sys --enable Map=MinionPro.map, then sudo mktexlsr again.
I then typeset my test file, whose code and output is shown below.
\documentclass[10pt]{article}
\usepackage[T1,T2A]{fontenc}
\usepackage[openg]{MinionPro}
\usepackage[utf8]{inputenc}
\usepackage[english,russian]{babel}

\begin{document}
\section*{English}
Hello! How are you? This sentence has \textbf{bold}, \textit{italic}, and \textbf{\textit{bold italic}} characters. This sentence has \textsc{small caps}.

\section*{Russian}
Здравствуйте! Как у вас дела? Это предложение имеет \textbf{жирные}, \textit{курсивные}, и \textbf{\textit{жирные курсивные}} буквы. Это предложение имеет \textsc{капительные буквы}.

\section*{Equations}
\[
  \psi_{nlm}(r,\theta,\rho) = \sqrt{\bigg(\frac{2}{na_0}\bigg)^3 \frac{(n - l - 1)!}{2n[(n + l)!]^3}} e^{-\rho / 2} \rho^{l} L_{n - l -1}^{2l + 1}(\rho) \cdot Y_{l}^{m}(\theta, \phi)
\]
\[
  y = x\tan(\theta) - \frac{g\sec^2(\theta)}{2v_0^2}x^2
\]
\end{document}

Note that the openg option also fails to display. This is strange to me, because it seems as if everything is working except for a few characters. Everything works great with XeLaTeX, but not when using the MinionPro package.
Forgive me if I'm being naïve. Thanks.

A: the current TeXLive version of MinionPro has no option [openg]. Without it I get the desired result.

With lualatex and
\documentclass[10pt]{article}
\usepackage{fontspec}
\setmainfont{Minion Pro}
\usepackage[english,russian]{babel}

I get the same output.


text:
Q: querySelectorAll's click button issue Anyone know why the below code is not working? suppose the website will get back something if i click the arrow button, any code i typed wrong in querySelectorAll?  many thanks!

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />

Dance Time

A: you had a wrong div placed after the buttons div there ,,,
that was probably the reason ... check again and let me know if sth goes wrong

        let arrows = document.querySelectorAll('.buttons .fas')
        for (const arrow of arrows) {
            arrow.addEventListener('click',function(){
                if (arrow.classList.contains('fa-arrow-up')) {
            console.log('arrow clicked')
                }
        })
        }
  .buttons {
            font-size: 48px;
        }

Dance Time

    first
    second
    third
    fourth

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add value to variable declared in TypeScript by ngfor in html I declared variable in my ts file and in html file I'm using ngfor and I need to increase variable declared in ts by each element from ngfor is it possible?

    {{item.ItemName}}
    {{item.ItemNetPrice}}
    {{item.ItemAmount}}
    {{item.ItemName}}
    {{item.ItemVATRate}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{netto += item.ItemNetPrice}}

netto is my variable

A: Change your html like below

    {{item.ItemName}}
    {{item.ItemNetPrice}}
    {{item.ItemAmount}}
    {{item.ItemName}}
    {{item.ItemVATRate}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{item.ItemName}}
    {{getTotal(i)}}

and create getTotal method in your typescript file as below
getTotal(i) {
return this.invoiceItems.slice(0,i +1).map(rec => rec. ItemNetPrice).reduce((prev, curr) => prev + curr, 0);
}


text:
Q: How to read a BMP file in Visual C++ and extract width, Height and data with a example Iam completely new to C++ but I am a pro in image processing  using MATLAB
Iam looking for a header file (ex: CImg.h )which can read BMP and retrieve length width and 2d array similar to 'imread' function in MATLAB... i am not allowed to use Opencv Opengl
An example would help
TIA


text:
Q: Как подключить к одной Arduino Uno 8 серво моторчиков? Cначала подумал, что это не проблема, но понял, что ЦИФРОВЫХ портов в Arduino Uno меньше 8. Как можно подключить все 8 серво моторчиков не покупая новую плату? (Каждый из них должен управляться отдельно)

A: В таких случаях я использую либо шину I2C как-раз для таких ситуаций или же можно использовать специальный расширитель портов он стоит подешевле чем mega. Но я бы использовал I2C. И насчет цифровых портов то их двенадцать штук только 0 и 1 (TLL) а остальные цифровые просто выводы 3, 5, 6, 9, 10 и 11 способны формировать широтно-импульсную модуляцию (ШИМ) с помощью функции analogWrite().


text:
Q: WebSync server on demand configuration problem I got a websync server on demand and registered a domain at www.hariwebsync.com and got the api key. In my javascript client , i wrote
  fm.websync.client.initialize({
    requestUrl: 'request.ashx',
    stream: {
        requestUrl: 'http://www.hariwebsync.com/request.ashx'
    },
    key: '1dee9f44-dc60-47f8-b544-ba9a466a6bae'
});

to initialize the client. But, when i am loading the html file, i get an error "page not displayed". It is not able to load the registered domain (www.hariwebsync.com).
Can someone explain what i am doing wrong here. I am completely new to WebSync. So, please put up with me.

A: If you are using WebSync On-Demand, you don't need to specify any URLs:
fm.websync.client.init({
    key: '1dee9f44-dc60-47f8-b544-ba9a466a6bae'
});

You should probably check out the Getting Started guide: http://docs.frozenmountain.com/#class=on-demand-getting-started-connecting-a-client


text:
Q: Addition of two algebraic integer numbers
Is the addition of two algebraic integer numbers also algebraic?

I, guess it is, but i can't prove it.
I wonder if multiplication of them is also algebraic.

A: Hint:

*

*$\alpha$ is an algebraic integer iff $\mathbf Z[\alpha]$ is a finitely generated $\mathbf Z$-module.

*If $\alpha$ and $\beta$ are an algebraic integers, then $\mathbf Z[\alpha,\beta]$ is a finitely generated $\mathbf Z$-module.

A: I mean, there's a Field of algebraic numbers, so yes.
quick look here should provide you with an insight https://en.wikipedia.org/wiki/Algebraic_number#The_field_of_algebraic_numbers


text:
Q: How to create different singleton instances in different class loaders? I have an application that uses a ClassLoader hierarchy to run plugins. We have one parent ClassLoader at the "server" level and then child ClassLoaders for each plugin. Each plugin gets access to a few services that are dedicated to that plugin, and I would like to provide access via a singleton.
public class PluginServices {
    private static PluginServices _instance = null;
    private PluginServices() {
    }
    public static PluginServices getInstance() {
        if (_instance == null) {
            _instance = new PluginServices();
        }
        return _instance;
    }

    public static Service1 getService1() { ... }
    public static Service2 getService2() { ... }

}

However, when I access the singleton from the plugins, I am always getting the same instance instead of a new one per plugin. It seems like this is occurring because the .class for PluginServices is located in a JAR that is loaded by the Parent ClassLoader, and so the instance is tied to that ClassLoader instead of my plugin ClassLoaders.
Is there any way that I can have the PluginServices Singleton instance tied to the plugin's ClassLoader and therefore each plugin would get its own instance?


text:
Q: #include  no such file or directory in Yocto compilation HI i have include botan_2.14.0.bb from http://cgit.openembedded.org/meta-openembedded/tree/meta-oe/recipes-crypto/botan/botan_2.14.0.bb?h=master and i have bitbake it into my yocto build.
below is the rpm outcome:
-rw-r--r-- 2 kjlau kjlau   155436 Jul   7 11:12 libbotan-2-bin-2.14.0-r0.cortexa8hf_neon.rpm
-rw-r--r-- 2 kjlau kjlau   246916 Jul   7 11:12 libbotan-2-doc-2.14.0-r0.cortexa8hf_neon.rpm
-rw-r--r-- 2 kjlau kjlau    16376 Jul   7 11:12 libbotan-2-python3-2.14.0-r0.cortexa8hf_neon.rpm
-rw-r--r-- 2 kjlau kjlau   255764 Jul   7 11:12 libbotan-2-dev-2.14.0-r0.cortexa8hf_neon.rpm
-rw-r--r-- 2 kjlau kjlau  1443276 Jul   7 11:12 libbotan-2-13-2.14.0-r0.cortexa8hf_neon.rpm
-rw-r--r-- 2 kjlau kjlau 19660652 Jul   7 11:13 libbotan-2-dbg-2.14.0-r0.cortexa8hf_neon.rpm

i try build a application with include the botan header #include <botan/botan.h>, i am getting error no such file or directory. Below is botanapp.bb contents
DECRIPTION = "Simple helloworld application"
LICENSE = "CLOSED"
DEPENDS = "botan"
PACKAGES = "${PN} ${PN}-dbg"
SRC_URI = "file://app.cpp"

S = "${WORKDIR}"
CXXFLAGS = "-g -std=gnu++11"
inherit pkgconfig autotools

do_compile() {

     ${CXX} ${CXXFLAGS} ${LDFLAGS} -I ${includedir}/botan-2/botan   ${S}/app.cpp -lbotan-2  -o ${S}/myBotan
}

do_install() {
    install -d ${D}${bindir}
    install -m 0755  ${WORKDIR}/myBotan ${D}${bindir}
}

FILES_${PN} += " \
        ${bindir}/myBotan \
"

i have check my botanapp recipe-sysroot of botanapp
$build/tmp/work/cortexa8hf-neon-poky-linux-gnueabi/botanapp/1.0-r0/recipe-sysroot/usr/include/botan-2/botan
$ ls botan*
    botan.h

The header is available, i am not sure what wrong.To my knowledge , i need do something like this
g++ app.cpp -I/usr/local/include/botan-2 -lbotan-2

to compile botan code in ubuntu. Kindly let me know if i do anything wrong.

A: What you needed is STAGING_INCDIR.
The ${includedir} is where the files will be at the image.  And so on the target.
But with DEPENDS, you ask Yocto to prepare a sysroot with everything there to build the recipe.  And STAGING_INCDIR is pointing to that sysroot.
A includedir can be used e.g. to tell the install command where to put the files in the image.
It's rather easy to find out how all others recipes are doing it.
A grep -r ' -I' in you sources will point to many recipes where a compiler command is used.

A: do_compile() {
     ${CXX} ${CXXFLAGS} ${LDFLAGS}  -o ${S}/botanBinary -I ${STAGING_DIR_TARGET}/${includedir}/botan-2 ${S}/app.cpp  -lbotan-2
}

This work for me, let me know if anything does not make sense. thanks


text:
Q: How to include javascript code into php view? I have to print news.php code out registering it into a variabile to put inside a grid in another view. My main problem is that the code in news.php doesn't show anything, after compilation it is just blank though I'm quite sure the script is working.
I've already tried to convert news.php into news.js but nothing changed, I guess there are problems in the registerJs().
news.php

view.php
     # put the js script inside my $news variable
     $this->registerJsFile(
         '@web/views/news.php',
         View::POS_HEAD);
     );
     echo '

'
                            . $rows['content'] . '

'
                    . $news . '

';

I expect the js code to be displayed inside the grid. Every help would be much appreciated.

A: If you don't load jQuery in your page how can you execute the javascript code related to jQuery. It will directly throw error. This kind of error you can easily solve just by opening the browser's console.


text:
Q: python running task in the background while allowing tkinter to be active When my program executes the python GUI freezes.  Here is my main code.  Can I get some help in doing threading? So the execution happens in the background and I can still be able to use the "x" button in the GUI if I want to end the execution?  Currently I just ask the user to close the cmd to end the program.
if __name__ == "__main__":

    root = Tk()
    root.title('Log')
    root.geometry("400x220")
    font1=('times', 15)
    font2=('times', 10)
    #Label inside root
    Label(root, relief=GROOVE, font=font2, text="level").pack()
    variable = StringVar(root)
    variable.set("INFO") # default value

    w = OptionMenu(root, variable, "CRITICAL", "DEBUG")
    w.pack()
    Button(root, font=font1, background= "yellow", text='START',command=main).pack()
    Label(root, text="To end just close the CMD window").pack()

    root.mainloop()

A: UPDATE: Turns out the Button callback was autorunning launch because the function object wasn't being set as the callback, the called function itself was. The fix is to replace the callback lambda: spawnthread(fcn) so that a function object is set as the callback instead. The answer has been updated to reflect this. Sorry for missing that.

The GUI mainloop will freeze when you try to run some other function, and has no way to restart itself (because it's frozen.)
Let's say the command you'd like to run alongside the GUI mainloop is myfunction.
Imports:
import time
import threading
import Queue

You need to set up a ThreadedClient class:
class ThreadedClient(threading.Thread):
    def __init__(self, queue, fcn):
        threading.Thread.__init__(self)
        self.queue = queue
        self.fcn = fcn
    def run(self)
        time.sleep(1)
        self.queue.put(self.fcn())

def spawnthread(fcn):
    thread = ThreadedClient(queue, fcn)
    thread.start()
    periodiccall(thread)

def periodiccall(thread):
    if(thread.is_alive()):
        root.After(100, lambda: periodiccall(thread))

You then want the widget calling the function to instead call a spawnthread function:
queue = Queue.Queue()

Button(root, text='START',command=lambda: spawnthread(myfunction)).pack() #<---- HERE

N.B. I'm adapting this from a multithreaded tkinter GUI I have; I have all my frames wrapped up in classes so this might have some bugs since I've had to tweak it a bit.


text:
Q: How to publish a dapp from Superblocks? I build a simple dapp using https://iot-academy.superblocks.com/ , how can I publish it online on a normal server?

A: You can host these DAPP in the  GitHub pages or in CDN. If not you can also download it from the superblock and host it locally using MyEtherWallet.
Apart from that even you can pay a rental and host in the Ethereum network.


text:
Q: GoLand gives incorrect HTML/JavaScript warnings and indicators
*

*GoLand is telling me that functions are not being used at all when they are being called with onClick instead of onclick. I realize onclick is correct, but it would be nice if it could also recognize onClick

*On line 4 of the below function, GoLand is telling me that my comparison will always be true since I'm comparing value: boolean to "true": string. However, value is not a boolean and is actually a string, which I found out when I removed the quotes from true and that caused my button to stop working.

I loaded up my workspace in VSCode and found that it accepted both onClick and onclick, and did not complain about hidden1.value !== "true". I love GoLand... how can I make it as smart of VSCode in these respects?
It appears that GoLand infers value is a boolean because of line 7 (setting value with a boolean). If I throw ToString() on there, the warning goes away, but I'd like to not have to add this... it works fine as-is and a colleague using vscode likely won't add it, therefore I don't want it to cause an issue for me, using GoLand.
This is in an html file that contains javascript directly inside the <script> tag. Is there a way to make this operate more like how vscode is seeing things?
My GoLand settings are HTML5, JSX syntax checking on, JS=ECMAScript 6+, TS=Bundled 4.7.4
    function pgMpFunc(el1, el2) {
        const hidden1 = document.getElementById(el1);
        const hidden2 = document.getElementById(el2);
        const turnOn = (hidden1.value !== "true");

        setCheckbox(el1, turnOn);
        hidden1.value = turnOn;

        if (turnOn) {
            setCheckbox(el2, !turnOn);
            enableCheckbox(el2, !turnOn);
            hidden2.value = !turnOn;
        } else {
            enableCheckbox(el2, true);
        }
    }

A: hidden1.value is a Boolean, once you change it
We can see this because you are creating it from a Boolean expression:
    const turnOn = (hidden1.value !== "true"); // Result is ALWAYS boolean

    setCheckbox(el1, turnOn);
    hidden1.value = turnOn; // And this is what you are putting in there

A better way to do that Boolean expression is as follows:
    const turnOn = ! hidden1.value;

Goland is correct about the spelling of onclick
If your browser is permissive, it might accept onClick, but that is not the standard name and some browsers may not accept it.
Generally, many things in HTML are non-case-sensitive, but JS itself is case-sensitive.
Therefore while it might work to use random capitalization in the HTML, it is not a good idea, because one day you may forget and do that in the JS, and it will fail and be a difficult bug to resolve.


text:
Q: WooCommerce disabled custom field addition to their free plugin? I am unable to create custom fields through WooCommerce Hooks as shown
function woocommerce_product_custom_fields()
{
    global $woocommerce, $post;
    echo '
';
    woocommerce_wp_text_input(
        array(
            'id'          => '_custom_product_title',
            'placeholder' => 'Arabic Product Title',
            'label'       => __('Arabic Product Title', 'woocommerce'),
            'desc_tip'    => 'true'
        )
    );

    woocommerce_wp_textarea_input(
        array(
            'id'          => '_arabic_desc',
            'placeholder' => 'Arabic Description',
            'label'       => __('Arabic Description', 'woocommerce')
        )
    );
    echo '
';
}

// Display Fields
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');

function woocommerce_product_custom_fields_save($post_id)
{
// Custom Product Text Field
$woocommerce_custom_product_text_field = $_POST['_custom_product_title'];
  if (!empty($woocommerce_custom_product_text_field))
     update_post_meta($post_id, '_custom_product_title', esc_attr($woocommerce_custom_product_text_field));

/*$woocommerce_custom_product_textarea = $_POST['_arabic_desc'];
  if (!empty($woocommerce_custom_product_textarea))
     update_post_meta($post_id, '_arabic_desc', esc_html($woocommerce_custom_product_textarea));*/
}
// Save Fields
//add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

But the Fields do not appear in Admin panel > New Products or in the Vendor > Add product pages.
I found two mentions in the WP.org from the WooCommerce authority here also this thread
So, did they just remove the functionality of these hooks in free method? Why wont that be documented then?
**
Update: I was looking at the wrong place to see the code running. And as the asnwerer reported it worked for him. I checked more to find out any output this could have generated, and found that, I had a tab collapsed which was recently updated due to WooCommerce plugin update at the previous day. Of course was some frustrating moments for a couple of days. Partly was for the typos I had at the 2nd TextArea name initially, but later it was due to collapsed tab and expecting result at another dashboard run by WCMarketPlace (another addon for vendors from WooCommerce).
**

A: I just checked the latest WooCommerce files since the update three days ago to verify the hooks and methods are still the same, and they are. woocommerce_product_options_general_product_data is still being used, as well as woocommerce_wp_text_input.
I then tested your code and for me it works.

You do have some typos in the code where you save your textarea. Here's the code without your typos (I believe you wrote procut instead of product).
$woocommerce_custom_product_textarea = $_POST['_arabic_desc'];
  if (!empty($woocommerce_custom_product_textarea))
     update_post_meta($post_id, '_arabic_desc', esc_html($woocommerce_custom_product_textarea));


text:
Q: How do I assign the selected indexes data to my ToolTips data? So I finally created a example that is runnable and testable.
What I've done so far is I created two buttons, both of which show a tooltip when hovering over.
When you click a button it allows yuo to chose a item from a Select element.
Here is the thing..
I want to display the information about the item selected in the corresponding ToolTip.
So if I click the button headBtn and select the first option, Then I want the information about that selected option to display in the tooltip that shows when you hover over that button.

var theArray = [];

function getHeadData() {
$("#itemSelect").empty();
        $.getJSON("https://api.myjson.com/bins/lf0tc", function (data) {
        for (var i = 0; i < data.length; ++i) {
                var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
                $('#itemSelect').append(html);
            }
            theArray = data;
        });
}

function getNeckData() {
$("#itemSelect").empty();
        $.getJSON("https://api.myjson.com/bins/bw34w", function (data) {
        for (var i = 0; i < data.length; ++i) {
                var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
                $('#itemSelect').append(html);
            }
            theArray = data;
        });
}

$('.tooltip').mouseover(function(event){
var index = $(".tooltip").index(this);
        switch (index) {
            case 0:
                //HeadItem

                break;

                case 1:
                //NeckItem

                break;

            default:
                break;
        }

        //How do I assign
 Item Name the value of theArray[i].Name?
        //How do I assign Item Icon the value of theArray[i].Icon?
});

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var head = document.getElementById("headBtn");

// Get the button that opens the modal
var neck = document.getElementById("neckBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
head.onclick = function() {
    modal.style.display = "block";
    getHeadData();
}

// When the user clicks the button, open the modal
neck.onclick = function() {
    modal.style.display = "block";
    getNeckData();
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
.tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: black;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px 0;

    /* Position the tooltip */
    position: absolute;
    z-index: 1;
}

.tooltip:hover .tooltiptext {
    visibility: visible;
}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

Move the mouse over the text below:

<button class="tooltip" id="headBtn">Select Helmet

 Item Name

 Icon

</button>

<button class="tooltip" id="neckBtn">Select Necklace

 Item Name

 Icon

</button>

    ×

Please Select An Item

            <select id="itemSelect">
            </select>

A: I've gone another way since your solution, having only one array, can only handle one item info at a time so you have to save the data somewhere anyway.
The idea is binding a change listener to your dropdown and altering the tooltip after selection.
Be aware that, with your current setup, this won't respond to selecting the first item right away, since it's considered already selected and doesn't fire change. The simplest way get around this is by adding a placeholder option with no value and filtering it on the handler but if you don't want this placeholder element it can be done by listening to click instead.

// Find first tooltip and save contents to a variable so we can restore it
emptyTooltip = $('.tooltiptext').first().html()

function getHeadData() {
  getData("https://api.myjson.com/bins/lf0tc")
  // Listen for changes on the 'select'. Pass the target div where to insert the result
  $('#itemSelect').change(function() {
    setData('#headBtn', $(this))
  });
}

function getNeckData() {
  getData("https://api.myjson.com/bins/bw34w")

  $('#itemSelect').change(function() {
    setData('#neckBtn', $(this))
  });
}

function getData(url) {
  /*
    Since the 'select' itself doesn't get removed from the dom,
    still has the previous content and listener attached.
    We remove them to avoid affecting the wrong element.
  */
  $("#itemSelect").empty().off('change');
  $.getJSON(url, function(data) {
    // Add a placeholder 'option' so it responds to the 'change' event
    $('#itemSelect').append('<option value="">Select an item</option>');
    for (var i = 0; i < data.length; ++i) {
      var html = '<option value="' + i + '" data-icon="' + data[i].Icon + '">' + data[i].Name + '</option>';
      // Collect other item statistics in the response.
      let itemStats = {};
      for (key in data[i]) {
        if ((key != 'Icon') && (key != 'Name')) {
          itemStats[key] = data[i][key];
        }
      }
      // Convert the option to a jQuery element and attach the data.
      $html = $(html)
      $html.data('stats', itemStats);
      $('#itemSelect').append($html);
    }
    /*
      This renders the placeholder option unnecessary since it forces
      a selection on 'select' load. This is done to reset the tooltip
      if the user dismisses the modal without selecting anything.
      The placeholder option is what signals this, since it has no 'value'.
      Otherwise it would force the first 'option' in the dropdown.
    */
    $('#itemSelect').trigger('change')
  });
}

/*
  target is where to insert the results
  $item is the 'select' itself. Not really necessary
        since it always be '#itemSelect' and can be retrieved in the function.
*/
function setData(target, $item) {
  $selection = $item.children('option:selected')
  // Get target element and corresponding tooltip
  $span = $(target).children('.tooltiptext')
  // Check if there's an actual selection or the placeholder item
  if ($selection.val() != "") {
    // Insert each element in its place
    $span.children('h3').text($selection.text())
    // Won't allow crossorigin elements
    // img = $('img').attr('src', $selection.data('icon'))
    $span.children('p').text('Icon Data')
    // Item stats accesible here
    // $selection.data('stats')
  } else {
    // No selection, reset tooltip.
    $span.html(emptyTooltip);
  }
}

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var head = document.getElementById("headBtn");

// Get the button that opens the modal
var neck = document.getElementById("neckBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
head.onclick = function() {
  modal.style.display = "block";
  getHeadData();
}

// When the user clicks the button, open the modal
neck.onclick = function() {
  modal.style.display = "block";
  getNeckData();
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content */

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

Move the mouse over the text below:

<button class="tooltip" id="headBtn">Select Helmet

 Item Name

 Icon

</button>

<button class="tooltip" id="neckBtn">Select Necklace

 Item Name

 Icon

</button>

    ×

Please Select An Item

    <select id="itemSelect">
    </select>

A: You'd just do it like this:
$('.tooltip').mouseover(function(event){
var index = $(".tooltip").index(this);
        switch (index) {
            case 0:
                //HeadItem

                break;

                case 1:
                //NeckItem

                break;

            default:
                break;
        }

        //NEW LINES
        $("#headBtn > .tooltiptext > h3.radio").html(theArray[index].Name;
        $("#headBtn > .tooltiptext > p.radio").html(theArray[index].Icon;
});

A: Try this. I added a var for headTip and neckTip. OnChange event (that I bind on modal show) I am assigning this value. Then I am simply replacing the h3 there.

var theArray = [];
var headTip, neckTip;

function getHeadData() {
$("#itemSelect").empty();
        $.getJSON("https://api.myjson.com/bins/lf0tc", function (data) {
        for (var i = 0; i < data.length; ++i) {
                var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
                $('#itemSelect').append(html);
            }
            theArray = data;
        });
}

function getNeckData() {
$("#itemSelect").empty();
        $.getJSON("https://api.myjson.com/bins/bw34w", function (data) {
        for (var i = 0; i < data.length; ++i) {
                var html = '<option id="' + data[i].id + '">' + data[i].Name + '</option>';
                $('#itemSelect').append(html);
            }
            theArray = data;
        });
}

$('.tooltip').mouseover(function(event){
var index = $(".tooltip").index(this);
        switch (index) {
            case 0:
                //HeadItem
                $(".tooltip h3").html(headTip);
                break;

                case 1:
                //NeckItem
                $(".tooltip h3").html(neckTip);
                break;

            default:
                break;
        }

        //How do I assign
 Item Name the value of theArray[i].Name?
        //How do I assign Item Icon the value of theArray[i].Icon?
});

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var head = document.getElementById("headBtn");

// Get the button that opens the modal
var neck = document.getElementById("neckBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
head.onclick = function() {
    modal.style.display = "block";
    getHeadData();
    $("#itemSelect").off("change").on("change", function(e){
        headTip = $(e.currentTarget).val()
    });
}

// When the user clicks the button, open the modal
neck.onclick = function() {
    modal.style.display = "block";
    getNeckData();
        $("#itemSelect").off("change").on("change", function(e){
        neckTip = $(e.currentTarget).val()
    });
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
.tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: black;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px 0;

    /* Position the tooltip */
    position: absolute;
    z-index: 1;
}

.tooltip:hover .tooltiptext {
    visibility: visible;
}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

Move the mouse over the text below:

<button class="tooltip" id="headBtn">Select Helmet

 Item Name

 Icon

</button>

<button class="tooltip" id="neckBtn">Select Necklace

 Item Name

 Icon

</button>

    ×

Please Select An Item

            <select id="itemSelect">
            </select>


text:
Q: Are there any good concurrency/parallelism books out there that are NOT focused on Java? I want a more C++/Linux oriented book. I do have some basics of multithreading/parallel programming under my belt, but I want to both brush my skills and improve them further.

A: The reference for pthreads is Programming with POSIX Threads, by David Butenhof; in addition to the specifics of pthreads, it presents a lot of very good information about concurrency in general.  It is, however, strictly C, and it doesn't really say much about parallel programming.  Still, I'd definitely recommend it.
There's also C++ Concurrency in Action: Practical Multithreading, by Anthony Williams.  This is a very new book, and I haven't seen it yet, but the author played an important role in the standardization of threading, and I've seen articles by him, so I expect it will be very good.


text:
Q: Performance of SQLite database with too many columns I am developing an iOS application, and the performance is really important for my application. It has a bookmark database that may contain up to 1000 rows, depending on the usage of each user.
Right now, each row has 10 columns and most of them are just null. So I'm wondering if it is better to group some columns into one column (and probably use commas to separate them)? Will this improve the performance? Those columns are not indexed, so there is no problem in doing this, and they are usually read together.
Thank you very much!

A: 1000 rows doesn't sound like alot to iterate over but every answer I tried to write was overly complicated without knowing what the columns were and why so many are null.
The best answer I can give you is no I do not think grouping columns together into a comma seperated list would help improve the performance of the database.  I think you would be wrestling an alligator trying to extract the information you actually wanted.

A: This sounds a lot like premature optimization.
I'd say: no, unless you're running into actual performance problems.  And even then I would suggest running a profiler, to see what's actually eating up your performance.
With 1000 rows max, using one or more columns will most likely not be your bottleneck.
In fact, chances are that multiple empty columns might be more efficient than a single non-empty column where you have to extract the different empty values from.
What kind of data is it?


text:
Q: Run Python virtualenv through Matlab I am trying to run a python code through matlab using system commands on a mac. I need to run the python code on a virtualenv to use opencv but I keep getting erors when I use "workon cv" and "mkvirtualenv cv" even though it works fine on the terminal.
status1 = system('workon cv')
status2 = system(char(cmm))

output:
/bin/bash: workon: command not found
status1 =
127
Traceback (most recent call last):
  File "test", line 5, in
    import cv2
ImportError: No module named cv2


text:
Q: Inconsistent read count in SentryOne Plan Explorer I am attempting to tune a query using the SentryOne Plan Explorer tool (version 3.0, build 11.0.84.0) and SQL Server Microsoft SQL Server 2014 (SP2-CU3).  Plan Explorer is reporting an inconsistent number of reads between the per-table numbers and the total reported for the query.  The reported total is an order-of-magnitude larger than the sum of the per-table reads, and much larger than it was with the original query.
I apologize that I am unable to post a screenshot.  I work in a high-security industry, and I am unable to access image-hosting sites.
This is the query I'm running:
SELECT sd.*, ss.*
    FROM dbo.SecurityActivityRange AS ar
    JOIN dbo.SecurityDaily AS sd ON sd.accountId = ar.accountId
        AND sd.securityId = ar.securityId
        AND sd.reportDate = 5000
        AND sd.isHeld = 1
    JOIN dbo.SecuritySemiStatic AS ss ON ss.accountId = sd.accountId
        AND ss.securityId = sd.securityId
        AND ss.semiStaticDate = sd.semiStaticDate
    WHERE ar.accountId = 1
            AND ar.startDate <= 5000
            AND ar.endDate >= 5000

I'm going to copy the per-table numbers from SSMS, because it's already text and contains the same information as what Plan Explorer is reporting:
Table 'SecurityActivityRange'. Scan count 0, logical reads 92, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'SecuritySemiStatic'. Scan count 0, logical reads 194, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'SecurityDaily'. Scan count 1, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

This is from Plan Explorer, in the "Results" tab, under "Statement":
Statement     Est Cost   Duration   CPU   Est CPU Cost   Reads   Writes   Est IO Cost   Est Rows   End Time   Actual Rows   Start Time
SELECT ...    100.0%     33         47    100.0%         3,590   78       100.0%        1          2017-...   46            2017-02...

You can see that the total reads is 3590, which is much larger than 292.  I'm also curious to know why it's reporting writes.
This is the textual version of the execution plan:
  |--Nested Loops(Inner Join, OUTER REFERENCES:([ss].[securityId]))
       |--Nested Loops(Inner Join, OUTER REFERENCES:([sd].[securityId], [sd].[semiStaticDate], [Expr1005]) WITH UNORDERED PREFETCH)
       |    |--Clustered Index Seek(OBJECT:([sws_db].[dbo].[SecurityDaily].[PK_SecurityDaily] AS [sd]), SEEK:([PtnId1001]=(100) AND [sd].[accountId]=(1) AND [sd].[reportDate]=(5000)),  WHERE:([sws_db].[dbo].[SecurityDaily].[isHeld] as [sd].[isHeld]=(1)) ORDERED FORWARD)
       |    |--Clustered Index Seek(OBJECT:([sws_db].[dbo].[SecuritySemiStatic].[PK_SecuritySemiStatic] AS [ss]), SEEK:([PtnId1003]=RangePartitionNew([sws_db].[dbo].[SecurityDaily].[semiStaticDate] as [sd].[semiStaticDate],(1),(1097),(1462),(1828),(1918),(2009),(2101),(2193),(2224),(2252),(2283),(2313),(2344),(2374),(2405),(2436),(2466),(2497),(2527),(2558),(2589),(2617),(2648),(2678),(2709),(2739),(2770),(2801),(2831),(2862),(2892),(2923),(2954),(2983),(3014),(3044),(3075),(3105),(3136),(3167),(3197),(3228),(3258),(3289),(3320),(3348),(3379),(3409),(3440),(3470),(3501),(3532),(3562),(3593),(3623),(3654),(3685),(3713),(3744),(3774),(3805),(3835),(3866),(3897),(3927),(3958),(3988),(4019),(4050),(4078),(4109),(4139),(4170),(4200),(4231),(4262),(4292),(4323),(4353),(4384),(4415),(4444),(4475),(4505),(4536),(4566),(4597),(4628),(4658),(4689),(4719),(4750),(4781),(4809),(4840),(4870),(4901),(4931),(4962),(4993),(5023),(5054),(5084),(5115),(5146),(5174),(5205),(5235),(5266),(5296),(5388),(5480),(5570),(5661),(5753),(5845),(5936),(6027),(6119),(6211),(6301),(6392),(6484),(6576),(6666),(6757),(6849),(6941),(7031),(7122),(7214),(7306),(7397),(7488),(7580),(7672),(7762),(7853),(7945),(8037),(8127),(8218),(8310),(8402),(8492),(8583),(8675),(8767),(8858),(8949),(9041),(9133),(9223),(9314),(9406),(9498),(9588),(9679),(9771),(9863),(9953),(10044),(10136),(10228),(10319),(10410),(10502),(10594),(10684),(10775),(10867),(10959),(11049),(11140),(11232),(11324),(11414),(11505),(11597),(11689),(11780),(11871),(11963),(12055),(12145),(12236),(12328),(12420),(12510),(12601),(12693),(12785),(12875),(12966),(13058),(13150),(13241),(13332),(13424),(13516),(13606),(13697),(13789),(13881),(13971),(14062),(14154),(14246),(14336),(14427),(14519),(14611),(14702),(14793),(14885)) AND [ss].[accountId]=(1) AND [ss].[semiStaticDate]=[sws_db].[dbo].[SecurityDaily].[semiStaticDate] as [sd].[semiStaticDate] AND [ss].[securityId]=[sws_db].[dbo].[SecurityDaily].[securityId] as [sd].[securityId]) ORDERED FORWARD)
       |--Clustered Index Seek(OBJECT:([sws_db].[dbo].[SecurityActivityRange].[PK_SecurityActivityRange] AS [ar]), SEEK:([ar].[accountId]=(1) AND [ar].[securityId]=[sws_db].[dbo].[SecuritySemiStatic].[securityId] as [ss].[securityId]),  WHERE:([sws_db].[dbo].[SecurityActivityRange].[startDate] as [ar].[startDate]<=(5000) AND [sws_db].[dbo].[SecurityActivityRange].[endDate] as [ar].[endDate]>=(5000)) ORDERED FORWARD)

You can see that it isn't using any operators that might spill to disk.
I've experimented with the query, and it seems that both joins are necessary to see this behavior.  I also found that dropping ss.* from the column clause makes the difference go away too.

A: Disclaimer: I work for SentryOne, the company that offers Plan Explorer to the community.
The "Reads" number in the statement tree is essentially what trace reports for batch completed, as opposed to a sum of individual I/Os on the Table I/O tab. Run your batch and capture it with a trace, and I bet you see similar numbers reported there for batch completed. It's not always easy to determine where these reads come from, especially when you are keeping so much from us, but they definitely came from your session.

*

*Does the table I/O tab have additional line items, like workfile / worktable?

*Are any of the expressions in the plan computed columns?

*Do any of the plan operators have warnings about residual I/O? (Apologies, I forget what builds of SQL Server surface that information in plan XML.)

Could also be from function calls (are any of these objects views?), which will only show up as their inner queries in the call stack, and won't show in the plan, as described in this answer:

*

*https://dba.stackexchange.com/a/54846/1186


text:
Q: Prevent custom url parameter in Product Page to be Cached I am working on a requirement to add a custom parameter in the configurable product page URL. This will have the simple SKU to preselect the color in the swatches, something like this:

https://site.test.com/product-page-url.html?v=simplesku

The user requires this way because these URLs will be generated by the marketing team and need an easy way to create a URL to each simple and send in the marketing communication (for example, newsletter or Facebook posts).
The customization works fine, and it selects the simple product in the swatches specified in the URL without a problem. However, this selection seems to be caching. So, for example, if you first go to this URL:

https://site.test.com/product-page-url.html?v=simplesku

It shows the correct color. But if you next go to:

https://site.test.com/product-page-url.html?v=simplesku2

https://site.test.com/product-page-url.html?v=simplesku3

https://site.test.com/product-page-url.html?v=simplesku4

Or even without the parameter in the URL:

https://site.test.com/product-page-url.html

The result is the same. The page shows the first color and ignores the parameter in all the subsequent attempts. Is it a way to add this custom parameter to prevent to be caching, and with that, each URL with a different value in it generates a different page result?

A: If you are using PHP to select the default swatch from the URL parameter, the full page cache will always cache the first instance of the request. This is because all of these URLs:
https://site.test.com/product-page-url.html?v=simplesku
https://site.test.com/product-page-url.html?v=simplesku2
https://site.test.com/product-page-url.html?v=simplesku3
https://site.test.com/product-page-url.html?v=simplesku4
...share the same cache key.
You can read up on how to customize an existing cache key, with overview info at https://developer.adobe.com/commerce/php/development/cache/partial/
That said, I'd recommend to pre-select the swatch with something like a JavaScript or UI Component, as that wouldn't affect the full page cache, and you wouldn't have to touch cache keys or worry about cache invalidation. Also, it will be more optimal, as really all of the above URLs should probably share a common cache, and modifying the cache keys would be inefficient, as that would require a separate cache file for each query combination.


text:
Q: List of listings name in header I have a two-sided book document and want to format the header such that the chapter name is on the outer part. Everything works fine, but one thing annoys me. I have some source code listings (listings package) and pseudo codes (algorithmicx package). All the chapter names are given "normally" but the list of listings (named "Listings") and list of algorithms are put in all-caps in the header.
I probably need to override some settings for these packages, but I cannot find out which. How can I change the way "Listings" and "List of Algorithms" is put by the \chaptermark command (if that's the correct one)?
Here is a small example that demonstrates the problem:
\documentclass[a4paper,twoside]{book}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage{listings}

\fancypagestyle{fancyplain}{%
\renewcommand{\headrulewidth}{0pt}
\fancyhf{}%
\renewcommand{\footrulewidth}{0pt}
\fancyfoot{\fancyplain}{}
}

\pagestyle{fancy}

\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{thesection\ #1}{}}

\renewcommand{\lhead}[1]{\fancyhead[OL,ER]{\fancyplain{}\chaptermark{#1}}}
\fancyhead[OR,EL]{\fancyplain{}\thepage}

\begin{document}

\chapter{My chapter}
\begin{lstlisting}[caption={My listing},label=lst:my_listing,language=C++]
  std::cout << "Hello World!" << std::endl;
\end{lstlisting}
\cleardoublepage

\lstlistoflistings
\addcontentsline{toc}{chapter}{Listings}
\thispagestyle{empty}
\cleardoublepage

\end{document}

A: One way is to remove or replace \tableofcontents by a modified version which does not have \MakeUppercase\contentsname.
\documentclass[a4paper,twoside]{book}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage{listings}

\usepackage{xpatch}

\makeatletter

\newcommand{\othertableofcontents}{%
    \if@twocolumn
      \@restonecoltrue\onecolumn
    \else
      \@restonecolfalse
    \fi
    \chapter*{\contentsname
        \@mkboth{%
          \contentsname}{\contentsname}}%
    \@starttoc{toc}%
    \if@restonecol\twocolumn\fi
}
\makeatother

\xpatchcmd{\lstlistoflistings}{%\
  \tableofcontents}{%
  \othertableofcontents}{}{}

%\lst@UserCommand\lstlistoflistings{\bgroup
%    \let\contentsname\lstlistlistingname
%    \let\lst@temp\@starttoc \def\@starttoc##1{\lst@temp{lol}}%
%    \othertableofcontents \egroup}

\fancypagestyle{fancyplain}{%
\renewcommand{\headrulewidth}{0pt}
\fancyhf{}%
\renewcommand{\footrulewidth}{0pt}
\fancyfoot{\fancyplain}{}
}

\pagestyle{fancy}

\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{thesection\ #1}{}}

\renewcommand{\lhead}[1]{\fancyhead[OL,ER]{\fancyplain{}\chaptermark{#1}}}
\fancyhead[OR,EL]{\fancyplain{}\thepage}

\begin{document}

\chapter{My chapter}
\begin{lstlisting}[caption={My listing},label=lst:my_listing,language=C++]
  std::cout << "Hello World!" << std::endl;
\end{lstlisting}
\cleardoublepage

\lstlistoflistings
\addcontentsline{toc}{chapter}{Listings}
\thispagestyle{empty}
\cleardoublepage

\end{document}

Update
Since the O.P. requested to have non upper case headings for ToC, LoT etc, I suggest to use \cftmarkX from the tocloft package.
I've done this and redefined the relevant commands using \markboth{...}{...} for both margins of the page -- this is alright, since the O.P. does a redefinition later on anyway.
\documentclass[a4paper,twoside]{book}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage{listings}
\usepackage{tocloft}

\renewcommand{\cftmarktoc}{\markboth{\contentsname}{\contentsname}}
\renewcommand{\cftmarklof}{\markboth{\listfigurename}{\listfigurename}}
\renewcommand{\cftmarklot}{\markboth{\listtablename}{\listtablename}}

\fancypagestyle{fancyplain}{%
\renewcommand{\headrulewidth}{0pt}
\fancyhf{}%
\renewcommand{\footrulewidth}{0pt}
\fancyfoot{\fancyplain}{}
}

\pagestyle{fancy}

\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{thesection\ #1}{}}

\renewcommand{\lhead}[1]{\fancyhead[OL,ER]{\fancyplain{}\chaptermark{#1}}}
\fancyhead[OR,EL]{\fancyplain{}\thepage}

\begin{document}
\tableofcontents
\cleardoublepage
\listoffigures
\cleardoublepage
\listoftables
\chapter{My chapter}
\begin{lstlisting}[caption={My listing},label=lst:my_listing,language=C++]
  std::cout << "Hello World!" << std::endl;
\end{lstlisting}
\cleardoublepage

\lstlistoflistings
\addcontentsline{toc}{chapter}{Listings}
\thispagestyle{empty}
\cleardoublepage

\end{document}


text:
Q: Graphics Issue Since Update, Kubuntu Plasma, Seems Worse With Greater System Resource Use I recently had a big update to my system. Ever since, I've been having issues with my graphics, especially when the machine is under a heavier workload. I have a fast processor and lots of RAM and had no performance issues before the update. I can still work on huge music files, so the issue seems confined to graphics... although once when it got really bad my whole system froze up and I had to force shutdown with the power button.
The Problem
The issue is icons, menu items, tops of windows, and a few other things scrambling, usually when I move the cursor over them or the object itself is moving, as well as text while typing (in both Libre Office and the terminal). It's especially bad when Jack audio server is running and when opening/closing programs. When I let the system sit idle for a bit, the problem mostly goes away until I fire it up again.
Booting from earlier kernels, I get the same problem. Windows works fine, so I don't think it's a hardware issue. Video works fine, whether streaming or playing from a hard drive (i.e. via SMPlayer).
I'm too new to the site to upload photos to my post, but here are some links to pics of examples. Speaking of which, one odd thing is that the problem goes away the instant I press the screenshot button. I had to take these with my phone.
1 Pic of scrambled window
2 Pic of scrambled text
My Setup
Operating System: Kubuntu 20.04 (with current Ubuntu Studio 20.04 LTS installed overtop of it)

KDE Plasma Version: 5.18.8

KDE Frameworks Version: 5.68.0

Qt Version: 5.12.8

Kernel Version: 5.4.0-99-lowlatency (the low-latency kernel was added by Ubuntu Studio when I installed it over the original Kubuntu with generic kernel. I have access to both and they get updated at the same time.)

OS Type: 64-bit

Processors: 8 × Intel® Core™ i5-1035G1 CPU @ 1.00GHz

Memory: 19.3 GiB of RAM

QjackCtl version 0.5.0

Graphics info:

VGA compatible controller: Intel Corporation Device 8a56 (rev 07) (prog-if 00 [VGA controller])

Subsystem: Acer Incorporated [ALI] Device 1429

Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx+

Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-

Latency: 0, Cache Line Size: 64 bytes

Interrupt: pin A routed to IRQ 129

Region 0: Memory at 6000000000 (64-bit, non-prefetchable) [size=16M]

Region 2: Memory at 4000000000 (64-bit, prefetchable) [size=256M]

Region 4: I/O ports at 4000 [size=64]

Expansion ROM at 000c0000 [virtual] [disabled] [size=128K]

Capabilities: <access denied>

Kernel driver in use: i915

Kernel modules: i915

Fernando posted a workaround below that worked for him (which I might try), but I was hoping to get to the root of the problem. Could one of these updates have messed with my graphics? If so, can it be fixed, and how? (I would need specific instructions - I'm a lot better at driving Linux than understanding what goes on under the hood.)
Thanks in advance.

A: Alright, I fixed my problem. This solution doesn't get to the underlying cause of the issue, but it does make it go away. If you're seeing screen glitches like the ones shown in my pics AND you're using KDE Plasma, this could solve your problem as well.
The latest changes to Plasma were released around the time I got this particular batch of updates. They included optimizations which appear to have come with a bug. Luckily, I stumbled upon a solution, and it didn't require me to install or uninstall anything or work with the terminal.
Solution
I have always left the compositor OFF because I don't really like desktop effects. However, I just discovered that when I turn the compositor ON, the graphical glitches go away. Then I just turned off all the desktop effects I don't want to see.
To turn on the compositor, go to System Settings - Display and Monitor - Compositor. Tick the "Enable compositor on startup" box. Press "Apply" at bottom right and now you can close the window. (You should be able to go to the next step without a reboot.)
Then, if you don't like any of the effects you just enabled by turning on the compositor (i.e. sweeps, shadows, etc.): search in the application launcher for "Desktop Effects," open it, and you will see a list of all the available effects, which you can easily enable or disable. Press "Apply" to see the outcome of any changes you make. Press "Okay" when you're done and you're good to go.

A: I think I'm having the same problem, with an old software that must be run under wine there are scramblings/blur like effects.. The coincidence I have with you is that the i915 is the loaded video module. To stop this strange effect from ocurring I had to edit as sudo /etc/default/grub and change GRUB_CMDLINE_LINUX_DEFAULT="" to GRUB_CMDLINE_LINUX_DEFAULT="i915.modeset=0" after quitting and saving you must run sudo update-grub and reboot. No more strange effects, resolutions are limited and this is like a VESA mode, but as it works I think that means the probable culprit is i915


text:
Q: BackboneJS How to get nested attributes of model My Backbone Model is fetching data from an API as JSON
the structure is like:
 releases
     tracks
        length

Now I specifically want to the lenght of a track. How do achieve that?
I tried to do
afterRender: function(){
   this.model.get('releases.tracks.length');
   console.log(track);
}

but that didnt work, gives me 'undefined'
please help


text:
Q: when is the proper time to call UIObject.getOffsetWidth? i want get the uiobject's offsetwidth in gwt. but this value depends:

*

*where the uiobject attached or not?

*where relative css loaded or not?

*uiobject's size may be modified in onload callback.

*...

so, things get complicate, especially when you want get this value of FlowPanel,Label,InlineLabel,etc.. which size is dynamically calculated.
my question: when or how to get offsetwidth properly?

A: You can get the correct size only after the page is completely rendered. Otherwise you will get zero values. Typically, there are two use cases:
(A) Tell the browser to render your view. Then use Scheduler to make sure the browser has finished rendering, before you check for sizes:
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
    @Override
    public void execute() {
        int width = myPanel.getOffsetWidth();
        // do something with this width
    ]
]

(B) Attach a resize handler to a Window. If a user changes the browser's window size, all width and heights may change. You don't need to use a Scheduler in the ResizeHandler - a browser will complete re-rendering the page before calling the ResizeHandler.


text:
Q: How to create a range query on array Here is the result of the query:
{
  "query": {
    "match_all": {}
  }
}

{
  "data": [
    {
      "hits": [
        {
          "_source": {
            "AR_UnitePoids": 3,
            "CatTarif": [
              {
                "PVTTCSite": 1
              },
              {
                "PVTTCSite": 2
              }
            ]
          }
        },
        {
          "_source": {
            "AR_UnitePoids": 5,
            "CatTarif": [
              {
                "PVTTCSite": 3
              },
              {
                "PVTTCSite": 4
              }
            ]
          }
        }
      ]
    }
  ]
}

If I want to get documents with AR_UnitePoids >= 5, I can do:
{
  "query": {
    "range": {
      "AR_UnitePoids": {
        "gte": 5
      }
    }
  }
}

{
  "data": [
    {
      "hits": [
        {
          "_source": {
            "AR_UnitePoids": 5,
            "CatTarif": [
              {
                "PVTTCSite": 3
              },
              {
                "PVTTCSite": 4
              }
            ]
          }
        }
      ]
    }
  ]
}

But now I want all documents where the second PVTTCSite of CatTarif is higher than 4:
{
  "query": {
    "range": {
      "CatTarif.1.PVTTCSite": {
        "gte": 4
      }
    }
  }
}

But this query doesn't work, I get 0 hits.
How can I do this ?
Edit:
Thank to @TusharShahi comment and this doc I managed to create this query:
{
  "query": {
    "nested": {
      "path": "CatTarif",
      "query": {
        "bool": {
          "must": [
            { "range": { "CatTarif.PVTTCSite": { "gte": 4 } } }
          ]
        }
      }
    }
  }
}

which works but I still can't query on a specific index of the CatTarif.

A: {
  "query": {
    "nested": {
      "path": "CatTarif",
      "query": {
        "bool": {
          "must": {
            "range": {
              "CatTarif.PVTTCSite": {
                "gte": 4
              }
            }
          },
          "filter": {
            "term": {
              "CatTarif.CatTarif": 1
            }
          }
        }
      }
    }
  }
}


text:
Q: how to point to a value in an arrayand use a method on it in java Hey I have the following codes, I want to check if the scanned item's value is the same as a value in one of the arrays, but struggling to get the code figured out, does anybody have any idea??
I am really struggling with this whole array coding, I know my code is long but please if you have an idea tell me.
And please only the constructive comments not wiseguys who judge me of my limited java knowledge, as I am a beginner in java.
   `package Library;
public class exercising 2 {
public static int id;

public exercising 2(){

    id=0;
    }
    public exercising 2(int _id){
        id=_id;
  }
    public void set id(int _id){
        id = _id;
  }

    public int get id(){
    return id;
  }
}*`

 * package Library;
import java.util.Scanner;
import java.util.Arrays;
public class learning {
public static void main(String args[]){

 exercising 2 exercising 1 = new exercising 2();

Scanner Reader = new Scanner(System.in);
exercising 2[] exercise = new exercising 2[5];
exercise[0] = new exercising 2(12345);
exercise[1] = new exercising 2(678910);
exercise[2] = new exercising 2(1112131415);
exercise[3] = new exercising 2(1617181920);
exercise[4] = new exercising 2(2122232425);
System .out .print l n("write your id no");

int get Id = Reader . next Int();
boo lean can Loan= false;
int i = 0;
 if(get Id==exercise .hash Code()exercising 1.get id(){
System .out .print l n("you can't loan");;
}
else{
can Loan=false;
System .out. print l n("you're okay");
}
}
}*"

A: Names in Java need to be in one word, consisting of letter and digits (underscore is allowed but discouraged). No spaces. So you class should be called Exercising2, not exercising 2. Similarly, your methods should be called setId and getId. Names consisting of more words are generally written in so-called camel case, where each word (excpet the first) is capitalized to make it clearer where a new word begins (now there are no spaces). When you want to call a mwthod named println you also need to type the name in one word without any spaces.
I am assuming that the backticks, asterisks and double-quote in you code are from your presentation on Stack Overflow and are not present in your real code. They should not be, at least.
Now we're discussing names, the conventions say library with a small l, package names are the exception to the camel case rule, they never have any capital letters at all. Class names should begin with a capital letter, so it's Exercising2 (as I have already mentioned) and Learning. Variables begin with a small letter, so it's reader with a lowercase r. While you are programming just for yourself, you may think that you don't need to care, but as soon as you want someone else to look at your code, for instance here on Stack Overflow, you will get more positive response if you try to stick to the conventions.
PS Something's gone wrong in this line:
if(get Id==exercise .hash Code()exercising 1.get id(){

If you tell us what you intended, someone may be able to guide you.


text:
Q: GridSplitter not splitting correctly I have the following grid
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

my GridSplitter is on Row 3 (4th row), define as follow:
<GridSplitter Grid.Row="3"
              ResizeDirection="Rows"
              Style="{StaticResource HorizontalGridSplitter}"
              IsTabStop="False" />
<Style x:Key="HorizontalGridSplitter"
       TargetType="{x:Type GridSplitter}">
    <Setter Property="Height"
            Value="4" />
    <Setter Property="HorizontalAlignment"
            Value="Stretch" />
    <Setter Property="VerticalAlignment"
            Value="Stretch" />
    <Setter Property="Margin"
            Value="0" />
</Style>

When I drag the split in order to split row 2/4, It doesn't really split the rows, it seems like the grid height gets bigger.

A: The GridSplitter has three different resize behaviours, as you can see below:

The GridSplitter re-sizes the specified two columns/rows according to the selected ResizeBehaviour and according to the available space for them, in your case you specified * height for the row before, and Auto height for the row after, which mean it can re-size only the row before, the row after will always remain Auto:

To fix this issue you have to set the row before and the row after to Width="*" and set the re-size behavior to ResizeBehavior="PreviousAndNext" see the following code snippet:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <GridSplitter Grid.Row="3" ResizeDirection="Rows"
                  Style="{StaticResource HorizontalGridSplitter}"
                  IsTabStop="False" HorizontalAlignment="Stretch"
                  ResizeBehavior="PreviousAndNext" />
</Grid>

It also better to set the height of all other rows to Auto or to a fixed value to avoid any weird behaviors :)


text:
Q: change the path where cronjob writes to I have a node js script which writes to a file in the same location where the nodejs script is.
I created a shell script to call this nodejs script (and some other commands which takes the output file from nodejs as input)
I schedule this shell script as a cron job. Now the output from nodejs gets saved in my /home folder. How do I change this so the file is in script folder?
I can't change this nodejs script since its from another team.

A: I think running you shell script that calls the nodejs script from inside the script folder is might work.
Either that or the nodejs script writes to "/filename" instead of "./filename" which i think you can only fix by changing the nodejs script, maybe ask the team that made it.

A: so i found a way, in crontab i did cd  and then script name.
0 0 * * * cd <path to scripts> && ./<script> >> <path/log.out> 2>&1


text:
Q: How can I prove that the cadinality of a set minus a finite number of elements of it is still the same as the original set? A is a finite subset of S, which is an infinite set.
How can I prove that $|S| = |S \setminus A|$?
I just finished proving that $|T \cup S|$ where $T$ is infinite and $S$ is countable is $|T|$. They seem related but I can't solve it because I am confused by the concepts.
Can someone help me?

A: Given that you proved that $|T\cup S| = |T|$ if $|T|$ is infinite and $|S|$ is countable, you can consider the identity $$S = (S\setminus A)\cup A.$$
Here, $A$ is countable (because it's finite), and $S\setminus A$ is infinite (because if it were finite then so would be $S$). By your identity,
$$|S| = |S\setminus A|.$$
In general, if $X$ and $Y$ are disjoint then $|X \cup Y| = |X| + |Y|$. When not both summands are finite, cardinal addition breaks down into taking maxes: $$|X| + |Y| = \max\{|X|, |Y|\}.$$
In your situation, let $X = S\setminus A$ and let $Y = A$.


text:
Q: Java JSONObject value cast to User I don't know that how can I do that Server send to client JSONObject. JSONObject has User but when Client get it then I can't cast to User.
I tried that I send list but the JSONObject doesn't let me.
Is it possible that I put User into JSONObject and after Client read it and cast to User ?
And what list has user and list put into JSONObject ?
Exception: Exception in thread "Thread-4" java.lang.ClassCastException: java.lang.String cannot be cast to application.User
Server.java :
message = new SerializableJSONObject(new JSONObject());
        message.getJSONObject().put("action", "friendsList");
        List<User> list = new ArrayList<User>();
        for (String s : userDatabase.getFriends(email)) {
            User u = server.getUser(s);
            if (u == null) {
                u = userDatabase.getFriendData(s);
            }else {
                u = u.getUser(); // getUser doesn't have Socket
                System.out.println(u.getEmail() +" -> "+u.getOutput() + ", "+u.getInput());
            }
            message.getJSONObject().put(email, u);

        }
        //message.getJSONObject().put("list", list);
        message.writeObject(out);

Cleint.java :
while(true) {
            json.readJSONObject(in);
            System.out.println("Receive: "+json.getJSONObject().get("action"));
            switch (json.getJSONObject().getString("action")) {
            case "login":
                LoginController.receiveMessage(json.getJSONObject());
                break;
            case "friendsList":
                List<User> list = new ArrayList<>();
                //SerializableJSONArray mA = (SerializableJSONArray)json.getJSONObject().get("list");
                //System.out.println(mA.getJSONArray().get(0));
                Iterator<String> keys = json.getJSONObject().keys();
                while(keys.hasNext()) {
                    String key = (String) keys.next();
                    System.out.println(json.getJSONObject().get(key));
                    list.add((User) json.getJSONObject().get(key));
                }
                MainController.addFrriendsList(list);
                break;
            default:
                break;
            }

        }

SerializableJSONObject.java :
public class SerializableJSONObject implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 11;

private transient JSONObject json;

public SerializableJSONObject(JSONObject json) {
    this.json = json;
}

public JSONObject getJSONObject() {
    return json;
}

public void writeObject(ObjectOutputStream out) throws IOException {
    out.writeObject(json.toString());
}

public void readJSONObject(ObjectInputStream in) throws ClassNotFoundException, IOException, JSONException {
    json = new JSONObject((String) in.readObject());

}
}

User.java :
public class User implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 11;

private String email;
private String name;
private Status status;
private ObjectOutputStream out;
private ObjectInputStream in;

public User(ObjectOutputStream out, ObjectInputStream in) {
    super();
    this.out = out;
    this.in = in;
}

public User(String email, String name, Status status, ObjectOutputStream out, ObjectInputStream in) {
    super();
    this.email = email;
    this.name = name;
    this.status = status;
    this.out = out;
    this.in = in;
}

public User(String email, String name, Status status) {
    super();
    this.email = email;
    this.name = name;
    this.status = status;
}

public String getEmail() {
    return email;
}

public String getName() {
    return name;
}

public Status getStatus() {
    return status;
}

public void setStatus(Status status) {
    this.status = status;
}

public ObjectOutputStream getOutput() {
    return out;
}

public ObjectInputStream getInput() {
    return in;
}

public User getUser() {
    return new User(getEmail(), getName(), getStatus());
}

A: In Server.java:
List<User> list = new ArrayList<User>();
//...
//message.getJSONObject().put("list", list); //list has type List<User>
//..

In Client.java
//...
//SerializableJSONArray mA = (SerializableJSONArray)json.getJSONObject().get("list");
//here list is of type List<User> not SerializableJSONArray
//...
//List<User> is not convertable to SerializableJSONArray.

Maybe you should construct a jsonArray from your ArrayList in Server.java first and then put it in the jsonObject Map.

*

*JsonArrayBuilder Class to create a JsonArray.

*Method to add a JsonObject to the JsonArray

*JsonObject method to return JsonArray
I hope it helps.


text:
Q: getting lat long from adding multiple markers on google maps I'm trying to find lat and long that I've added on maps. I've aldready tried so many things but can't figured out.
here is my full code
function initialize() {
  var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(41,29),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  google.maps.event.addListener(map, 'click', function(e) {
    placeMarker(e.latLng, map);
  });
}

function placeMarker(position, map) {
  var marker = new google.maps.Marker({
    position: position,
    map: map,
draggable: true
  });
  map.panTo(position);
}

google.maps.event.addDomListener(window, 'load', initialize);

A: supernova is right - Google Maps API does not provide a way to reference markers once they have been added to the map in any other way than by keeping the original google.maps.Marker. A simple solution is to define an array outside of your function and to push all your markers on it one by one as they are created. A function for this could be similar to this:
(function() {
   var markers = [];
   window.addMarkerToMap(parameters, map) {
     var params = parameters || {};
     params.map = map;
     var marker = new google.maps.Marker(params);
     markers.push({ "object": marker, "lat": params.position.lat(), "long": params.position.long() });
     return marker;
   };
   window.getMarkers() {
     return markers;
   };
})();

This gives you the addMarkerToMap() global function with signature: parameters: Object, map: google.map. Every time you add a marker using it, it will be available in the array returned by window.getMarkers(). From there, the marker is conveniently in object, while lat/long coordinates are in lat and long respectively.


text:
Q: Vb.net regex escaping optional backslash optional in the end of a string I have a string and i want to know if it includes some pattern in the end of it.
I want to know if it has "jobs" or "jobs/" the "/" is optional
for example:
www.example.jobs/
www.example.jobs
So far i have this:
 \.(com|org|edu|net|jobs?/|gov)$

The problem is that if i have a string that ends with "jobs" it doesn't catch it.

A: Just add ? optional quantifier to /
\.(com|org|edu|net|jobs?/?|gov)$

Regex Demo

*

*/? ensures that the / is matched zero or one time, making it optional

A: You need to escape the / so the pattern becomes
.+\.(?:com|org|edu|net|jobs|gov)\/?$

demo


text:
Q: How to get an NSarray of all file names in a directory on a remote server? How do I get an NSArray of the NAMES of all files stored in a specific directory such as: "http://www.someurl/somedirectory/"?

A: That's really something that has to be generated server-side, then parsed on the device. I know Apache has an option where you can turn on Directory Indexes, so you could do that, then download the generated directory index and parse the HTML (using an NSXMLParser or some other parsing library), adding an NSString to an NSMutableArray every time you find a file name.

A: Should be something along these lines..
NSURL* url = [NSURL URLWithString: @"http://address.tld/path/files.txt"];
NSString* data = [NSString stringWithContentsOfURL: url];

if(data)
{
    NSArray* files = [data componentsSeparatedByString: @"\n"];

    for(NSString* filename in files)
    {
        NSLog(@"%@", filename);
    }
}


text:
Q: How to initiate a logout with MSAL2Provider I am using the React Login Microsoft-Graph-Toolkit component (see snippet Below) and MSAL2Provider to log users into my Active Directory application, which works well. However, I have a requirement to logout a user from a custom logout button.  The button should be able to logout the current user session. Can anyone advise how do to initiate a login/logout using MSAL2Provider?
Code Snippet:
Providers.globalProvider = new Msal2Provider({
   clientId: "client-id"
 });

 <Login
   loginCompleted={(event) => {mgtSSOLoggedIn(event)}}
   loginFailed={(event) => {mgtSSOFailed(event)}}
 />

A: Actually, I was looking for the authentication process for MSALProvider.  Please see link for details: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md.


text:
Q: AzureDevOps clone and commit external repo I have a azure devops pipeline which checkout a github repo , i also want to have a bash task to checkout another repo and modify it , check it back in .
git clone https://$(githubApiKey)@mygithub.private.com/myrepo/ops-one-code.git

Error message:

fatal: could not read Password for 'https://***@mygithub.private.com':
terminal prompts disabled

A: Did you generate personal access token on GitHub?
Just create new token from the below page with needed scopes:

settings > developer settings > personal access tokens > generate new
token

Then use git clone command like below:
git clone https://auth-token-goes-here@mygithub.private.com/myrepo/ops-one-code.git

A: You can accomplish your requested task using two powershell tasks:
Task to checkout a Github repository:
- task: PowerShell@2
  displayName: Checkout Repo
  inputs:
    targetType: 'inline'
    script: |
      git config user.email "user.email"
      git config user.name "user.name"
      Remove-Item s1 -Recurse -Force -ErrorAction Ignore
      git clone https://username:$(PAT)@github.com/org/repo.git s1
      cd s1
      git checkout main
    workingDirectory: '$(Pipeline.Workspace)'

Task to push back on the Github repository
- task: PowerShell@2
  displayName: Push git changes
  inputs:
    targetType: 'inline'
    script: |
      git config user.email "user.email"
      git config user.name "user.name"
      git add --all
      git commit -m "message"
      git push https://username:$(PAT)@github.com/org/repo.git s1
    workingDirectory: '$(Pipeline.Workspace)/s1'

A: Problem was the azure variable was a secret and it didn't work with it hence it prompted for the password


text:
Q: Screensaver does not offer option to use any photos On iMac with Yosemite, my screensaver has lost the option to use photos.  Where there should be an option to select a photos folder there is only a bar "Screen Saver Options" i.e. color, speed etc of the cg saver options which are still available.  If I try to select a photo option e.g. "Photo Mobile" I get an endless rotating color disk.
I have tried reinstalling Yosemite, deleting all screensaver-related plists in preferences and rebuilding iPhoto, with no luck.
Any suggestions?

A: [[Note: if you see a spinning "Beachball" it may be that your photo library is quite large so the processor may need time to display everything.  You may find that placing photos you wish to display in a folder stored outside of iPhoto or the Photos app will improve performance.]]
Assuming you have photos in a folder or imported into the Photos app, this procedure should help.

*

*Go to System Preferences

*Select Desktop & Screen Saver

*Select the Screen Saver tab

*Choose one of the photo type screen saver options such as Floating or Reflections

*From the Source pop-up menu select your source from Photos or a folder with your pictures by selecting Choose Folder... or Photo Library...


text:
Q: Not able to get response_body from response hash I made a call and in response I am getting like this:
   http_response = make_request
   => #<Faraday::Response:0x00007fa2adf6b010
   @env=
   #<struct Faraday::Env
     method=:post,
     request_body=
     "{\"abc\":\"abc\",\"xyz\":\"xyz\"}",
     url=#<URI::HTTPS https://localhost:3000/user/data>,
     request=
      #<struct Faraday::RequestOptions
      params_encoder=nil,
      proxy=nil>,
      request_headers={"Content-Type"=>"application/json", "Accept"=>"application/json", "User-Agent"=>"Grab"},

      response=#<Faraday::Response:0x00007fa2adf6b010 ...>,

      status=200,
      reason_phrase="OK",
      response_body=
        "{\"abc\":\"abc\",\"xyz\":\"xyz\"}">,
     @on_complete_callbacks=[]>

I want to fetch response_body from http_response. How can I get it and how can I compare this with actual object in rails rspec.
In rspecs:
      expect(response).to eq true

A: Have you tried below to parse response
JSON.parse(http_response.body)


text:
Q: Why ArrayList.addAll(...) doesn't check the given colleciton for nonempty? We found out that ArrayList.addAll(...) method doesn't check if the given collection is not empty.
It means we will re-allocate memory (System.arrayCopy(...) will be called) even if we don't actually need it.
Shoud we add an IF check for an optimization?
For example:  elapsed time for the first code is more than 8 times faster than the second one.
It seems like our optimization works properly, so why it wasn't implemented already?
List<Integer> existed = new ArrayList<>();
List<Integer> empty = new ArrayList<>();
for (int i = 0; i < 100_000_000; i++) {
    if(!empty.isEmpty())
       existed.addAll(empty);
}

VS
List<Integer> existed  = new ArrayList<>();
List<Integer> empty = new ArrayList<>();
for (int i = 0; i < 100_000_000; i++) {
    existed.addAll(empty);
}

A: In JDK14 ArrayList.addAll() makes a copy of the collection to add as an array and increments the ArrayList modification count - even if there are no elements to add.
public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    modCount++;
    int numNew = a.length;
    if (numNew == 0)
        return false;
    ...

So your testcase which is not using isEmpty() beforehand, it will cause unnecessary allocation of 100,000,000 instances of new Object[0] and increments the modification count same number of times and which would explain why it appears slower.
Note that System.arrayCopy is not called unless the array is growing beyond the capacity of the existing array.
I've scanned in my own code just now and I doubt whether adding the isEmpty() test would speed up the code as there is generally something to add each time, and so putting in these extra checks would unnecessary. You'd need to decide for your own situation.


text:
Q: How to use Yolo V5 in C# with a GPU? I spend the last days trying to get Yolo to work on my GPU. I tried using https://github.yuuza.net/mentalstack/yolov5-net, I followed their guide to use GPU and it didn't work. All other C# Yolo wrappers are not using the Yolov5 version and I want to use this one. So my question is, how can I use YoloV5 in C# (.net 5.0) with my GPU. Here is the code I used with yolov5-net :
using var image = Image.FromFile(path);

            using var scorer = new YoloScorer<YoloCocoP5Model>("tinyyolov2-8.onnx");

            List<YoloPrediction> predictions = scorer.Predict(image);
            using var graphics = Graphics.FromImage(image);

            foreach (var prediction in predictions)
            {
                double score = Math.Round(prediction.Score, 2);

                graphics.DrawRectangles(new Pen(prediction.Label.Color, 8),
                    new[] { prediction.Rectangle });

                var (x, y) = (prediction.Rectangle.X - 3, prediction.Rectangle.Y - 23);
                graphics.DrawString($"{prediction.Label.Name} ({score})",
                    new Font("Arial", 40, GraphicsUnit.Pixel), new SolidBrush(prediction.Label.Color),
                    new PointF(x, y));
            }
            Console.WriteLine(outputPath);
            image.Save(outputPath);

The above code works, but it eats my CPU, and it's clearly not possible to use this to process many images fast.

A: you can try this:
using var image = Image.FromFile(path);
var options = SessionOptions.MakeSessionOptionWithCudaProvider(0);
using var scorer = new YoloScorer<YoloCocoP5Model>("Assets/Weights/yolov5n.onnx", options);

make sure you installed CUDA toolkit and cudnn.
this code maybe work or not, i'm not sure but you can try this, that's all I can help


text:
Q: Help with VF page and Querying OpportunityLineItems I am doing some work for a client and they have asked if I could make a "child/parent" relationship between OpportunityLineItem (OLI) records.
I have been told by someone they have seen it done before and it has been done by adding a lookup to the Product2 to another Product2 record.
The client then wants the OLI parents to be displayed on a page (I will be using apex:repeat for this due to the table style), they they want a nested table within this table where they display the child OLI's. I have been able to work the VF side so far and it all looks good.
However I have been racking your brains trying to work out how to do this... but I just can not get it to work D: does anyone have any ideas or pointers?
I just need the most basic set of fields from the OLI's to display, it's literally just the Name, Quantity, Discount, ListPrice, UnitPrice and TotalPrice from both the parent and child.
****UPDATE****
I am displaying the Opp at the top of a VF page, then under that I need to display a table of all of the Parent/"Master" OLI's and in each OLD row, I need to display the Child/"Extra" OLI's so it will be kind of like this:
-------- Opp Info --------
| Name        Stage      |
--------------------------
|  OLI 1 Master Details  |
|                        |
|  --------------------- |
|  |OLI 1 Child Details| |
|  --------------------- |
--------------------------
|  OLI 2 Master Details  |
|                        |
|  --------------------- |
|  |OLI 2 Child Details| |
|  --------------------- |
--------------------------

A: I worked this out in quite a long winded way, but it seems to be displaying okay so far...
Method:
Map<OpportunityLineItem, List<OpportunityLineItem>> masterToExtraMap = new Map<OpportunityLineItem, List<OpportunityLineItem>>();
List<OpportunityLineItem> liList = new List<OpportunityLineItem>();
liList = [SELECT Id, Name, Quantity, ListPrice, Description, ProductCode, TotalPrice
          FROM OpportunityLineItem
          WHERE OpportunityId =: opp.Id
          AND Product2.RecordType.Name =: 'Master'];

for(OpportunityLineItem oli : liList){
    List<OpportunityLineItem> extraLi = new List<OpportunityLineItem>([SELECT Id, Name, Quantity, ListPrice, Description, ProductCode, TotalPrice
                                                                       FROM OpportunityLineItem
                                                                       WHERE Product2.Master_Product__c =: oli.Product2Id
                                                                       AND Product2.RecordType.Name =: 'Extra']);
    masterToExtraMap.put(oli, extraLi);
}

oppLineItems = masterToExtraMap;

Then I am using apex:repeat nested in an apex:outputPanel which is surrounded in an apex:repeat again....
As I said it's long winded but seems to work okay :)

A: Unless you have a field that shows the child relationship between the Parent OLI, I'm not entirely certain how you can accomplish what you're asking other than perhaps by sorting the returned records by CreatedDate and Product2Id. Assuming you have the Actual OppId, I'd expect the query to look something like this:
list<OpportunityLineItem>OLI = [SELECT ID, Name, Quantity, ListPrice, UnitPrice,
  TotalPrice, Product2ID, CreatedDate OpportunityId FROM OpportunityLineItem
  WHERE OpportunityId =: ActualOpp.Id ORDER BY Product2ID ];

You should be able to do an ORDER BY on this without needing to make it an AggregateResult. Optionally, you could also add the CreatedDate after the Product2Id as a secondary sort if you don't have a field that allows you to generate the parent-child relationship you're looking for. I've assumed they'd have the same Product2Id, but I could be wrong on that as only you would know. Whatever the criteria is, use it in your Order By clause, then put the results in a wrapper class.


text:
Q: piping find into grep I am trying to pipe find into grep with the negative match option but I don't get the desired results. I am using the Ubuntu subshell for Windows and running the command:
find / -name CCP.cf | grep -v '*denied'

This produces the output (a lot omitted for brevity):
find: '/mnt/c/Config.Msi': Permission denied
find: '/mnt/c/Intel/IntelOptaneData': Permission denied
find: '/mnt/c/Program Files/WindowsApps': Permission denied

Is this printout from the find and can it not be directed to grep?
Essentially I want to be able to use find and it return the directory of the file to me (I'm going to wrap it into a function later).

A: The error messages go to standard error, but you're only piping standard output to grep. To redirect stderr as well, use 2>&1, this redirects stderr (FD 1) to stdout (FD 1), which has already been redirected to the pipe.
find / -name CCP.cf 2>&1 | grep -v 'Permission denied'

You could also just filter out all error messages:
find / -name CCP.cf 2>/dev/null


text:
Q: CodeIgniter Library: Access to CodeIgniter Superobject causes PHP Error of Severity:Notice I have a CodeIgniter library. When I access it from my controller a PHP Error of Severity:Notice is generated. However, the debugger shows that the super object exists in the library and is the CI super object.
Here is the library class:
    class Auth_lib {

    protected $CI;

    public function __construct()
    {
        $this->$CI =& get_instance();
        $this->$CI->load->model('auth_model');
        $this->$CI->load->library('session');
    }

    /**
     * checks if the current user is logged into a session
     * @param
     * @return boolean
     */
     public function is_logged_in(){
        $result = $this->$CI->session->userdata('is_logged_in');
        return $result;
    }
}

And this is how the library is called from my controller:
        public function __construct()
        {
            parent::__construct();
            $this->load->helper('url_helper');
            $this->load->library('auth_lib');

            // test if user is logged in and authorised, if not redirect to login controller

            if($this->auth_lib->is_logged_in() != null){
                // check if is admin
                }
            } else {
                // not logged in, redirect to login controller
            }

        }

So, why I am getting this error:

A PHP Error was encountered
  Severity: Notice
  Message: Undefined variable: CI
  Filename: libraries/Auth_lib.php
  Line Number: 20

A: *

*Use $this->CI instead of $this->$CI.

*return isset($result)?TRUE:FALSE; from library's is_logged_in() function.
libraries/Auth_lib.php
class Auth_lib {

  protected $CI;

  public function __construct()
  {
    $this->CI =& get_instance();
    $this->CI->load->model('auth_model');
    $this->CI->load->library('session');
  }

/**
 * checks if the current user is logged into a session
 * @param
 * @return boolean
 */
   public function is_logged_in(){
     $result = $this->CI->session->userdata('is_logged_in');
     return isset($result)?TRUE:FALSE;//make sure that you have set  session or not
   }
}

Controller
public function __construct()
    {
        parent::__construct();
        $this->load->helper('url_helper');
        $this->load->library('auth_lib');

        // test if user is logged in and authorised, if not redirect to login controller

        if($this->auth_lib->is_logged_in()){
            // check if is admin
            }
        else {
            // not logged in, redirect to login controller
        }

    }


text:
Q: http_ssl_module failed to install when compile from source code of nginx I am trying to setup my https using certbot , so I need to recompile ngx adding '--with-http_ssl_module', here is the complete steps:
 - sudo make clean  sudo
 - ./auto/configure --prefix=/var/www/html
   --sbin-path=/usr/sbin/nginx --conf- path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log
       --error-log-path=/var/log/nginx/error.log --with-pcre --with-http_ssl_module  --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --modules-path=/etc/nginx/modules
 - check Makefile , I can see 'http_ssl_module' added in objs/Makefile
 - ./auto/configure sudo make sudo make install

After completed all steps above(no error observed) I checked 'ngx_modules.o'(still missing ssl module) and ran command below
sudo certbot --nginx -d feedme.pub
Saving debug log to /var/log/letsencrypt/letsencrypt.log
The nginx plugin is not working; there may be problems with your existing configuration.
The error was: PluginError('Nginx build is missing SSL module (--with-http_ssl_module).')

Also , I checked my ssl lib- libssl is intalled:
ldconfig -p | grep libssl
    libssl3.so (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libssl3.so
    libssl.so.1.1 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libssl.so.1.1
    libssl.so.1.0.0 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libssl.so.1.0.0
    libssl.so (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libssl.so

Anyone can help to answer why I am not able to build '--with-http_ssl_module' in ?


text:
Q: Prism 4.1 How to loading modules with directory scan andapply them to mvvm pattern for navigation In prism 4.1 I want to use module loading and build my project using mvvm.
Now I register the module using directory scanning,but navigation is not possible in the view model
the code for the module
[Module(ModuleName = "ModuleA", OnDemand = true)]
public class ModuleAModule : IModule
{
    private IRegionManager RegionManager { get; set; }
    private ViewA ViewA;

    public ModuleAModule(IRegionManager RegionManager, IUnityContainer container)
    {
        if (RegionManager != null)
        {
            this.RegionManager = RegionManager;
        }
        if (container != null)
        {
            this.container = container;
        }
    }

    public void Initialize()
    {
        this.container.RegisterType<object, ViewA>(nameof(ViewA));

        IRegion MathRegion = RegionManager.Regions["ContentRegions"];
        MathRegion.Add(this.ViewA, "ViewA");
    }
}

Then I start in Bootstrapper
 class Bootstrapper : UnityBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        return ServiceLocator.Current.GetInstance<MainWindow>();
    }

    protected override void InitializeShell()
    {
        base.InitializeShell();
        Application.Current.MainWindow.Show();
    }

    protected override IModuleCatalog CreateModuleCatalog()
    {
        return new DirectoryModuleCatalog() { ModulePath = @".\Modules" };
    }
}

I wrote it like this in the view model
class MainWindowViewModel : NotificationObject
{
    private readonly IRegionManager _regionManager;
    public DelegateCommand<string> NavigateCommand { get; private set; }

    public MainWindowViewModel(IRegionManager regionManager)
    {
        _regionManager = regionManager;
        NavigateCommand = new DelegateCommand<string>(Navigate);
    }

    private void Navigate(string navigatePath)
    {

        if (navigatePath != null)
            _regionManager.RequestNavigate("ContentRegion", new Uri(navigatePath, UriKind.Relative));
    }
}

Xaml in MainWindow:

<DockPanel LastChildFill="True">
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Top" Margin="5">
        <Button Command="{Binding NavigateCommand}" CommandParameter="ViewA" Margin="5">NavigateCommand A</Button>
    </StackPanel>
    <TabControl prism:RegionManager.RegionName="ContentRegions" Margin="5"/>
</DockPanel>

    public MainWindow(IRegionManager region)
    {
        InitializeComponent();
        this.DataContext = new MainWindowViewModel(region);
    }

I can't use the buttons to navigate right now, nothing happens after clicking. Is it because I made a mistake when registering the module? Or is the module not found for other reasons?

A: You want to register ViewA for navigation, not add it to the region immediately.
That is:
container.Register<object, ViewA>( nameof(ViewA) );

then, upon RequestNavigate, the container will create a new instance and the region manager will put it in the region.


text:
Q: Creating A Custom Excel Report I should be able to customize excel script reports here:
C:\Users\ [user] \sahi_pro\config\reports\excel\script_report
As explained here: http://sahipro.com/docs/faq/how-to-customize-html-reports.html
When I make changes, they don't apply.

*

*Edit the script_report XSLT Stylesheet

*Run a script

*Go to logs

*Click on the script that's ran. Should see the script report.

*Click on the excel icon on the top right.

This should produce the customized excel report.
I tested to see if the html reports could be edited and I can custom html reports anyway I want using this method.

A: Editing the XSLT Stylesheets seem to be working for the html reports, not excel sheets. To write custom excel reports, I am using the "Sahi Pro - File Manipulation APIs" in my scripts.
http://sahipro.com/docs/sahi-apis/file-apis.html#_writeCSVFile


text:
Q: Passing parameter to the drill thru report in cognos How to Pass a Calculated Member/measure to a Drill-thru Target Report
In order to avoid using Calculated Members--because from googling some people were saying you could not pass them via Drill-thru--I went back to my FM model and created 3 new measures (High Risk, Low Risk and Medium Risk). Now these will show up in the drill-thru definitions parameter list . . . my only problem is that how can I do a check to see which of the three measures has been selected by a user?
Remember, I basically have a line chart with 3 lines, one for each measure above (High, Medium or Low Risk) by time frame. A user will select a data point, High risk for March or Medium Risk for Semester 2, for example. I then need to pass the value for that datapoint to my Target (2nd) report. How can I check for which of the three measure values they passed through?!?