text:
Q: Calculating the reciprocal distance matrix without inflicting `ComplexInfinity` Given a list of coordinates r (r[[i]]!=r[[j]]), I'd like to know the reciprocals of distances of all pairs in the list, and for the convenience subsequent operations, the trace of the resulting matrix should be all zero. I feel that this should be a frequent need, but I can't do it optimally.
My code:
R = Outer[Norm, r, r, 1];
rR = Quiet[1/R] /. {ComplexInfinity -> 0.}

But this is not such a good idea as ReplaceAll is significantly slower than the other calculations in this code. Is it a good idea to use For or Table and loop over all indices, or is there a better way to do this?

A: If the coordinates are machine reals and speed is an issue, I would Compile a function:
reciprocalDist = Compile[{{r, _Real, 2}},
  Module[{R},
   R = Outer[Subtract, r, r, 1];    (* Outer[Norm,..] is not supported in Compile *)
   Map[If[# == 0, 0, 1/#] &@Norm[#] &, R, {2}]
   ]]

SeedRandom[0]; (* for reproducibility *)
reciprocalDist[RandomReal[{-1, 1}, {4, 3}]] // MatrixForm

Theoretically one could cut the speed in half by calculating the upper triangular part.  One could preallocate a zero matrix and fill the distances two at a time with a Do loop, for instance.

A: Since DistanceMatrix[] is built-in, it seems natural to use it for this problem. Using Michael's example, let me present two approaches:
BlockRandom[SeedRandom[0]; (*for reproducibility*)
            pts = RandomReal[{-1, 1}, {4, 3}]];

(* method 1 *)
With[{id = IdentityMatrix[Length[pts]]}, 1/(DistanceMatrix[pts] + id) - id]

(* method 2 *)
DistanceMatrix[pts, DistanceFunction -> (With[{d = EuclideanDistance[##]},
                                              If[d == 0, 0, 1/d]] &)]

Both should return

A: reci[R_] :=
 With[{l = Length@R}, {m = SparseArray[Band[{1, 1}] -> 1, {l, l}]}, (1 - m)/(R + m)]

If you're before v10.4:
reci[R_] :=
 With[{l = Length@R},
  With[{m = SparseArray[Band[{1, 1}] -> 1, {l, l}]}, (1 - m)/(R + m)]]


text:
Q: Knockout custom components not updating I've got a custom component which uses functions to pass in the parameters.  In this case the observable value ($data) is not changing, but the function makes use of another observable (which is changing) and a hash table (which is changing, but cannot be made observable).
The display updates when I use this syntax:

But it does not update when I use this syntax:
        <rotate style="width: 50px; position: absolute; left: 1100px;text-align:center" params="{values: Helper.GetWeatherByFlight($data, ''Hi'')}"></rotate>

This is the component:
ko.components.register('rotate', {
    viewModel: function (params) {
        var values = [];
        var inputValues = ko.isObservable(params.values) ? params.values() : params.values;
        var length = inputValues.length;
        this.MyClass = length > 1 ? "fade-effect" : "";
        if (length >= 1) {
            var index = m_counter % length;
            $.each(inputValues, function (i, value) {
                var opacity = (index == i) ? 1 : 0;
                values.push({ value: value, opacity: opacity });
            });
        }
        this.values = values;
    },
    template: '\
                    \
                '
});

I'd prefer to be able to use the second format, but for now I am stuck with the first.  Is there something I can change, either in the component, or the way that the component is called, so make both formats update properly?  I realize that this is a somewhat unconventional usage.

A: The only reason your component refreshes in the first case is that the component binding is looking for changes, and then re-initializes the entire component when it detects any.
The rotate component itself isn't treating your parameters like they're observable it's only looking at the unwrapped values so there's nothing to tell it to refresh its view. You'll need to rewrite the component view-model to use observables and computed properties so that it can react to changes in the data.
Something like this:
viewModel: function (params) {
    var self = this;
    this.inputValues = params.values; //preserve the observable instead of unwrapping its values
    this.MyClass = ko.observable("");

    //values is a computed property so that it updates when the dependent observable (inputValues) is modified.
    this.values = ko.computed(function(){
        var values = [];
        //use ko.unwrap to safely handle either case of inputValues being an observable or non-observable.
        var length = ko.unwrap(self.inputValues).length;
        self.MyClass(length > 1 ? "fade-effect" : "");
        if (length >= 1) {
            var index = m_counter % length;
            $.each(ko.unwrap(self.inputValues), function (i, value) {
                var opacity = (index == i) ? 1 : 0;
                values.push({ value: value, opacity: opacity });
            });
        }
        return values;
    });
},

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to label my bar chart with numbers? I am using gchart and I am trying to use markers to label my bar char with numbers. So that ever bar has a number value on top of it.
I tried
markers: [$.gchart.marker('number', 'red', -1)]
markers: [$.gchart.marker('number', 'red', -1, -1)]
markers: [$.gchart.marker('number', 'red', -1, 'every')]
markers: [$.gchart.marker('number', 'red', -1, 'every1')]

I can only make it appear on the one bar. I want it to show up on every bar.
What am I doing wrong?

See it has no label on the first one.
https://chart.apis.google.com/chart?chs=400x500&cht=bvg&chd=t:55|47&chco=FDFF0F,1FEEFF&chm=N,ff0000,-1,-1,10,0&chdl=test2|test1&chdlp=b|l&chxt=x,y&chxl=0:|atest

 $('#id').gchart({
                        type: 'barVertGrouped',
                        markers: [$.gchart.marker('number', 'red',-1)],
                        height: 500,
                        width: 400,
                        series: data, // xml data from server.
                        legend: 'bottom',
                        extension: { chxt: 'x,y', chxl: '0:|atest' }
                    });

A: For non-stacked bar graphs, you need to add a marker per series:
$('#id').gchart({
    type: 'barVertGrouped',
    markers: [
        $.gchart.marker('number', 'red',0),
        $.gchart.marker('number', 'blue',1)
    ],
    height: 500,
    width: 400,
    series: [
        $.gchart.series('test1', [47], 'blue'),
        $.gchart.series('test2', [60], 'red')
    ],
    legend: 'bottom',
    extension: { chxt: 'x,y', chxl: '0:|atest' }
});


text:
Q: Java vertical line behind text? Like the line in an editor that indates where a page ends I currently have a program that goes through a code file, and aligns all the comments to the right (100 characters) so they are all in a column and outputs the code in a JList (so each line of the code is an item in the list). What i am trying to do is add a vertical line in the background where all the comments start (similar to the line in netbeans indicating where a page ends) when the adjusted code is outputted. I have a feeling this isnt possible using a JList, can anyone confirm that for sure? Is this possible at all in java, and if so how should i go about doing it?

A: Try javax.swing.BorderFactory.createMatteBorder() on the enclosing panel; use a non-zero value for the right side.
panel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.red));

A: Try to play with ListUI to draw a line in background:
public static void main(String[] args) {
    JDialog dialog = new JDialog();

    JList list = new JList();
    list.setUI(new LinedListUI());

    dialog.add(new JScrollPane(list));

    dialog.setPreferredSize(new Dimension(300, 300));
    dialog.pack();
    dialog.setLocationRelativeTo(null);
    dialog.setVisible(true);
}

static class LinedListUI extends BasicListUI {

    public void paint(Graphics g, JComponent c) {

        super.paint(g, c);
        g.setColor(Color.gray);
        int x = (int) (c.getWidth() * 0.8);
        g.drawLine(x, 0, x, c.getHeight());
    }
}

A: I'm not entirely sure what you're doing, but it seems to me like you could get a decent solution by adding an element in your JList that looks something like "-------------------" where a page break would be so that it displays.  I'm not sure if that's what you're looking for though.

A: Add the lines as html.
Below I have used apache commons StringEscapeUtils.
final String COMMENT_BEGIN =
    "";
line = "" + StringEscapeUtils.escapeHtml(line)
    .replaceFirst("//", COMMENT_BEGIN + "$0");

In the same way you could simply make the comment green or so.


text:
Q: UITextField Placeholder and Text Size should be separate - Swift My requirement is such that when placeholder of textfield is visible then its color should be gray and font size 10, but when user starts typing into the textfield, its color should be black and font size 14. I have tried this:
textField.attributedPlaceholder = NSAttributedString(string: placeholderText,
                                                    attributes: [NSAttributedString.Key.foregroundColor: Color.iPhoneGrayColor, NSAttributedString.Key.font: UIFont(name: "SourceSansPro-Regular", size: 10)!])
    textField.textColor = UIColor.black
    textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!

But, my placeholder font size is getting overridden by textfield.font, so I am unable to get placeholder of size 10. Where am I going wrong? Tried this for couple of hours now. Any help will be appreciated.

A: Simply set the placeholder after setting the font since setting the font also applies to the placeholder (see https://developer.apple.com/documentation/uikit/uitextfield/1619604-font):
textField.font = ...
textField.textColor = ...

textField.attributedPlaceholder = ...

A: Try this code into your viewDidLoad() method:
textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: Color.iPhoneGrayColor, NSAttributedString.Key.font: UIFont(name: "SourceSansPro-Regular", size: 10)!])
    textField.textColor = UIColor.black
    textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!

A: Just try this code, take the UITextFieldEditingChanged action outlet and use as below.
@IBAction func nameTextFieldEditingChanged(_ sender: UITextField) {
        if sender.text?.isEmpty ?? true {
            //placeholder text size set here
            textField.font = UIFont(name: "SourceSansPro-Regular", size: 10)!
        } else {
            // When user starting typing
            textField.textColor = UIColor.black
            textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!
        }
    }

If any doubt please comment ].

A: Just try this code may help you for further:
    var myMutableStringTitle = NSMutableAttributedString()
    let Name  = "Enter Title" // PlaceHolderText

    myMutableStringTitle = NSMutableAttributedString(string:Name, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 20.0)!]) // Font
    myMutableStringTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count))    // Color
    txtTitle.attributedPlaceholder = myMutableStringTitle


text:
Q: Cannot log in to backend of a copied TYPO3 site A copy of a TYPO3 4.4 site has been installed on a Windows 10 system. PHP and Apache versions are approximately equal. The site itself is functional and appears complete.  I can log in to the backend of the live site.  I cannot log in to the backend of the copied site.
Trials:

*

*Change database character set from latin1 to utf8

*Change my credentials to database credentials (username, md5('password')) used in localconf.php

*Comment out modified $TYPO3_CONF_VARS['BE']['installToolPassword'] in localconf.php

*./typoconf/temp_* deleted

Edit #1:
If localconf.php is modified to point to the live database I am able to log in. This suggests that the issue may be a difference in server versions.
Edit #2:
Installing MySQL server version 5.5.54 (live site has 5.5.53) makes no difference.

A:
Have you tried to set

from:
'loginSecurityLevel' => 'rsa',

to:
'loginSecurityLevel' => 'normal',

in your localconfig.php file?

A: I had the same problem. The reason was that someone copied the system via phpmyadmin.
I copied the typo3 mysql-DB via
mysqldump ... > ...sql
and
mysql ... < ...sql
and now it works

A: Maybe you should look at your cookie domain in localconf.php

A: It took a look a ancient history to see that one source of the error was the MySQL strict mode.  The clue that told me I was logged in was a record in the sys_log table with a current timestamp & my userid. An old bug report included a comment on strict mode.  By changing MySQL 5.7 my.ini from sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" to sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" I gained access to my sandbox. Hooray for wayback machines everywhere.


text:
Q: Display output of cursor I wrote this procedure
create or replace procedure copia_telefoni2 as

cursor cur_out_tel is
  select nome as original_list
  from parlamentari;

begin
for n_tel in cur_out_tel loop
  dbms_output.put_line(n_tel.original_list);
end loop;
end copia_telefoni2;

but when I run this procedure by ide or by sql*plus, the system returns me this output

Source does not have a runnable target.

Instead, if I run in the prompt of sql*plus the query of the cursor, the system returns me a list of name. Why?

A: I answer myself. In sqlplus, the first time when you run a function, you must run the instruction

set serveroutput on;

and only then must run the instruction for lunch the procesure

execute copia_telefoni2();

The following calls with sql*plus at the procedure can be omitted the first instruction


text:
Q: Which of these stories are in the same continuity as Batman: The Long Halloween? I've heard some conflicting reports as to exactly which DC comics and graphic novels are in the same continuity as Batman: The Long Halloween.
I know that Batman: Dark Victory and Catwoman: When in Rome are direct sequels, so they're definitely in the same series.
However, I've also heard people claim that The Long Halloween is in the same continuity as Batman: Year One, The Dark Knight Returns, the Batman Annual series, and Robin: Year One.
Then there is Batman: Haunted Knight, which has the same creative team and what appear to be identical character designs.
Which of these are truly in the same continuity as The Long Halloween? Are there any others that I have missed?

A: Batman: Year One (written/drawn by Frank Miller) along with Batman: The Long Halloween, Batman: Dark Victory, and Catwoman: When in Rome (all three written by Jeph Loeb/drawn by Tim Sale) share direct continuity with each other; Robin: Year One (written by Chuck Dixon and Scott Beatty/drawn by Javier Pulido and Marcos Martin) is generally held to be in the same continuity (as are the Batman Annual series - collected as the trade paperback Batman: Four of a Kind, written by Bob Kane, Chuck Dixon, Alan Grant, Doug Moench and all drawn by Brian Apthorp and featuring 'Year One' stories of Poison Ivy, Scarecrow, Riddler, and Man-Bat) although there are some inconsistencies, for example Jim Gordon's rank.
Batman: Haunted Knight is tricky. It collects three tales, all written by Jeph Loeb and drawn by Tim Sale - which subsequently led to the aforementioned collaborations The Long Halloween, Dark Victory, and When in Rome. Arguments still go on as to whether the timeline and events of any of the tales contained in Haunted Knight can be reconciled into consistency with those of The Long Halloween, Dark Victory, and When in Rome (which are generally placed in the 3rd and 4th years of Batman's career).
As for The Dark Knight Returns confusion sometimes arises here because Batman: Year One is actually held to be the 'start point' of two different DC continuities, a 'fork' if you like, leading to the main DC continuity as discussed above (lasting up until Flashpoint/The New 52) and also to the entirely separate so-called 'Miller-verse' (all Batman works, written - and sometimes drawn by - Frank Miller) comprising Batman: Year One, All-Star Batman & Robin the Boy Wonder, Spawn/Batman, Dark Knight Returns: The Last Crusade, The Dark Knight Returns, The Dark Knight Strikes Again, and The Dark Knight III: The Master Race.


text:
Q: GMAPS API V3 Custom InfoWindow: static position I really want to know if there's a way to make the InfoWindow display on the center of the screen and not above the marker.
Also, how can I get rid of that predefined crappy speech bubble style of the window itself?
When the marker gets clicked, the InfoWindow shall be displayed in the center of the screen with a width of 720px, a black opaque background and a little content (no speech bubble, no pan, just pure css). I cant find anything coming close to what I need.
I included the infobox.js to try to get what I want, but I got 2 problems with this:

*

*It doesn't take my position: absolute and the given top/left values.

*After closing the InfoBox once, it won't open again.

Some code that could be relevant:
// creating the box

var ib'.$counter.' = new InfoBox(myOptions);

// box options - just the style part

var myOptions = { boxStyle: { ,width: "720px" ,position:"absolute" ,top:
    "-100px" ,left: "100" } };

// add listener - plane js

google.maps.event.addListener(marker'.$counter.', "click",
function() { ib'.$counter.'.show() });

I would really appreciate any kind of help!
Best regards,
Rellston.


text:
Q: Page range truncation with imakeidx This is a followup question to egreg's answer to Can one truncate page ranges in index using splitidx? The answer runs into a problem if an index topic occurs in more than one page range. The following MWE, based on egreg's answer:
\begin{filecontents*}{subjind.ist}
delim_0 ", \\checkrange{"
delim_t "}"
\end{filecontents*}

\documentclass{book}
\usepackage{xparse}
\usepackage{imakeidx}

\makeindex[title=Subject Index,options=-s subjind]

\ExplSyntaxOn
\NewDocumentCommand{\checkrange}{>{\SplitArgument{1}{--}}m}
 {
  \formatrange#1
 }
\NewDocumentCommand{\formatrange}{mm}
 {
  \IfNoValueTF { #2 }
   { % no --, it's not a range
    #1
   }
   { % it's a range
    \egreg_range:nn { #1 } { #2 }
   }
 }

\bool_new:N \l__egreg_range_compare_bool

\cs_new_protected:Nn \egreg_range:nn
 {
  % print the start number
  #1--
  \int_compare:nNnTF { \str_count:n { #1 } } = { \str_count:n { #2 } }
   {% same number of digits, remove equal ones at the start
    \__egreg_range_compare:nn { #1 } { #2 }
   }
   {% different number of digits, print both
    #2
   }
 }
\cs_new_protected:Nn \__egreg_range_compare:nn
 {
  \bool_set_true:N \l__egreg_range_compare_bool
  % do a loop on the digits in the first number
  \int_step_inline:nn { \str_count:n { #1 } }
   {
    \bool_if:NTF \l__egreg_range_compare_bool
     {
      % if the digits coincide, print nothing
      \str_if_eq:eeF { \str_item:nn { #1 } { ##1 } } { \str_item:nn { #2 } { ##1 } }
       {
        \str_item:nn { #2 } { ##1 }
        % at the first differing digit, don't compare any longer
        \bool_set_false:N \l__egreg_range_compare_bool
       }
     }
     { \str_item:nn { #2 } { ##1 } }
   }
 }
\ExplSyntaxOff

\begin{document}
\setcounter{page}{95}\index{Topic0|(}Text\newpage
\setcounter{page}{101}\index{Topic0|)}Text\newpage
\setcounter{page}{124}\index{Topic1|(}\index{Topic2|(}Text\newpage
\setcounter{page}{126}\index{Topic1|)}Text\newpage
\setcounter{page}{134}\index{Topic2|)}Text\newpage
\setcounter{page}{141}\index{Topic0}Text\newpage
\index{Topic0}Text\newpage
\index{Topic0}Text
\printindex
\end{document}

yields the following error message:
! LaTeX3 Error: Too many '--' tokens when trying to split argument.

For immediate help type H <return>.
 ...

l.3   \item Topic0, \checkrange{95--101, 141--143}

Entering non-stop yields the following output:

which omits "-3" from the second index entry of Topic0. The question is how to get around this.
Edit following up on egreg's ingenious solution.  I don't know if I should ask a new follow up question, so I'm posing it first here in this edit.  egreg's solution doesn't seem to handle index sub-topics.  If one adds the following 4 lines
\setcounter{page}{135}\index{Topic0!sub0|(}Text\newpage
\setcounter{page}{136}\index{Topic0!sub0!subsub0|(}Text\newpage
\setcounter{page}{139}\index{Topic0!sub0!subsub0|)}Text\newpage
\setcounter{page}{140}\index{Topic0!sub0|)}Text\newpage

after
\setcounter{page}{134}\index{Topic2|)}Text\newpage

in the solution, one gets the following errors:
Output written in mwe.ind.
Transcript written in mwe.ilg.
 (mwe.ind
! Extra }, or forgotten \endgroup.
l.4     \subitem sub0, 135--140}

? r
OK, entering \nonstopmode...
! Extra }, or forgotten \endgroup.
l.5       \subsubitem subsub0, 136--139}

) [145] (mwe.aux) )

and this output:

Alas I don't understand egreg's code well enough to make the required changes.

A: Here it is:
\begin{filecontents*}{subjind.ist}
delim_0 ", \\checkrange{"
delim_1 ", \\checkrange{"
delim_2 ", \\checkrange{"
delim_t "}"
\end{filecontents*}

\documentclass{book}
\usepackage{xparse}
\usepackage{imakeidx}

\makeindex[title=Subject Index,options=-s subjind]

\ExplSyntaxOn
\NewDocumentCommand{\checkrange}{m}
 {
  \seq_set_from_clist:Nn \l__ssind_in_seq { #1 }
  \seq_set_map:NNn \l__ssind_out_seq \l__ssind_in_seq { \checkrangeaux{##1} }
  \seq_use:Nn \l__ssind_out_seq {,~}
 }
\seq_new:N \l__ssind_in_seq
\seq_new:N \l__ssind_out_seq

\NewDocumentCommand{\checkrangeaux}{>{\SplitArgument{1}{--}}m}
 {
  \formatrange#1
 }
\NewDocumentCommand{\formatrange}{mm}
 {
  \IfNoValueTF { #2 }
   { % no --, it's not a range
    #1
   }
   { % it's a range
    \egreg_range:nn { #1 } { #2 }
   }
 }

\bool_new:N \l__egreg_range_compare_bool

\cs_new_protected:Nn \egreg_range:nn
 {
  % print the start number
  #1--
  \int_compare:nNnTF { \str_count:n { #1 } } = { \str_count:n { #2 } }
   {% same number of digits, remove equal ones at the start
    \__egreg_range_compare:nn { #1 } { #2 }
   }
   {% different number of digits, print both
    #2
   }
 }
\cs_new_protected:Nn \__egreg_range_compare:nn
 {
  \bool_set_true:N \l__egreg_range_compare_bool
  % do a loop on the digits in the first number
  \int_step_inline:nn { \str_count:n { #1 } }
   {
    \bool_if:NTF \l__egreg_range_compare_bool
     {
      % if the digits coincide, print nothing
      \str_if_eq:eeF { \str_item:nn { #1 } { ##1 } } { \str_item:nn { #2 } { ##1 } }
       {
        \str_item:nn { #2 } { ##1 }
        % at the first differing digit, don't compare any longer
        \bool_set_false:N \l__egreg_range_compare_bool
       }
     }
     { \str_item:nn { #2 } { ##1 } }
   }
 }
\ExplSyntaxOff

\begin{document}
\setcounter{page}{95}\index{Topic0|(}Text\newpage
\setcounter{page}{101}\index{Topic0|)}Text\newpage
\setcounter{page}{124}\index{Topic1|(}\index{Topic2|(}Text\newpage
\setcounter{page}{126}\index{Topic1|)}Text\newpage
\setcounter{page}{134}\index{Topic2|)}Text\newpage
\setcounter{page}{135}\index{Topic0!sub0|(}Text\newpage
\setcounter{page}{136}\index{Topic0!sub0!subsub0|(}Text\newpage
\setcounter{page}{139}\index{Topic0!sub0!subsub0|)}Text\newpage
\setcounter{page}{140}\index{Topic0!sub0|)}Text\newpage
\setcounter{page}{141}\index{Topic0}Text\newpage
\index{Topic0}Text\newpage
\index{Topic0}Text
\printindex
\end{document}

Now \checkrange splits its input at commas and does the processing as before to every item. This also copes with subitems.


text:
Q: What is a better way of writing this SQL Query? I have written a query like this,
select Client_Id, Driver_Id
  from Trips
 where Client_Id not in (select Users_Id from Users where Banned = 'Yes')
   and Driver_Id not in (select Users_Id from Users where Banned = 'Yes')

I tried the following, but that gives me an error. Why? If this is not possible, what is a better way to write this query?
select Client_Id, Driver_Id
  from Trips
 where Client_Id not in (select Users_Id from Users where Banned = 'Yes') banned
   and Driver_Id not in banned

A: First, I would suggest NOT EXISTS over NOT IN because it works better when there are NULL values.  It can also have better performance.  So:
select t.Client_Id, t.Driver_Id
from Trips t
where not exists (select 1
                  from users u
                  where t.Client_Id = u.Users_Id and
                        u.Banned = 'Yes'
                 ) and
      not exists (select 1
                  from users u
                  where t.Driver_Id = u.Users_Id and
                        u.Banned = 'Yes'
                 );

Note that all column references are qualified, meaning that the table alias is part of the column reference.  That is also a best practice.
From a performance perspective, you want an index on users(user_id, banned).
This seems like a good way to write the query.  Attempting to simplify the query to:
where not exists (select 1
                  from users u
                  where (t.Client_Id = u.Users_Id or
                         t.Driver_Id = u.Users_Id
                        ) and
                        u.Banned = 'Yes'
                 )

Would probably kill performance because or is often a performance killer in correlated subqueries and joins.

A: Considering User_ID as Primary/Unique Key, using joins instead of where clause, in my personal experience, has a lot more difference in speed rather using where clause.  Therefore, what my suggestion would be to write the query serving the same purpose would be as follows:-
select T.Client_Id, T.Driver_Id from Trips T
  Left Join Users UC On T.Client_ID=UC.Users_ID and UC.Banned='Yes'
  Left Join Users UD On T.Driver_ID=UD.Users_ID and UC.Banned='Yes'
 where UC.User_ID Is Null and UD.User_ID Is Null

A: It seems you could use a common table expression and NOT EXISTS.  Something like this
with users_cte(Users_Id) as (
    select Users_Id from Users where Banned = 'Yes')
select t.Client_Id, t.Driver_Id
from Trips t
where not exists (select 1 from users_cte uc where t.Client_Id=uc.Users_Id)
      and not exists (select 1 from users_cte uc where t.Driver_Id=uc.Users_Id);

Here's a fiddle


text:
Q: Questions about one file copy I have used python to make testing of copy large file by different ways and compare the time consumptions, but i got a unexpectation answer compared with the theory, multiple processes or threads copy consumed much more time compared with single thread copy, i didnt know why, anyone can explain ? the code as follows:
    import os
    import time
    import shutil
    import multiprocessing
    from threading import *
    from multiprocessing import Process

    dest = 'D:\\temp\\empty\\winx64_12201_database.zip'
    src = 'D:\\05 软件\\winx64_12201_database.zip'
    thread_size = 10
    process_size = multiprocessing.cpu_count()

    def copy():
        shutil.copy(src, dest)

    def copyStream():
        source = src
        destination = dest
        if os.path.isfile(destination):
            os.remove(destination)
        copied = 0
        source = open(source, "rb")
        target = open(destination, "wb")
        while True:
            chunk = source.read(1024)
            if not chunk:
                break
            target.write(chunk)
            copied += len(chunk)
        source.close()
        target.close()

    def multiCopy():
        source = src
        source_size = os.stat(source).st_size
        if source_size%thread_size == 0:
            block_size = source_size / thread_size
        else:
            block_size = round(source_size / thread_size)
        threads = []
        for thread_id in range(thread_size):
            thread = CopyWorker(source_size, block_size, thread_id)
            thread.start()
            threads.append(thread)
        for t in threads:
            if t.is_alive():
                t.join()

    class CopyWorker(Thread):
        def __init__(self, source_size, block_size, tid):
            Thread.__init__(self)
            self.source_size = source_size
            self.block_size = block_size
            self.tid = tid

        def run(self):
            source = open(src, "rb")
            target = open(dest, "wb")
            start_position = self.block_size * self.tid
            end_position = start_position + self.block_size
            if end_position > self.source_size:
                end_position = self.source_size
            source.seek(int(start_position))
            target.seek(int(start_position))
            while start_position < end_position:
                if (start_position + 1024) < end_position:
                    chunk = source.read(1024)
                else:
                    chunk = source.read(int(end_position - start_position))
                if not chunk:
                    break
                target.write(chunk)
                start_position += 1024
            source.close()
            target.close()

    def copyMulti():
        source = src
        source_size = os.stat(source).st_size
        if source_size % process_size == 0:
            block_size = source_size / process_size
        else:
            block_size = round(source_size / thread_size)
        processes = []
        for process_id in range(process_size):
            process = Process(target=copyWorker, args=(source_size, block_size, process_id))
            process.start()
            print(process.pid)
            processes.append(process)
        for p in processes:
            if p.is_alive():
                p.join()

    def copyWorker(source_size, block_size, pid):
        source = open(src, "rb")
        target = open(dest, "wb")
        start_position = block_size * pid
        end_position = start_position + block_size
        if end_position > source_size:
            end_position = source_size
        source.seek(int(start_position))
        target.seek(int(start_position))
        while start_position < end_position:
            if (start_position + 1024) < end_position:
                chunk = source.read(1024)
            else:
                chunk = source.read(int(end_position - start_position))
            if not chunk:
                break
            target.write(chunk)
            start_position += 1024
        source.close()
        target.close()

    if __name__ == '__main__':

        print("========== Single thread Copy ==========")
        time_0 = time.time()
        copy()
        print("End:", time.time() - time_0, "\n")

        print("========== Single thread stream Copy ==========")
        time_0 = time.time()
        copyStream()
        print("End:", time.time() - time_0, "\n")

        print("========== Multi threads stream Copy ==========")
        time_0 = time.time()
        multiCopy()
        print("End:", time.time() - time_0, "\n")

        print("========== Multi processes stream Copy ==========")
        time_0 = time.time()
        copyMulti()
        print("End:", time.time() - time_0, "\n")


text:
Q: Address for Excel table cells I have a table HP_175 that has headers one of which is NOx. In a cell outside the table if I start a formula (=) and click on the header cell I get this address.
=HP_175[[#Headers],[NOx]]

How do I address the cells in the rows in the NOx column?
I tried replacing '#Headers' with a row number - didn't work.

A: To reference the seventh row (including the header),
=INDEX(HP_175[[#All],[Nox]], 7)

To reference the seventh row (not including the header),
=INDEX(HP_175[Nox], 7)


text:
Q: Windows Performance Recorder - Failed to gather system information (Error Code 0x8007002) I am trying to perform a boot trace on my computer (because it takes 10 minutes to boot Windows 10 and I'm trying to find the reason why), but after it boots and 2 minutes passes it spits out the following error:
Failed to gather system information for On/Off - Boot Trace
-> Unable to find the specified file
Screenshot
Have no clue what to do


text:
Q: libGDX Alert Dialog I have used code below:
 AlertDialog.Builder bld;

 if (android.os.Build.VERSION.SDK_INT <= 10) {
     //With default theme looks perfect:
     bld = new AlertDialog.Builder(AndroidLauncher.this);
 } else {
     //With Holo theme appears the double Dialog:
     bld = new AlertDialog.Builder(AndroidLauncher.this, android.R.style.Theme_Holo_Dialog_MinWidth);
 }

 bld.setIcon(R.drawable.ic_launcher);
 bld.setTitle("Exit");
 bld.setMessage("Are you sure you want to exit?");
 bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); }
 });
 bld.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) { finish(); }
 });
 bld.setCancelable(false);
 bld.create().show();

It seems fine, but it says "import android.app.AlertDialog cannot resolve".
It is a standard libGDX project in Android Studio.

A: The problem is that you are trying to create an Android widget which I suspect you are doing it in the Libgdx-core implementation. The core implementation does not have any references to Android SDK.
That is because it is the Android project which inherits the core project. As a result the core project is not aware of any dependencies loaded to the Android implementation.
To overcome this you need to create an interface between Android project and Core Project. That will allow you to call methods inside the Android Project.
The interface must be created inside the core Project in order for both projects to have access to it.
For example you create CrossPlatformInterface.java inside core Project. But first let's create a callback to get feedback from the Ui Thread inside the Libgdx Thread. It is important to remember that Libgdx has a seperate thread that Android main thread!!! If you try to run Widgets of Android from Libgdx threads the Application will crush.
Let's make the callback for the AlertDialog. I will suggest an Abstract class here in order to be able to override only the methods you want because sometimes Alertdialog can have 1,2 or 3 buttons.
In Core Project create AlertDialogCallback.java:
public abstract class AlertDialogCallback{

    public abstract void positiveButtonPressed();
    public void negativeButtonPressed(){}; // This will not be required
    public void cancelled(){}; // This will not be required

}

In Core Project also create CrossPlatformInterface.java:
public interface CrossPlatformInterface{
    public void showAlertDialog(AlertDialogCallback callback);
}

You notice that in the showAlertDialog method we pass the callback to get feedback when buttons are pressed!
Then you create a Class inside Android project that will implement the CrossPlatformInterface like:
public ClassInsideAndroidProject implements CrossPlatFormInterface{

   private AndroidLauncher mActivity; // This is the main android activity

   public ClassInsideAndroidProject(AndroidLauncher mActivity){
        this.mActivity = mActivity;
   }
   public void showAlertDialog(final AlertDialogCallback callback){

      mainActivity.runOnUiThread(new Runnable(){

        @Override
        public void run() {

            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setTitle("Test");
            builder.setMessage("Testing");
            builder.setPositiveButton("OKAY", new OnClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    callback.positiveButtonPressed();

                }
            });
            builder.setNegativeButton(negativeButtonString, new OnClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    callback.negativeButtonPressed();

                }

            });

            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });
   }
}

Important notes

*

*The CrossPlatformInterface will be instantiated inside the MainActivity (AndroidLauncher) as you will see below.

*The AlertDialog will be created inside the android UI thread. Because we are coming from the Libgdx thread to create the AlertDialog we need to use runOnUiThread to ensure the AlertDialog is created in ui thread.

Finally how to execute this:
Instantiate CrossPlatform interface inside Android main Activity and pass the Activity to the Interface instance which is passed inside the MyGdxGame:
public class MainActivity extends AndroidApplication {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
            cfg.useGL20 = false;

    initialize(new MyGdxGame(new ClassInsideAndroidProject(this)), cfg);
    }
}

Finally when the MyGDxGame is created we get the instance of the crossplatform interface and we can the call any functions we want to the android ui thread.
public class MyGdxGame extends Game {

ClassInsideAndroidProject crossPlatformInterface;

public MyGdxGame(ClassInsideAndroidProject crossPlatformInterface){
     this.crossPlatformInterface = crossPlatformInterface;
}

@Override
public void create() {

    crossPlatformInterface.showAlertDialog(new AlertDialogCallback(){

       @Override
       public void positiveButtonPressed(){

       //IMPORTANT TO RUN inside this method the callback from the ui thread because we want everything now to run on libgdx thread! this method ensures that.
          Gdx.app.postRunnable(new Runnable().....)

       }
       @Override
       public void negativeButtonPressed(){

       }; // This will not be required
       @Override
       public void cancelled(){

        }; // This will not be required
    });
}

@Override
public void render() {
    super.render();
}

public void dispose() {
    super.dispose();
}

public void pause() {
    super.pause();
}
}

I think it was much more writing I first intended. It might look daunting but actually is fairly simple. Well after you've done it everything looks simpler :).
The advantage of this effort is after you make this interface any call to android widget will be very easy and thread safe.
Hope it gives a good picture.

A: In libgdx you should use a scene2d dialog instead of the native Android DialogInterface. Below is how you would add a completely skinned dialog to the stage in libgdx with custom button images and background image. You would just need to substitute your own background and button image textures and font, then call quitGameConfirm() when you're ready to display the dialog...
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;

public void quitGameConfirm() {

    LabelStyle style = new LabelStyle(_fontChat, Color.WHITE);
    Label label1 = new Label("Are you sure that you want to exit?", style);
    label1.setAlignment(Align.center);
    //style.font.setScale(1, -1);
    style.fontColor = Color.WHITE;

    Skin tileSkin = new Skin();
    Texture tex = new Texture(myButtontexture);
    tex.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    tileSkin.add("white", tex);
    tileSkin.add("default", new BitmapFont());

    TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
    textButtonStyle.up = tileSkin.newDrawable("white");
    textButtonStyle.down = tileSkin.newDrawable("white", Color.DARK_GRAY);
    textButtonStyle.checked = tileSkin.newDrawable("white",
            Color.LIGHT_GRAY);
    textButtonStyle.over = tileSkin.newDrawable("white", Color.LIGHT_GRAY);
    textButtonStyle.font = _myTextBitmapFont;
    textButtonStyle.font.setScale(1, -1);
    textButtonStyle.fontColor = Color.WHITE;
    tileSkin.add("default", textButtonStyle);

    TextButton btnYes = new TextButton("Exit", tileSkin);
    TextButton btnNo = new TextButton("Cancel", tileSkin);

    // /////////////////
    Skin skinDialog = new Skin(Gdx.files.internal("data/uiskin.json"));
    final Dialog dialog = new Dialog("", skinDialog) {
        @Override
        public float getPrefWidth() {
            // force dialog width
            // return Gdx.graphics.getWidth() / 2;
            return 700f;
        }

        @Override
        public float getPrefHeight() {
            // force dialog height
            // return Gdx.graphics.getWidth() / 2;
            return 400f;
        }
    };
    dialog.setModal(true);
    dialog.setMovable(false);
    dialog.setResizable(false);

    btnYes.addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y,
                int pointer, int button) {

            // Do whatever here for exit button

            _parent.changeState("StateMenu");
            dialog.hide();
            dialog.cancel();
            dialog.remove();

            return true;
        }

    });

    btnNo.addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y,
                int pointer, int button) {

            //Do whatever here for cancel

            dialog.cancel();
            dialog.hide();

            return true;
        }

    });

    TextureRegion myTex = new TextureRegion(_dialogBackgroundTextureRegion);
    myTex.flip(false, true);
    myTex.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
    Drawable drawable = new TextureRegionDrawable(myTex);
    dialog.setBackground(drawable);

    float btnSize = 80f;
    Table t = new Table();
    // t.debug();

    dialog.getContentTable().add(label1).padTop(40f);

    t.add(btnYes).width(btnSize).height(btnSize);
    t.add(btnNo).width(btnSize).height(btnSize);

    dialog.getButtonTable().add(t).center().padBottom(80f);
    dialog.show(stage).setPosition(
            (MyGame.VIRTUAL_WIDTH / 2) - (720 / 2),
            (MyGame.VIRTUAL_HEIGHT) - (MyGame.VIRTUAL_HEIGHT - 40));

    dialog.setName("quitDialog");
    stage.addActor(dialog);

}

A:
This works (tested). Simply pass in the FragmentActivity or Activity
  via your game constructor.  You have to pass something in (like
  ClassInsideAndroidProject). Why not pass in a really useful element !.

//---------------------------------------------------------------------------
        /**  INSIDE the libgdc core, create a custom NATIVE android dialog
         * :- breaks the rules somewhat for the core,
         *  but if you ONLY using Android, why not use android Native!
         *   @member_var  private final FragmentActivity m_fa;
         * @constructor public xx_your_app_xx(FragmentActivity m_fa)
         *{
         *  this.m_fa = m_fa;
         *}
         *  @called_with if(m_fa != null) showCustomDialog(m_fa);
         * @param fa
         */
        public static void showCustomDialog(final FragmentActivity fa) //or Activity
        {
            fa.runOnUiThread(new Runnable()
            {
    //          boolean[] info;
                @Override
                public void run()
                {
                    LinearLayout ll_Main     = new LinearLayout(fa);
                    LinearLayout ll_Row01    = new LinearLayout(fa);
                    LinearLayout ll_Row02    = new LinearLayout(fa);
                    LinearLayout ll_Row09    = new LinearLayout(fa);
                    LinearLayout ll_Row10    = new LinearLayout(fa);

                    ll_Main.setOrientation(LinearLayout.VERTICAL);
                    ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
                    ll_Row02.setOrientation(LinearLayout.HORIZONTAL);
                    ll_Row09.setOrientation(LinearLayout.HORIZONTAL);
                    ll_Row10.setOrientation(LinearLayout.HORIZONTAL);

                    final CheckBox checkBox  = new CheckBox(fa);
                    final CheckBox cb_debug  = new CheckBox(fa);
                    final EditText et_User   = new EditText(fa);
                    final EditText et_Pass   = new EditText(fa);

                    TextView tv_Check        = new TextView(fa);
                    TextView tv_Debug        = new TextView(fa);
                    TextView tv_User         = new TextView(fa);
                    TextView tv_Pass         = new TextView(fa);

                    tv_Check.setText("rotation lock: ");
                    tv_Debug.setText("debug: ");
                    tv_User.setText("Username: ");
                    tv_Pass.setText("Password: ");

                    ll_Row01.addView(tv_Check);
                    ll_Row01.addView(checkBox);

                    ll_Row02.addView(tv_Debug);
                    ll_Row02.addView(cb_debug);

                    ll_Row09.addView(tv_User);
                    ll_Row09.addView(et_User);

                    ll_Row10.addView(tv_Pass);
                    ll_Row10.addView(et_Pass);

                    ll_Main.addView(ll_Row01);
                    ll_Main.addView(ll_Row02);
    //              ll_Main.addView(ll_Row09);
    //              ll_Main.addView(ll_Row10);

                    AlertDialog.Builder alert = new AlertDialog.Builder(fa);//this.getActivity()
                    alert.setTitle("Camera settings");
                    alert.setView(ll_Main);
                    alert.setCancelable(false);
                    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
    //                      info1[0] = checkBox.isChecked();
    //                      info1[1] = cb_debug.isChecked();
    //                      String user = et_User.getText().toString();
    //                      String pass = et_Pass.getText().toString();
                            //do something with the data
                            Gdx.app.log("INFO", "**** positiveButtonPressed works here too! ***");
                            Toast.makeText(fa,
                                    "checkBox: " + checkBox.isChecked() +
                                    ", cb_debug: " + cb_debug.isChecked(),
                                    Toast.LENGTH_LONG).show();
                            //IMPORTANT TO RUN inside this {} means everything now  run's on libgdx thread!.
                            Gdx.app.postRunnable( new Runnable()
                               {
                                    public void run()
                                    {
                                        //do something with the data
                                        Gdx.app.log("INFO", "**** positiveButtonPressed works here ****");
                                    }//run
                                });//postRunnable
                        }//onClick
                    });//setPositiveButton
                    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            dialog.dismiss();
                        }//setPositiveButton
                    });//setNegativeButton
                    AlertDialog dialog = alert.create();
                    dialog.show();
                }//run
            });//runOnUiThread
        }//showCustomDialog
    //--------------------------------------------------------------------------------


text:
Q: woocommerce delete all variations using REST API I want to delete all variations using REST API without passing variation ID. I didn't see any instructions in wooCommerce REST API doc.

A: I solved it by using an alternative method. The two requests created in this method. First, to call the product than pass the response variation ID's to another batch request, It will delete all the variations but still there is a limit of maximum 100 variation ID's. It won't delete more than 100 variations in a single request.
If anyone knows the better method, please share.
WooCommerce.get("products/794")
  .then((response) => {

WooCommerce.post("products/"+response.data.id+"/variations/batch", response.data.variations)
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error.response.data);
  });

  })
  .catch((error) => {
    console.log(error.response.data);
  });


text:
Q: No exception being thrown when opening MySqlConnection? I'm just starting out with async and Task's and my code has stopped processing. It happens when I have an incoming network packet and I try and communicate with the database inside the packet handler.
public class ClientConnectedPacket : IClientPacket
{
    private readonly EntityFactory _entityFactory;

    public ClientConnectedPacket(EntityFactory entityFactory)
    {
        _entityFactory= entityFactory;
    }

    public async Task Handle(NetworkClient client, ClientPacketReader reader)
    {
        client.Entity = await _entityFactory.CreateInstanceAsync( reader.GetValueByKey("unique_device_id"));

        // this Console.WriteLine never gets reached
        Console.WriteLine($"Client [{reader.GetValueByKey("unique_device_id")}] has connected");
    }
}

The Handle method gets called from an async task
if (_packetRepository.TryGetPacketByName(packetName, out var packet))
{
    await packet.Handle(this, new ClientPacketReader(packetName, packetData));
}
else
{
    Console.WriteLine("Unknown packet: " + packetName);
}

Here is the method which I think is causing the issue
public async Task<Entity> CreateInstanceAsync(string uniqueId)
{
    await using (var dbConnection = _databaseProvider.GetConnection())
    {
        dbConnection.SetQuery("SELECT COUNT(NULL) FROM `entities` WHERE `unique_id` = @uniqueId");
        dbConnection.AddParameter("uniqueId", uniqueId);

        var row = await dbConnection.ExecuteRowAsync();

        if (row != null)
        {
            return new Entity(uniqueId, false);
        }
    }

    return new Entity(uniqueId,true);
}

DatabaseProvider's GetConnection method:
public DatabaseConnection GetConnection()
{
    var connection = new MySqlConnection(_connectionString);
    var command = connection.CreateCommand();

    return new DatabaseConnection(_logFactory.GetLogger(), connection, command);
}

DatabaseConnection's constructor:
public DatabaseConnection(ILogger logger, MySqlConnection connection, MySqlCommand command)
{
    _logger = logger;

    _connection = connection;
    _command = command;

    _connection.Open();
}

When I comment out this line, it reaches the Console.WriteLine
_connection.Open();

A: I ran a POC project spinning 100 parallel tasks both with MySql.Data 8.0.19 and MySqlConnector 0.63.2 on .NET Core 3.1 console application. I create, open and dispose the connection into the context of every single task. Both providers runs to completion without errors.
The specifics are that MySql.Data queries run synchronously although the library provide async methods signature e.g. ExecuteReaderAsync() or ExecuteScalarAsync(), while MySqlConnector run truly asynchronously.
You may be running into:

*

*a deadlock situation not specifically related to the mysql provider

*not properly handling exceptions inside your tasks (you may inspect the task associated aggregate exception and also monitor mysql db logs)

*you execution be still blocked (not returning result) when you assume it's not working, if you running a high number of parallel tasks with MySql.Data as it executes synchronously

A: Multi-threading with MySQL must use independent connections.  Given that, multithreading is not a MySQL question but an issue for the client language, C# in your question.
That is, build your threads without regard to MySQL, then create a connection in each thread that needs to do queries.  It will be on your shoulders if you need to pass data between the threads.
I usually find that optimizing queries eliminates the temptation to multi-thread my applications.


text:
Q: updaing Windows Vista machine to Ubuntu server 20.04 My first Ubuntu install, so I'm a little lost.

*

*downloaded Ubuntu-20.04-live-server-amd64 from the website

*downloaded Rufus 3.0

*used Rufus to burn the file onto a memory stick

Q: Does it matter where (what machine) step 3 takes place on? (because I was only able to download Ubuntu and Rufus on a different Windows 10 machine in-order to burn the memory stick)

*went into my Vista machine BIOS and made sure it will start off of external disk

*reboot machine with my memory stick plugged in

I have tried the load process 6 times and failed over and over, but for various reasons...
A) error 28 not enough space (even though I have 500GB and 4GB RAM on that machine)
B) install goes all the way and tells me it's complete, but upon reboot machine says No Operating System installed.
I hope I've included enough info, for what I'm sure is an extremely elementary issue...thanks in advance for any help that can be provided!

A:
Q: does it matter where (what machine) step 3 takes place on?

No, but since your machine has Windows Vista, I must ask if its processor is 64bit or 32bit...
If its 32bit you could try install Xenial
https://releases.ubuntu.com/16.04/
Also, maybe you should be installing the desktop image?

my first Ubuntu install

Server image will not install a graphical user interface.
As for your problem:
The "no operating system found" is not an ubuntu message. If your machine has more then one hard drive I would check for wrong bios boot configurations, else, check this post: Setup Ubuntu Server 19.10 with MBR


text:
Q: Drawing specific layers of mapfile with MapScript? Is it possible to call a draw on a mapFile with a list of layers to include with mapScript?
I have a bunch of layers defined on my mapfile but I don't want to call all of them. I don't use "STATUS DEFAULT", i would like to call specifics layers like we can do with the get parameters, for example: "LAYERS=LAYER1,LAYER2,LAYER3&...."
For now this is my code.
$oMapFinal = ms_newMapObj($filename) or die("die\n");
$oMapImageFinal = $oMapFinal->draw();

A: With PHP-MapScript, you can get all layer names as an array.
You can make an array of the layers wish to enable, using the layer name.
This is not the most elegant solution, and there is likely a better method supported through the API, but quick and dirty you can just step through the entire list of layers and disable them and only enable the ones you want.
Step through both arrays, disabling all layer, but enabling if there is a match in the array containing the lists you wish to enable.
$enableLayers = ["LAYER1","LAYER2","LAYER3"];
$allLayers = $oMapFinal->getAllLayerNames();

foreach ($allLayers as $evalLayer)
{
   $layer = $oMapFinal->getLayerByName($evalLayer);
   $layer->updateFromString("STATUS MS_OFF");

   foreach ($enableLayers as $setLayer)
   {
      if ($setLayer === $evalLayer)
      {
         $layer->updateFromString("STATUS MS_ON");
      }
   }
}

Then call your draw statement.
Let me know if that works, I just templated that code without any testing.


text:
Q: Converting a list of strings into a dictionary where the first 4 letters of each string is the key and the rest is the value in Python I have a list that looks like this :
my_list = ['some: abcde' , 'no some: zytej', 'some: dkfja', 'no some: sdfas']

I want to convert this into a dictionary where the keys would be either 'some' or 'no some' depending on how the string starts and the values to be the rest of the string like 'abcde' etc.
Is there a way I could do this?
I would really appreciate the help.

A: It can not be converted, since you will have collisions, because any key ('some', 'no some') can have a single value.
You can instead use 'some' / 'no some' as dictionary values and 'abcde' etc as the keys.

A: 1.Create new dict
2.For every component in list split this component with str.split() by ":"
3.Add new value to dict with our Key ( KeyVal is list like ["some","abcde"]).
But your keys should be different, either values in dict will be overwritten.
my_dict = {}
my_list = ['some: abcde' , 'no some: zytej', 'some: dkfja', 'no some: sdfas']
for component in my_list:
   KeyVal = component.split(':')
   my_dict[KeyVal[0]] = KeyVal[1]


text:
Q: Hybris custom email setting custom attributes I'm creating a custom email, which should be sent to the customer after filling the form for making an appointment. I needed additional attributes, so I've extended AbstractEmailContext:
public class AppointmentEmailContext extends AbstractEmailContext
{
   private String myAttribute;
   ...
}

I'm setting the attributes in my EventListener before I'm starting the process:
final AppointmentProcessModel storeFrontCustomerProcessModel = (AppointmentProcessModel) getBusinessProcessService()
                .createProcess(
                        "appointmentEmailProcess-" + event.getEmail() + "-" + System.currentTimeMillis(),
                        "appointmentEmailProcess");

storeFrontCustomerProcessModel.setMyAttribute("test@test.com");
getModelService().save(storeFrontCustomerProcessModel);
getBusinessProcessService().startProcess(storeFrontCustomerProcessModel);

In the init method of the AppointmentEmailContext I can't get those parameters so I could set them properly and pass them to the email template. The other thing is, the entering ProcessModel in init method isn't instance of AppointmentProcessModel, but it's the instance of StoreFrontCustomerProcessModel, even though my AppointmentProcessModel is extending it.
I also tried to add AppointmentProcessModel like this:
public class AppointmentEmailContext extends AbstractEmailContext<AppointmentProcessModel>
{
...
}

and adjust init method with correct parameters (+ add overriding methods), but then I got error while creating the process:
ERROR [hybrisHTTP21] [HybrisApplicationEventMulticaster] java.lang.InstantiationException: mypackage.core.appointment.model.AppointmentProcessModel
 java.lang.RuntimeException: java.lang.InstantiationException: mypackage.core.appointment.model.AppointmentProcessModel

I don't know if there is a problem with persisting those attributes, or if I should pass those attributes some other way.
UPDATE:
I tried to add the AppointmentProcess to the *-items.xml file and I did the system update, but no changes. I checked in the backoffice that the type is added and it is extending from StoreFrontCustomerProcess. The definition is as follows:
        <itemtype code="AppointmentProcess" extends="StoreFrontCustomerProcess"
                  autocreate="true" generate="true"
                  jaloclass="mypackage.jalo.AppointmentProcess">
            <attributes>
                <attribute qualifier="email" type="java.lang.String">
                    <persistence type="property" />
                </attribute>
            </attributes>
        </itemtype>

A: Cross verify through HMC, whether your attribute gets saved in storeFrontCustomerProcessModel or not?
Try changing AppointmentEmailContext class like
public class AppointmentEmailContext extends AbstractEmailContext<AppointmentProcessModel>
{
   private String myAttribute;

    @Override
    public void init(final AppointmentProcessModel appointmentProcessModel, final EmailPageModel emailPageModel)
    {
        super.init(appointmentProcessModel, emailPageModel);
        myAttribute = appointmentProcessModel.getMyAttribute();
    }

    public String getMyAttribute() {
        return myAttribute;
    }

    //...
}

Edit
A user hasn't created the Item type for AppointmentProcess, later he has created it as I mentioned in the comment and issue resolved!!


text:
Q: Unexpectedly found nil while unwrapping an Optional value bluetooth with swift import UIKit
import CoreBluetooth
import SciChart

let maestroBrainDataCBUUID = CBUUID(string: "49535343-1E4D-4BD9-BA61-23C647249616")

class HRMViewController: UIViewController {
    var sciChartSurface: SCIChartSurface?
    var wave:Double! = 0.0

    var lineDataSeries: SCIXyDataSeries!
    var scatterDataSeries: SCIXyDataSeries!

    var lineRenderableSeries: SCIFastLineRenderableSeries!
    var scatterRenderableSeries: SCIXyScatterRenderableSeries!

    var timer: Timer?
    var phase = 0.0
    var i = 0

    @IBOutlet weak var brainRateLabel: UILabel!

wave is meaning of bluetooth data as realtime.
    var centralManager: CBCentralManager!
    var maestroPeripheral:CBPeripheral!

    override func viewDidLoad() {
        super.viewDidLoad()

        <elide>
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if nil == timer{
            timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: updatingDataPoints)
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if nil != timer{
            timer?.invalidate()
            timer = nil
        }
    }

    func updatingDataPoints(timer:Timer){
        i += 1
        if wave != nil {
            lineDataSeries.appendX(SCIGeneric(i), y: SCIGeneric((wave)))
        }

        phase += 0.01

        sciChartSurface?.zoomExtents()
        sciChartSurface?.invalidateElement()
    }

    func createDataSeries(){
        lineDataSeries = SCIXyDataSeries(xType: .double, yType: .double)
        lineDataSeries.fifoCapacity = 500
        lineDataSeries.seriesName = "line series"

        for i in 0...500{
            lineDataSeries.appendX(SCIGeneric(i), y: SCIGeneric(wave))
        }

        i = Int(lineDataSeries.count())
    }

I tried to make realtime chart using sci-chart framework.
But if I try to run coding, I get the error:

"Unexpectedly found nil while unwrapping an Optional value"

How to solve this problem?
Is there anyone who have experience like as me TT?
extension HRMViewController: CBCentralManagerDelegate {
  func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {

    <elide>
  }
}

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic,
                  error: Error?) {
    switch characteristic.uuid {
      case maestroBrainDataCBUUID:
        wave = Double(brainData(from: characteristic))*3.3/65536

      default:
      print("Unhandled Characteristic UUID: \(characteristic.uuid)")
    }
  }

I used it to chart a wave value, but I got an error when I stripped off the option. So if we use if to make the line chart appear if it is not nil, then there was an error, and I tried several times and got a runtime error. What should I do?

A: I think it could be caused by missing createDataSeries() call in your code. So when updatingDataPoints() is called lineDataSeries instance isn't initialized.
Try adding createDataSeries() call before updateDataPoints() will be called or at least add nil check for lineDataSeries instance in updateDataPoints().


text:
Q: Вёрстка html письма в Outlook Подскажите, может кто сталкивался, есть ли возможность сделать картинку фоном для письма в Outlook.
Такой пример не работает:

...

Необходимо корректно отображать в Outlook 2010 и owa (веб Outlook).
Верстка табличная, стили инлайновые.
Не пинайте, впервые сталкиваюсь.

A: Воспользуйтесь стилями, код может выглядеть примерно вот так...

Приведённый код не будет работать для всех клиентов. Лучше воспользовался вот таким способом...
Добавте сразу после  таг:

Далее ваш контент и перед закрытием  таг:

Если вы хотите узнать больше о картинке в сообщение, пожалуйста посмотрите этот ресурс. Это на Английском, но браузер переведет.


text:
Q: ember build fails after code change I am trying to run ember locally on my Windows 7 machine
When I load my app for the first time, the ember build is successful and ember serve starts and I can access my app.
However, as soon as I make even a small change in my code and try to refresh, I get the following error;

ENOTEMPTY, directory not empty
  'C:\MyCode\myProj\tmp\tree_merger-tmp_dest_dir-cQOjj10S.tmp\modules\ember-validations\validators'

I am using Sublime Text editor and have added the following in Preferences: Settings > User
"folder_exclude_patterns": [".svn", ".git", ".hg", "CVS", "tmp/*"]

While I have seen other solutions like
Disable Windows Search Index for temporary files (Windows does not seem to be already indexing my tmp folder)
Disable Windows Defender for temporary files
Please note I do not have Admin rights on my system (it's a company provided system).
I do have anti-virus running, but cannot disable it.
So kindly suggest any fixes accordingly.


text:
Q: Can I put front end app in an external folder in Heroku and serve it on request? I have a Node server and a React app compiled into its 'public' folder. My host is Heroku (a must for me).
My problem is that whenever I compile a new change on the React app I need to re-deploy the server.
Is there any way in Heroku to store the front end outside the server so that when I push a new code to the front end the server doesn't re-deploy?
Probably a bucket of some sort, or a server router that redirect calls depending on URL? Or any other solution?
Thanks!
Edit: I found an answer. It's called 'Bucketeer' in Heroku. It's the same S3 bucket from AWS. However, this is mainly for storing bulks of data, and it might not be fast enough to serving static app. So if you have any better idea I would appreciate sharing it.


text:
Q: Getting an error with Instagram when trying to authenticate In a Universal Windows App (UWP), I'm trying to log the user into his/her Instagram account, but have no luck. I keep getting the following error after the user enters their credentials and pressed the login button:

Here is the code being used:
var scopes = new List<OAuth.Scope>();
scopes.Add(InstaSharp.OAuth.Scope.Basic);

var link = InstaSharp.OAuth
                .AuthLink
                (
                    _config.OAuthUri + "authorize",
                    _config.ClientId,
                    _config.RedirectUri,
                    scopes,
                    InstaSharp.OAuth.ResponseType.Token
                );

var webAuthResult = await WebAuthenticationBroker
                                .AuthenticateAsync
                                (
                                    WebAuthenticationOptions.None,
                                    new Uri(link)
                                );

switch (webAuthResult.ResponseStatus)
{
    case WebAuthenticationStatus.Success:
        return true;

    case WebAuthenticationStatus.UserCancel:
        return false;

    case WebAuthenticationStatus.ErrorHttp:
        return false;

    default:
        return false;
}

Am I doing something wrong??

UPDATE 1:

Here is a UWP quick sample that demonstrates the issue:
UWP SAMPLE

UPDATE 2:

I found the problem that caused the "cannot connect to service" error. Here was the code that caused the problem:
        _config = new InstagramConfig(clientIdTextBox.Text,
                                clientSecretTextBox.Text,
                                WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(),
                                WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString());

My 3rd parameter, the Redirect Url, is not a web address, but an application link. If I were to change that to a simple Url like www.instagram.com, then it works, HOWEVER the browser stays open on that redirect url.
How do I make the browser redirect back to my UWP app using the redirect Url ???

A: I found my problem!
In the end, my redirect Url was not matching exactly to the Url I provided in my Instragram developer account, that was causing the issue.
UPDATE:
Although I fixed my problem, and I receive my access code correctly, it seems there is a bigger problem with Instragram because I always receive a 400 Bad Request. And from what I've seen around online from other developers, this is a very common problem. I'm in a sandbox environment, I wonder if that has anything to do with it.

A: What is the final string of the link variable you are using. It should be like the below URL
https://instagram.com/oauth/authorize/?client_id={your_client_id}&redirect_uri={your_redirect_url}&response_type=code
If you have a parameter value as part of your redirect URL, you have to add another=true both in the Instagram app and in your redirect URL that you are sending from the code.
Then you have to proceed to step 2 of the oauth process after receiving the response from instagram website for the above call.

A: It seems that you are developing a WPF windows application. In this case, i would suggest that you create a web service or WCF service and put the logic of calling instagram API and receiving the access token from the instagram API in the web service and host the service in the server. Then you can give the service web address in the instagram App as the valid URl. If you have a server IP then it is fine. If you are hosting in the local IIS, then try tunneling your localhost to the internet.
I do not have the code for WPF windows application. Below is the code i use for my c# WEB API that does the Instagram OAuth2. You can translate this to your case.
Method 1:- First Step of Oauth
private void MakeRequestForToken()
{
    string instagramIntialRedirectUrl = "https://instagram.com/oauth/authorize/?client_id={yourclientid}&redirect_uri={Should  be a valid URL that can be accessed by instagram}&response_type=code"
    Response.Redirect(instagramUrl);
}

Method 2 :- Second Step of Oauth(The Redirect URL should be given in such a way that the response which is directed to the redirect URL from instagram reaches this method)
private void HandleAuthorizeTokenResponse()
{
    var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token");
    var postData = "client_id=" + AppKey + "&client_secret=" + AppSecret + "&grant_type=authorization_code&code=" + Code + "&redirect_uri=" + RedirectUrl;
    var data = Encoding.ASCII.GetBytes(postData);
    request.Method = "POST";
    request.ContentType = "application/json; charset=utf-8";
    request.ContentLength = data.Length;
    using (var stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    var reader = new StreamReader(response.GetResponseStream());
    string objText = reader.ReadToEnd();
}

Hope this helps!


text:
Q: Reading a .json to initialize my Postgresql container using Docker-Compose Assuming the following docker-compose.yml:
version: '3'

services:
  db:
    image: postgres:12
    restart: always
    environment:
      - POSTGRES_USER=root
      - POSTGRES_PASSWORD=password
    volumes:
      - ./postgres:/docker-entrypoint-initdb.d/
    ports:
      - 5420:5420

With the knowledge of: How can I import a JSON file into PostgreSQL? to load data from a json file into Postgres... i.e:
sql> \set content `cat /tmp/test.json`
sql> create temp table t ( j jsonb );
sql> insert into t values (:'content');
sql> select * from t;

How do I ensure that I my initialize script can see the .json files when executing  cat /tmp/test.json inside docker?


text:
Q: AWS Comprehend custom classification job output has more rows than input I have used AWS Comprehend to train an NLP model. The prediction on the test set runs successfully, but the output file has more rows than the input:
input:  1000 rows
output: 2082 rows
Output looks like this:
predictions.json <...>
{"File": "test.csv", "Line": "0", "Classes": [{"Name": "No", "Score": 0.7022}, {"Name": "Yes", "Score": 0.2892}, {"Name": "tag", "Score": 0.0086}]}
{"File": "test.csv", "Line": "1", "Classes": [{"Name": "No", "Score": 0.6252}, {"Name": "Yes", "Score": 0.3747}, {"Name": "tag", "Score": 0.0001}]}
{"File": "test.csv", "Line": "2", "Classes": [{"Name": "No", "Score": 0.9295}, {"Name": "Yes", "Score": 0.0705}, {"Name": "tag", "Score": 0.0}]}
{"File": "test.csv", "Line": "3", "Classes": [{"Name": "No", "Score": 0.5247}, {"Name": "Yes", "Score": 0.4753}, {"Name": "tag", "Score": 0.0}]}
...
{"File": "test.csv", "Line": "2080", "Classes": [{"Name": "No", "Score": 0.8528}, {"Name": "Yes", "Score": 0.1471}, {"Name": "tag", "Score": 0.0001}]}
{"File": "test.csv", "Line": "2081", "Classes": [{"Name": "No", "Score": 0.5318}, {"Name": "Yes", "Score": 0.4682}, {"Name": "tag", "Score": 0.0}]}

Can anyone help me on how to use the output?

A: I faced the same issue. In my case the error was because the prediction file (Test.csv in your case) was not in the specified encoding. AWS Comprehend requires - "UTF-8" Encoding.
AWS Docs Link

A: One option is to split each sentence in a different file and use the whole folder as test set, fixing the option:
 "InputFormat": "ONE_DOC_PER_FILE"

Other options is try to find how many '/n' are there in the dataset, the error could be this one.

A: In my case, besides UTF-8 it was also the presence of carriage return \r in the text.


text:
Q: How do you differentiate between Windows 8 RTM and Windows 8 Enterprise Evaluation? This has created a lot of confusion. The Windows 8 Enterprise Evaluation cannot be upgraded and it will expire in 90 days. On the other hand the one from MSDN - Windows 8 RTM has no such restrictions.
Is it so that both Windows 8 RTM and Windows 8 Enterprise Evaluation ARE the same?
Also, is it possible to obtain ONLY the key for Windows 8 RTM from DreamSpark Premium?
Thanks!

A: To be exact, these are the additional features available with Window 8 Enterprise:

*

*Device encryption  – Device encryption, a feature introduced in Windows Mobile 6.5, encrypts the contents of a mobile device to enhance their security. Most of the organizations/enterprises would require this feature inorder to safeguard their business data.

*Windows To Go – is a feature in Windows 8 Enterprise that allows Windows 8 Enterprise to boot and run from USB mass storage devices such as flash drives and external hard drives. It is a fully manageable corporate Windows 8 environment. It is intended to allow enterprise administrators to provide users with an imaged version of Windows 8 that reflects the corporate desktop and as such is aimed at enterprises. Creation of Windows To Go drives is not supported by other Windows 8 editions.

*DirectAccess -  is a VPN-like technology that provides intranet connectivity to client computers when they are connected to the Internet. Unlike many traditional VPN connections, which must be initiated and terminated by explicit user action, DirectAccess connections are designed to connect automatically as soon as the computer connects to the Internet. DirectAccess was introduced in Windows Server 2008 R2, providing this service to Windows 7 clients (Ultimate and Enterprise editions only).

*BranchCache - a feature of Windows 7 and later, locally caches contents received from a file server or web server to enable faster subsequent uses.

*Virtualized by RemoteFX – Windows 8 Enterprise can be virtualized using RemoteFX – a set of Remote Desktop virtualization technology by Microsoft to enhance visual experience of the Remote Desktop Protocol.

*Modern UI Style App deployment (of internal applications) – you can deploy MetroUI/Windows Store internal applications hosted internally in your organization network.

You Can Claim Just the key from DreamSpark:

*

*If your a student and have a legit account, you should be able to claim the key.

*It work's similar to the BizSpark account, which is for budding Entrepreneurs.

*Attaching a screenshot on how to claim a key.


text:
Q: Getting rid of Value attribute of a textBox when using clone method in jQuery I'm having a problem with this form I'm working on. Whenever I add, or refresh the page, the values are still there. I believe this is because the clone method copies the value attribute from the textBox. Is there any way I can get rid of them when I add another textBox?

    <title>JQuery Example</title>

    <form id =
          method="POST"
          action="http://cs.harding.edu/gfoust/cgi-bin/show">

        Email:
        <input type = "text" name="email" />
        <input type ="button" value ="X" onclick = "removeTextBox()"/>

        Add another email

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

A: The Following addition should work:
var $clonedTextBox = $textBox.clone();
$($clonedTextBox).val('');


text:
Q: Dynamic data type casting in C++ I am working on a DLL that uses a fixed set of 10 data types: unsigned/signed integers of 8/16/32/64-bit and floats of 32/64-bit.
I receive a void pointer to a buffer from the client along with an enum representing the data type. I then have to look at the data type enum supplied to know what data type to cast the buffer to in order to extract the value.
Example:
nU8Val  = (*(U8*)pvBuffer);
nU16Val = (*(U16*)pvBuffer);
nU32Val = (*(U32*)pvBuffer);

Is there any way to combine this logic into a single line such as:
nMyVal = *((TypeOf(nMyVal)*)pvBuffer);

Where I don't need to define variables for all data types and repeat the same logic for each data type enumeration
EDIT: I updated the example logic for clarity on what I was trying to do as far as casting the void* buffer to a pointer of the receiving variable's data type

A: Here's a template that can deduce the type from the assignee, so that you don't have to repeat it:
template<typename To>
void copy_deduced(void* from, To& to) {
    to = *reinterpret_cast<To*>(from); // avoid c-style casts
}
copy_deduced(pvBuffer, nU8Val);
// ...

A: The problem here is that it's already in a dynamic type, namely void*. What I would do, if I understand your problem correctly, is create a struct with a void* (I would allocate a new block) and an enumeration value representing the data type. Then, use a switch statement to decide among very similar pieces of code when using the values. You can't simply cast everything to some 64-bit type such as double or unsigned long long, as is suggested in comments, because that could result in an unauthorized member l memory access error if the allocation is less than 8 bytes, which is quite conceivable, since 70% of the possible types are smaller than that.


text:
Q: Creating a custom provider angularjs I am trying to create some routing that will resolve calls to my rest api
before the page loads. Because I can't inject a service created using
app.factory(), I am attempting to create a provider to do this so I can use it in my config routing, but I'm
getting Error: [$injector:unpr] Unknown provider: $http
I want to be able to call the provider in mainFlow.api for 4 or five endpoints
that will resolve before the page loads. Am I going about this the correct way?
My code:
service.js
var mainApp = angular.module('mainApp');

mainApp.provider('choiceService', ['$http', function($http) {
    return {
        $get: function() {
            return {
                get: function(url) {
                    return $http.get(url);
                }
            };
        }
    };
}]);

config.js
var mainApp = angular.module('mainApp', [
    'ui.router'
]);

mainApp.config(['$stateProvider', '$urlRouterProvider', '$choiceServiceProvider',
    function($stateProvider, $urlRouterProvider, choiceServiceProvider) {

        $stateProvider
            .state('mainFlow', {
                abstract: true,
                url: '/base',
                template: '<ui-view/>'
            })
            .state('mainFlow.choose-main', {
                url: '',
                templateUrl: '/choose_main.html',
            })
            .state('mainFlow.contact', {
                controller: 'ContactFormController',
                url: '/contact-details',
                templateUrl: '/panel_contact_info.html',
            })
            .state('mainFlow.api', {
                url: '/about-your-api',
                controller: 'ApiFormController',
                templateUrl: '/panel_about_your_api.html',
                resolve: {
                    choice: function(choiceServiceProvider) {

                        return choiceServiceProvider.get('/api/yes-no-choice/');
                    },
                    other_choice: function(choiceServiceProvider){
                        return choiceServiceProvider.get('/api/my-other-choice/')
                    }

                }
            })

Then I can use the resolved data in controller.js
controller.js
var mainApp = angular.module('mainApp');
mainApp.controller('ApiFormController', [
    '$scope',
    '$state',
    'choiceService',
    function($scope, $state, choiceService) {

        $scope.choices = choiceService;
    }
]);

A: I was passing $http in service.js when there was no need. I was also passing in '$choiceServiceProvider' in config.js when it should have been just 'choiceServiceProvider'


text:
Q: System memory usage increase after using GPU? When I use pytorch/tensorflow to build my neural network, I find that system memory usage increase when I use GPU.
The example code is pretty simple using pytorch, a small Conv1d neural network.
When I set use_gpu=False, the system memory usage is just 131M, . But when I set use_gpu=True, system memory usage increases to more than 2G.
As far as I know, when using gpu, many parameters will be pinned into GPU'S memory, that means the system memory usage will decrease.
Could anyone help to explain the situation ?


text:
Q: Doubts with scatterplot: how to reproduce the marker area and unit square of [0,1]x[0,1] I need to generate a series of 100 random points in a unit square [0,1]x[0,1] and plot them into a scatterplot so points are green if the distance from (0,0) is less then 1; they are red otherwise.
Furthermore, the marker area of a point (x,y) should be proportional to x+y.
I have created the following code:
import matplotlib.pyplot as plt
import numpy as np
n = 100
x = np.random.rand(n)
y = np.random.rand(n)
colors = [('r' if cond else 'g') for cond in np.logical_and(x > 0.5, y > 0.5)]
colors = np.where(np.logical_and(x < 1, y < 1) ,'g', 'r')
plt.scatter(x, y, c=colors)
plt.show()

but I am not sure if:

*

*I have reproduced the unit square of [0,1]x[0,1];

*the marker area proportional to x + y sum;

Could please give any confirmation or in case, provide some piece of advice to suit better this requirements.
Thank you so much


text:
Q: Do something when all deferreds are resolved I have the following code:
loadOpportunities: function () {
    return $.getJSON("/Opportunity/GetAll").pipe(function (result) {
        //do stuff
    });
},

loadTypes: function () {
    return $.getJSON("/OpportunityTypes/GetAll", null, function (result) {
      //do stuff
    });
},

loadView: function () {
    var self = this;
    var deferred = $.Deferred();
    if (!self.viewLoaded) {
        imp2.mainViewModel.loading(true);
        deferred.pipe($.get('/Opportunities/Opportunity/GetView')
        .done(function (data) {
            $('div#opportunity').html(data);
        }));
        deferred.pipe(self.loadTypes);
        deferred.pipe(self.loadOpportunities)
        .done(function () {
            imp2.mainViewModel.loading(false);
        });
    }
    return deferred.resolve();
},

I want to do something when loadView has finished completely, including all callbacks. In other words: I want to execute some code when the GetView ajax call, the loadTypes function and the loadOpportunities function including their callbacks are all done.
The following then callback function fires when not all is completed. How can I do this?
self.loadView.then(function () {
    //Do something after ALL stuff, including all callbacks is done in loadView
});

A: I sense there may be a little confusion on the use of deferred, promises, and pipes here.
I think what you want is something like this (http://jsfiddle.net/JohnMunsch/ghdgD/):
var testObject = {
  loadOpportunities: function () {
    // This is basically saying that we're getting something via AJAX, but we want to take a swipe at changing it
    // before anyone else gets it, so by using pipe we're returning a different promise than the AJAX promise and
    // the value returned from that is what we want others to get.
    return $.ajax({
        url: "/echo/json/",
        data: opportunities,
        type: "POST"
      }).pipe(
        function (result) {
          console.log("[1]", result);

          // Change the result in some way and then return the changed result. Otherwise there's no point in using
          // a pipe() here, a done() would work as well.
          result.opportunities[0].name = "meat packer";

          return result;
        }
      );
  },

  loadTypes: function () {
    // This example is different from loadOpportunities in that it isn't using a pipe() so what is returned from
    // this function is the same promise that $.ajax() gave us. Any call to .done() just echos back the same
    // promise you gave it.
    return $.ajax({
        url : "/echo/json/",
        data : opportunityTypes,
        type : "POST"
      }).done(
        function (result) {
          console.log("[1]", result);

          // We can do something with the data received here, but outside of this function, anything that tied to
          // the promise from the $.ajax() will see the original data, not any changes we might make here.
        }
      );
  },

  loadView: function () {
    // The self = this, scope = this, etc. that you see at the start of functions is only necessary if there are
    // closures below where this might be something else. This code doesn't have that so this line is unneeded.
    //
    // Be careful about cargo-cult programming and just doing something because you do it everywhere else or you
    // see someone else do something. Try to understand why it's there.
    // var self = this;

    if (!this.viewLoaded) {
      console.log("loading");
      var viewPromise = $.ajax({
          url : "/echo/json/",
          data : view,
          type : "POST"
      }).done(
        function (result) {
          console.log("[1]", result);

          // We might take this and dump it in a <div> somewhere.
        }
      );

      var typesPromise = this.loadTypes();
      var opportunitiesPromise = this.loadOpportunities();

      // The following line hands back a single promise (that's what $.when() does) that wraps all three of the
      // other promises and only fires when all three have completed OR when any one of them has failed.
      return $.when(typesPromise, opportunitiesPromise, viewPromise).done(
        function () {
          // Here I've tied a function to the promise as soon as I've created it. But since I'm handing back the
          // promise, I can also tie functions to it later as well, even after the promise has resolved or been
          // rejected.
          console.log("[2]", "All done loading types, views, and opportunities");
        }
      );
    }

    return true;
  }
};

// Note: Unlike with all the steps labeled [1], I don't believe there is a formal ordering for the
// .done()'s attached to the same promise like both [2] and [3]. So it may be possible for those two steps to
// happen [2]/[3] or [3]/[2] although they always happened [2]/[3] in my testing.
$.when(testObject.loadView()).done(
  function () {
    console.log("[3]", "This will only trigger after all the steps in load view have completed.");
  }
);

Note: I changed the style of your AJAX calls but that was just because I needed to build a working example in jsFiddle. Click on the link above to see this in action over there. It works and it orders things as you expect. You probably don't need pipe as much as you think unless you plan to manipulate the AJAX results before anyone tied to the promise sees the results. Otherwise, .done(), .fail(), and .when() will handle most situations.


text:
Q: Trying to hide a paragraph tag using jQuery addClass when an inline html onclick is clicked? I am trying to hide a paragraph tag using jQuery addClass when an inline html onclick is clicked, however it does not seem to be working, any suggestions?

     .remove {

        display: none;

     }

           ›

Where Innovation

<button>Hide</button>

This is a paragraph with little content.

This is another small paragraph.

A: You can do it like this:

$(".next").click(function(){
  $(".fade1").addClass("remove");
});
.remove {
  display: none;
}

›

Where Innovation

If you prefer jQuery over JavaScript then you always have to include its library in order to use it, otherwise it won't work. Here I am using jQuery CDN (Content Delivery Network) of version 2.1.1.
But you can also download it (production or development / compressed or uncompressed) and reference it with the

Where js is a typical folder name where you keep all of your jQuery/JavaScript files, jquery-2.1.1.min is a file name with the information about the used version and .js as a necessary file extension.


text:
Q: How to handle transaction on two or more methods in which second one depends on first to complete? I am keeping my two methods in a single transaction. Both the methods are working on same tables.
When I keep both in a single transaction, the second one when go to operate on the same tables, it doesn't execute.
I tried to keep both the methods in different transaction , after committing the first one I begin the second one but the same problem occurs.
Then I tried making different objects of session and still the result is same.
I want to keep these methods in transactions . kindly suggest me the suitable way to handle this.
I don't want to make any changes in the stored procedure , I want to handle it on C# code level in my windows application.
Regards,
Nitish

A: Create a Threaded environment. Say Thread 1 is T1 (First Method), Thread 2 is T2(Second Method). Start T1 and T2. But in the T2, Wait for T1 to complete that Pause the T2 and Resume when T1 is completed.
[You can do this easily by using the Transactions at server itself :) ]


text:
Q: How do I add a select button to this list please? How do I change this list from a drop down list that automatically changes to the URL in the drop down field, to a drop down list where the user has to select a green "select" button?
Thank you,
Steve.
<select name="cars" id="dynamic_select">
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Borrowing-Power-Calculator.aspx?ID=MFAA">Borrowing Power Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Loan-Repayment-Calculator.aspx?ID=MFAA">Loan Repayment Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Lump-Sum-Repayment-Calculator.aspx?ID=MFAA">Lump Sum Repayment Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Extra_Repayment_Calculator.aspx?ID=MFAA">Extra Repayment Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Budget-Planner.aspx?ID=MFAA">Budget Planner</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Loan-Comparison-Calculator.aspx?ID=MFAA">Loan Comparison Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/How-Long-to-Repay-Calculator.aspx?ID=MFAA">How Long to Repay Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Split-Loan-Calculator.aspx?ID=MFAA">Split Loan Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Property-Selling-Cost-Calculator.aspx?ID=MFAA">Property Selling Cost Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Property-Buying-Cost-Calculator.aspx?ID=MFAA">Property Buying Cost Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Saving-Calculator.aspx?ID=MFAA">Saving Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Term-Deposit-Calculator.aspx?ID=MFAA">Term Deposit Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Stamp-Duty-Calculator.aspx?ID=MFAA">Stamp Duty Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Credit-Card-Calculator.aspx?ID=MFAA">Credit Card Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Income-Tax-Calculator.aspx?ID=MFAA">Income Tax Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Reverse-Mortgage-Calculator.aspx?ID=MFAA">Reverse Mortgage Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Leasing-Calculator.aspx?ID=MFAA">Leasing Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Home-Loan-Offset-Calculator.aspx?ID=MFAA">Home Loan Offset Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Honeymoon-Loan-Calculator.aspx?ID=MFAA">Honeymoon Loan Calculator</option>
  <option value="http://www.visionabacus.com/Finance/Australia/1/SuiteA100/640/Comparison-Rate-Calculator.aspx?ID=MFAA">Comparison Rate Calculator</option>
</select>

<script>
    $(function(){
      // bind change event to select
      $('#dynamic_select').on('change', function () {
          var url = $(this).val(); // get selected value
          if (url) { // require a URL
              window.location = url; // redirect
          }
          return false;
      });
    });
</script>

A: Check this out:
<select name="cars" id="dynamic_select">
  <option value="https://google.com">google.com</option>
  <option value="https://google.de">google.de</option>
</select>

JS:
  $('#dynamic_select').on('change', function () {
      var url = $(this).val();
        window.location = url;
  });

Update:

 $('#Submit').on('click', function () {
      var url = $('#dynamic_select').val();
        window.location = url;
        alert(url); // remove this line later
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="cars" id="dynamic_select">
  <option value="https://google.com">google.com</option>
  <option value="https://google.de">google.de</option>
</select>
<input id="Submit" value="Go" type="submit"/>


text:
Q: c++ matrix class dynamic array argument I want to implement a Matrix class. I coded an array of arrays of pointers. When I set the values of each element of the array to 0 with a for loop, it works fine (apparently). But when I try to declare a function of my class (setvalues) to take the values of a 1D array and store them in the matrix, theres a problem with the arguments. I am not sure how to declare a function that takes a dynamic array as argument.
#include<iostream>
using namespace std;

class Matrix{
    int rows, columns, numE;
    double *mData=new double[numE];

    public:
    double** matrix;
    Matrix(int,int);
    setmatrix();
    setvalues(double);
};

Matrix::Matrix(int x, int y){
    rows=y;
    columns=x;
    matrix=new double*[columns];
    for(int i = 0; i < columns; ++i){
            matrix[i]=new double[rows];
    }
}

Matrix::setmatrix(){
    for(int i=0;i<rows;i++){
        for(int j=0;j<columns;j++){
            matrix[i][j]=0.0;
            cout<<matrix[i][j]<<endl;
        }
    }
}

Matrix::setvalues(double mData[]){
    for(int i=0;i<rows;i++){
        for(int j=0;j<columns;j++){
            matrix[i][j]=mData[i];
        }
    }
}
int main(){

Matrix AA(2,2);
AA.setmatrix();
//AA.setvalues();
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){
          cout<<AA.matrix[i][j] << endl;
        }
    }

cout<< AA.matrix << endl;
delete [] AA.matrix;
return 0;
}

PS: I don't want to use vector or smart pointers. Also if you have any feedback about my code regarding functionaity, readability and if you know a smarter way to do it please tell me.


text:
Q: Connection between controller and view in rails In users_controller.rb I've got my method:
def showallusers
 @users = User.all

 respond_to do |format|
  format.html  # showallusers.html.erb
  format.json  { render :json => @users }
 end
end

and in app/views/users I've got showallusers.html.erb and in it:

test

but when I type
 http://localhost:3000/users/showallusers

in browser, it shows me show.html.erb instead.
My routes.rb
  resources :users

  resources :projects do
    resources :issues
  end

  #resources :issues

  resources :projects

  resources :sessions

  root :to => "users#index"

  match "/auth/:provider/callback" => "sessions#create"
  match "/signout" => "sessions#destroy", :as => :signout

Do you know, what is wrong and how can I fix it? thanks

A: In your routes.rb:
resources :users do
  collection do
    get :showallusers # why not :show_all_users? Isn't it more readable?
    # you may also need
    # post :showallusers
  end
end

Then restart your server to make sure the new url-helpers are generated (the new helper should be showallusers_users_path)


text:
Q: undefined method `page' for # My Active admin version is 0.3.0, other than that m also using 'Will_paginate' i had made the configuration settings of conflict between kaminari and will_paginate but still m getting this error. i dont know where m making a mistake everything is working fine for other model but not for this model, need help, i have searched also found some links but not get satisfactory answer, it give me error on bold line
    ActiveAdmin.register User do
      menu :parent => 'Reports'

      filter :id
      filter :user_id
      filter :updated_at
# and other filters

      scope :all, :default => true do |user|
        User.all
      end
      scope :active do |user|
        User.where("user.status = ?", 'actvie')
      end
      scope :rejected do |user|
        User.where("user.status = ?", 'non_active')
      end

      actions :index, :show

      index do
        column "ID" do |u|
          link_to u.id, cs_user_path(u)
        end
        column "Status" do |u|
          status_tag(u.status)
        end
        column "User" do |u|
          link_to(u.user.full_name, cs_user_path(u.user)) rescue nil
        end
      end

      collection_action :index, :method => :get do
        scope = User.includes([:group,:address]).scoped
        scope = scope.order params[:order].gsub(/_/,' ') if params[:order]

        @collection = scope.paginate(:per_page => 25,:page => params[:page]) if params[:q].blank?
        @search = scope.metasearch(clean_search_params(params[:q]))

        **super do |format|**
          format.html {
            render "active_admin/resource/index"
          }
        end
      end
    end

A: The GitHub documentation of will_paginate states that arrays are not supported that well.
I will suggest using the kaminari gem which includes a helper method for array pagination.
You should be able to take it from here.