text:
Q: value of jquery with autoNumeric textbox into c# I have 4 textboxes, in 3 of them can numbers be insert and the 4th will output the sum.
Now I'm trying to get the sum to c# as an integer, so I try it with an hidden field "HF_ProjekteGK".
This is my jquery code:
 <script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="Scripts/autoNumeric.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#<%= TB_ProjekteGK.ClientID%>').autoNumeric({ aSep: '.', aDec: ',', aSign: ' €', pSign: 's', aPad: false });
        $('#<%= TB_ProjekteAK.ClientID%>').autoNumeric({ aSep: '.', aDec: ',', aSign: ' €', pSign: 's', aPad: false });
        $('#<%= TB_ProjekteMAE.ClientID%>').autoNumeric({ aSep: '.', aDec: ',', aSign: ' €', pSign: 's', aPad: false });
        $('input:text[id$=TB_ProjekteSumme]').autoNumeric('init', { aSep: '.', aDec: ',',     aSign: ' €', pSign: 's', aPad: false });
});
</script>

<script type="text/javascript">
    $(function () {
        var textBox1 = $('input:text[id$=TB_ProjekteGK]').keyup(projekte);
        var textBox2 = $('input:text[id$=TB_ProjekteAK]').keyup(projekte);
        var textBox3 = $('input:text[id$=TB_ProjekteMAE]').keyup(projekte);

     function projekte() {
            var value1 = textBox1.autoNumeric('get');
            var value2 = textBox2.autoNumeric('get');
            var value3 = textBox3.autoNumeric('get');
            var projekte = add(value1, value2, value3);
            $('input:text[id$=TB_ProjekteSumme]').autoNumeric('set', projekte);

            $("#HF_ProjekteGK").val(projekte);

        }
     function add() {
            var sum = 0;
            for (var i = 0, j = arguments.length; i < j; i++) {
                if (IsNumeric(arguments[i])) { sum += parseFloat(arguments[i]); }
            }
            return sum;
        }
        function IsNumeric(input) {
            return (input - 0) == input && input.length > 0;
        }
    });

     </script>

This runs and $("HF_ProjekteGK").val(gesamtsumme); shows the right sum.
Now I'm trying to catch the value to the hidden field:
 protected void Button1_Click(object sender, EventArgs e)
    {
        int test = Convert.ToInt32(HF_ProjekteGK.Value);
    }

Here I get an exception that the input string has no correct format becaue it is null. How can I fix this? Thanks!


text:
Q: run jar file from c++ I am runing the follwing c++ code and the value of "ret" is -1 (the create of javavm is falid)
what is the problem with the code?
#include <iostream>
#include <conio.h>
#include <jni.h>
using namespace std;
#pragma comment (lib,"jvm.lib");

int main(){
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;

options.optionString="hello.jar";
vm_args.version=JNI_VERSION_1_6;
vm_args.nOptions=1;
vm_args.Option=&options;
vm_args.ignoreUnrecognized=0;
int ret=JNI_CreatJavaVM(&jvm,(void**)&env,&vm_args);

 }

thats for the help

A: If you pass in an invalid option to the CreateJavaVM call, because of the ignoreUnrecognized = 1 it will fail to launch the JVM.
When I create a simple jar with a public static void main method, and use the following code, it correctly invokes the main method:
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;
options.optionString = "-Djava.class.path=hello.jar";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;
int ret = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (ret == 0) {
    jclass cls = env->FindClass("hello");
    if (cls != 0) {
        jmethodID meth = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
        jarray args = env->NewObjectArray(0, env->FindClass("java/lang/String"), 0);
        env->CallStaticVoidMethod(cls, meth, args);
    }
}
return ret;

This assumes that hello.jar is in the working directory of the executable. If it isn't then you need to specify the full path to the jar file. e.g. c:\hello.jar.

A: I wrote the next code now:
#include "stdafx.h"
#include <iostream>
#include "jni.h"
#include <conio.h>
using namespace std;

#pragma comment (lib,"jvm.lib")

int main()

    {
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;

options.optionString="-Djava.class.path=hello.jar";
vm_args.version=JNI_VERSION_1_6;
vm_args.options=&options;
vm_args.ignoreUnrecognized=0;
int ret=JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);

     }

and it's writen me the follwing erore when i try to run :
Error 1   error LNK2019: unresolved external symbol _imp_JNI_CreateJavaVM@12 referenced in function _main   C:\Users\Hilla\Documents\Visual Studio 2012\helloworld\helloworld\helloworld.obj    helloworld
jvm.lim and jvm.dll are at the working directory
thanks for the help

redpajama_set_name: RedPajamaStackExchange


text:
Q: I still wasn't able to get help for this Jquery event below In the ESNList text field , multiple values need to be entered separated with a comma , yet they have to be in the same range .. For example , in the condition below in the loop , if you input a number in ESNList between 986329 and 999999 , the second input in the ESNList field after the comma should be in the same range as the first input and so on otherwise I throw an alert saying that Both ESNs should be in the same range .. I did a loop to perform the check but it's not working .. Can someone demonstrate to me where the error is .. a fiddle would help tons ,

    <form id="provision">
        ESNList:    <input  type="text" id="ESNList" name="ESNList" size="30" />

        ESN Start:<input type="text" id="ESNStart" name="ESNStart" size="10" />

        ESN End: <input type="text" id="ESNStart" name="ESNStart" size="10" />

        UnitName:<input type="text" id="STxName" name="STxName" size="30"  />

         Unit Model:   <select name="STxName" id="ddl_StxName">
        <option value="stx2">STX2</option>
        <option value="stm3" selected>STM3</option>
        <option value="acutec">Acutec</option>
         <option value="trackpack">Trackpack</option>
        <option value="mmt">MMT</option>
        <option value="smartone">Smartone</option>
        <option value="smartoneb" >SmartOneB</option>
        </select>

        RTU Model Type:
         <select name="rtumodel" id ="ddl_rtumodel">
        <option value="globalstar">GlobalStar</option>
        <option value="both">Both</option>
        <option value="comtech">Comtech</option>
        <option value="stmcomtech">STMComtech</option>
        </select>

        <input type="submit" value ="submit"  />
        </form>

A: Oh my, where to start?
For one thing, keyup is going to be triggered after each successive keyup event, which means you're going to do a lot of comparisons over and over again, and get a lot of "negatives" before the user has even finished putting in the first value.
To save some pain, I started with your code, in this Fiddle: http://jsfiddle.net/mori57/68s68/
(Notice that I placed a textarea at the bottom to serve as an output, so you can see exactly how the range-checks are occurring. I also commented out the alert, as that, in combination with keyup, was creating a pretty nasty loop.)
The problem is that each comparison only exists within the context of the current value... it can't tell what the "start range" should be because you're not storing any such thing to compare against, so, when it comes to the next value in the loop, it's only testing to see if the item it currently is looking at is within the specified ranges, NOT that it falls into the same range as the last looked-up item.
You might do that by storing the first comparison in an outside variable, and then comparing every value after the first against the range that is saved in that outside variable. See the code below for an example to get you started. Also, see it in context, here:
http://jsfiddle.net/mori57/68s68/2/
$(function () {
    var out = $("#output");
    var debug = function(txtIn){
        out.val(out.val() + "\n" + txtIn);
    };
    // store your ranges here, in an array
    var ranges = [
        [986329,999999],
        [660000,699999],
        [200000,299999],
        [1202114,1299999]
    ];

    // store the activeRange that is set by the first item in the comparison loop
    var activeRange = -1;

    // use this to test the a value against a given range array
    var withinRange = function(comparitor, range) {
        return (comparitor >= range[0] && comparitor <= range[1]);
    };

    $(":text").css("border", "2px solid red");
    // start the test onBlur, rather than on keyup
    $(":text").blur(function () {
        var enteredData = $(this).val()
        console.log(enteredData);
        if (enteredData == "") {
            $(this).css("border", "2px solid red");
        } else {
            $(this).css("border", "inherit");
        }
        if ($(this).attr("id") == "ESNList") {
            esnList = enteredData.split(',');
        }

        // loop through your values...
        for (var i = 0; i < esnList.length; i++) {
            // store the current value, rather than re-parseInt'ing it for every comparison
            var intVal = parseInt(esnList[i]);

            debug("intVal = " + intVal);

            // now, find out if an activeRange has been set
            if(activeRange == -1) {
                // if not, we need to find out what the activeRange is
                if (withinRange(intVal, ranges[0])) {
                    activeRange = ranges[0];
                } else if (withinRange(intVal, ranges[1])) {
                    activeRange = ranges[1];
                } else if (withinRange(intVal,ranges[2])) {
                    activeRange = ranges[2];
                } else if (withinRange(intVal,ranges[3])) {
                    activeRange = ranges[3];
                }
            } else {
                // if an activeRange has been set already,
                // we need to find out if the current item is outside the activeRange
                if (!withinRange(intVal, activeRange)) {
                    debug("Value out of active range.");
                }
            }

            // Now that you know what your activeRange should be, you can
            // decide what to set your drop down lists to reflect
            switch (activeRange) {
                case ranges[0]:
                    $("#ddl_StxName").val("stx2");
                    $("#ddl_rtumodel").val("globalstar");
                    break;
                case ranges[1]:
                    $("#ddl_StxName").val("mmt");
                    $("#ddl_rtumodel").val("globalstar");
                    break;
                case ranges[2]:
                    $("#ddl_StxName").val("stm3");
                    $("#ddl_rtumodel").val("stmcomtech");
                    break;
                case ranges[3]:
                    $("#ddl_StxName").val("smartone");
                    $("#ddl_rtumodel").val("globalstar");
                    break;
                default:
                    debug("Value out of range.");
                    break;
            }
        }
    });
});


text:
Q: Is Swindrik a liar? Swindrik can be found hanging out on the east side of the Dueling Weapons/Armoury Limited shop in Trinsic, as shown below:

He tells the player to ask about mandrake root at the Folley Tavern in Paws. However, nobody at the Folley Tavern seems to know anything about mandrake root. I haven't been able to find an explanation for this online.
What gives? Is he full of it?
Edit
Apparently I should be able to ask Greg or Rob about it, but the only thing I am able to ask them about is food or ale:

At this point, the game only accepts "A" or "F" as input. After paying, he asks "Somethin' else?" to which the player can respond "Y" or "N". Then the conversation repeats.

A: I had to bribe the barkeep by paying him more than 2gp. I paid 4gp, at which point he asked "What do you want to know?" and I was able to ask him about mandrake root. He doesn't give any useful information until he receives additional bribes however. I ended up paying him 44gp total (4gp originally, then 20gp twice) before he would tell me.


text:
Q: What's the probability of a gambler losing \$10 in this dice game? What about making \$5? Is there a third possibility? Can you please help me with this question:

In a gambling game, each turn a player throws 2 fair dice. If the sum of numbers on the dice is 2 or 7, the player wins a dollar. If the sum is 3 or 8, the player loses a dollar. The player starts to play with 10 dollars and stops the game if he loses all his money or if he earns 5 dollars. What's the probability for the player to lose all the money and what's the probability to finish the game as a winner? If there some 3rd possibility to finish the game? If yes, what's its probability?

Thanks a lot!

A: [edit: Apparently I misread the question. The player starts out with 10 dollars and not five.]
Given that "rolling a 2 or 7" and "rolling a 3 or 8" have the same probability (both occur with probability 7/36), the problem of the probability of a player earning a certain amount of money before losing a different amount of money is the same as the problem of the Gambler's Ruin.
What's different when considering individual rounds is that there's a possibility of a tie. But because a tie leaves everything unchanged, the Gambler's Ruin still applies simply because we can simply consider only events that do change the state of each player's money.
Therefore, the probability that the player makes \$5 before losing \$10 is the same probability as flipping coins against somebody with $5, or 2/3. And the probability of the opposite event is 1/3.
The third outcome, that the game goes on forever, has a probability that vanishes to zero.

A: The game is fair as $P(2 \text{ or } 7)=P(3 \text{ or } 8)=\frac 7{36}$, so if we ignore the non-paying rolls, it just flipping a coin.  As the game is fair, $\frac 23$ of the time he will earn $5$ and  $\frac 13$ of the time lose $10$.


text:
Q: About the position of the object clause 1.Which of the sentences below is best, and why?

People are saying that this is great about X (for example: our new product).
  People are saying about X that this is great.
  People are saying great about X.

2.Is the 'about X' phrase an adverb phrase?

A: "People are saying that this is one of the great things about X." is more appropriate than any of the suggestions you gave.


text:
Q: Text left, figure WITH CAPTION right I try to get the text at the left side of the document and the figure on
the right side of the document. Unfortunately, there are still some issues:
In the first example, the lettering differs (font, gaps, type) from the lettering of the main text.
In the second example, no caption appears.
I could not find any solution so far and would be really grateful about any help from you!
1) Example
\documentclass[11pt]{article}
    \begin{document}
\begin{figure}[htbp]
    \begin{minipage}{0.4\textwidth}
   sfsdaa
   sdfsfasfs
   10L-bach of water that flows through the device, it dispenses a dose of 3 mL of NaOCl solution into a mixing chamber. The chlorinated water is then flushed by an automatic siphon into a storage reservoir and dispensed via a tap \citep{Amin2016}.
Difficulties experienced with the application of this device
    \end{minipage}\hfill
    \begin{minipage}{0.4\textwidth}
     \centering
      \includegraphics[width=0.8\textwidth]{Zimba.PNG}
      \caption{Bild rechts}
    \end{minipage}
  \end{figure}
\end{document}

2) Example
    \documentclass[11pt]{article}

\begin{document}
    \begin{minipage}{0.6\linewidth}
     \noindent {\textbf{Zimba}}\\
    The Zimba device is connected to handpumps. For every 10L-bach of water that flows through the device, it dispenses a dose of 3 mL of NaOCl solution into a mixing chamber. The chlorinated water is then flushed by an automatic siphon into a storage reservoir and dispensed via a tap \citep{Amin2016}.
    Difficulties experienced with the application of this device
    are the variations in dosing due to clogging of the regulator \citep{Pickering2015}. Moreover, the Zimba dispenser uses a non-standard low concentration NaOCl solution (0.4\%), which requires dilution before filling.
    \end{minipage}
    \hfill
    \begin{minipage}{0.45\linewidth}
       \centering
       \includegraphics[scale=0.9]{Zimba.PNG}
       %\rule{0.9\linewidth}{0.5\linewidth}
       \caption{Zimba \citep{Amin2016}}
       \label{fig:Zimba}
    \end{minipage}

    \end{document}

A: It looks a bit like you are trying to do something that is implemented by the wrapfig package. Here is an easy example:
\documentclass{scrartcl}
\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{lipsum}

\begin{document}
    \lipsum[1]
    \begin{wrapfigure}{r}{.5\linewidth}
        \includegraphics[width=\linewidth]{example-image-a}
        \caption{Bild rechts}
    \end{wrapfigure}

    \lipsum[2-3]
\end{document}

With the output being:

A: \documentclass[11pt]{article}
    \begin{document}
\begin{tabular} {p{6cm} p{5cm}}
    {\begin{minipage}{0.4\textwidth}
   sfsdaa
   sdfsfasfs
   10L-bach of water that flows through the device, it dispenses a dose of 3 mL of NaOCl solution into a mixing chamber. The chlorinated water is then flushed by an automatic siphon into a storage reservoir and dispensed via a tap .
Difficulties experienced with the application of this device
    \end{minipage}\hfill} &
    {\begin{minipage}{0.4\textwidth}
     \centering
    I would like to say that I do not have any pictures, text or table. % \includegraphics[width=0.8\textwidth]
%      \caption{Bild rechts}
    \end{minipage}}
  \end{tabular}\\
  \vspace{1cm}

 \begin{tabular} {p{6cm} p{5cm}}
    {\begin{minipage}{0.6\linewidth}
     \noindent {\textbf{Zimba}}\\
    The Zimba device is connected to handpumps. For every 10L-bach of water that flows through the device, it dispenses a dose of 3 mL of NaOCl solution into a mixing chamber. The chlorinated water is then flushed by an automatic siphon into a storage reservoir and dispensed via a tap.
    Difficulties experienced with the application of this device
    are the variations in dosing due to clogging of the regulator . Moreover, the Zimba dispenser uses a non-standard low concentration NaOCl solution (0.4\%), which requires dilution before filling.
    \end{minipage}} &

    {\begin{minipage}{0.45\linewidth}
       \centering

       Some thing is missing here
       %\includegraphics[scale=0.9]{Zimba.PNG}
       %\rule{0.9\linewidth}{0.5\linewidth}
       %\caption{Zimba \citep{Amin2016}}
       \label{fig:Zimba}
    \end{minipage}}

    \end{tabular}
\end{document}

% please compile with full tex. I hope this is useful to you. I compiled it and saw that it works.


text:
Q: visual studio code is missing in the installation of anaconda3 I need visual studio code installation as a component of anaconda3. I downloaded anaconda installer (02/2020 .exe file), but no visual studio code component in the installed anaconda3 navigator or in my PC. Does anybody know how I could make this missing component back in anaconda3 navigator?
Besides, I have also noticed that different anaconda3 NAVIGATOR packages are installed each time when I execute anaconda-2020-02 exe file. Is there a way I could selectively install anaconda packages in its navigator by myself?

A: For that, there is a way to install VSCode once you have Anaconda installed. Check out this link: https://nathancarter.github.io/MA346-course-notes/_build/html/vs-code-installation.html
And regarding your other question, it would be good if your provided some examples of the packages that are installed. And yes, of course you can install them by yourself. You can do this by using the conda command in the console, for example:
conda install scipy

will install scipy.
For more information on how to manage packages in conda, check:
https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-pkgs.html


text:
Q: Add Text To TinyMCE Visual Pane In WordPress I have successfully written a TinyMCE plugin for a WordPress site that inserts a script tag into the html of a new post or page. However, since the script tag contains no text, in the "visual" pane nothing shows up.
There must be a way to provide something to show in the visual pane while still only having a script tag in the "text" pane no?
My code:
jQuery(document).ready(function($) {

    tinymce.PluginManager.add('myplugin', function(editor, url) {

        editor.addButton('civicsciencejspoll', {
            text: 'CivicScience JSPoll',
            icon: false,
            onclick: function() {
                    var html = "<script src=\"mydomain.com/js/file.js\"></script>";
                    editor.insertContent(html);
                }
            }
        });
    });
});

A: I ended up using WordPress's ShortCode API to achieve my desired effect:
https://codex.wordpress.org/Shortcode_API


text:
Q: What is the best way to load data with tf.data.Dataset in memory efficient way I'm trying to load data for optimizing model for object detection + instance segmentation. However using tf.data.Dataset is giving me a bit headache with loading instance segmentations masks. tf.data.Dataset is using all the memory on the server (more than 128 GB) with a small dataset.
Is there a way to effectively load data in more memory efficient way, right now we are using this code:
train_dataset, train_examples = dataset.load_train_datasets()
ds = (
    train_dataset.shuffle(min(100, train_examples), reshuffle_each_iteration=True)
    .map(dataset.decode, num_parallel_calls=args.num_parallel_calls)
    .map(train_processing.prepare_for_batch, num_parallel_calls=args.num_parallel_calls)
    .batch(args.batch_size)
    .map(train_processing.preprocess_batch, num_parallel_calls=args.num_parallel_calls)
    .prefetch(AUTOTUNE)
)

The problem is that the second map call with train_processing.prepare_for_batch (takes single element) and third with train_processing.preprocess_batch (takes batch of elements) is creating a lot of binary masks for segmentation which are using all the memory.
Is there a way to reorganize the mapping functions to save the memory? I was thinking something like: 1. take first 100 samples, 2. decode the samples, 3. prepare the the masks and bounding boxes for one sample 4. takes the batch of them 5. final preparation of data per batch 6. FIT ONE step/one batch of data 7. clean the data from memory

A: Manually
First make a list of all the filenames in the dataset and a list of all the labels in the dataset.
    filenames = [abc.png, def.png, ...]
    labels = [0, 1, ...]

Then create dataset from tensor slices
    dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
    dataset = dataset.shuffle(len(filenames))
    dataset = dataset.map(PARSE_FUNCTION, num_parallel_calls=PARALLEL_CALLS)
    dataset = dataset.batch(BATCH_SIZE)
    dataset = dataset.prefetch(1)

Through a function
    def dataset(csv, parse):
        filenames = []
        labels = []
        for i, row in csv.iterrows():
            filename = row[0]
            filenames.append(filename)
            label = row[1]
            labels.append(label)
        encoder = LabelEncoder()
        labels = encoder.fit_transform(labels)
        labels = np_utils.to_categorical(labels)
        dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
        dataset = dataset.shuffle(len(filenames))
        dataset = dataset.map(PARSE_FUNCTION, num_parallel_calls=PARALLEL_CALLS)
        dataset = dataset.batch(BATCH_SIZE)
        dataset = dataset.prefetch(1)
        return dataset

Disclaimer: this method assumes csv is in (filenames, label) format


text:
Q: Least painful way to gather a system state snapshot (memory %, HD space, etc) in .NET app? We have an app that is getting reports out 'in the wild' of slowing down, locking up, and other unwanted behaviors after many hours of running. Of course this hasn't occurred in the development and staging environments.
Looking for a way of collecting as much system information as we can from within the app (every 10-15 minutes or so) and then report this via a web service we already have set up. This will either rule in or rule out a resource issue as it relates to systems' vital signs.
Thinking this wheel has probably been invented already... Is there a reusable library normally used for tech support environments or something similar that would save us the time querying individual WMI objects and so forth? Suggestions welcome.

A: Why would it have to be from within the app?
You can monitor and log various performance counters using PerfMon.
For a more in-depth answer, see http://dotnetdebug.net/2005/06/30/perfmon-your-debugging-buddy/.


text:
Q: Fedora: Can I Install Fedora 13 without the Gnome Desktop? I have a CD with the standard 64-bit version of Fedora 13. I want to install it on a VirtualBox VM for local web development testing. How can I install it without Gnome and all the extra content that goes along with the Gnome environment?

A: http://docs.fedoraproject.org/en-US/Fedora/13/html/Installation_Quick_Start_Guide/images/pkgselection/pkg-group.png Select Customize now (at the bottom) and than remove the Gnome/KDE and the xserver package.

A: You should be able to just ignore all Gnome, KDE, and X packages on install. I don't remember all of the specifics off the top of my head. You could also install Fedora regularly and then use runlevels to just boot into CLI only mode. More information can be found here: http://forums.fedoraforum.org/showthread.php?t=89849

A: During installation I watched for an opportunity to modify the packages to be installed, but I never saw it. I'm sure I just missed it; however I did notice a few people saying that they'd tried blocking X/Gnome from installation but it installed them anyway. Something about Fedora being intended as a Desktop environment, not a Server. Go figure.
At any rate, I had to just uninstall them after the OS was completely installed, and once that was done I still had to change the default runlevel. Talk about a pain, but at least it's working.

A: If you have the Gnome LiveCD - the short answer is that you probably can't (or at least you'll have to install, and the uninstall Gnome.
The LiveCD has a fixed configuration that it copies over to the hard drive, and isn't truly an install CD/DVD.

A: while installation dont choose Xserver

A: if you are after a headless / commandline version of Linux (which uses yum or redhat / fedora like) install CentOS.
http://www.if-not-true-then-false.com/2010/centos-netinstall-network-installation/


text:
Q: System.Net.WebException: Sharing violation on path Estoy creando una app en Xamarin para android que al finalizar su tarea, crea un PDF con iTextSharp.
Tengo un problema ya que esta app tiene un SignaturePad, captura la firma y la inserta en el PDF.
Cuando captura la firma por primera vez no tengo ningún problema, pero cuando lo hago por 2da vez salta la siguiente excepcion:

Unhandled Exception:
System.Net.WebException: Sharing violation on path /mnt/sdcard/ProyectoTest/Firma.jpg

No tengo ni idea a que se debe, ya que la imágen de la firma se está guardando sin problemas y en el PDF antes de insertar la firma pongo 2 o 3 imágenes más y en ninguna de ellas tengo problema.
Dejo aquí la parte donde ingreso la imágen para que puedan revisarlo, si necesitan más partes del código me avisan en los comentarios:
string RutaFirma = "/mnt/sdcard/ProyectoTest/Firma.jpg";
Image FirmaPaciente = Image.GetInstance(RutaFirma);
FirmaPaciente.ScalePercent(20);
FirmaPaciente.SetAbsolutePosition(380, 150);
document.Add(FirmaPaciente);

A: Después de lidiar bastante con el asunto encontré el problema:
El problema fue algo muy básico de IO.
Este es el método donde se genera la firma:
private async void BtnAceptar_Click(object sender, EventArgs e)
{
    var directory = new Java.IO.File("/mnt/sdcard", "ProyectoTest").ToString();

    if (!Directory.Exists(directory)){
        Directory.CreateDirectory(directory);
    }

    path = System.IO.Path.Combine(directory, "Firma.jpg");

    if (System.IO.File.Exists(path)){
        System.IO.File.Delete(path);
    }

    Stream bitmap = await FirmaPaciente.GetImageStreamAsync(SignatureImageFormat.Png, Color.Black, Color.White, 1f);
    FileStream dest = System.IO.File.OpenWrite(path);
    await bitmap.CopyToAsync(dest);
    FinishAfterTransition();
}

Faltaba el dest.Close(); antes del FinishAfterTransition();!!!


text:
Q: I keep getting this error: TypeError: tuple indices must be integers or slices, not tuple I am trying to do this tutorial: https://colab.research.google.com/drive/1d8PEeSdVlP0JogKwkytvFeyXXPu_qfXg?usp=sharing#scrollTo=sDixMreeUS_9
and this is https://github.com/mjpramirez/Volvo-DataX the repository in GitHub
So when I am trying to run the model I kept getting this error and I already find which file has this error and this is where the problem:
unmatched_trackers = []
  for t,trk in enumerate(trackers):
    if(t not in matched_indices[:,1]):
      unmatched_trackers.append(t)

I tried to replace 1 with 0 but still not working.

A: You need to replace the sklearn.utils.linear_assignment_.linear_assignment function by the scipy.optimize.linear_sum_assignment function by importing like from scipy.optimize import linear_sum_assignment as linear_assignment.
The difference is in the return format: linear_assignment() is
returning a numpy array and linear_sum_assignment() a tuple of numpy arrays.
You obtain the same output by converting the output of linear_sum_assignment() in array and transpose it.
 Example:
  matched_indices = linear_assignment(-iou_matrix)
  matched_indices = np.asarray(matched_indices)
  matched_indices = np.transpose(matched_indices)

  OR

matched_indices = np.array(list(zip(*matched_indices)))


text:
Q: What format does the internal disk need to be in to to install Big Sur from USB? I have a 2016 128Gb MacBook Pro and am trying to install Big Sur from a USB. I have deleted both the Macintosh HD and Macintosh HD - data using Disk Utility in recovery mode.
In Disk Utility, under the Internal header, I have a main disk called Apple SSD AP0128J Media (GUID Partition Map). Nested under that I have a Container disk2.
When I am in recovery mode, I have the option to "Reinstall macOS Big Sur" from my USB. However, when asked which disk I want to install it on, there isn't the option to install it onto the HD disk - only the USB. Therefore, I think that the HD disk isn't formatted correctly.
How should I format the HD in Disk Utility so that I can install Big Sur on to it?


text:
Q: Does assignment with a comma work? Why does aaa = 1,2,3 work and set the value of aaa to 1?
Why doesn't var bbb = 1,2,3 work?
Why does var bbb = (1,2,3) work and set the value of bbb to 3?

A: Comma has multiple uses in Javascript. In the expression:
a = 1, 2, 3;

it's an operator that simply returns its right-hand argument. But it's also part of the syntax of var declarations, which are:
var var1 [ = val1 ], var2 [ = val2 ], var3 [ = val3 ], ...;

(where [...] means that part is optional). Your var declaration is missing the variable names after the commas, so it doesn't parse. You could get the effect you wanted with:
var a = (1, 2, 3);

The parentheses force the commas to be treated as operators rather than delimiters between variable declarations.

A: In your examples, the comma is used in two contexts:
var statement
The syntax of var statement is:
var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];

Here, comma is used to separate variable name-value pairs. The following will not work because a variable name cannot start with a digit (see identifier names):
var bbb = 1, 2, 3;
// SyntaxError: Unexpected number

Comma Operator
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. The following expressions work as follows:
aaa = 1, 2, 3;

*

*aaa = 1, 2 yields 2

*

*note that aaa = 1 is evaluated first because = has higher priority than ,

*2, 3 yields 3

var bbb = (1, 2, 3);

*

*the expression (1, 2, 3) yields 3 as described above

*The variable bbb is assigned the value 3

A: There's a lot going on here, but basically, it comes down to the comma operator.

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

This code:
aaa = 1,2,3

Is equivalent to:
aaa = 1;
2;
3;

So aaa is implicitly declared and assigned a value of 1. Notice that the output on the console is the result of the last statement, 3.

This code:
var bbb = 1,2,3

Is a syntax error because commas in variable declarations are used to declare multiple variables in a single line. As the MDN article points out,

Note that the comma in the var statement is not the comma operator, because it doesn't exist within an expression. Rather, it is a special character in var statements to combine multiple of them into one.

So this code is roughly equivalent to:
var bbb = 1;
var 2;
var 3;

Of course, 2 is not a valid identifier, so it fails at that point.

This code:
var bbb = (1,2,3)

Is very similar to the first, except because the numeric values are wrapped in a parentheses, they are evaluated first. So this is rougly equivalent to:
1;
2;
var bbb = 3;

A: In the first case:
aaa = 1,2,3
the commas serve as expression separators.  It performs an assignment to aaa, then it calculates 2 and discards it, then it calculates 3 and discards it.
In the second:
var bbb = 1,2,3

The var keyword tells the Javascript compiler that the next thing after a , should be another variable name.  It isn't finding on, so it dies and gags.
var bbb = (1,2,3)

Here, the compiler first evaluates 1 and ignores it.  Then it evaluates 2 and ignores it.  Then it evaluates 3 and that is left on the stack so it is assigned to bbb
While using commas to separate expressions isn't common, it is sometimes useful in things like for looks.
for (i = 0, l = 10; i < l; i++) {
  console.log(i);
}


text:
Q: django.db.utils.IntegrityError: (1062, "Duplicate entry '22-add_' for key 'content_type_id'") I am using django multiple DB router concepts, having multiple sites with different db's. Base database user will login with all other sub sites.
When i try syncdb in base site its worked properly(at any time), but trying syncdb with other sites works first time only, if we try next time on-wards it throws integiry error like below

*

*django.db.utils.IntegrityError: (1062, "Duplicate entry
'22-add_somesame' for key 'content_type_id'")
Once i removed multiple DB router settings in that project means syncdb works properly(at any time).
So is this relates to multiple db router? or what else?
Please anyone advise on this, thanks.

A: The problem here is with the db router and django system objects. I've experienced the same issue with multiple DBs and routers. As I remember the problem here is with the auth.permission content types, which get mixed in between databases. The syncdb script otherwise tries to create these in all databases, and theb it creates permission content type for some object, which id is already reserved for a local model.
I have the following
BASE_DB_TYPES = (
 'auth.user',
 'auth.group',
 'auth.permission',
 'sessions.session',

)
and then in the db router:
def db_for_read(self, model, **hints):
    if hasattr(model, '_meta') and str(model._meta) in BASE_DB_TYPES:
        return 'base_db' # the alias of base db that will store users
    return None # the default database, or some custom mapping

EDIT:
Also, the exception might say that you're declaring a permission 'add_somesame' for your model 'somesame', while Django automatically creates add_, delete_, edit_ permissions for all objects.


text:
Q: Copy "Distinct" (Text) Values to Clip Board VBA Excel Normally when I need to have distinct (non-duplicated values) using for SUMIFS, I just copy the whole column to another sheet/range and use "Removes Duplicates" function.
I wish I could just right click on the range of a column and select "Copy Distinct Values". When I copy and paste, only non-duplicated values pasted.
In other words/way, on the "Paste Options" - there is another function call "Paste Distinct"
The important step is to get the distinct values which I am having problem.
I could do the long way by create a "temp sheet" to store all of the values and remove the duplicates and then copied them to clip board. However, I am avoiding this.

A: Since you have the creation of the customized menu down, here's my stab at creating an in-memory collection of unique values and exporting them to another part of the worksheet.  You'll have to modify this code to suit your particular situation, but hopefully it will get you going in the right direction.
It's important to note that you will need to set a reference to the Microsoft Scripting Runtime for this to work (that's where the Dictionary object lives):
Sub test()

Dim dictValues       As New Dictionary
    Dim i            As Long
    Dim sheetValues  As Variant
    Dim exportValues As Variant
    Dim joinedValues As String

    sheetValues = Sheet1.Range("A1").Resize(Sheet1.Range("A1048576").End(xlUp).Row, 2)

    For i = 1 To UBound(sheetValues)
        dictValues(sheetValues(i, 1)) = sheetValues(i, 2)
    Next

    exportValues = dictValues.Keys

    Sheet1.Range("B1").Resize(UBound(Application.Transpose(exportValues)), 1) = Application.Transpose(exportValues)

End Sub


text:
Q: spyOn function in Jasmine that returns random element from array I am currently building a Rock, Paper, Scissors game in Javascript and using TDD to guide my code. I am trying to run a Jasmine test that forces one of my functions to return a set value. I want my "compChoice" function to return a random element from the 'choices' array ["Rock", "Paper", "Scissors"] and in my test want to set this to 'Rock'. My tests are below.
describe("Game", function() {

var game;

beforeEach(function(){
game = new Game();
});

describe('user choice', function(){

it('should equal the choice the user selected', function(){
  game.userSelect("Rock");
  expect(game.userChoice).toEqual("Rock")
});
})

describe('draw', function(){

it('should equal true if user choice and comp choice are the same', function()       {
  game.userSelect("Rock");
  spyOn(game,'compChoice').and.returnValue("Rock");
  expect(game.opponentChoice).toEqual("Rock")
  // expect(game.draw).toEqual(true);
});
})

});

I can tell there's something wrong with my spyOn as my test comes back with                        "Expected ' ' to equal 'Rock'."
I don't know why it's not calling the spy and setting the value to "Rock" like I asked.
My actual code is down below for reference:
function Game() {
this.choices = ["Rock","Paper","Scissors"];
this.userChoice = "";
this.opponentChoice = "";
}

Game.prototype.userSelect = function(choice){
this.userChoice = choice;
}

Game.prototype.compChoice = function(){
this.opponentChoice =    this.choices[Math.floor(Math.random()*this.choices.length)];
return this.opponentChoice;
 }

A: It looks like you haven't invoked spied method. You define in spy what should happen when function is invoked so in your case
spyOn(game,'compChoice').and.returnValue("Rock");

You have defined, that function compChoice from game object should be spied and when it is invoked that it should return "Rock" value. In next line you do expect
 expect(game.opponentChoice).toEqual("Rock")

So you check here if object attribute opponentChoice is set to "Rock"
But you miss to invoke method compChoice, which should set value of opponentChoice. You should paste this
game.compChoice();

between spyOn and expect in your code.
EDITED:
Ok, now I see what's going on. Spy is creating a mock for compChoice method. But it is only a mock and you defined that this mock should return "Rock" value. But actually this mocked function doesn't work like normal compChoice method. So it does not assign opponentChoice value to game object. It only returns "Rock" value as you defined.
It also looks little strange, because it's not unit test. It's more like integration test. You are trying to test how this methods work together. So I think Jasmine doesn't fit for this kind of tests. However if you really would like to test this behaviour you can use callFake method in the following way:
spyOn(game,'compChoice').and.callFake(function(){

              game.opponentChoice = "Rock";
              return "Rock";
});

In this way you are calling fake function which assign also opponenChoice value.


text:
Q: Why can't I remote manage a domain-joined Windows 10 computer? I have a Active Directory domain of old Windows 7 computers and introduced a new Windows 10 computer.  However, when I right-click the Win10 computer in AD Users & Computers, and select Manage, I receive this error:

Computer (name of computer) cannot be managed.  Verify the network path is correct, the computer is available on the network, and that the appropriate Windows Firewall rules are enabled on the target computer.

The message continues by listing the correct firewall rules to enable.  The problem is that I have already done so via Group Policy for all the computers in the same OU.  As far as I can tell, the Win10 has the same policies applied to it (from running gpresult).  When trying to use the AD Group Policy Results tool, it too fails.  It seems that anything that depends on WMI / DCOM fails, but the services appear to be running fine on the Win10 computer.
I uninstalled anti-virus and disabled Windows Firewall and it still does not work.  If it matters, the Win10 computer has Hyper-V installed, but nothing else that's unusual.


text:
Q: How to pass a string variable as a shell script argument? I have string variables as
String var1 = "I am"
String var2 = "here"
String cmd = ("sh /path/shell.sh \""+var1+"\" \""+var2);
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);

But when I execute echo $1 $2 from my shell script, I get the output as I am. Why doesn't the quotes work?

A: You'll want to call the command as follows:
Process process = new ProcessBuilder().command("sh", "/path/shell.sh", var1, var2);
Scanner scan = new Scanner(process.getInputStream());
while(scan.hasNextLine()) {
    //...
}
//...
scan.close();
process.destroy();

You'll probably want to wrap that in a try-catch block too.


text:
Q: Given 10,000 record IDs, which way is the correct way to delete the records? Which is better, a delete statement with a where clause containing 10,000 or filters (e.g. delete from table where id=1 or id=2 or id=3, etc) or a executing 10,000 delete statements (e.g. delete from table where id=1; delete from table where id=2;, etc)? The database is MS SQL Server.
EDIT
The IDs are not sequential and there is no where clause I can use to catch all of them (e.g where id > 100 and id < 50) because I have no idea how these IDs are related (besides the fact that they're all from the same table). So it's really down to a question of performance.

A: Where'd you get the IDs to delete? Surely with that many they're in the database somewhere. If that's the case, you do it like this:
DELETE FROM MyTable
WHERE ID IN ( /* Select query that returns your 10000 IDs here */ )

If they're not in the database, add them, even if it means creating a table to hold them that will only exist long enough to complete this.

A: For performance the worst method is to delete one row at a time. However, deleting too many at a time can also cause user issues  with locking and blocking. Often the best bet is a hybrid of the two where you delete a batch (say about a 1000 records) at a time.
Now this gets much more complex when you consider that the records being deleted may have child records in a another table. Some people do the deletes then through cascade delete and others start from teh child tables and work up. Either situation may mean you have considerably more more than 10000 records to delete and then the batches would need to be smaller to avoid locking. Some people might want to do one record at a time in this case to ensure that the failure if an existing child record was not deleted first, the other records are stil inseterd and you know which records failed. this is particularly true of the types of records whenre the very existance of child record means that you should not delte the parent (you can't delete a customer who has actually bought things or the finanical records get all messed up for instance).

A: Are the IDs sequential? If so, you could run the following SQL statement:
DELETE FROM table_name
WHERE ID BETWEEN id_lowest and id_highest;


text:
Q: Delete the row based on order column using perl I have a table separated by ',' I want to order and test if the value from num+1 exists in num column, or the value from num+2 exists in num, or the value from num+3 field exists in num, or the value from num+4 field exists in num for each row then delete the row if true.
my script is:
#!"C:\perl\bin\perl.exe"

use strict;
use warnings;

my $file_name = shift @ARGV;

die "Usage ./$1 <file_to_be_processed> > <output_file>" unless defined $file_name;

my $dic; # This is going to hold all values to be excluded.

open IN, "<", $file_name or die "Could not open $file_name $!\n";

while(<IN>) {
        chomp;
        @_ = split /,/;
        shift @_;
        map{$dic->{$_}++} @_;
}

close IN;

open IN, "<", $file_name or die "Could not open $file_name $!\n";

while(<IN>) {
        chomp;
        @_ = split /,/;
        print $_."\n" unless defined $dic->{$_[0]};
}

close IN;

there is my table:
num,num+1,num+2,num+3,num+4
1014,1015,1016,1017,1018
1015,1016,1017,1018,1019
1019,1020,1021,1022,1023
1025,1026,1027,1028,1029
1030,1031,1032,1033,1034

there is expected result:
num,num+1,num+2,num+3,num+4
1014,1015,1016,1017,1018
1019,1020,1021,1022,1023
1025,1026,1027,1028,1029
1030,1031,1032,1033,1034

My script works but excludes num 1019 from result, there is output of actual script:
num,num+1,num+2,num+3,num+4
1014,1015,1016,1017,1018
1025,1026,1027,1028,1029
1030,1031,1032,1033,1034

A: Looks like a misuse of map to me - if you're not using the result of map then you should probably be using a for loop instead.
But that aside - what you're doing here is creating a list of every symbol in column 1,2,3,4 and excluding a line if it exists?
Because your sample data includes 1019 on the previous line, that's why it's being excluded.
Your $dic looks like:
$VAR1 = {
          '1016' => 2,
          '1021' => 1,
          '1022' => 1,
          '1028' => 1,
          '1034' => 1,
          'num+3' => 1,
          '1017' => 2,
          'num+1' => 1,
          '1015' => 1,
          '1020' => 1,
          'num+2' => 1,
          '1023' => 1,
          '1026' => 1,
          '1019' => 1,
          '1031' => 1,
          '1027' => 1,
          '1032' => 1,
          '1033' => 1,
          '1018' => 2,
          '1029' => 1,
          'num+4' => 1
        };

As 1019 is in it, the 1019 line gets skipped.
Also:

*

*Data::Dumper is useful for seeing what's in a data structure.

*don't use map like that. Use a  for loop.

Something like:
while(<IN>) {
    chomp;
    $dic->{$_}++ for split /,/;
}

*

*don't use @_ like that - it's a special variable, with a specific meaning. Call it something else.

*current good practice is to use a lexical filehandle with open. e.g. open ( my $in, '<', $filename ) or die $!; because of keeping the scope down.

*if you just want to check the first column, you can assign like this: my ( $col, @rest ) = split /,/; and just test $col. Or you can skip the chomp entirely and just do:
print unless defined $dic->{(split /,/)[0]};

A: You have to dynamically change your hash when you skip a line:
#!/usr/bin/perl
use warnings;
use strict;

my %dic;
my $pos = tell DATA; # Remember where the data start.

while (<DATA>) {
    chomp;
    my @ar = split /,/;
    # Fix SO syntax highlighting error: /
    shift @ar;
    $dic{$_}++ for @ar;
}

seek DATA, $pos, 0; # Back to the data start.

while (<DATA>) {
    chomp;
    my @ar = split /,/;
    if ($dic{ $ar[0] }) {
        delete $dic{ $_ } for @ar[1 .. $#ar]; # <-- this was missing!
    } else {
        print "$_\n";
    }
}

__DATA__
1014,1015,1016,1017,1018
1015,1016,1017,1018,1019
1019,1020,1021,1022,1023
1025,1026,1027,1028,1029
1030,1031,1032,1033,1034

A: 1019 is being skipped because even though the 1015 row will be skipped in the second loop, the 1019 key was already defined for $dic in your first loop.
map{$dic->{$_}++} @_;

On the second iteration of the first loop (the 1015 row), that line is setting keys 1016, 1017, 1018, and 1019 (to 1). Then in your second loop:
print $_."\n" unless defined $dic->{$_[0]};

your unless skips 1015, but doesn't do anything to remove the keys that the 1015 row defined with it, so it continues to remove the 1019 row.

A: If I understand you correctly then this is all you need
use strict;
use warnings;

my %seen;

while ( <DATA> ) {
    chomp;
    my @fields = split /,/;
    if ( not $seen{ shift @fields } ) {
        $seen{$_} = 1 for @fields;
        print "$_\n";
    }
}

__DATA__
1014,1015,1016,1017,1018
1015,1016,1017,1018,1019
1019,1020,1021,1022,1023
1025,1026,1027,1028,1029
1030,1031,1032,1033,1034

output
1014,1015,1016,1017,1018
1019,1020,1021,1022,1023
1025,1026,1027,1028,1029
1030,1031,1032,1033,1034


text:
Q: Inserting Text At Cursor Location With Quill.js I am trying to add a custom piece of functionality ("module") to quill.js and cannot seem to do it. Here is what I need:
If want to add a button that inserts a template replacement variable... say
something like {{company}} at the location of the cursor in the
editor, is that currently possible with the API - I thought I could do
it using insertText but I cant seem to get it to work.
Thanks

A: This code snippet is to add symbol at cursor position with a custom button with Quill.js.
First declare quill variable:
var quill = new Quill('.editor', {
    theme: 'snow'
});

With button click event, add symbol at caret position.
$('.symbols').click(function(){
    quill.focus();
    var symbol = $(this).html();
    var caretPosition = quill.getSelection(true);
    quill.insertText(caretPosition, symbol);
});

A: What I ended up doing in a very similar setup:
let mergeFieldText = '{{company}}';
var selection = this._quill.getSelection(true);
this._quill.insertText(selection.index, mergeFieldText);

A: You should be able to do this with insertText but you might need to use getSelection to get the cursor location. The object returned by getSelection will have an index and length key. Adding the button and necessary click handler will be up to the implementor. Note focus should be returned back to the editor before calling getSelection with focus or simply passing true to getSelection.

A: For any of you still having problems with this, know that if you have a bootstrap modal showing when trying to focus on the Quill to be able to use method getSelection(), you first need to close the modal before forcing focus on the quill instance.


text:
Q: array value not showing length, but when i open so the element is exist array value not showing length, but when i open so the element is exist. but length and some other functions of array not working...
"""const getingLikedNft = async () => {
setMyNftLoading(true);
const res = await axios.get(${BACKEND_URL}views_and_likes);
console.log("resshan", res);
// let likedNft = [];
var myLikedNft = new Array();
res?.data.forEach((element) => {
  // console.log("xshan", element);
  if (element?.likedAccounts.length > 0) {
    element?.likedAccounts.forEach(async (elem) => {
      if (elem?.toLowerCase() == user?.address?.toLowerCase()) {
        console.log("resshan_elem", element);
        try {
          let res = await axios.post(`${BACKEND_URL}single-nft`, {
            tokenId: element.tokenId,
            tokenAddr: element.tokenAddr,
          });
          console.log("reslikedNFT", res.data);
          // const uri = await contracts?.closedSeaNft?.methods
          //   .tokenURI(element.tokenId)
          //   .call();
          // const res = await axios.get(uri);
          var nftData = {
            description: res?.data?.metadata?.description,
            image: res?.data?.metadata?.imageUrl,
            title: res?.data?.metadata?.name,
            url: `/asset/${res?.data?.tokenAddr}/${res?.data?.tokenId}`,
          };
          console.log("reslikedN22FT2324232", Array.prototype.nftData);
          myLikedNft = [...myLikedNft, nftData];
          // myLikedNft.push({
          //   description: nftData.description,
          //   image: nftData.imageUrl,
          //   title: nftData.name,
          //   url: `/asset/${res?.data?.tokenAddr}/${res?.data?.tokenId}`,
          // });
        } catch (err) {
          console.log("element?.likedAccounts [err]", err);
        }
        // likedNft.push(element);
        // console.log("elem", elem);
      }
    });
  }
});
console.log("reslikedNFT2321312341312dasd", myLikedNft);
setMyLikesCollection(myLikedNft);
setTimeout(() => {
  setMyNftLoading(false);
}, 2000);

};"""
you can see it is showing empty array.

but when i open this so the element is exists.

how can i solve this kindly help...

A: You are making an async call for every iteration in the forEach loop. But the execution of the forEach will finish before you get a response for each of your async calls.
When you print the myLikedNft to the console, at the time of printing, the array has no data, because the async calls have not resolved. But when you expand them in the console, it gives you the latest value of the expression.


text:
Q: SQL WHERE ... IN clause with possibly null parameter I am having some problems with my WHERE clause (using SQL 2008) .  I have to create a stored procedure that returns a list of results based on 7 parameters, some of which may be null.  The ones which are problematic are @elements, @categories and @edu_id.  They can be a list of ids, or they can be null.  You can see in my where clause that my particular code works if the parameters are not null.  I'm not sure how to code the sql if they are null.  The fields are INT in the database.
I hope my question is clear enough.  Here is my query below.
BEGIN
DECLARE @elements nvarchar(30)
DECLARE @jobtype_id INT
DECLARE @edu_id nvarchar(30)
DECLARE @categories nvarchar(30)
DECLARE @full_part bit
DECLARE @in_demand bit
DECLARE @lang char(2)

SET @jobtype_id = null
SET @lang = 'en'
SET @full_part = null -- full = 1, part = 0
SET @elements = '1,2,3'
SET @categories = '1,2,3'
SET @edu_id = '3,4,5'

select
jobs.name_en,
parttime.fulltime_only,
jc.cat_id category,
je.element_id elem,
jt.name_en jobtype,
jobs.edu_id minEdu,
education.name_en edu
from jobs
left join job_categories jc
on (jobs.job_id = jc.job_id)
left join job_elements je
on (jobs.job_id = je.job_id)
left join job_type jt
on (jobs.jobtype_id = jt.jobtype_id)
left join education
on (jobs.edu_id = education.edu_id)
left join
(select job_id, case when (jobs.parttime_en IS NULL OR jobs.parttime_en = '') then 1 else 0 end fulltime_only from jobs) as parttime
on jobs.job_id = parttime.job_id
where [disabled] = 0
and jobs.jobtype_id = isnull(@jobtype_id,jobs.jobtype_id)
and fulltime_only = isnull(@full_part,fulltime_only)
-- each of the following clauses should be validated to see if the parameter is null
-- if it is, the clause should not be used, or the SELECT * FROM ListToInt... should be replaced by
-- the field evaluated: ie if @elements is null, je.element_id in (je.element_id)
and je.element_id IN (SELECT * FROM ListToInt(@elements,','))
and jc.cat_id IN (SELECT * FROM ListToInt(@categories,','))
and education.edu_id IN (SELECT * FROM ListToInt(@edu_id,','))

order by case when @lang='fr' then jobs.name_fr else jobs.name_en end;

END

A: Something like
and (@elements IS NULL OR je.element_id IN
(SELECT * FROM ListToInt(@elements,',')))
and (@categories IS NULL OR
jc.cat_id IN (SELECT * FROM ListToInt(@categories,',')))
....

should do the trick

A: je.element_id IN (SELECT * FROM ListToInt(@elements,',')) OR @elements IS NULL

that way for each one

A: Have you tried explicitly comparing to NULL?
and (@elements is null or je.element_id IN (SELECT * FROM ListToInt(@elements,','))

And so on.


text:
Q: Objects in XML Layout is overlapping on keyboard showing How do I ensure the the multiline edittext that starts with "+++++++++++++++++" is right below when the keyboard is showing.
Right now it shows up like this:
http://imageshack.us/photo/my-images/21/pw95.png/
My XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@drawable/bginset2" >
        <TextView
            android:id="@+id/tvTripName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Trip Name:"
            android:textStyle="bold"
            android:textColor="#2B00E4"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:paddingLeft="2dp"
            android:layout_marginTop="4dp" />
        <EditText
            android:id="@+id/etFileName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/tvTripName"
            android:ems="10"
            android:inputType="textNoSuggestions|textCapWords"
            android:layout_marginLeft="2dp"
            android:singleLine="true"
            android:textColor="#569741"
            android:textSize="16dp"
            android:textStyle="bold"
            android:maxLength="30" />
        <EditText
            android:id="@+id/etShowLog"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textMultiLine|textNoSuggestions"
            android:lines="20"
            android:textStyle="normal"
            android:paddingLeft="2dip"
            android:singleLine="false"
            android:textColor="#999999"
            android:textSize="14dp"
            android:gravity="top"
            android:layout_above="@+id/btnClear" />
        <Button
            android:id="@+id/btnClear"
            android:background="@drawable/otherbuttons"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Clear Trip"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:shadowColor="#000000"
            android:shadowDx="1"
            android:shadowDy="1"
            android:shadowRadius="2"
            android:layout_alignParentBottom="true" />
        <Button
            android:id="@+id/btnSave"
            android:background="@drawable/otherbuttons"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save Trip"
            android:layout_gravity="right"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:shadowColor="#000000"
            android:shadowDx="1"
            android:shadowDy="1"
            android:shadowRadius="2"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true" />
</RelativeLayout>

How can I ensure, the any open space between the Trip Name and the two buttons below is taken up by the EditText regardless if the keyboard is out or not?

A: you need to set elements to be below one another so that when the keyboard comes up, they stay in their relative position.
for example to keep the edittext below the trip name textview you would do this
android:layout_below="@+id/tvTripName"


text:
Q: F# async stack overflow I am surprised by a stack overflow in my async-based program. I suspect the main problem is with the following function, which is supposed to compose two async computations to execute in parallel and wait for both to finish:
let ( <|> ) (a: Async<unit>) (b: Async<unit>) =
    async {
        let! x = Async.StartChild a
        let! y = Async.StartChild b
        do! x
        do! y
    }

With this defined, I have the following mapReduce program that attempts to exploit parallelism in both the map and the reduce part. Informally, the idea is to spark N mappers and N-1 reducers using a shared channel, wait for them to finish, and read the result from the channel. I had my own Channel implementation, here replaced by a ConcurrentBag for shorter code (the problem affects both):
let mapReduce (map    : 'T1 -> Async<'T2>)
              (reduce : 'T2 -> 'T2 -> Async<'T2>)
              (input  : seq<'T1>) : Async<'T2> =
    let bag = System.Collections.Concurrent.ConcurrentBag()

    let rec read () =
        async {
            match bag.TryTake() with
            | true, value -> return value
            | _           -> do! Async.Sleep 100
                             return! read ()
        }

    let write x =
        bag.Add x
        async.Return ()

    let reducer =
        async {
            let! x = read ()
            let! y = read ()
            let! r = reduce x y
            return bag.Add r
        }

    let work =
        input
        |> Seq.map (fun x -> async.Bind(map x, write))
        |> Seq.reduce (fun m1 m2 -> m1 <|> m2 <|> reducer)

    async {
        do! work
        return! read ()
    }

Now the following basic test starts to throw StackOverflowException on n=10000:
let test n  =
    let map x      = async.Return x
    let reduce x y = async.Return (x + y)
    mapReduce map reduce [0..n]
    |> Async.RunSynchronously

EDIT: An alternative implementation of the <|> combinator makes the test succeed on N=10000:
let ( <|> ) (a: Async<unit>) (b: Async<unit>) =
  Async.FromContinuations(fun (ok, _, _) ->
    let count = ref 0
    let ok () =
        lock count (fun () ->
            match !count with
            | 0 -> incr count
            | _ -> ok ())
    Async.Start <|
        async {
            do! a
            return ok ()
        }
    Async.Start <|
        async {
            do! b
            return ok ()
        })

This is really surprising to me because this is what I assumed Async.StartChild is doing. Any thoughts on which solution would be optimal?

A: I think that the stack overflow exception happens when starting the asynchronous workflow created using the <|> operator. The call to Async.StartChild starts the first workflow, which is combined using <|> and so it makes another call to Async.StartChild etc.
An easy way to fix it is to schedule the workflow in a handler of a timer (so that the it isn't added to the current stack). Something like:
let ( <|> ) (a: Async<unit>) (b: Async<unit>) =
    async {
        do! Async.Sleep 1
        let! x = Async.StartChild a
        let! y = Async.StartChild b
        do! x
        do! y }

A better way to fix it would be to create your own Seq.reduce - the current implementation folds it one-by-one so you'll get a tree of depth 10000, that contains just a single work item on the right, and all other work items on the left. If you created a ballanced binary tree of work items, then it shouldn't stackoverflow because the height will be only 15 or so.
EDIT Try replacing Seq.reduce with the following function:
module Seq =
  let reduceBallanced f input =
    let arr = input |> Array.ofSeq
    let rec reduce s t =
      if s + 1 >= t then arr.[s]
      else
        let m = (s + t) / 2
        f (reduce s m) (reduce m t)
    reduce 0 arr.Length

A: I believe Tomas got the intuition right in the answer, but here it is in my own words and more detail, after spending quite a bit of time to figure this out.

*

*The problem is that the above code does not implement the intended mapReduce algorithm due to excessive synchronization. In particular, a <|> b <|> c does not start c before both a and b have completed, so in fact <|> is useless for parallelism with more than two computations.

*The second problem is that async.Return x is isomorphic to Async.FromContinuations(fun (ok, _, _) -> ok x). The example then in fact executed sequentially, on the single thread, and the allocated closures blew the stack.
For the curious reader, below is my second attempt to design this algorithm, which seems to fare a little better (~1 sec on n=100000 and ~21 sec on n=100000 with map and reduce functions extended with Async.Sleep 1000, I have Core i3).
let mapReduce (map    : 'T1 -> Async<'T2>)
              (reduce : 'T2 -> 'T2 -> Async<'T2>)
              (input  : seq<'T1>) : Async<'T2> =
    let run (a: Async<'T>) (k: 'T -> unit) =
        Async.StartWithContinuations(a, k, ignore, ignore)
    Async.FromContinuations <| fun (ok, _, _) ->
        let k = ref 0
        let agent =
            new MailboxProcessor<_>(fun chan ->
                async {
                    for i in 2 .. k.Value do
                        let! x = chan.Receive()
                        let! y = chan.Receive()
                        return run (reduce x y) chan.Post
                    let! r = chan.Receive()
                    return ok r
                })
        k :=
            (0, input)
            ||> Seq.fold (fun count x ->
                run (map x) agent.Post
                count + 1)
        agent.Start()

A: Very interesting discussion!
I had a similar issue with Async.Parallel
let (<||>) first second = async { let! results = Async.Parallel([|first; second|]) in return   (results.[0], results.[1]) }

let test = async { do! Async.Sleep 100 }
(test, [1..10000])
||> List.fold (fun state value -> (test <||> state) |> Async.Ignore)
|> Async.RunSynchronously // stackoverflow

I was very frustrated... so I solved it by creating my own Parallel combinator.
let parallel<'T>(computations : Async<'T> []) : Async<'T []> =
  Async.FromContinuations (fun (cont, exnCont, _) ->
    let count = ref computations.Length
    let results : 'T [] = Array.zeroCreate computations.Length
    computations
        |> Array.iteri (fun i computation ->
            Async.Start <|
                async {
                    try
                        let! res = computation
                        results.[i] <- res
                    with ex -> exnCont ex

                    let n = System.Threading.Interlocked.Decrement(count)
                    if n = 0 then
                        results |> cont
                }))

And finally inspired by the discussion, I implemented the following mapReduce function
// (|f ,⊗|)

let mapReduce (mapF : 'T -> Async<'R>) (reduceF : 'R -> 'R -> Async<'R>) (input : 'T []) : Async<'R> =
let rec mapReduce' s e =
    async {
        if s + 1 >= e then return! mapF input.[s]
        else
            let m = (s + e) / 2
            let! (left, right) =  mapReduce' s m <||> mapReduce' m e
            return! reduceF left right
    }
mapReduce' 0 input.Length

A: Another, simple implementation can be something like:
let mapReduce' (map    : 'T1 -> Async<'T2>)
              (reduce : 'T2 -> 'T2 -> Async<'T2>)
              (input  : seq<'T1>) : Async<'T2> =
        async {
            let! r = input |> Seq.map map |> Async.Parallel
            return r |> Array.toSeq
                   |> Seq.reduce (fun a b -> reduce a b |> Async.RunSynchronously)

        }

In this the map phase is executed in Parallel and then reduce phase is sequential as it has data dependency on the previous calculated value.


text:
Q: Setting chart dimensions without calling .resize() Is it possible to programmatically set the dimensions of a chart before rendering? I have 10-20 charts on one page. Rendering the charts is a performance bottleneck, and having to resize the charts means that they are needlessly rendered twice. It would be a big time saver if I could just specify the size before they are rendered via style or parameter.
I have tried:

*

*Putting the Charts in a styled chart widget.

*Adding style to both the chart widget and the chart itself via dom-style.

*Setting the "plotArea" attribute on the chart.

*Adding "height" and "width" attributes as arguments to the addPlot() function

*Going through the source code to find a parameter.

Thanks!

A: When the chart renders, it should create a surface based on the underlying node that the chart is built off of. So by changing the styling of the node that your chart is using, then the chart should render based on that node.


text:
Q: how do I add a click attribute to a DIV without it applying to elements inside it? I have a DIV that when clicked on expands to reveal some inputs and buttons, and will close when clicked on again, hiding those elements. The problem I am having is that when I click on the buttons or the input boxes the closing animation happens anyway. I know I can solve this by taking the inputs and buttons out of the DIV but the DIV is very important for their formatting and organization. Any help would be great, thanks!
html:
<div id='inputArea1' class='inputAreas'>
   <input id='email' class='evInput' placeholder='example@gmail.com'>
   <input id='comf' class='evInput' placeholder='Comfirmation Code'>
   <button id='sndCde' class='evBut'>Send Code</button>
   <button id='comfBut' class='evBut'>Comfirm</button>
</div>

JS:
var main = function() {
  $('.box').click(function() {
    var el = $(this);
    if (!el.hasClass('selected')) {
      el.animate({
        "height": "300px"
      }, 200)
      el.addClass("selected");
      el.find('.inputAreas').show();
    } else {
      el.animate({
        "height": "85px"
      }, 200);
      el.find('.inputAreas').hide();
      el.removeClass("selected");
    }
  })
}
$(document).ready(main);

FULL CODE: https://jsfiddle.net/dL2vzga0/

A: event.stopPropagation(); can do the job:
$('#inputArea1').click(function(event){
  event.stopPropagation();
});

Fixed Fiddle


text:
Q: Rewrite ASP.NET page output A little background: I am trying to create a lightweight cookieless database-backed user session using a highly striped down ASP.NET implementation. This site audience will be mobile users connecting via celluar networks, so the page sizes need to be very small. I am not using the .NET session, viewstate, etc. and most page contain very few if any server controls.
I want to be able to process the output of a page request so I can modify internal links in the response with my own session information. I have read that there was an ISAPI filter to allow cookieless sessions pre-ASP.NET. That is basically what I want to build, just inside the application.
Has anyone done anything like this? I'm already inheiriting the System.Web.UI.Page class for my page base for other reasons. It seems like I should be able to do something from here.
Thanks

A: Look into using an HttpModule for this. You can process the entire response on the way out.
You might also be able to do something with a base class - perhaps go through all the server-side controls that might have links in them on the PreRenderComplete event. This wouldn't help you with HTML <A> tags, though.

A: HttpModules can give you complete control over your output, but there are also a couple other things you can do that are a little simpler.

*

*Create a custom Filter for the Response.Filter. More or less you create a Stream that you run everything through before sending it onto the underlying stream letting you make your changes there.

*Override the render event for the Page and write all your contents to a string and then make your changes there... for example...
.
//this is from memory, you might need to check it
override void Render(HtmlTextWriter writer) {

StringWriter html = new StringWriter();
HtmlTextWriter render = new HtmlTextWriter(html);
base.Render(render);
string output = html.ToString()

//make your changes to output
//output = ???

writer.Write(output);

}


text:
Q: Verificar se parêntese foi fechado Preciso de um Regex que verifique se dentro da string, o parêntese foi fechado.
Este é meu exemplo:
/regex/.test("fdfdfdf(ddsd");  //retorna false, porque o parentese nao foi fechado;.

/regex/.test("fdfedff(ffd)dd") //retorma true,  porque o parentese foi fechado;.

Minha preferência é que fosse feita como Regex, mas se for difícil ou impossível, pode ser de outra forma, porém minha exigência irredutível, é que seja em JavaScript puro.
Obs.: Isto vai ser feito em uma caixa de texto, então o número de caracteres dentro e fora do parêntese irá variar.

A: Você procura por um algoritmo de balanceamento de parenteses.
Definição do algoritmo: Percorra a String caractere a caractere registrando a quantidade de parenteses abertos e a quantidade de parenteses fechados. Se, em qualquer momento quantidade de parenteses abertos - quantidade de parenteses fechados < 0 então essa é uma expressão inválida. Se no fim da String esse saldo for positivo então existem parenteses abertos.
function isBalanced(s)
{
  var open = (arguments.length > 1) ? arguments[1] : '(';
  var close = (arguments.length > 2) ? arguments[2] : ')';
  var c = 0;
  for(var i = 0; i < s.length; i++)
  {
    var ch = s.charAt(i);
    if ( ch == open )
    {
      c++;
    }
    else if ( ch == close )
    {
      c--;
      if ( c < 0 ) return false;
    }
  }
  return c == 0;
}

Fonte: RossetaCode.org - Balanced brackets

UPDATE
Exemplo funcional no Ideone.

A: Se você possui um número fixo de parênteses (ex.: 1 e apenas 1 - não zero ou um, não um ou dois, apenas um) você pode fazer com a seguinte regex:
[^()]*[(][^()]*[)][^()]*

Caso contrário é impossível de se fazer com regex (não corresponde a uma linguagem regular). Veja a resposta do Anthony Accioly para uma possível solução.


text:
Q: Can I change the input color of my Bash prompt to something different than the terminal default? My default terminal color is gray, and that's fine.
My Bash prompt displays a bunch of colors, and this works fine:
PS1="${COLOR_RED}\u${COLOR_WHITE}@${COLOR_RED}${COMPUTERNAME} ${COLOR_BLUE}\w${GITPROMPT} ${COLOR_RESET}"

But the text I type in, at the end of the prompt, is gray. I want it to be white (ANSI code "[37m").
If I add a COLOR_WHITE at the end of the prompt, instead of the COLOR_RESET, then the default terminal color changes to white until it is reset. This makes a weird effect of some gray text, with some white text bleeding through at the top.
How can I change the "input text" color of the Bash prompt, to something other than the terminal default color?

A: Simply add the following line:
export PS1=" \[\033[34m\]\u@\h \[\033[33m\]\w\[\033[31m\]\[\033[00m\] $ "

Preview:

These are my preferred colors. You can customize each part of the prompt's color by changing m codes (e.g., 34m) which are ANSI color codes.
List of ANSI color codes:

*

*Black: 30m

*Red: 31m

*Green: 32m

*Yellow: 33m

*Blue: 34m

*Purple: 35m

*Cyan: 36m

*White: 37m

A: Try this one. It is simpler:
export PS1="\e[0;32m\t \e[32;1m\u@\h:\e[0;36m\w\e[0m$ "

A: I would suggest changing your terminal emulator's settings.
It appears you are using iTerm2 (if you are on iTerm, I suggest looking at iTerm2), so:
Settings → Profiles → Your Profile → Color. Under 'basic colors', adjust 'foreground'.
For just changing the color of the input text, in Z shell (zsh) you could use a
preexec () { echo -ne "\e[0m" }

Source 1
I have found a hack-ish way to try this with Bash:

Not natively, but it can be hacked up using the DEBUG trap. This code sets up preexec and precmd functions similar to zsh. The command line is passed as a single argument to preexec.
Here is a simplified version of the code to set up a precmd function that is executed before running each command.

preexec () { :; }
preexec_invoke_exec () {
    [ -n "$COMP_LINE" ] && return  # do nothing if completing
    local this_command=$(history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g");
    preexec "$this_command"
}

trap 'preexec_invoke_exec' DEBUG
This trick is due to Glyph Lefkowitz; thanks to [bcat] for locating the original author.
http://www.macosxhints.com/dlfiles/preexec.bash.txt

Source 2

A: I found that in my installation of Debian 8 (Jessie) I already have this, but it is commented by default. It is
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
        # We have color support; assume it's compliant with Ecma-48
        # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
        # a case would tend to support setf rather than setaf.)
        color_prompt=yes
    else
        color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

I just uncommented the line that says force_color_prompt=yes.
If you didn't already have this in your .bashrc file then you can copy this and paste it in yours.


text:
Q: Create a function factory in R from a given function instead of a typed function Usually in R one can create a function factory by writing the code of the "mother" function inside. But I want to use an already defined function as the "mother" function.
I do the following:
#
# typical way of creating a function factory:
#
power_factory <- function(exp) {
  function(x) {
    x ^ exp
  }
}
square <- power_factory(2)

rlang::env_print(square)
#> <environment: 0x7fae8900f3b8>
#> parent: <environment: global>
#> bindings:
#>  * exp: <lazy>

rlang::fn_env(square)$exp
#> [1] 2

#
# but I need to do this from an already defined "mother" function:
#
mother_fun <- function(x) {
  x ^ exp
}
power_factory <- function(exp) {
  mother_fun
}
square <- power_factory(2)

rlang::env_print(square)
#> <environment: global>
#> parent: <environment: package:rlang>
#> bindings:
#>  * power_factory: <fn>
#>  * mother_fun: <fn>
#>  * .Random.seed: <int>
#>  * square: <fn>

rlang::fn_env(square)$exp
#> NULL

Obviously one cannot directly include the variable containing the mother function (i.e., mother_fun) like I did above as the variable exp does not get binded. I have tried many things in the context of metaprogramming trying to use expressions and quasiquotations, but without success. Any help would be welcomed! Thanks.

A: You can do this (as long as the function is a closure and not a primitive function):
mother_fun <- function(x) {
  x ^ exp
}

environment(mother_fun) <- new.env()
environment(mother_fun)$exp <- 2

mother_fun(3)
#[1] 9


text:
Q: Find a permutation $\sigma$ maximizing the sum $\sum_{i=1}^n {a_i \over \sigma(i)}$.
Given  $$a_1< a_2<\dots <  a_n,$$
find a permutation $\sigma$ maximizing the sum >$$\sum_{i=1}^n {a_i \over \sigma(i)}.$$

I can't figure our where to begin. I know that the solution is $\sigma=e$, but I cannot prove it.


text:
Q: Qual a melhor maneira de traduzir projetos em PHP? Terminei um site do curso esses dias, e um dos requisitos era ele ter suporte a pelo menos 3 idiomas, depois de pesquisar um tempo vi que um método bastante recomendado era criar a mesma array em arquivos separados, mesmas chaves, mudando apenas o valor de cada chave, e dar o include dependendo do idioma selecionado (fiz por cookie).
Minha pergunta é: Esse foi mesmo o melhor método? Meu projeto não foi lá esse monstro gigante, mas deu uma canseira chamar cada palavra ou frase como array em cada arquivo dele.

A: Você deve utilizar o php-gettext com suporte para arquivos .po ou .pot, parecido com o que é feito no Wordpress. Veja este guia:
http://www.devin.com.br/php-gettext/


text:
Q: error when running application i get this answer when I'm trying to run my application both on my iphone and in simulator.
Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_AppDelegate", referenced from:
      objc-class-ref in main.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


text:
Q: Unknown space while highlighting part of text in a texblock (WPF) From trial and error I managed to highlight part of text in a textblock which is in a datatemplate of a listbox bounded to a property of a custom class. But the problem now is that when highlighting the text i get a weird unknown space between the highlighted text and the rest of the text.
Here is part of the XAML
<Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBox Name="textBox1" TextChanged="textBox1_TextChanged"/>
    <ListBox Grid.Row="1" Name="listBox1">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Name="gridOfListbox" Height="25" Margin="0,2">
                    <DockPanel Name="dockpanelWithTxtBlock">
                        <TextBlock Name="textbloxk" DockPanel.Dock="Left" FontSize="15" TextAlignment="Center">
                            <Run Background="Yellow" Text=""></Run>
                            <Run Text="{Binding ProductID}"></Run>
                        </TextBlock>
                    </DockPanel>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

And here part of the code used
ObservableCollection<TItem> items = new ObservableCollection<TItem>();
TItem[] source = new TItem[] { new TItem("Hello"), new TItem("World"), new TItem("System"), new TItem("SystemDefault"), new TItem("SystemFolder") };

And the method for event changedtext
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        string match = textBox1.Text;
        foreach (TItem TItem in listBox1.Items)
        {
            ListBoxItem lbi = (ListBoxItem)this.listBox1.ItemContainerGenerator.ContainerFromItem(TItem);
            TextBlock txtBlck = FindFirstElementInVisualTree<TextBlock>(lbi);
            Run bold = (Run)txtBlck.Inlines.FirstInline;
            Run normal = (Run)txtBlck.Inlines.LastInline;

            string s = bold.Text + normal.Text;

            if (s.ToLower().StartsWith(match.ToLower()))
            {
                bold.Text = s.Substring(0, match.Length);
                normal.Text = s.Substring(match.Length);
            }
            else
            {
                bold.Text = "";
                normal.Text = s;
            }
        }
    }

FindFirstElementInVisualTree method is used to find the textboxes needed to search of.
If anymore code is needed let me know.
I also added an image to demonstrate what the problem is.
An help will be appreciated!
Link for image: http://i.stack.imgur.com/rOj0m.png

A: When you use Run within a TextBlock in XAML, everything not wrapped in <> are considered actual strings. Having a line break would mean a space. Put the two Runs within the same line (without a space in between too).
<TextBlock Name="textbloxk" DockPanel.Dock="Left" FontSize="15" TextAlignment="Center">
    <Run Background="Yellow" Text="" /><Run Text="{Binding ProductID}" />
</TextBlock>

Edit
By the way, I just saw your first question which was marked as duplicate. This question is asked correctly; so you should ask questions in this manner in the future.


text:
Q: Using parameters from file into function I have a settings.php file with parametric variables and a functions.php with well, some functions.
functions.php uses some parameters from settings.php and also, functions.php is required once inside index.php. Well, for some reason, when trying to execute index.php the functions can not read the parameters from settings.php in this method. Does anyone know why and a possible workaround for this?

A: Your problem is probably variable scope.

Any variable used inside a function is by default limited to the local function scope.

However, without more information it's hard to say for certain.  You can find a full explanation of variable scope and global vs. local variables in the PHP manual.
Adding a line like the one below will likely resolve the issue.
<?php
global $variable_name_from_settings_dot_php;
?>

After that line, inside the function, you would have access to $variable_name_from_settings_dot_php as it was defined in settings.php.


text:
Q: Parse data from JSON response I have a JSON response data as follows
{"response":"9",
 "status":"Success",
 "msg":"Valid Access",
 "data":[{"id":"1","title":"A"},
        {"id":"2","title":"B"},
        {"id":"3","title":"C"}]
 }

How can I fetch only the data array using jquery?
Showing error as parsererror; SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 666 of the JSON data in console while parse/stringify

A: Use dot notation
var obj = {"response":"9",
 "status":"Success",
 "msg":"Valid Access",
 "data":[{"id":"1","title":"A"},
        {"id":"2","title":"B"},
        {"id":"3","title":"C"}]
 }

console.log(obj.data);

https://jsfiddle.net/c8z35au4/
or parse the data
var unparsed = '{"response":"9",
     "status":"Success",
     "msg":"Valid Access",
     "data":[{"id":"1","title":"A"},
            {"id":"2","title":"B"},
            {"id":"3","title":"C"}]
     }';
var obj = JSON.stringify(unparsed);
console.log(obj.data);

A: If it's Ajax request:
$.ajax({
    dataType: 'json',
    success: function (response) {
        console.log(response.data);
    }
});

If it's string, than use var response = JSON.parse(string) and response.data

A:

var data = {"response":"9",
 "status":"Success",
 "msg":"Valid Access",
 "data":[{"id":"1","title":"A"},
        {"id":"2","title":"B"},
        {"id":"3","title":"C"}]
 }

 console.log(JSON.stringify(data.data))

A: The best way is
 var data = {"response":"9",
     "status":"Success",
     "msg":"Valid Access",
     "data":[{"id":"1","title":"A"},
            {"id":"2","title":"B"},
            {"id":"3","title":"C"}]
     }

    data=JSON.parse(data);
   var requiredData=data.data;
   for(var i in requiredData)
{
     var id = requiredData[i].id;
     var title = requiredData[i].title;
     console.log(id);
     console.log(title);

}


text:
Q: how to check an index of array of pointers which has a certian value? i am new at c++ and i'm trying to get hold of the concept of pointers and arrays so my problem is thati have a class called "reservation" where it keeps a waiting list for unconfermed reservations
and i have an array of pointers . My question is how to check if the reservation is 1 using the array of pointers?
let's say
reservation** wait[i] ; // my array of pointers
if (wait[i]==1) // does this mean that i am checking if the index value is one?

thank you so much for answering and i would like some further explanation on this topic if you are willing? =)

A: first: reservation** wait[i] ; // my array of pointers
you better use capital letters for class names.
what you declared is an array of pointers to pointers to objects of class reservation
you have i as the length of the array, you can't use a variable for the length of the array.
it needs to be constant given at compile time
so what you should write is:
const int SIZE = 50; // change the value as you like
Reservation* wait[SIZE] ; // my array of pointers

now to check if the reservation at index i is available , there should be a member you access to give you that, something like:
    if (wait[i] -> isReserved()) // you can access field from a pointer using ->
                                  // assuming isReserved() is a member of reservation
                                 // that returns a boolean

showing your class reservation would be helpful


text:
Q: Can I template operator overloading for operator<< I have these two overloaded operator<< functions.  Can I use the template system to condense these to 1 function?
std::ostream& operator<<(std::ostream& os, const std::vector<glm::vec3>& vertices){
  for (auto i = vertices.begin(); i != vertices.end(); ++i){
    os << glm::to_string(*i) << '\n';
  }

  return os;
}

std::ostream& operator<<(std::ostream& os, const std::vector<glm::ivec3>& vertices){
  for (auto i = vertices.begin(); i != vertices.end(); ++i){
    os << glm::to_string(*i) << '\n';
  }

  return os;
}

A: Yes, you can use a function template and  std::enable_if in order to have a single function which works with both glm::vec3 and glm::ivec3:
template <typename T>
auto operator<<(std::ostream& os, const std::vector<T>& vertices)
    -> std::enable_if_t<
            std::is_same<T, glm::vec3>::value || std::is_same<T, glm::ivec3>::value,
            std::ostream&>
{
  for (auto i = vertices.begin(); i != vertices.end(); ++i){
    os << glm::to_string(*i) << '\n';
  }

  return os;
}

live wandbox example

If you want to instead support every type that works with glm::to_string, you can use expression SFINAE:
template <typename T>
auto operator<<(std::ostream& os, const std::vector<T>& vertices)
    -> decltype(glm::to_string(std::declval<T>()), std::declval<std::ostream&>())
{
    // ... as before
}

live wandbox example


text:
Q: c++ firebase segmentation fault, linux, at std::string::assign Cannot access memory at address 0xf Problem with using firebase C++ SDK on linux, for some reason it throws segmentation fault from inside the library.
I have next code:
#include <iostream>
#include "firebase/app.h"
#include "firebase/analytics.h"
extern "C" int common_main(int argc, const char* argv[]);
int main(int argc, const char* argv[]) {
    return common_main(argc, argv);
}
    int common_main(int argc, const char* argv[]) {
    namespace analytics = ::firebase::analytics;
    ::firebase::App* app;
    ::firebase::AppOptions appOptions;
    appOptions.set_app_id("project-540NUMBERNUMBER67RR"); // changed
    appOptions.set_api_key("CoDeCoDeCoDeCoDeOcDeCoDeCoDeCoDeCoDeCod"); // changed
    app = ::firebase::App::Create(appOptions);
    analytics::Initialize(*app);
    return 0;
}

And next stacktrace:
Program received signal SIGSEGV, Segmentation fault.
std::string::assign (this=this@entry=0x6170d0, __str=<error reading     variable: Cannot access memory at address 0xf>)
at /var/tmp/portage/sys-devel/gcc-5.3.0/work/build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.tcc:693
693     /var/tmp/portage/sys-devel/gcc-5.3.0/work/build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.tcc: No such file or directory.
(gdb) bt
#0  std::string::assign (this=this@entry=0x6170d0, __str=<error reading variable: Cannot access memory at address 0xf>)
    at /var/tmp/portage/sys-devel/gcc-5.3.0/work/build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.tcc:693
#1  0x0000000000402175 in std::string::operator= (__str=<error reading variable: Cannot access memory at address 0xf>, this=0x6170d0)
    at third_party/crosstool/v18/stable/toolchain/x86_64-grtev4-linux-gnu/include/c++/4.9.x-google/bits/basic_string.h:555
#2  firebase::AppOptions::operator= (this=0x6170c8) at blaze-out/gcc-4.X.Y-crosstool-v18-hybrid-grtev4-k8-opt/genfiles/firebase/app/client/cpp/include/firebase/app.h:23
#3  firebase::App::Create (options=..., name=0x402bb5 "default") at firebase/app/client/cpp/src/app_stub.cc:43
#4  0x00000000004013ae in common_main (argc=1, argv=0x7fffffffdea8) at /home/ivan.sidarau/source/firebase_t/firebaseTest/main.cpp:29
#5  0x0000000000401306 in main (argc=1, argv=0x7fffffffdea8) at /home/ivan.sidarau/source/firebase_t/firebaseTest/main.cpp:14

on x86_64 platform. With Firebase C++ SDK version 1.0.
So problem probably somewhere in this code / otherwise ABI / or SDK.
Anyone met something like that before?

A: For now is not possible to use C++ SDK with on linux platform.
Google Firebase C++ SDK use JNI/Java SDK internals on Android or iOS. It is not available on linux.


text:
Q: a lemma for Lebesgue outer measure An interval in $\mathbb{R}$ can be either open, closed, or half closed, $l(I)= b-a$ where $b, a,\ (a<b)$ are exactly the boundaries of $I$.
The following lemma is important in order to prove the countable subadditivity of the Lebesgue outer measure;
Let $(I_m)$ and $(J_n)$ be sequences of intervals such that the $I_m$'s are pairwise disjoint, prove for $k,\ p$ arbitrary in $\mathbb{N}$, that $\bigcup\limits_{m=1}^k I_m\subseteq \bigcup\limits_{n=1}^p J_n$ implies $\sum\limits_{m=1}^kl(I_m)\leq \sum\limits_{n=1}^pl(J_n)$

A: We prove this by mathematical induction on $k$, considering the proposition :
$P(k):$ $\quad$ for any $p$ in $\mathbb{N}$, if $I_m$'s are pairwise disjoint intervals such that $\bigcup\limits_{m=1}^k I_m\subseteq \bigcup\limits_{n=1}^p J_n$ then $\sum\limits_{m=1}^kl(I_m)\leq \sum\limits_{n=1}^pl(J_n)$

*

*Clearly $P(1)$ holds; if $I_1\subseteq \bigcup\limits_{n=1}^p J_n$ then we can show by induction on $p$ that $l(I_1)\leq \sum\limits_{n=1}^pl(J_n)$

*Suppose $P(k)$ holds, we want to prove $P(k+1)$, we will use induction on $p$;
Clearly for $p=1$, if $I_m$'s are pairwise disjoint intervals such that $\bigcup\limits_{m=1}^{k+1} I_m\subseteq J_1$ then $\sum\limits_{m=1}^{k+1}l(I_m)\leq l(J_1)$
Suppose now that the implication holds for a number $p$ of intervals $J_n$'s, and let $\{I_m\}_{m=1}^{k+1}$ be pairwise disjoint intervals such that $\bigcup\limits_{m=1}^{k+1} I_m\subseteq \bigcup\limits_{n=1}^{p+1} J_n$
We want to prove that $\sum\limits_{m=1}^{k+1}l(I_m)\leq \sum\limits_{n=1}^{p+1}l(J_n)$ so to show that $P(k+1)$ holds and we will be done.
If one of the $p+1$ intervals $J_n$'s doesn't contain any point from any interval $I_m$, name it $J_{n_0}$, then obviously $\bigcup\limits_{m=1}^{k+1} I_m\subseteq \bigcup\limits_{n=1, n\neq n_0}^{p+1} J_n$ and by the hypothesis $\sum\limits_{m=1}^{k+1}l(I_m)\leq \sum\limits_{n=1, n\neq n_0}^{p+1}l(J_n) \leq \sum\limits_{n=1}^{p+1}l(J_n)$,
So we can assume that each interval of the $J_n$'s intersect with at least one of the $I_m$'s,
we can discuss two cases here:

*

*In the case where there exists one $J_{n_1}$ that contains a whole interval $I_{m_1}$, we can have $k$ intervals $\{I_m\}_{m=1, m\neq m_1}^{k+1}$ contained in $\bigcup\limits_{n=1}^{p+1} J_n$ so by the first induction hypothesis $$\sum\limits_{m=1, m\neq m_1}^{k+1}l(I_m)\leq \sum\limits_{n=1}^{p+1}l(J_n)$$ but also we know that this covering contain the interval $J_{n_1}$ with length exceeding the total length of the $I_m$'s by a quantity greater or equal to $l(I_{m_1})$, recall that the $I_m$'s are pairwise disjoint, so we can add this length without losing the inequality :
$l(I_{m_1})+ \sum\limits_{m=1, m\neq m_1}^{k+1}l(I_m)\leq \sum\limits_{n=1}^{p+1}l(J_n)$, in that case then we have verified the needed.

*In the other case, when there is no interval from $(J_n)$ that contains a whole interval $I_m$, this means each interval $I_m$ is covered by at least two intervals from $(J_n)$, recall again that the $I_m$'s are pairwise disjoint, so necessarily in this case $p+1> k+1$, we can consider now the interval $I_{m_{LE}}$ that is the most 'at the left' (considering simply the interval that contain a real number lesser than all numbers in the other intervals), Notice that this interval is covered partially by $J_{n_{LE}}$ such that also this $J_{n_{LE}}$ cover no other interval, we can then have $k$ intervals $\{I_m\}_{m=1, m\neq m_{LE}}^{k+1}$ contained in $\bigcup\limits_{n=1, n\neq n_{LE}}^{p+1} J_n$ so by the first induction hypothesis $$\sum\limits_{m=1, m\neq m_{LE}}^{k+1}l(I_m)\leq \sum\limits_{n=1, n\neq n_{LE}}^{p+1}l(J_n)$$
but also here we have for one part of the interval $I_{m_{LE}}$: $l(I_{m_{LE}}\cap J_{n_{LE}})\leq l(J_{n_{LE}})$,
the other remaining part has length that is already in the 'excess' of the total length $\sum\limits_{n=1, n\neq n_{LE}}^{p+1}l(J_n)$, Thus $\sum\limits_{m=1}^{k+1}l(I_m)\leq \sum\limits_{n=1}^{p+1}l(J_n)$. QED

A: There is a shorter proof that involves counting. If you were on a finely graded line, the length of a segment would be proportional to the number of gradations in the segment
$$l(I) \approx n(I) \cdot \Delta$$
where $\Delta$ is the distance between the points of the gradation. If we think a little about it, we have the estimates
$$(n(I)-1) \Delta \le l(I) < (n(I)+1) \Delta$$
from where we get
$$\frac{l(I)}{\Delta} -1 < n(I)\le \frac{l(I)}{\Delta}+1$$
Now, if the family of disjoint segments is contained in the union of $J_1$,$\ldots$ $J_p$ then we have
$$\sum n(I_m) \le \sum n(J_n)$$
just be counting . Applying the previous estimates for $n(I)$ we get
$$\sum (\frac{l(I_m)}{\Delta} -1) < \sum(\frac{l(J_n)}{\Delta}+1)$$
that is
$$\sum l(I_m) < \sum l(J_n) + \Delta\cdot (p-k)$$
Now take $\Delta\to 0$ and get the required inequality.
You can give a similar argument in higher dimensions, but one has to be a bit more careful with the estimates for number of lattice points.
One objection to the above argument is that it uses the fact that $\mathbb{R}$ is archimedean. In fact, it the statement is really purely combinatorial, and so, it should be valid for totally ordered abelian groups.


text:
Q: Displaying a scrollable box for editing text in android I am trying to display a box which has a scrollbar, and that allows the user to type in their inputs. Currently I have a blank (The one with 'this') that accepts multi-line input using the following layout:
 <EditText
            android:id="@+id/event_description"
            android:hint="@string/hint_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:textColor="#02960B"
            android:textSize="14sp"
            android:inputType="textMultiLine"/>

Does anyone know how I could display a box with a scroll bar on the side for multi-line input

A: Wrap the EditText in a ScrollView.