text:
Q: How I can write polymeric reaction in latex Is it possible write this reaction in latex ?

I used this code, but the "image" of raction is very big. How I can reduce it ?
    \documentclass[12pt,twoside,a4paper,openright]{report}
    \usepackage[portuguese]{babel}
    \usepackage[utf8]{inputenc}
    \usepackage[inner=3cm,outer=2cm,tmargin=2.0cm,bmargin=2.0cm, includefoot, includehead]{geometry}
    \usepackage{chemfig}
    \usepackage{chemmacros}
    \usepackage{enumitem}

    \begin{document}
    \newcommand\setpolymerdelim[2]{\def\delimleft{#1}\def\delimright{#2}}
    \def\makebraces[#1,#2]#3#4#5{%
    \edef\delimhalfdim{\the\dimexpr(#1+#2)/2}%
    \edef\delimvshift{\the\dimexpr(#1-#2)/2}%
    \chemmove{%
    \node[at=(#4),yshift=(\delimvshift)]
    {$\left\delimleft\vrule height\delimhalfdim depth\delimhalfdim
    width0pt\right.$};%
    \node[at=(#5),yshift=(\delimvshift)]
    {$\left.\vrule height\delimhalfdim depth\delimhalfdim
    width0pt\right\delimright_{\rlap{$\scriptstyle#3$}}$};}}
    \setpolymerdelim()

    \begin{enumerate}[label=(\arabic*)]
\setcounter{enumi}{3}
 \item\setatomsep{1.8em}
\chemfig{R-O-Si(-[2]OR)(-[6]OR)-[@{downleft,0.9},2]O-Si(-[2]OH)(-[6]OR)-[@{downright,0.4},2]OH}

%\schemestart
%\arrow(.mid east--.mid west){->[\parbox{5cm}{\centering -m \si{H_2O}\\-k ROH}]}[,1.8]
%\schemestop
%\arrow(.mid east--.mid west){->[\parbox{5cm}{\centering -m \si{H_2O}\\-k ROH}]}[,1.8]
%\setchemrel{1pt}{}{6em}
\chemrel[-m {\si{H_2O}//-k ROH}]{->}
%\chemrel[$-\mathrm{m\,H_2O}$]{->}
%\arrow{->[\parbox{5cm}{\centering -m \si{H_2O}\\-k ROH}]}
 \chemfig{-O-Si(-[2]O-[2]Si([2]-)([4]-)-)(-[6]O-[4]R)-O-Si(-[2]O-[8]H)(-[6]O-[6]Si([6]-)([4]-)-)-O-Si(-[2]O-[2]Si([2]-)([4]-)-)(-[6]O-[8]H)-O-Si([2]-)([6]-)([8]-)}

\makebraces[40pt,40pt]{n}{downleft}{downright}
\end{enumerate}

    \end{document}

A: I propose the following solution. I've made a number of changes:

*

*First of all I find your use of enumerate a bit strange. It looks like you want equation numbers for your reactions. If that's it then I'd use an equation environment. With the class option leqno its numbers will be placed on the left.

*I'd still use chemfig's \schemestart ... \schemestop mechanism. In it the \arrow command can be used to have the reaction downwards instead to left.  This can be done by using the optional <angle> argument:
\arrow{<arrow spec>}[<angle>,<length>]

I use an angle of -90 below. In order for the label not to rotate you can use the * syntax of \arrow labels:
\arrow{->[*{<angle>}<label>]}[-90]

Using *{0} will give the label a horizontal orientation.

*This one is more a cosmetic thing: I use a lot more indentation inside \chemfig{} which makes the formulae much more readable.

*For placing several lines on the arrow I use a tabular. This is more comfortable than a \parbox because there's no need to specify a width.

*I use math mode for the stoichiometric factors.

*Last I changed the syntax of \makebraces a bit into a more LaTeX-like syntax and renamed it into \makepolymerbraces. This is only my personal taste...

The complete example gives:

Here's the code:
\documentclass[12pt,leqno]{article}
\usepackage[utf8]{inputenc}

\usepackage{chemfig}
\usepackage{chemformula}

% polymer delimiters:
\makeatletter
\newcommand*\setpolymerdelim[2]{\def\polymer@delimleft{#1}\def\polymer@delimright{#2}}

\newcommand*\makepolymerbraces[5]{%
  \edef\polymer@delimhalfdim{\the\dimexpr(#1+#2)/2}%
  \edef\polymer@delimvshift{\the\dimexpr(#1-#2)/2}%
  \chemmove{
    \node[at=(#4),yshift=(\polymer@delimvshift)]
      {$
       \left\polymer@delimleft
         \vrule height\polymer@delimhalfdim depth\polymer@delimhalfdim width0pt
       \right.
      $};
    \node[at=(#5),yshift=(\polymer@delimvshift)]
      {$
        \left.
          \vrule height\polymer@delimhalfdim depth\polymer@delimhalfdim width0pt
        \right\polymer@delimright_{\rlap{#3}}
      $};
  }%
}
\makeatother

\usepackage{lipsum}% dummy text

\begin{document}

\lipsum[2]

\begin{equation}
  \setpolymerdelim[]\setatomsep{2em}
  \schemestart
    $x$
    \chemfig{
      R-O-Si
        (-[2]OR)
        (-[6]OR)
      -[@{b1,.6},1.5]
      O-Si
        (-[2]OH)
        (-[6]OR)
      -[@{b2},2]
      OH
    }
    \arrow{%
      ->[*{0}%
      \begin{tabular}{c}
        \ch{$-m$ H2O} \\
        \ch{$-k$ ROH}
      \end{tabular}%
      ]%
    }[-90,1.5]
    $z$
    \chemfig{
      -O-Si
        (-[2]O-[2]Si([2]-)([4]-)-)
        (-[6]O-[4]R)
      -O-Si
        (-[2]O-[8]H)
        (-[6]O-[6]Si([6]-)([4]-)-)
      -O-Si
        (-[2]O-[2]Si([2]-)([4]-)-)
        (-[6]O-[8]H)
      -O-Si
        ([2]-)
        ([6]-)
      -
    }
  \schemestop
  \makepolymerbraces{30pt}{30pt}{$n$}{b1}{b2}
\end{equation}

\lipsum[2]

\end{document}

A: Please use the package chemfig for this. For the braces you should have a look in chapter 12.5 of its documentation.
Here is some code to start with:
% arara: pdflatex

\documentclass{article}
\usepackage{chemfig}

\begin{document}
\setatomsep{7mm}
\chemfig{x\,Et-O-Si(-[2]OEt)(-[6]OEt)-O-Si(-[2]OH)(-[6]OEt)-OH}
\chemrel[$-\mathrm{m\,H_2O}$]{->}
\chemfig{z-O-Si(-[2]O-[2]Si([2]-)([4]-)-)(-[6]O-[4]Et)-O-Si-O-Si-O-Si-}
\end{document}


text:
Q: Change a select list dynamically after choosing one of the radio buttons with JSP I'm building a web app with JSP/JavaBeans etc. Only started this stuff for about 3 weeks. Is it possible to do the example here with JSP?
Tried to get the value printed out on the JSP first to test out but gave me a null value.

Select which you want to do:

            <input type="radio" value="buy" name="purchase" checked />Buy
            <input type="radio" value="rent" name="purchase" />Rent
        <%
            String choice = request.getParameter("purchase");
            out.println(choice);
        %>

A: Expression Language (EL) statements and scriptlets in JSPs are executed on the server before the page is sent to the browser.
The radio button changes in response to user input. EL and scriptlets cannot detect this.
The only way to manage this with EL is to send a request to the server whenever the radio button changes. Sending such a request would have to be implemented with Javascript or Jquery.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to improve aggregation query in mongoDB? Let's say i have this 2 of huge documents:
[
 {
  _id: ....,
  status: "A",
  class: "DIP1A",
  "created.user._id": ...,
  "created.dt": ....,
  "category": "private",
  price: 100.00 //type double
 },
 {
  _id: ....,
  status: "A",
  class: "DIP2A",
  "created.user._id": ...
  "created.dt": ...,
  "category": "public",
  price: 200.00 //type double
 },
];

Query:
    var pipeline = [

              {
                $match: {
                  "created.user._id": ....
                }
              },
              {
                $unwind: "$class"
              },
              {
                $unwind: "$price"
              },
              {
                $group: {
                  _id: "$class",
                  price: {
                    $sum: "$price"
                  },
                  count: {
                    $sum: 1
                  }
                }
              },
              {
                $project: {
                  _id: 0,
                  class: '$_id',
                  count: 1,
                  price: 1
                }
              }
    ];

 db.myCollection.aggregate(pipeline);

Problem issue:

*

*Query without calculate/$sum "$price", it's running really faster;

Indexes:
db.myCollection.ensureIndex({ 'created.user._id': -1 });
db.myCollection.ensureIndex({ 'created.user._id': -1, class: 1 });
db.myCollection.ensureIndex({ 'created.user._id': -1, price: 1});

Performance:

*

*without $sum calc : 5 second with huge of records.

*with $sum cals : 20 minutes with huge of records.

A: The one thing you really should do is move the $project stage to right after the $match stage (if the documents contain more data then stated in your question (huge documents)).
You want as little data as possible through the pipeline.
Also i see an $unwind on price and class but in your example they aren't array's. It could be a copy/paste issue ;-)
Like :
var pipeline = [

          {
            $match: {
              "created.user._id": ....
            }
          },
         {
            $project: {
              _id: 0,
              class: '$_id',
              count: 1,
              price: 1
            }
          },
          {
            $unwind: "$class"
          },
          {
            $unwind: "$price"
          },
          {
            $group: {
              _id: "$class",
              price: {
                $sum: "$price"
              },
              count: {
                $sum: 1
              }
            }
          },
];


text:
Q: Parsing custom tags using Simple XML Serialization I have the below XML :
<com.abc.xyz.container>
 <data class="list">
   <com.xyz.abc.VO.fruits>
       <id>28</id>
       <name>
        <![CDATA[ Apple ]]>
       </name>
   </<com.xyz.abc.VO.fruits>

   <com.xyz.abc.VO.fruits>
       <id>29</id>
       <name>
         <![CDATA[ Orange ]]>
       </name>
   </<com.xyz.abc.VO.fruits>
<com.abc.xyz.container>

I tried to create class in this manner :
@Root(name = "com.abc.xyz.container")
public class Response {

    @Element(required = false)
    private Data list;

    public Data getList() {
        return list;
    }
    public void setList(Data list) {
        this.list = list;
    }
}

public class Data {

    @ElementList(inline = true, name = "com.xyz.abc.VO.fruits", required = false)
    private List<Fruits> fruits;

    public List<Fruits> getfruits() {
        return fruits;
    }

    public void setfruits(List<Fruits> fruits) {
        this.fruits = fruits;
    }
}

EDIT 1
public class Fruits{

    @Element(required = false)
    private int id;
    @Element(required = false)
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

But when i try to get the size of the List<Fruits> it gives me NullPointerException.
How can i correct my code ? I am using Simple XML Serialization(org.simpleframework.xml.*).


text:
Q: In Perl, how can I convert multiple decimal numbers in a string to their hexadecimal equivalent? In Perl, how do I convert multiple decimal numbers in a line of a file to their hexadecimal equivalents?
I have code which will convert the last number found but leaves the prior numbers unconverted, I want to convert all the numbers not just the last one found:
if ($line =~ /[0-9]+/) {
   $loc = index($line,/\s+[0-9]+\s*/);
   $mybyte = substr($line,$loc);
   $newbyte = sprintf("%x\n", $mybyte);
   $newline = substr($line,0,$loc).$newbyte;
   print my_report $newline;
}

A: $line =~ s/([0-9]+)/sprintf "%X", $1/eg;


text:
Q: using R to web scrape data from javascripted download button I am trying to web scrape the csv generated by clicking the 'CSV' button on this site (located below the left side of the graph). The problem is that the CSV is generated from Javascript that parses the embedded table (below middle of graph). I am aware I could just scrape the embedded table . I do not want to do this.
I want a solution that uses R to download a csv from the 'CSV' button. My attempt so far uses the r packages "rvest" and "V8". I'm just confused on what I do as I can't find good examples of the V8  package being used on javascript download buttons. Here's what I got so far.
I'm confused on the line ct <- v8() onwards... How do i apply the V8 package in the context of the javascript in the source code of the above URL?
library(rvest)
library(V8)

URL <- https://www.bankofengland.co.uk/boeapps/database/fromshowcolumns.asp?Travel=NIxSTxTIxSUx&FromSeries=1&ToSeries=50&DAT=RNG&FD=1&FM=Jan&FY=2009&TD=30&TM=Mar&TY=2020&FNY=&CSVF=TT&html.x=91&html.y=29&C=IIN&Filter=N#

raw_html <- GET(URL) %>%
     content() %>%
     rvest::html_nodes("script") %>%
     html_text()

 ct <- v8()

   read_html(ct$eval(gsub('document.ready','',raw_html))) %>%

   html_text()

For Context, the javascript for the buttons are as below
<script>
$(document).ready(function() {
    $.fn.dataTable.moment( 'DD MMM YY' );

    $('#stats-table').DataTable( {
    paging: false,
    "info":     false,
    "order": [ 0, 'desc' ],
    fixedHeader: {
    header: true
    },
     dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'print'
        ]
    } );

} );
</script>

A: A RSelenium solution,
library(RSelenium)
driver = rsDriver(browser = c("firefox"))

remDr <- driver[["client"]]
# Naigate to website
remDr$navigate("https://www.bankofengland.co.uk/boeapps/database/fromshowcolumns.asp?Travel=NIxSTxTIxSUx&FromSeries=1&ToSeries=50&DAT=RNG&FD=1&FM=Jan&FY=2009&TD=30&TM=Mar&TY=2020&FNY=&CSVF=TT&html.x=91&html.y=29&C=IIN&Filter=N#")
#Download the CSV file
button_element <- remDr$findElement(using = 'xpath', value = '//*[@id="stats-table_wrapper"]/div[1]/a[2]')
button_element$clickElement()


text:
Q: Glueing Sheaves. I have two questions about glueing sheaves. See Hartshorne Ch2 Ex1.22.
Let X be a topological space, let $\{U_i\}$ be an open cover of X, and suppose we are given for each $i$ a sheaf $\mathcal{F}_i$ on $U_i$, and for each $i,j$ an isomorphism of sheaves $\phi_{ij}:\mathcal{F}_i\mid_{U_i\cap U_j}\to\mathcal{F}_j\mid_{U_i\cap U_j}$,
such that (1) for each $i$, $\phi_{ii}=$ id, and (2) for each $i,j,k$, $\phi_{ik}=\phi_{jk}\phi_{ij}$ on $U_i\cap U_j\cap U_k$.
Then there exists there exists a unique sheaf $\mathcal{F}$ on X, together with isomorphisms $\psi_i:\mathcal{F}\mid_{U_i}\to\mathcal{F}_i$ such that for each $i,j$, $\psi_j=\phi_{ij}\psi_i$ on $U_i\cap U_j$.
My questions are:

*

*Is the assumption that $\{U_i\}$ is covering X is necessary? I mean we could construct $\mathcal{F}$ without it.

*I have no idea of where to use the above property (2) in the process of construction.
If V is a open set of X, a section of $\mathcal{F}(V)$ will be represented by $<s_i>$ such that for each $i$, $s_i \in \mathcal{F}_i(U_i\cap V)$ and for each $i,j$, $\phi_{ij}(s_i\mid _{U_i\cap U_j\cap V})=s_j\mid _{U_i\cap U_j\cap V}$.
I think I could prove $\mathcal{F}$ satisfies sheaf properties and $\psi$ is commutative without the assumption.


text:
Q: How to use same function in different angular components I have a Component A which has a set of 2 functions and 2 class attributes that another component B needs to use too.
Previously I just copy paste those code parts into the component B and use it.
But I'm pretty sure it's not normal to do some redundant code.
EDIT: In fact I have a component "add element" with complex forms
and a second one "modify element" and I want to use the same skeleton for those two components.
Is someone know a way to achieve this in Angular 8?
Thanks in advance.

A: If the goal is avoiding redundant code and the components don't need to share state (property values), you can use an abstract class.
export abstract class AbstractComponent {

  property1: string;
  property2: long;

  commonMethod(): string {
      ...
  }
}

@Component({
   selector: 'app-component1',
   ...
})
export class Component1 extends AbstractComponent {
   ...
}

@Component({
   selector: 'app-component2',
   ...
})
export class Component2 extends AbstractComponent {
   ...
}

A: i used same scenario my application. i want to create dynamic address component. for used many forms. so first i create common component
import { Component, OnInit, Input, Output, EventEmitter, OnDestroy, AfterViewInit } from '@angular/core';
import { AddressModal } from '../../modals/opportunity.modal';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.css'],
})
export class AddressComponent implements OnInit, AfterViewInit {

  form_address: FormGroup;
  @Input('addressModal') addressModal: AddressModal;

  @Output()
  private formReady: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();

  listCountry = [];
  public formSubmitAttempt: boolean = false;

  constructor(private fb: FormBuilder) {
    this.getCountryList();
    this.createForm();
  }

  ngOnInit(): void {
    this.formReady.emit(this.form_address);
    if (this.addressModal && this.addressModal !== undefined) {
      setTimeout(function () {
        this.form_address.setValue(this.addressModal);
      }.bind(this), 500);

    }
  }

  ngAfterViewInit(): void {

  }
  createForm() {
    const requiredValidations = [
      Validators.required,
      this.conf.noWhitespaceValidator,
    ];

    this.form_address = this.fb.group({
      id: [''],
      row_id: [''],
      opportunity_id: [''],
      address1: ['', requiredValidations],
      address2: [''],
      city: ['', requiredValidations],
      state: ['', requiredValidations],
      zipcode: ['', requiredValidations],
      country: ['S1ptmVWUWsjyGvlr', requiredValidations],
      added_date: [''],
      modified_date: [''],
      status: ['']
    });
  }

  getCountryList() {
    let _self = this;
    this.conf.getApiCall('get_countries', {}, function (res) {
      if (res.data !== undefined && res.data.countries != undefined) {
        _self.listCountry = res.data.countries;
      }
    }, function (err) {
      console.log(err);
    });
  }
}

then i implement in our component.html file
   <app-address (formReady)="addFormControl($event)" [addressModal]="address"></app-address>

after fire event in component.ts file
private addFormControl(name: string, formGroup: FormGroup): void {
    if (!this.form1.controls[name] && !this.form1.controls[name] !== undefined) {
        this.form1.addControl(name, formGroup);
    }
}

private addBlankAddress(): void {
    let address_obj: AddressModal = {
        id: '',
        row_id: this.conf.randomRowId(),
        opportunity_id: '',
        address1: '',
        address2: '',
        city: '',
        state: '',
        zipcode: '',
        country: 'S1ptmVWUWsjyGvlr',
        added_date: '',
        modified_date: '',
        status: ''
    };
    this.list_address.push(address_obj);
    //return address_obj;
}


text:
Q: How to "literally" open up an excel sheet? Not looking for pd.read_excel but something that opens and displays the sheet in excel I have a Python GUI where I convert a .txt file to a .xlsx file. If any values are out of norm, then the script reformats those cells by highlighting the background and then I save the .xlsx file. When completed, I want to open the .xlsx file for the actual GUI user to be able to see and correct the highlighted cells.
Something like...

pandas.read_excel('foo.xlsx')

but literally opens the Excel application

A: import os
file = 'foo.xlsx'
os.startfile(file)


text: Q: Book where main character has female ai in mind and nano armor I read this book around 2010. It's set in the future on, I believe, Mars. The main character has an ai implanted in his mind that's described as a woman. He also has nanotechnology armor that I remember is described as moving and concentrating at the point of impact. I believe the main character is also missing an eye? I don't remember any of the plot aside from there being giant insect like creatures and the protagonist and ai bantering often.


text:
Q: Problema em máscara de moeda em input Estou com um problema na máscara de moeda com AngularJS.
Eu achei essa thread no Stackoverflow em inglês. A máscara funciona beleza digitando no input e chega certo no controller, porém quando eu mando formatado do controller para a tela não rola.
Aqui tem um exemplo.

*

*Trecho do código da directive
    app.directive('format', ['$filter',
        function ($filter) {
            return {
                require: '?ngModel',
                link: function (scope, elem, attrs, ctrl) {
                    if (!ctrl) return;

                    ctrl.$formatters.unshift(function (a) {
                        return $filter(attrs.format)(ctrl.$modelValue)
                    });

                    ctrl.$parsers.unshift(function (viewValue) {
                        elem.priceFormat({
                            prefix: '',
                            centsSeparator: ',',
                            thousandsSeparator: '.'
                        });

                        return elem[0].value;
                    });
                }
            };
        }
    ]);

*

*Código da pagina

    <!DOCTYPE html>

      <meta charset="utf-8" />
      <title>AngularJS Plunker</title>

      <link rel="stylesheet" href="style.css" />

Original Example
    <input type="text" ng-model="test" format="number" />

{{test|json}}

    Example 1<input type="text" ng-model="test_2" format="number" />

{{test_2|json}}

    Example 2<input type="text" ng-model="test_3" format="number" />

{{test_3|json}}

A: Não sei de onde você tirou esse código, mas ele é claramente inconsistente. Numa função você usa o $filter padrão do AngularJS, na outra você usa um plugin do jQuery para formatação de números.
O $filter só roda no início, com os números que já estão definidos no $scope, o outro roda a cada alteração.
Apesar d'eu achar que não é uma boa idéia misturar plugins de jQuery que lidam com elementos no DOM misturados com filters do AngularJS, se você usar a mesma função nos dois casos a coisa funciona:
app.directive('format', ['$filter',
  function($filter) {
    return {
      require: '?ngModel',
      link: function(scope, elem, attrs, ctrl) {
        if (!ctrl) return;

        ctrl.$formatters.unshift(function(a) {
          elem[0].value = ctrl.$modelValue
          elem.priceFormat({
            prefix: '',
            centsSeparator: ',',
            thousandsSeparator: '.'
          });
          return elem[0].value;
        });

        ctrl.$parsers.unshift(function(viewValue) {
          elem.priceFormat({
            prefix: '',
            centsSeparator: ',',
            thousandsSeparator: '.'
          });
          return elem[0].value;
        });
      }
    };
  }
]);

Plunker.
EDIÇÃO:
Aqui uma forma melhor de fazer essa coisa:
Defina um filter para fazer a conversão copiando parcialmente o código do plugin do jQuery:
app.filter('priceformat', function () {
      var is_number = /[0-9]/;
      var prefix = ''
      var suffix = ''
      var centsSeparator = ','
      var thousandsSeparator = '.'
      var limit = false
      var centsLimit = 2
      var clearPrefix = false
      var clearSufix = false
      var allowNegative = false
      var insertPlusSign = false
      if (insertPlusSign) allowNegative = true;

      function to_numbers(str) {
        var formatted = '';
        for (var i = 0; i < (str.length); i++) {
          char_ = str.charAt(i);
          if (formatted.length == 0 && char_ == 0) char_ = false;
          if (char_ && char_.match(is_number)) {
            if (limit) {
              if (formatted.length < limit) formatted = formatted + char_
            } else {
              formatted = formatted + char_
            }
          }
        }
        return formatted
      }

      function fill_with_zeroes(str) {
        while (str.length < (centsLimit + 1)) str = '0' + str;
        return str
      }

      return function (str) {
        var formatted = fill_with_zeroes(to_numbers(str));
        var thousandsFormatted = '';
        var thousandsCount = 0;
        if (centsLimit == 0) {
          centsSeparator = "";
          centsVal = ""
        }
        var centsVal = formatted.substr(formatted.length - centsLimit, centsLimit);
        var integerVal = formatted.substr(0, formatted.length - centsLimit);
        formatted = (centsLimit == 0) ? integerVal : integerVal + centsSeparator + centsVal;
        if (thousandsSeparator || $.trim(thousandsSeparator) != "") {
          for (var j = integerVal.length; j > 0; j--) {
            char_ = integerVal.substr(j - 1, 1);
            thousandsCount++;
            if (thousandsCount % 3 == 0) char_ = thousandsSeparator + char_;
            thousandsFormatted = char_ + thousandsFormatted
          }
          if (thousandsFormatted.substr(0, 1) == thousandsSeparator) thousandsFormatted = thousandsFormatted.substring(1, thousandsFormatted.length);
          formatted = (centsLimit == 0) ? thousandsFormatted : thousandsFormatted + centsSeparator + centsVal
        }
        if (allowNegative && (integerVal != 0 || centsVal != 0)) {
          if (str.indexOf('-') != -1 && str.indexOf('+') < str.indexOf('-')) {
            formatted = '-' + formatted
          } else {
            if (!insertPlusSign) formatted = '' + formatted;
            else formatted = '+' + formatted
          }
        }
        if (prefix) formatted = prefix + formatted;
        if (suffix) formatted = formatted + suffix;
        return formatted
      }
})

(Aqui está com os valores diretos no código, mas você pode fazer diferentes)
Depois use esse filter na sua directive:
  ctrl.$formatters.unshift(function(a) {
     return $filter('priceformat')(ctrl.$modelValue)
  });
  ctrl.$parsers.unshift(function(viewValue) {
     return $filter('priceformat')(viewValue)
  });

Plunker.

A: Aqui eu criei uma função para formatar.
//Função formatação e Mascara de input.
function funSftMask(value, format) {
    /* Aqui verifica se o campo aceita mais de um formato.
    Ex:(99)99999-9999|(99)9999-9999 sepada por pipe(|)  */
    format = format.indexOf("|") !== -1 ? format.split("|") : format;
    /* Varre a lista e verifica o valor passado e aplica a mascara conforme o tamanho da string. */
    if(format instanceof Array){
        for(var i = 0; i < format.length; i++){
            if(format[i].replace(/[^\d]+/g, '').length === value.length){
                format = format[i];
                break;
            }
        }
    }
    /* Caso não indentifique um tamanho padrão seleciona o primeiro  */
    if(format instanceof Array){
        format = format[1];
    }
    value = value.split("");
    format = format.split("");
    var result = "";
    var x = 0;
    for (var i = 0; i < format.length; i++) {
        if (format[i] !== "9") {
            x--;
        }
        if (x >= value.length)
            break;
        result += format[i] === '9' ? value[x] : format[i];
        x++;
    }
    return result;
}

Aqui o input que recebera a mascara
<input type="text" placeholder="Somente numeros" sft-mack="(99)99999-9999|(99)9999-9999" />

aqui a directiva que formatara o input conforme for digitando.
nomedaApp.directive('sftMack', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var id = '#' + attrs.id;
            elem.add(id).on('keyup', function () {
                var x = funSftMask(elem.val().replace(/[^\d]+/g, ''), attrs.sftMack);
                elem.val(x);
            });
        }
    };
});


text:
Q: "Too much recursion" error when using intanceof over typeof? I was making a function to convert all dates in an object to strings and when I used the following function I got a error in FF  "too much recursion". (It also fails in IE and chrome)
    function datesToString(obj) {
        if (obj instanceof Object) {
            if (obj instanceof Date) {
                obj = "this part does not matter";
            } else {
                for (var key in obj) { obj[key] = datesToString(obj[key]); }
            }
        }
        return obj;
    }

but when I changed it to use typeof it worked fine?
    function datesToString(obj) {
        if (obj  && typeof obj == "object") {
            if (obj instanceof Date) {
                obj = "this part does not matter";
            } else {
                for (var key in obj) { obj[key] = datesToString(obj[key]); }
            }
        }
        return obj;
    }

It should be the same amount of recursion. Am I missing something? Why am I getting an error with the first example but not the second?
Update:
here is an example of the object I was using (in json form)
Contact = {
    "LContactID": "00000000-0000-0000-0000-000000000000",
    "CellPhone": "",
    "HomePhone": "4564564560",
    "OtherPhone": "",
    "BirthDate": new Date(-62135575200000),
    "SSN": "456456456",
    "HowToContact": 1,
    "ContactType": 3,
    "Address1": "123 test",
    "Address2": "apt. 1",
    "City": "Valparaiso",
    "State": "IN",
    "Zip": "46383",
    "FullAddress": "123 test, apt. 1",
    "BuilderID": "",
    "FullAddressWithCityState": "123 test\r\napt. 1\r\nValparaiso, IN 46383",
    "WorkHours": "9-5",
    "ContactTime": "",
    "ContactMethod": "???",
    "IsMilitaryOrSelfEmployed": false,
    "AlternateContactName": "",
    "AlternateContactPhone": "",
    "ContactID": "00000000-0000-0000-0000-000000000000",
    "Password": null,
    "FirstName": "updatetest",
    "MiddleName": null,
    "LastName": "test_",
    "Suffix": null,
    "EmailAddress": null,
    "EmailAddressAlternate": null,
    "WorkPhone": "6546546540",
    "WorkPhoneExt": null,
    "CreatedOn": new Date(1263597309000),
    "CreatedOnOverride": new Date(-62135575200000),
    "ModifiedOn": new Date(1264014749000),
    "SCRep": "",
    "HBCRep": "",
    "PPPRep": "",
    "DPSRep": "",
    "DRSRep": "",
    "RDRep": "",
    "OwnerID": "00000000-0000-0000-0000-000000000000",
    "FullName": "updatetest test_",
    "ImportID": 0,
    "IncludeEmail": false,
    "PreferredLanguage": 1,
    "CarbonCopyList": [],
    "HearAboutUs": 5,
    "HearAboutUsOther": "",
    "init": function() { },
    "update": function() { },
    "load": function() { }
}

It looks like when I remove the method parameters (init,update and load) it works with the instanceof example.
UPDATE: This is a ASP.Net ScriptManager problem it turns out. Sorry for not including the fact that I was working with an ASP.Net website.The ASP.Net ScriptManager prototypes methods to Function which causes an infinity loop when doing a recursive for in loop on a function.

A: (First, let me say that I tried your code on FF 3.5.7 and it didn't run into an infinite recursion. maybe you used a different input example?)
Anyway, to answer your questions:
(a) Why do you get an infinite recursion? Because an object may refer to itself. If o.f==o then calling your function on o will fire a subsequent call on o.f which is actually o and so on...
(b) Why the difference between the two versions? obj instanceof Object checks if obj is an instance of Object or an instance of a subclass thereof. Given that every Javascript object inherits from Object then this condition is trivially true, and is thus meaningless. Net result is that the first if always succeeds. On the other hand typeof obj == "object" checks that obj is an instance of Object. This may be false, for example, if obj is an instance of String (at which case typeof obj yields String). Hence, the difference.


text:
Q: Remove Swing Component Using Validate or Revalidate Whenever I remove and add swing components from say JPanel, shall I perform call on validate or revalidate?

A: revalidate() would be better. revalidate() marks all the container upto the top level as not proper or not valid. Then it calls validate() on the top level. The validate() method of the parent checks if at least one of its immediate children is signaled invalid or improper. it calls validate of the parent.
so calling revalidate() automatically means calling validate().

A: revalidate() is basically a invalidate() followed by a validate().
Look at Sun's Java source code.
You want to call revalidate().

A: At least in Java 7, revalidate() doesn't necessarily "erase" removed components from the screen. I believe that happens when the bounding box shrinks. For these cases, call repaint() after the revalidate().

A: I would think revalidate() is what you want.  The validate() method will be automatically called for you after a call to revalidate().  See the Java API for JComponent.revalidate().


text:
Q: Archive-Custom-Post-Type order by Event Date, ASC, and hide events that have completed I am building a site for a personal project and I have a series of Events created via a Custom Post Type.
I then need these events to be displayed by a custom meta value (Event Start Date) and in ASC order. I have managed to figure that out and the code I used is below:
/*CUSTOM ARCHIVE FOR EVENTS*/
    function events_pagesize( $query ) {
    // exit out if it's the admin or it isn't the main query
    if ( is_admin() || ! $query->is_main_query() )
    return;
    // so its not admin, and its the main query, is it the tr-events post archive?
    if ( is_post_type_archive( 'tr-events' ) ) {
    // it is!! Set the posts_per_page to 6
    $query->set( 'posts_per_page', 4 );
    $query->set( 'order' , 'asc' );
    $query->set( 'meta_key', 'wpcf-tr-order-date');
    $query->set( 'orderby', 'meta_value');
    return;
    }
    }
    add_action( 'pre_get_posts', 'events_pagesize', 1 );

My question is how to hide posts past a specific date AND how would I also create an Archive view to display Events that have completed? I've seen tons of posts about this and most options break pagination. This option as a function in the functions.php gets me 70% there.

A: I quess that it would be easiest for you to store date as unix timestamp in post meta - than you can easily filter posts by post meta less than current timestamp (or any other date timestamp).
See this example (not exactly for your code, but you'll catch the punch line:
$args = array(
   'post_type' => 'tr-events',
   'meta_key' => 'wpcf-tr-order-date',
   'orderby' => 'meta_value_num',
   'order' => 'ASC', //DESC, its up to you
   'meta_query' => array(
       array(
           'key' => 'wpcf-tr-order-date',
           'value' => strtotime('now'),
           'compare' => '<',
       )
   )
 );
 $query = new WP_Query($args);

As I mentioned, you'll have to rewrite this piece of code to $query->set(); format


text:
Q: Where shall I put my self-written Python packages? Is there a canonical location where to put self-written packages? My own search only yielded a blog post about where to put version-independent pure Python packages and a SO question for the canonical location under Linux, while I am working on Windows.
My use case is that I would like to be able to import my own packages during a IPython session just like any site-package, no matter in which working directory I started the session. In Matlab, the corresponding folder for example is simply C:/Users/ojdo/Documents/MATLAB.
import mypackage as mp
mp.awesomefunction()
...

A: I'd use the home scheme for this:
http://docs.python.org/2/install/#alternate-installation-the-home-scheme

A: I had the same question, and your answer is very helpful.
To add a little bit, I came across this example that's helpful to me:
http://python-packaging.readthedocs.io/en/latest/minimal.html
It is a minimal example of how to package your own code, and properly install it locally (I imagine this is what you actually want), or distribute on PyPI. Doing things the python way.

A: Place the source of your package wherever you'd like, but at least give your package a minimal setup.py file, immediately outside the package:
import setuptools

setuptools.setup(name='mypackage')

Then fake-install your package into your python install's site-packages by running:
python setup.py develop

This is a lot like running python setup.py install, except the egg just points to your source tree, so you don't have to install after every source code change.
Finally, you should be able to import your package:
python -c "import mypackage as mp; print mp.awesomefunction()"

A: Thanks to the two additional links, I found not only the intended answer to my question, but also a solution that I like even more and that - ironically - was also explained in my first search result, but obfuscated by all the version-(in)dependent site-package lingo.
Answer to original question: default folder
I wanted to know if there was a canonical (as in "default") location for my self-written packages. And that exists:
>>> import site
>>> site.USER_SITE
'C:\\Users\\ojdo\\AppData\\Roaming\\Python\\Python27\\site-packages'

And for a Linux and Python 3 example:
ojdo@ubuntu:~$ python3
>>> import site
>>> site.USER_SITE
'/home/ojdo/.local/lib/python3.6/site-packages'

The docs on user scheme package installation state that folder USER_SITE - if it exists - will be automatically added to your Python's sys.path upon interpreter startup, no manual steps needed.

Bonus: custom directory for own packages

*

*Create a directory anywhere, e.g. C:\Users\ojdo\Documents\Python\Libs.

*Add the file sitecustomize.py to the site-packages folder of the Python installation, i.e. in C:\Python27\Lib\site-packages (for all users) or site.USER_SITE (for a single user).

*This file then is filled with the following code:
import site
site.addsitedir(r'C:\Users\ojdo\Documents\Python\Libs')

*Voilà, the new directory now is automatically added to sys.path in every (I)Python session.

How it works: Package site, that is automatically imported  during every start of Python, also tries to import the package sitecustomize for custom package path modifications. In this case, this dummy package consists of a script that adds the personal package folder to the Python path.


text:
Q: Anyone know why I can't access the winevt folder programmatically in C#? I've been trying to get into the 'C:\Windows\System32\winevt\Logs' folder programmatically using C# so I can copy the event log files to a backup directory and then clear the event logs as a part of a daily backup apparatus, but I don't seem to be able to get access to this directory.
I've tried changing the application manifest to run under administrator (  ) which gives me the UAC prompt when I execute the program and I've even gone as far as to spawn a shell under NT AUHORITY\SYSTEM identity to execute the code but it still says it's an invalid path,  even though I can manually go into the directory under both administrative shell and the SYSTEM shell.
I've isolated it to just not being able to go into the winevt dir.
I use this code to see if I can access the directory.
Environment.CurrentDirectory = System.Environment.SystemDirectory + @"\winevt\";
only to receive
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Windows\system32\winevt\'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.Directory.SetCurrentDirectory(String path)
   at System.Environment.set_CurrentDirectory(String value)
   at dev_EventLog.Program.Main(String[] args) in D:\SourceCodes\dev_EventLog\dev_EventLog\Program.cs:line 30
I've tried many different ways to specify the directory but it's all the same, and I've also tried different subfolder of System32 and of the 10 or so I tried winevt is the only one to act like this.
This has been driving me nuts,   anyone know why this isn't working under C# or am I forced to use VBScript to do this,  since the following VBScript code works to copy the event log file.
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
filesys.CopyFile "C:\Windows\System32\winevt\Logs\Application.evtx", "C:\rusl\Application.evtx"

A: Is your application running as a 32-bit application on a 64-bit version of Windows? If so, any access to %windir%\System32 is redirected to %windir%\SystemWOW64 (where there is no winevt directory).
If you use %windir%\Sysnative\winevt you should be able to access it.

A: Here is the code that I have that works now after I changed system32 to sysnative as per John Rasch suggestion.
string LogFileDirectory = @"C:\Windows\Sysnative\winevt\Logs\";
string LogFileExtension = ".evtx";
string Date = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();
string BackupDir = @"C:\Backups\" + Date + "\\";
Directory.CreateDirectory(BackupDir);
foreach (EventLog log in EventLog.GetEventLogs())
{
 string source = LogFileDirectory + log.Log + LogFileExtension;
 string dest = BackupDir + log.Log + LogFileExtension;
 try
 {
  File.Copy(source, dest);
 }
 catch (Exception e)
 {
  Console.WriteLine("Error occured :" + e.Message);
  Console.WriteLine(e);
 }
 finally
 {
  if (!File.Exists(dest))
  {
   Console.WriteLine("Backup Failed for " + log.Log);
  }
  else
  {
   Console.WriteLine("Backup Successful for " + log.Log);
   //log.Clear();  // Commented out during development
  }
 }
}


text:
Q: Set AutoIncrement value with Subquery in MySQL I am trying to provide the value for auto increment value through the subquery in mysql
I tried with this command
alter table xxx auto_increment = (select max(id) from xxx) ;

But am getting the syntax error as

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(select max(id) from xxx)' at line 1

Please anyone help me on this issue....Thanks in advance

A: You cannot set AUTO_INCREMENT by this way - new AUTO_INCREMENT value is literal and cannot be an expression.
To achieve your goal it is enough to set AUTO_INCREMENT to 1. For this statement the provided value is always checked, and if some rows exists and it must be above provided value then it is adjusted to MAX(AI_column) + 1 automatically.
DEMO:
CREATE TABLE test ( id INT AUTO_INCREMENT PRIMARY KEY );
INSERT INTO test VALUES (DEFAULT), (DEFAULT);
SELECT * FROM test;      -- rows id=1,2 inserted
SHOW CREATE TABLE test;  -- AUTO_INCREMENT = 3

id

1

2

Table
Create Table

test
CREATE TABLE `test` (  `id` int NOT NULL AUTO_INCREMENT,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

ALTER TABLE test AUTO_INCREMENT = 10;           -- set value above current
SHOW CREATE TABLE test;  -- AUTO_INCREMENT = 10 -- specified value applied

Table
Create Table

test
CREATE TABLE `test` (  `id` int NOT NULL AUTO_INCREMENT,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

ALTER TABLE test AUTO_INCREMENT = 1;           -- set value below current
SHOW CREATE TABLE test;  -- AUTO_INCREMENT = 3 -- value adjusted to MAX(id)+1

Table
Create Table

test
CREATE TABLE `test` (  `id` int NOT NULL AUTO_INCREMENT,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

fiddle

A: You need to use dynamic sql for this:
select concat("alter table foo auto_increment=",max(id)) from foo into @maxid;
prepare setautoinc from @maxid;
execute setautoinc;
deallocate prepare setautoinc;

fiddle


text:
Q: JBoss Logging in IntelliJ via Maven prints to System.error I have a project in IntelliJ where I have imported JBoss Logging via a Maven library.
Maven:org.jboss.logging:jboss-logging:3.3.1.Final

I have created a logger for my class.
private final Logger LOG = Logger.getLogger(MyClass.class.getName());

And then I log some info messages.
LOG.info("some info here");

Everything is printed to the console and seem to be working as it should. Except the fact that everything is red, the same red as errors in intelliJ. I am guessing this is because the logger is sending to System.error instead of System.out. Regular System.out.print() is the standard light grey color.
I have tried finding out how to configure this setting for the logger, but no online resource seems to know how. I might have missed something, I have been at this for a while now. Hopefully someone here knows the solution.


text:
Q: Maintain a list of bounding client rectangles in a component I have a component which must be aware of the position of all nodes contained within it.
class ContextAwareGrid extends Component {
  state = { nodes: { } };
  render() {
    return (<div className="grid">
      {this.renderNodes()}
    </div>);
  }
  renderNodes() {
    return Object.entries().map(entry => {
      const [ id, node ] = entry;
      return (<GridNode
        key={id}
        id={id}
        {...node}
      />);
    });
  }
}

My goal is to find the distance of a node along an axis relative to another node as they are moving. The problem is, in order to do this, I will need to know the getBoundingClientRect property in the parent for when any child moves.
The most naive answer I've found is to include a ref while instancing the components that calls a function like:
onComponentMounted = (id, component) => {
  this.setState(state => {
    const rect = component.getBoundingClientRect();
    state.elements[id] = rect;
    return state;
  });
}

However, this causes problems whenever the component is moved or otherwise changed.
My last attempts yielded Maximum Call Stack Exceeded, so obviously, I came to stack overflow to fix the problem
Is there any way to maintain references to all child components of a specific class in the parent component?


text:
Q: Algorithm: Explanation of a graph based In Futaba Kindergarten, where Shinchan studies, there are N students, s_0, s_1...s_(N-1), including Shinchan. Every student knows each other directly or indirectly. Two students knows each other directly if they are friends. Indirectly knowing each other means there is a third students who knows both of them. Knowing each other is a symmetric relation, i.e., if student s_a knows student s_b then student s_b also knows student s_a.
Ai-chan is a new admission in the class. She wants to be friend with all of them. But it will be very cumbersome to befriend each of the N students there. So she decided to befriend some of them such that every student in the class is either a friend of her or friend of friend of her.
Help her to select those students such that befriending them will complete her objective. The lesser number of students the better it is.
Input
First line of input will contain two space separated integer, N M, number of students at Futaba Kindergarten, excluding Ai-chan, and number of pairs of students who are friend to each other, i.e. they knows each other directly. Then follows M lines. In each line there are two space separated integer, s_u s_v, such that student s_u and s_v are friend to each other.
Output
In first line print the total number, P, of such students. Then in next line print P space separated index of students, such that befriending them will help Ai-chan to achieve her objective.
Constraints:
1 <= N <= 10^5

1 <= M <= min(10^5, N*(N-1)/2)

0 <= s_u, s_v <= N-1

s_u != s_v

Each pair of students (s_u, s_v) knows each other, directly or indirectly.
Score: ((N-P)/N)*200
**Sample Input**
6 7
0 1
0 2
1 2
1 3
2 4
3 4
3 5

**Sample Output**
4
0 2 3 5

Im My opinion be friending with only 1 and 3 will do the job. Am i missing something ?
I am not looking for the solution , just the explanation of sample input and output.

A: The solution is a simple greedy algorithm. Suppose that C is the set of students.
S = {}
R = {}
while (C != {}) {
   - sort the students based on their number of friends
   - pick the student s with the highest number of friends
   - add R = R + {s}
   - add s and friends of s to the set S and remove them from C
}
print(R)


text:
Q: Botón en lugar específico de un div, sin importar tamaño de contenido, con CSS Bootstrap Poseo el siguiente código con el cual necesito ayuda con CSS Bootstrap.
Tengo un div el cual posee un botón para realizar funciones en él.
Como pueden ver en el ejemplo corto, el botón esta bien posicionado, en la esquina superior derecha del DIV
¿Cuál es el problema? Que esto no mantiene posición una vez que el contenido es más grande.
En el segundo ejemplo, pueden ver lo que ocurre con claridad.
La idea es que el botón mantenga la posición superior derecha del DIV sin importar el resto.

.showHover {
  visibility: visible;
  color: black;
  position: relative;
  top: -12px;
  right: -12px;
  font-size: 25px;
  margin: -5px;
}

#divDescription {
  border-radius: 1.5rem;
}

#divDescription:hover {
  border-radius: 1.5rem 0rem 1.5rem 1.5rem;
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.55) !important;
}

#divDescription:hover .showHover {
  visibility: visible;
  color: black;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">

    Sed ut perspiciatis

    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

A: Lo que hice fue mover el botón al inicio de tu texto:

   Sed ut perspiciatis ...

Y al botón le di la siguiente propiedad, con esto ya quedaría:
#editDescription {
  float: right;
}

Código final:

body {
  padding: 20px;
}

.showHover {
  visibility: visible;
  color: black;
  position: relative;
  top: -12px;
  right: -12px;
  font-size: 25px;
  margin: -5px;
}

#divDescription {
  border-radius: 1.5rem;
}

#editDescription {
  float: right;
}

#divDescription:hover {
  border-radius: 1.5rem 0rem 1.5rem 1.5rem;
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.55) !important;
}

#divDescription:hover .showHover {
  visibility: visible;
  color: black;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">

      Sed ut perspiciatis

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?


text:
Q: Access user's info domain or username and login into web api I m developing an asp.net web api and have to access user details from LDAP.
Sentcha is used to create an app that is using this api,what I want that is user can access or log-in inito this api using windows authentication.
Please let me know .


text:
Q: Update using a subquery SQL PL/SQL I am trying to update a table, but I can't get my syntax to work. I added new elements from a temp table to my element table and I want to update column_name in metadata_attribute and table_name in metadata_table table. This is what I have:
UPDATE METADATA_ATTRIBUTE
   SET C.ELEMENT_ID = (SELECT ELEMENT_ID
                         FROM ELEMENT A , TEMP B
                        WHERE A.ELEMENT_NAME = B.WMIS_COLUMN_NAME)
 FROM ELEMENT A, TEMP B, METADATA_ATTRIBUTE C,  METADATA_TABLE D
WHERE C.COLUMN_NAME = B.WMIS_COLUMN_NAME
  AND D.TABLE_NAME = B.WMIS_TABLE_NAME
  AND ELEMENT_ID IS NULL;

A: Updating two tables from a single update statement is not possible in oracle.
You need to write a PL/SQL block (procedure or trigger)  to solve this problem.
Elaborate your question if you need more help.

A: What happens when you try this?
update a set a.element_id = b.element_id
from element a, temp b, metadata_attribute c, metadata_table d
where c.column_name = b.wmis_column_name and
d.table_name = b.wmis_table_name and
element_id is null;

A: try this:

UPDATE METADATA_ATTRIBUTE m
SET m.ELEMENT_ID =    /* changed C to m */
   (SELECT ELEMENT_ID /* this query must not return multiple rows! */
      FROM ELEMENT A , TEMP B
      WHERE A.ELEMENT_NAME = B.WMIS_COLUMN_NAME
   )
where m.rowid in /* I added this line */
   (select C.rowid
      FROM ELEMENT A, TEMP B, METADATA_ATTRIBUTE C,  METADATA_TABLE D
      WHERE C.COLUMN_NAME = B.WMIS_COLUMN_NAME
       AND D.TABLE_NAME = B.WMIS_TABLE_NAME
       AND ELEMENT_ID IS NULL
       /* the ELEMENT table is not explicitly joined to any table - Carteansan Product!!!*/
    );

This will update rows in the METADATA_ATTRIBUTE table.


text: Q: Onboard video and audio issues, Ubuntu 20 04, ASRock N68C GS4 FX motherboard I have an ASRock N68C GS4 FX motherboard and an AMD Phenom II 940x4 cpu, 4gb memory. I installed Ubuntu 20 04. I can't seem to get the video right for I have distortional lines over the panther picture and any other picture I use. Also when I open up the Ubuntu software and move my cursor over each icon they turn white and can not be read easily. I have searched the Nvidia driver search tool on their page with no luck on Ubuntu drivers. The Audio only works through the front port earphone jack as well. Can't get any audio from the back of the motherboard what so ever. Getting frustrated a bit one might say! Anyone know what my next move would be for this boards video and audio drivers?


text:
Q: Xamarin Android - Optimising code causes App to crash VS 2019 - Xamarin 4.8
In the PCL Project I have the Optimize Code checkbox checked.
In the Android Project, if I check the Optimize Code checkbox, the App crashes immediately on start up.  If I don't have it checked, it works fine.
Question:  Is ticking the Optimize Code checkbox in the Android Project required if it is already ticked in the PCL project?  (to produce optimised code)
I have tried the options from this page:
https://forums.xamarin.com/discussion/55666/app-runs-in-debug-mode-crashes-in-release-mode

A: Changing the "Code Shrinker" option from blank to r8 seems to have fixed the issue.  In case others are having a similar issue, here are my "Android Options":

And here are by Android Build settings:


text:
Q: Test stay signed in with Rspec I'm a bit stumped on how (and where) to write some rspec tests for the "stay signed in" functionality you see all over, including on the google login.
The examples I found on the web weren't much help. Specifically I want to test these two scenarios.
1

*

*a) user signs in with valid credentials without having clicked "stay
signed in"

*b) user closes the browser, re-opens it and requests a protect page.

*The user should not see the protected page.

*The user should see the page asking them to signed in.

2

*

*a) user signs in with valid credentials and having clicked "stay
signed in"

*b) user closes the browser, re-opens it and requests a protected page.

*The user should not see the page asking them to sign in.

*The user should be taken to the protected page.

My first attempt at solving the problem involved simulating a browser close by deleting the user_id I stored in the session (since it gets deleted on browser close). However, these tests failed because I was working in the request spec folder and have no access there to the session variables. My earlier related question: session available in some rspec files and not others. how come?
What is the best way to do these test with rspec?

A: There are two problems here, that I think belong into different tests:

*

*User cannot access protected page when not logged in. That's a controller test.

*User gets logged in automatically even after the session has been destroyed, so long the "remember" me flag was set in the cookie.

For #1, you can try something like:
describe UsersController do
  context "when not logged in" do
    context "GET users/edit" do
      it "redirects to login" do
        get :edit, :id => 123
        response.should redirect_to login_path
      end
    end
  end
end

You can make a more general test case that asserts all actions which aren't explicitly listed, so that you don't have test gaps if the access code later becomes more permissive by accident. But that's a more subtle point.
For #2 you can write a request spec that sets the "remember me flag", then logs out, then logs in again and checks that you get to the page you expected. Drive all this from the browser by filling out credentials, checking the remember me box, clicking buttons.
The question is: Why? Why do you want to test this? Are you using a home-grown login system? Highly discouraged, unless you're a top-notch security expert. If you're not using a home-grown system, but instead Devise which comes tested, then don't re-test the library functionality. Just only test your application code, such as access rights to certain pages, which is covered by #1. You can also take a look at the tests that come with Devise how they test for this condition.
Hope this helps.
Update To clarify the request spec for #2. As mentioned in the other answer by @cutalion (who deserves the credit for the right answer), the mechanism for verifying that login can persist across session closing is built into the ActionDispatch IntegrationTest framework with open_session.
See Rails docs IntegrationTest API which includes examples. A blog post expanding on the use of a custom DSL.

A: I think you should try standard rails method for integration tests - open_session.
Personally I never did that and can't give you tested code.
See multiple sessions example on rails guides.

A: This still seems to be a recurring problem in 2018. Some basic documentation is clearly missing. I finally found a solution: "Show me the cookies" gem.
Switching the Capybara driver clears the session, so one possibility would be changing the driver in the middle of a test to simulate browser close/open. But getting an alternative driver (for example selenium, or selenium_chrome) to work is not trivial, and besides this method would probably delete all cookies.
Also this simple command resets the session: Capybara.reset_sessions! But the problem again is that it not only destroys the session cookie but also permanent cookies. So it's useless for testing "Remember me" functionality.
I finally settled on Show me the cookies gem. It was very simple to install and implement. I just followed the provided directions for rspec. The command expire_cookies provides a satisfying simulation of quitting and opening a browser.


text:
Q: Flask flash message wont show I have a web application with flask in which I can upload a file to an s3 storage. However, I want the users to track the upload progress of their files. For this, I'm using flash which I want to update frequently with the new upload percentage.
The problem now is that the upload progress I wrote to the terminal is perfect, but the message won't appear in my HTML.
The Python Flask code looks like this:
class ProgressPercentage(object):

    def __init__(self, filename):
        self._filename = filename
        self._size = float(os.path.getsize(filename))
        self._seen_so_far = 0
        self._lock = threading.Lock()
        print(f'Ground_Filename: {filename}; Size: {self._size}; Filename: {self._filename}; Seen: {self._seen_so_far}')

    def __call__(self, bytes_amount):
        with app.test_request_context():
            with self._lock:
                self._seen_so_far += bytes_amount
                percentage = (self._seen_so_far / self._size) * 100
                sys.stdout.write(
                    "\r%s  %s / %s  (%.2f%%)" % (
                        self._filename, self._seen_so_far, self._size,
                        percentage))
                flash(rf"""

                                {{ self.filename }} • Uploading
                                {{ percentage }}%

""")
            sys.stdout.flush()

@app.route('/dashboard', methods=['POST'])
@login_required
def dashboard_post():
    s3_client = boto3.client('s3',
                            aws_access_key_id=AWS_KEY,
                            aws_secret_access_key=AWS_SECRET_KEY)

    file = request.files['input_file']

    if file:
        filename = secure_filename(file.filename)
        file.save(filename)
        s3_client.upload_file(
            Bucket='deepstream-input',
            Filename=filename,
            Key=filename,
            Callback=ProgressPercentage(filename))

And this is the HTML:
    <form method="POST" enctype="multipart/form-data">

        <input id="file-upload" type="file" name="input_file" accept="video/*" onchange="form.submit()"/>

Zu verfremdende Datei auswählen

    </form>

      {% with messages = get_flashed_messages() %}
        {% if messages %}
          {{ messages[0] }}
      {% endif %}
      {% endwith %}

Does someone have an idea where the problem is? And if there is a problem with my question please tell me so I can edit it.

A: I seems that you sending html in the flash message you should add safe to jinja
{% with messages = get_flashed_messages() %}
    {% if messages %}
        {{ messages[0]|safe }}
    {% endif %}
{% endwith %}

I hope this helps.


text:
Q: get list item by id I have a list:
List<string> theList = new List<string>;

There are a few elements in the List. And now I want to get an item by the index. e.g. I want to get element number 4. How can I do it?

A: To get 4th item, you can use indexer:
string item = theList[3];

if you prefer to use methods, then you can use ElementAt or (ElementAtOrDefault):
string item = theList.ElementAt(3);

A: Just use the indexer
string item = theList[3];

Note that indexes in C# are 0 based.  So if you want the 4th element in the list you need to use index 3.  If you want the 5th element you would use index 4.  It's unclear from your question which you intended
The indexer is a common feature on .Net collection types.  For lists it's generally index based, for maps it's key based.  The documentation for the type in question will tell you which and if it's available.  The indexer member will be listed though as the property named Item

http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

A: You can use the Indexer  to get the Item at selected index
string item = theList[3];

A: Use the indexer:
string the4th = theList[3];

Note that this throws an exception if the list has only 3 items or less since the index is always zero-based. You might want to use Enumerable.ElementAtOrDefault then:
string the4th = theList.ElementAtOrDefault(3);
if(the4th != null)
{
    // ...
}

ElementAtOrDefault returns the element at the specified index if index < list.Count and default(T) if index >= theList.Count. So for reference types(like String) it returns null and for value types their default value(e.g. 0 for int).
For collection types which implement IList<T>(arrays or lists) it uses the indexer to get the element, for other types it uses a foreach loop and a counter variable.
So you could also use the Count property to check if the list contains enough items for the index:
string the4th = null;
if(index < theList.Count)
{
    the4th = theList[index];
}

A: use the Indexer Syntax:
var fourthItem = theList[3];

A: this should do it, access via array index.
theList[3]

its 3 as index's start at 0.

A: You can use the Indexer to get the Item at selected index
     string item = theList[3];

Or if u want to get the id (if accessing from database) define a class e.g.
    public class Person
    {
      public int PId;
      public string PName;

    }

and access as follow
     List<Person> theList = new List<Person>();
    Person p1 = new Person();
    int id = theList[3].PId


text:
Q: ForkJoinPool.invokeAll(ArrayList) I'm trying to invoke a list of RecursiveTask<Double> instances on a ForkJoinPool using invokeall() but it's complaining about the types.
I'm not pretty sure why it's not working.
I have the task classes which are defined as follows:
public class WorkerTask<G extends Game> extends RecursiveTask<Double>

I create n of these tasks and then I would like to let them loose in a ForkJoinPool. I know I can invoke them one by one using pool.invoke(getValue) but that's not what I want in the end.
The docs tell me that it has to be a list of objects that implement Callable. I followed the type hierarchy upwards up to ForkJoinTask. There I can see a class defined static final class AdaptedCallable<T> extends ForkJoinTask<T> so I think it should work.
What am I doing wrong here?

A: According to the api ForkJoinTask doesn't implement any Callable interface?
Looking at this example I'm not sure you're supposed to be using the invokeAll on the ForkJoinPool. You're supposed to add new WorkerTask to a list in the compute method itself and then call invokeAll(List<WorkerTask>).


text:
Q: Need help understanding FF indirect call instruction x86 I'm trying to recode a simple ftrace but I'm having trouble understanding FF indirect calls like this one :
ff 15 76 0b 20 00       callq  *0x200b76(%rip)        # 600ff0 <__libc_start_main@GLIBC_2.2.5>

Does it work like the E8 instruction with an offset ? If not, how to find the address the call point to ? And the address of return of that call ?

A: The instruction callq  *0x200b76(%rip) does the following things:

*

*Load one 64 bit word from rip + 0x200b76 where rip is the instruction pointer. According to the comment, this should be the address 0x600ff0 but it can be different if your code is relocated.

*Push the address of the next instruction on the stack as a return address.

*Jump to the value of the datum we read in step one.

The difference to the normal call (i.e. opcode e8) instruction is that this is an indirect function call where the address we call is loaded from memory instead of being specified right there. This is indicated by the asterisk (*). call foo is to call *foo like mov $foo,%eax is to mov foo,%eax.

A: Jumps can be characterized by several properties:

*

*Direct or indirect (i.e. whether the address is given in the instruction or retrieved from a memory pointer).

*Relative (address is given as an increment, relative to where the CALL opcode is) or absolute (jump to the actual, provided address). Indirect jumps are always absolute.

*Near (in the same segment) or far (in a different segment). Far jumps are always absolute.
Now, E8 is direct, near, and relative. In contrast, FF is indirect, near, and absolute. There is a variant of FF that's far rather than near, which is used mainly for call gates AFAIK. See here for a succinct table of CALLs.
See also this: How can I tell if jump is absolute or relative?.
So to your questions:

how to find the address the call point to

The 15 indicates that the pointer is relative to RIP (if it were relative e.g. to RAX then you'd have ff 90). The offset relative to RIP is in the four bytes immediately following the 15 - in your example, these are 0x00200b76. See Why call instruction opcode is represented as FF15? for additional explanation on decoding.

the address of return of that call

The return address is always the instruction immediately following the CALL instruction. So if the CALL is at address 0x100000 then the return address will be 0x100006.

A: Indirect branches (indirect jumps and indirect calls) are the main challenges for binary analysis tools. you need to check several tools to understand how these tools deal with indirect branches. Most popular binary analysis tools are:

*

*IDA Pro

*Radare2

*Dyninst

*Ghidra

*BAP

Those technique use different approaches to resolve indirect branches (compiler patterns, recursive disassembly, and propagation).
However, in my opinion, there is no tool that is able to resolve all types of indirect branches.
Important note:
Indirect branches are:

*

*indirect jumps,

*indirect call functions,

*tail functions, and

*non-returning function


text:
Q: Typescript required key A or key B I am new to typescript
I have an interface ABC in which I want either propA or propB to be there. it also have other properties
interface ABC {
  propA: string
  propB: string
  propC: string
  propD?: string
}

How can I do that?
I did this based on this answer https://stackoverflow.com/a/40510700/10433835
interface ABC {
   propC: string
   propD?: string
}

interface A extends ABC {
  propA: string
}

interface B extends ABC {
    propB: string
}

export type final = A | B

but then when I do something like this
 function somethingCalled (a:A) {
 }

 const b:final = req.body

 somethingCalled(b)

it throws following error Argument of type 'final' is not assignable to parameter of type 'interface A'.

A: I think what you want is to use discriminating union where a union's individual object is differentiated by the property that discriminates them with each other. In your case, propA tells that it is A and propB tells, it is B. Here is how we use them:
interface ABC {
  propC: string
  propD?: string
}

interface A extends ABC {
  propA: string
  anotherA: number;
}

interface B extends ABC {
    propB: string
    somethingB: boolean;
}

export type FinalType = A | B

 function somethingCalled (a:FinalType) {
     if('propA' in a){
         a.anotherA
         a.somethingB; // Error: Property 'somethingB' does not exist on type 'A'
     } else {
         a.somethingB
         a.anotherA // Error: Property 'anotherA' does not exist on type 'B'.
     }
 }

const req: any = '';

 const b:FinalType  =( req as any).body

 somethingCalled(b)

You can see how Typescript could tell other properties don't belong to the type once discrimination is made clear.
TS Playground link: https://tsplay.dev/mpvDpw


text:
Q: GWT ImageResource @source path outside project folder in my project, i am using a ClientBundle for my images used in the project. The images I would be using were already used by other non-gwt project, a Flex web application so these images are placed in a single directory found outside my gwt project.
hierarchy:
server
 - image
     - myimage.gif
 - gwtprojects
     - myproject
        - com.gwt.sample
           - CImageResource.java

In my CImageResource class:
@Source("../../../../../image/myimage.gif")
ImageResource myImage();

And gwt says "Resource file is missing".
How can i used the image in my ClientBundle class?
As much as possible, I don't wanna copy the image i'm gonna use in my project folder if there's a way to access it.

A: GWT loads everything from the classpath, so just put the image folder in the classpath and you can reference your myimage.gif with @Source("myimage.gif"), @Source("/myimage.gif") or @Source("../../../myimage.gif").


text:
Q: Pascal's Triangle output alignment So I've come up with the code to the values of the triangle itself. What I'm currently strugling is how to aligne/center the values that are printed. I tried many things but, I could use some help now. If anyone has an idea how this can be done feel free to share! Thank you
Program Tri_pas;
Uses Crt;
Var
    linha,ordem,a,b: byte;

Function fat(X: byte): real; // factorial
Var fat1:  real;
Begin

  fat1:=1;
  If X <= 1 Then
    fat:=1
  Else
  Begin
    Repeat
      fat1:=(fat1 * X);
      X:=(X - 1);
    Until X <= 1;
    fat:=fat1;
  End;

End;

Procedure nCp(n,p: byte);  //Combinations
Var
    i: byte;
    nCp: real;
Begin

  If n < 1 Then
    n:=0
  Else
    n:=(n-1);

  For i:=0 to n do
  Begin
    writeln;
    For p:=0 to i do
    Begin
      nCp:= fat(i) / (fat(p) * fat(i - p));    //  mathematic formula for the combinations
      Write(nCp:1:0,' ');
    End;
  End;

End;

{ Main Programa  }

Begin

  Write('Insert a line(1 -> n) :  ');
  Readln(linha);
  nCp(linha,ordem);
  readln;

End.

A: Just add appropriate number of empty spaces before strings. Note that I used double-spaces, and changed placeholder size to 4 (3+1) to make better formatting.
For p := 1 to (n - i) do
  Write('  ');

For p:=0 to i do
Begin
  nCp:= fat(i) / (fat(p) * fat(i - p));    //  mathematic formula for the combinations
  Write(nCp:3:0,' ');
End;

P.S. There are more effective ways to calculate Ncr in reasonable range without real numbers.


text:
Q: Interest rate, bond problem I am trying to solve the following problem:

Debtor issued a bond on 20 000€ (including interest rate) with
  maturity rate of 8 months and interest rate of 8% per annum. Month
  later, the creditor sold the bond to a different person, who discount
  the bond with 9% interest rate p.a.
How much did the creditor receive for the bond?

My solution is the following:
$FutureValue$ $= P(1+i*t*t/12) = 20000(1+0,08*8*8/12) = 28533$
Is it correct? Thanks

A: If the bond only pays at maturity, it pays $20000 +\frac 8{12} \cdot 8\% \cdot 20000$ at the end of $7$ months.  You are expected to discount at $9\%$ per year back to present value.

A: Assume the creditor sold the bond one month after acquiring it, the creditor receives
$$  20000 \times \frac{1+0.08\cdot \frac {8}{12} }{ 1+0.09\cdot \frac {7}{12} } = 20015.8$$


text:
Q: MySQL trigger to keep duplicate records from being entered I have a table that has a the following columns:
ID(primary key),
USER,
ACTION
TIME
LOCATION

I am looking to use a trigger or something that runs when the table is updated to insure that there are no duplicate entries based on the grouping of USER, ACTION, TIME, LOCATION. A preavious question was answered for me about how to clear the existing entries which resulted in:
DELETE t1.*
        FROM
  testlogins t1 INNER JOIN testlogins t2
  ON t1.user=t2.user
     AND t1.action=t2.action
     AND t1.time=t2.time
     AND t2.location=t2.location
     AND t1.id>t2.id;

This worked to clear the existing records. I thought i might be able to create a trigger based of this and I came up with this:
DELIMITER $$
create trigger del_duplicates
after insert
on test.testlogins for each row
begin
    DELETE t1.*
        FROM
  testlogins t1 INNER JOIN testlogins t2
  ON t1.user=t2.user
     AND t1.action=t2.action
     AND t1.time=t2.time
     AND t2.location=t2.location
     AND t1.id>t2.id;
end
$$

However that returns:
Error Code: 1442. Can't update table 'testlogins' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

I assume this is because I am asking the system to do a delete after a insert. I have also wondered if it would be worth while calling a stored procedure during a trigger to accomplish this.
What would be the best way to keep duplicate rows from being added that match in these four columns: USER, ACTION, TIME, LOCATION

A: The previous answer was about how to remove duplicates, but if you want to prevent duplicates to happen it's better to add a unique index:
CREATE UNIQUE INDEX idx_userlogins ON testlogins (USER, ACTION, TIME, LOCATION)

then to prevent an error to get raised when inserting a duplicated row, you could use this syntax:
INSERT INTO testlogins VALUES (value1, value2, value3, value4)
ON DUPLICATE KEY UPDATE user=user;

A: CREATE UNIQUE INDEX body_idx ON testlogins (action, time, location);

This will prevent duplicates of (action, time, location) from existing.

A: Like others have said, create a UNQUE INDEX (any field that will be unique for each user i.e. userName)
REPLACE INTO testlogins (`USER`, `ACTION`, `TIME`, `LOCATION`) VALUES (val1, val2, val3, val4)

replace into is a cool function that will replace if the unique index's match or insert if the unique index doesnt have a match


text:
Q: Why doesn't delayed job load my serialized arguments from the DB? When I schedule my delayed job, I do it in the usual way:
NotificationMailer.delay.notify(self, @current_user)

And if I peek at the object on the Delayed::Job queue (before the worker sees it), I can see my serialized parameter current_user in the handler:
[33] my_project »  Delayed::Job.first
  Delayed::Backend::ActiveRecord::Job Load (0.7ms)  SELECT "delayed_jobs".* FROM "delayed_jobs" ORDER BY "delayed_jobs"."id" ASC LIMIT 1
=> #<Delayed::Backend::ActiveRecord::Job:0x0000010d546fb0> {
          :id => 764161,
    :priority => 0,
    :attempts => 0,
     :handler => "--- !ruby/object:Delayed::PerformableMailer\nobject: !ruby/class 'SurveyCompletionNotificationMailer'\nmethod_name: :notify\nargs:\n- !ruby/ActiveRecord:MyInstance\n  attributes:\n    id: 10786\n   created_at: 2013-12-19 03:52:21.082910000 Z\n    updated_at: 2014-07-23 19:12:27.967755000 Z\n  delta: true\n- !ruby/ActiveRecord:User\n  attributes:\n    id: 30\n    first_name: Andrew\n    last_name: Anderson\n    created_at: 2013-01-16 16:40:20.980147000 Z\n    updated_at: 2013-01-16 16:40:20.980147000 Z\n    title: Compensation Analyst\n    primary_phone_number: '123456789'\n    supervisor_id: \n    status: modified\n    disabled: \n    prefix: \n    suffix: ''\n    department: ''\n    general_info: ''\n    contact_id: 4428\n    emulating: true\n",
  :last_error => nil,
      :run_at => Wed, 23 Jul 2014 14:12:27 CDT -05:00,
   :locked_at => nil,
   :failed_at => nil,
   :locked_by => nil,
       :queue => nil,
  :created_at => Wed, 23 Jul 2014 14:12:27 CDT -05:00,
  :updated_at => Wed, 23 Jul 2014 14:12:27 CDT -05:00
}

But I find that Delayed Job will ignore the serialized argument data and reload the User record from the database.  So if the User record changes between when the job is queued and when it executes, the new data will be used.  This is not what I want.  Why even bother the serialize the parameters if you're not going to use it?  Am I missing something?  Any way to get DJ to use the serialized argument data?

A: This is the behavior of DJ, it just uses the deserialized id to load the ActiveRecord object from DB (here is a related FAQ entry). If you want it to do something different, you would either need to monkeypatch ActiveRecord, or to pass the attributes as additional parameters to the mailer.


text:
Q: Parsing Html using Mojo::Dom in perl i am trying to parse a html content using Mojo::Dom in perl
The html content is

Hello everyone !        #<---- data which i want

   Text

                    Jacqueline

The code i have used is.,
my $desc=$dom->find('#description');
        print $desc;
this print all the data inside the div. but i only want the content from parent div. please give some suggestion .

A: say $dom->at("#description")->text;

A: From the perldoc
#Find
say '$dom->at(\'#description\')->text';
say $dom->at('#description')->text;

say '$dom->find(\'h2\')->text';
say $dom->find('h2')->text;

say '$dom->find(\'[id]\')->attr(\'id\')';
say $dom->find('[id]')->attr('id');

Outputs:
$dom->at('#description')->text
Hello everyone ! #<---- data which i want

$dom->find('h2')->text
Text

$dom->find('[id]')->attr('id')
description
shop-about

As you can see, $dom->at('#description')->text looks to do what you're looking for.


text:
Q: Passing data to components via subscription method I tried to pass data from my Newproducts component(parent component) to Newcard component (child component) via subcription but when i try to console log the data by clicking on the save button i dont see anything...the second time i click on save button then the data is displayed on the console log
Newproducts.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Productservice } from 'src/app/services/products.service';

@Component({
  selector: 'app-new-products',
  templateUrl: './new-products.component.html',
  styleUrls: ['./new-products.component.scss']
})
export class NewProductsComponent implements OnInit {
  default = "Bread";
  values;
  @ViewChild('f') form: NgForm;
  constructor(private router: Router,
              private route: ActivatedRoute,
              private prservice: Productservice) { }

  ngOnInit() {

  }

  onsubmit() {
    this.values = this.form.value;
    this.prservice.productcard.next(this.values);
    // console.log(this.form.value)
    // console.log(this.values)
    this.router.navigate(['card'], { relativeTo: this.route })
  }
}

Newcard.component.ts
import { Component, OnInit } from '@angular/core';
import { Productservice } from 'src/app/services/products.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-new-card',
  templateUrl: './new-card.component.html',
  styleUrls: ['./new-card.component.scss']
})
export class NewCardComponent implements OnInit {
  subscription: Subscription;

  constructor(private prservice: Productservice,
              router: Router,
              route: ActivatedRoute) { }

  ngOnInit() {
    this.subscription = this.prservice.productcard.subscribe(
      (value) => {
        const cardvalue = value;
        console.log(cardvalue);
      }
    )
  }
}

Products.service.ts
import { Subject } from "rxjs";

export class Productservice {
   productcard = new Subject<[]>();
}

A: Please use better code formating before you post this.
Its hard to get around that code. Anyways if your card route activates the child component. Then the problem is that you pass a new value to the subject before the child component is created. And because of that child component is unaware of "subject" change, because it didn't happen after the subscription.
Normal Subject works like this. You have to subscribe to subject before it changes else it won't give you any value if subscription occures after!
You should use BehaviorSubject. The difference here is that BehaviorSubject always holds a value. And when someone subscribes to it. It will emit the last value it held.
Hope I answered to your question.

A: You don't nee this Productservice, all you need is to pass value to the child component using @Input() binding.
Read more about this in docs Pass data from parent to child with input binding
Then in your child component you must implement NgOnChange interface and the ngOnChange() method will be called each time a value of the attribute decorated with @Input() has changed.

A: There is potential that @Ales answer is correct however, assuming that your child component is created before the shared service emits a new value on its subject via the parent then you could have a dependency instance bug.
your service is created when you provide it if you are using this syntax then the service ensures it is a singleton (i think).
@Injectable({
  providedIn: UserModule,
})

however with this syntax at a module level it is possible to have multiple service instances active that different components use therefore different subjects to subscribe to
@NgModule({
  providers: [UserService],
})


text:
Q: Applescript to place applications on specific desktops I've got an applescript, created in Automator, that opens a number of applications and folders that I use as part of a workflow for creating a photo book.  The way my flow works is Photoshop Elements in Desktop 1, four Finder windows on Desktop 2, iPhoto on Desktop 3 and Booksmart on Desktop 4.
My applescript opens each of these just as I'd like, the only problem is it opens everything on the desktop that I'm on at the time.  I then have to go into mission control and move around my windows putting each application onto the desktop I'd like it to be on.  This takes as long as opening the applications one by one on their requisite desktop.
I have tried assigning desktops to the applications, but this doesn't appear to work consistently.
Is there any applescript that I can use that will open an application on a specific desktop?
I'm running OS X 10.8.2.
Many thanks

A: Did you try assigning the application to a desktop?

This will open the application on the right desktop without the help of a script.


text:
Q: Dependant dropdown list does not show options Following code developed to create four dependent dropdownlist using codeigniter. Four dropdown list are used to select Client Name, project, task and task cost respectively. But only options for first three dropdown list are fetched from database. Options for the third dropdown list do not fetch from database.Also no error isshown in console log
Controller
<?php
ob_start();
// security first always....
(defined('BASEPATH') or exit('No direct script access allowed'));
/**
 * Class Controller
 *
 * Class Dropdown Controller to handle login & logout
 */
class Dropdown extends CI_controller
{
    /**
     * Class Constructor
     */
    public function __construct()
    {
        // execute parent class constructor
        parent::__construct();
        // load model
        $this->load->model('Dropdown_model');
    }

    /**
     * Default method to execute if method name missing
     * @return [type] [description]
     */
    public function index(){
  $array_data = array();
  // only on Ajax Request
  if ($this->input->is_ajax_request()) {
      // if request for projects
      if ($this->input->post('action') && $this->input->post('action') == 'project') {
          // get client name
          $client     = $this->input->post('client', true);
          // get project data by client name
          $array_data = $this->Dropdown_model->get_dropdown_data(trim($client), 'project');
          // AjaxPOST JSON response
          //set page header json type
          $this->output->set_content_type('application/json');
          $this->output->set_output(json_encode($array_data));
      }
      // if request for task
      else if ($this->input->post('action') && $this->input->post('action') == 'task') {
          // get project name
          $project    = $this->input->post('project', true);
          // get task data by project
          $array_data = $this->Dropdown_model->get_dropdown_data(trim($project), 'task');
          // AjaxPOST JSON response
          //echo json_encode($array_data);die();
          //set page header type json
          $this->output->set_content_type('application/json');
          $this->output->set_output(json_encode($array_data));
      }
      else if ($this->input->post('action') && $this->input->post('action') == 'taskcost') {
          // get project name
          $task    = $this->input->post('task', true);
          // get task data by project
          $array_data = $this->Dropdown_model->get_dropdown_data(trim($task), 'taskcost');
          // AjaxPOST JSON response
          //echo json_encode($array_data);die();
          //set page header type json
          $this->output->set_content_type('application/json');
          $this->output->set_output(json_encode($array_data));
      }
  }else{
    //put all view part in else
    // else get all client data
    $array_data = $this->Dropdown_model->get_dropdown_data(null, null);
    // send to view
    $this->load->view('dropdown', ['data' => $array_data]);
  }

}
}
?>

Model
<?php
// No direct script execution
defined('BASEPATH') or exit('No direct script access allowed');
/**
 * Class Dropdown_model to handle all related information from MySQL
 */
class Dropdown_model extends CI_Model
{
    /**
     * MySQL table which contains all data about users
     * @var string
     */
    protected $table = 'task';
    /**
     * Returns, User First Name by Email ID
     * @param  [type] $email_addres   [description]
     * @return [type] [description]
     */
    public function get_dropdown_data($where_data = null, $type = null)
    {
        $query = '';

        // clients only
        if (is_null($type) && is_null($where_data)) {
            // desire column from table
            $this->db->select('cname');
            // only unique clients
            $this->db->distinct('cname');
            // mysql table
            $query = $this->db->get($this->table);
        }

        // projects by client
        elseif ($type == 'project' && !is_null($where_data)) {
            // desire column from table
            $this->db->select('projectname');
            // where clause
            $this->db->where('cname', $where_data);
            // mysql table
            $query = $this->db->get($this->table);
        }

        // task by project
        elseif ($type == 'task' && !is_null($where_data)) {
            // desire column from table
            $this->db->select('task');
            // where clause
            $this->db->where('projectname', $where_data);
            // mysql table
            $query = $this->db->get($this->table);
        }
        // task by project
        elseif ($type == 'taskcost' && !is_null($where_data)) {
            // desire column from table
            $this->db->select('taskcost');
            // where clause
            $this->db->where('task', $where_data);
            // mysql table
            $query = $this->db->get($this->table);
        }

        // if record exist
        if ($query->num_rows() > 0) {
            // return all data as array
            return $query->result_array();
        } else {
            // error
            return false;
        }
    }
}

View
<!DOCTYPE html>

    <title>CodeIgniter: Dependent dropdown list by using single table value</title>

    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            Client
            <select class="form-control" id="clients" name="clients">
                <option value="0">--Select Clients--</option>
                <?php if (isset($data)):?>
                    <?php foreach ($data as $key => $value): ?>
                        <option value="<?=$value['cname']?>"><?=$value['cname']?></option>
                    <?php endforeach ?>
                <?php endif ?>
            </select>

            Projects
            <select class="form-control" id="projects" name="projects">
                <option value="0">--Select Projects--</option>
            </select>

            Tasks
            <select class="form-control" id="tasks" name="tasks">
                <option value="0">--Select Tasks--</option>
            </select>

            Tasks
            <select class="form-control" id="taskcost" name="taskcost">
                <option value="0">--Select Tasks--</option>
            </select>

            <input type="button" class="btn btn-primary" value="Submit">

A: There is a syntax error in your JS. A closing of projects.on function was missing, added it. Rectified code is as below.
$(document).ready(function(){
    // client select box
    var client     = $('select#clients');
    // project select box
    var projects   = $('select#projects');
    // task select box
    var tasks      = $('select#tasks');
    var taskcost      = $('select#taskcost');
    // on change client name, get projects
    client.on('change', function () {
        // get selected client name
        var client_val = $(this).find('option:selected').val();
        // post data with CSRF token
        var data = {
            action:'project',
            client: client_val,
            "<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
        };
        // AjaxPOST to get projects
        $.post('.', data, function(json) {
            var projects_data = '<option value="0">--Select Projects--</option>';
            $.each(json, function(index, obj){
                projects_data += '<option value="'+obj.projectname+'">'+obj.projectname+'</option>';
            });
            // append all projects in project dropdown
            projects.html(projects_data);
        }, 'JSON');
    });
    // on change project, get task
    projects.on('change', function () {
        // get selected project name
        var project = $(this).find('option:selected').val();
        // AjaxPOSt wit CSRF
        var data = {
            action:'task',
            project: project,
            "<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
        };
        $.post('.', data, function(json) {
            var task_data = '<option value="0">--Select Task--</option>';
            $.each(json, function(index, obj){
                task_data += '<option value="'+obj.task+'">'+obj.task+'</option>';
            });
            // append all task data in Task dropdown
            tasks.html(task_data);
            }, 'JSON');
        });
        taskcost.on('change', function () {
        // get selected project name
        var tasks = $(this).find('option:selected').val();
        // AjaxPOSt wit CSRF
        var data = {
            action:'taskcost',
            tasks: tasks,
            "<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
        };
        $.post('.', data, function(json) {
            var taskcost_data = '<option value="0">--Select Task--</option>';
            $.each(json, function(index, obj){
                taskcost_data += '<option value="'+obj.taskcost+'">'+obj.taskcost+'</option>';
            });
            // append all task data in Task dropdown
            tasks.html(taskcost_data);
        }, 'JSON');
    });
  });

Please confirm the above code.


text:
Q: Jenkins: prevent from reloading configuration I am currently doing an analysis whether jenkins could fit for our needs.
Therefore I need to know something about (NOT) reloading configurations:
I know that there is an explicit way to reload a configuration (via WebGUI and CLI).
BUT:
Is there also a way to PREVENT Jenkins from reloading configs?
One requirement is that the CI-System reads in all config-files (general and job-configs) ONCE at the start of the ci-system. And afterwards a modification of the config-files shall take NO effect!
Do you know whether this is already the case (except I press that button under "manage Jenkins" | "reload Configuration from hard disk" [exact options might sound a little different because I only have a German version here])
Would be very thankful for your help,
Lukas

A: I run a Git repo to control the config.xml files so have experience of the xml files changing while Jenkins is running.
I can confidently state that Jenkins will not reread the config.xml file unless you specifically ask it to via the UI or cli. In fact if the config is changed via the UI any changes that has been done to the config.xml file will be overwritten with the in-memory version.