text:
Q: 1 функция с аргументом вместо двух, Nuxt js Я работаю с Nuxt JS. Я пытаюсь практиковать свои навыки в js, в коде есть пара функций с одинаковым функционалом только для разных элементов. Можно ли как-то объединить эти две функции в одной, сделать универсальную с передачей аргумента?

 openOutSettings() {
    this.isOutOpen = !this.isOutOpen;
  }
  openInSettings() {
    this.isInOpen = !this.isInOpen;
  }

Думала реализовать нечто похожее

 openSettings(first, second) {
 if (first) {
    this.isOutOpen = !this.isOutOpen; } else {
    this.isInOpen = !this.isInOpen;}
  }

Но этот код не работает для меня. Подскажите, как правильно написать универсальную функцию в моем случае?

A: Можно сделать что-то вроде такого, хотя это и будет немного неправильно. Неправильно потому что явное - всегда лучше не явного.
 toogle(property) {
    this[property]= !this[property];
  }


text:
Q: accessing pictures in my exe of wpf app from codebehind im currently accessing my image in XAML and setting it to a picturebox with
Source="/SocialShock-WPF-Client;component/Images/blue-bar-replication.png"

how would i do this in the codebehind?

A:     public static BitmapImage GetImageFromResource(string name)
    {
        var res = new BitmapImage();
        res.BeginInit();
        res.StreamSource = Assembly.GetExecutingAssembly().GetManifestResourceStream("SocialShock-WPF-Client.Images." + name);
        res.EndInit();

        return res;
    }

Invoke this method with the image name, "blue-bar-replication.png" in your case.
The image build action should be set to EmbededResource.

A: Exactly the same way. Create BitmapImage object (pass Uri object with the same path to its constructor). Then set Image's Source property to the newly created BitmapImage object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: run newest version of file via batch I'm trying to find the simplest way to call the newest file version in a folder to run.
For example, C:\users\user\Desktop\filestest contains 4 files:

program-A.0011.exe
program-A.0012.exe
program-A.0013.exe
program-A.0014.exe

With 0014 being the newest version, but possibly not the last modified file.
cd C:\users\user\Desktop\filestest && program-A.%v%.exe with %v% being the highest variable? What am I missing here?
keep in mind the files are sorted in no particular order, I'm just looking for a way to call the latest version. in this case 0014
Test .exe files here

A: If the file names are always formatted such that the "latest" on would be sorted last, you can use a FOR loop to find it. This is not tested.
SET "THEDIR=%USERPROFILE%\Desktop\filestest"
FOR /F "delims=" %%A IN ('DIR /B /O:N "%THEDIR%\program-A.*.exe"') DO (SET "LATEST=%%~a")
ECHO The latest file is "%THEDIR%\%LATEST%"

If you wanted to get ahead into PowerShell, you could:
$Latest = (Get-ChildItem -File -Path $Env:USERPROFILE\Desktop\filestest -Filter 'program-A.*.exe' |
    Select-Object -Last 1).FullName

A: figured this one out.
This can easily break if naming structure changes, but it does exactly what I need it to do for the moment.
thanks everyone for the input.
cd "%USERPROFILE%\Desktop\filetest"
setlocal enableDelayedExpansion
set max=0
for /f "tokens=1* delims=-.0" %%A in ('dir /b /a-d program-A.*.exe') do if %%B gtr !max! set max=%%B
echo higest version: program-%max%

pause


text:
Q: Executing Python File from A String Directory in Jupyter Notebook Currently I am running a .py file at Jupyter Notebook using the following command:
!python /Users/manage.py /Users/u.data

Sometimes I have a really long file path. Thus, is there a way that I can execute it with anything similar to this?
path_name = "/Users/"
!python "{}manage.py".format(path_name) "{}u.data.format(path_name)

A: The notebook will interpolate variables in magic commands if you prefix the variable name with $
path_name = "/Users/"
py_file = "{}manage.py".format(path_name)
data = "{}u.data".format(path_name)

!python $py_file $data


text:
Q: justify - Best approach webkit browser is not supported "ruby of justify".
I found this javascript (https://code.google.com/p/justify/).
As a result of using this, a new problem has occurred...

 &ltul id="list"&gt
  &ltli&gt
   &lth3 id="main"&gt&ltruby&gtLorem&ltrt id="sub"&gtIpsum&lt/rt&gt&lt/ruby&gt&lt/h3&gt
   &ltp&gtLorem ipsum dolor sit amet...... &lt/p&gt
  &lt/li&gt
 &lt/ul&gt

This is fine. But this script used "document.getElementById".
When the element is increased, of course, it does not work.
When I rewrite "document.getElementById" to "document.getElementsByClass", Uncaught TypeError: Object #<NodeList> has no method...
When the element is increased, what I do I do?
(Sorry... I'm not good at English)

A:
Uncaught TypeError: Object #<NodeList> has no method...

This error occurs because you are trying to treat a list of nodes like a single node.  Probably because you are forgetting to get an element out of the result of getElementsByClassName.
getElementById returns a single DOM element, but getElementsByClassName returns a list (array-like object) of DOM elements.  You have to index into the latter, but not the former.

should alert "true"


text:
Q: Labels at the end of curves (matplotlib-seaborn) I have multiple data frames in this format:
year    count   cum_sum
2001    5   5
2002    15  20
2003    14  34
2004    21  55
2005    44  99
2006    37  136
2007    55  191
2008    69  260
2009    133 393
2010    94  487
2011    133 620
2012    141 761
2013    206 967
2014    243 1210
2015    336 1546
2016    278 1824
2017    285 2109
2018    178 2287

I have generated a plot as the followig:
enter image description here
The following code has been utilized for this purpose:
fig, ax = plt.subplots(figsize=(12,8))

sns.pointplot(x="year", y="cum_sum", data=china_papers_by_year_sorted, color='red')
sns.pointplot(x="year", y="cum_sum", data=usa_papers_by_year_sorted, color='blue')
sns.pointplot(x="year", y="cum_sum", data=korea_papers_by_year_sorted, color='lightblue')
sns.pointplot(x="year", y="cum_sum", data=japan_papers_by_year_sorted, color='yellow')
sns.pointplot(x="year", y="cum_sum", data=brazil_papers_by_year_sorted, color='green')

ax.set_ylim([0,2000])
ax.set_ylabel("Cumulative frequency")

fig.text(x = 0.91, y = 0.76, s = "China", color = "red", weight = "bold") #Here I have had to indicate manually x and y coordinates
fig.text(x = 0.91, y = 0.72, s = "South Korea", color = "lightblue", weight = "bold") #Here I have had to indicate manually x and y coordinates

plt.show()

The problem is that the method for adding text to the plot is not recognizing the data coordinates. So, I have had to manually indicate the coordinates of the labels of each dataframe (please see "China" and "Korea"). Is there a clever way of doing it? I have seen an example using ".last_valid_index()" method. However, since the data coordinates are not being recognized, it is not working.

A: You don't need to make repeated calls to pointplot and add labels manually. Instead add a country column to your data frames to indicate the country, combine the data frames and then simply plot cumulative sum vs year using country as the hue.
Instead, do the following:
# Add a country label to dataframe itself
china_papers_by_year_sorted['country'] = 'China'
usa_papers_by_year_sorted['country'] = 'USA'
korea_papers_by_year_sorted['country'] = 'Korea'
japan_papers_by_year_sorted['country'] = 'Japan'
brazil_papers_by_year_sorted['country'] = 'Brazil'

# List of dataframes with same columns
frames = [china_papers_by_year_sorted, usa_papers_by_year_sorted,
          korea_papers_by_year_sorted, japan_papers_by_year_sorted,
          brazil_papers_by_year_sorted]

# Combine into one dataframe
result = pd.concat(frames)

# Plot.. hue will make country name a label
ax = sns.pointplot(x="year", y="cum_sum", hue="country", data=result)
ax.set_ylim([0,2000])
ax.set_ylabel("Cumulative frequency")
plt.show()

Edit: Editing to add that if you want to annotate the lines themselves instead of using the legend, the answers to this existing question indicate how to annotate end of lines.


text:
Q: Trying to read the contents from strstream causes access violation I am trying to read the contents of an ostrstream using the str (). While trying to do so, i always come across access violations and my application crashes. Is there a way to read from strstream without causing stream errors?
I am working on a legacy project built on Borland C++. I am presently using Borland C++ v5.02 for building my project. Since the code is vast and scattered over a large number of files, I am unable to paste the code here. However, I will try to highlight my use case.
ps is the stream which is being used throughout the project to print receipts. I need to get the receipt data from this strstream without breaking the code.
string str = ps.pStr->str ();
ps.Pstr->rdbuf ()->freeze (0);
ps << EndJob;
The last line causes access violation

A: You missed set null in the end of the buffer.
Before any call to str() that uses the result as a C string, the buffer must be null-terminated, typically with std::ends.


text:
Q: Scarce / non-renewable items I'm trying not to be too vague here, as I suspect a complete answer would require a massive Wiki/DB, but which items are "renewable" vs "scarce" ?
Obviously "boss" parts like Queen Endraga Pheremones or Kayran bits are unique, but:
If I'm looking for silver ore, will there always be some around?
Most crafting components can themselves be crafted, but are the raw materials always plentiful, or is there a limited amount of iron ore in each town?
What about monsters, am I going to end up wishing I'd saved more Nekker parts because there are finite Nekkers spawned in the game?
Is there a danger of "missing out" on various components, or can I theoretically just grind local creatures to produce whatever I need (assuming sufficient money for the purchasing and crafting labor)?

A: The inventory of merchants does respawn after a while, you have to meditate for about 24-48 hours and there should be a new selection of stuff to buy. I used that to get enough iron and silver ore for some swords, as the shop did not sell enough of the ore at once to craft the new sword.
Plants also do respawn after a short while, those you also can farm indefinitely. I'm not sure if you can get every single alchemy ingredient everywhere just from plants and respawning monsters, but there is usually an alchemy shop in every area so you should be able to buy anything you're missing. Except for certain quests, you only need the 9 base alchemy types, you don't need any specific ingredients, just something that e.g. contains Quebrith.
So, as long as you have enough money and the merchants generally stock the items you need, you shouldn't run out of crafting ingredients.


text:
Q: How can I identify the document created last using Lotusscript from a collection of documents that share the same document number? I have a database that contains about 20,000 documents.  One of the views is categorized by Document Number and sorted such that the document created last is the first document in each category.  Some categories (document numbers) only have on document associated with it, but others have multiply documents associated with it.  I would like to identify the document created last in each category and write to a field indentifying it as the latest revision.   I thought this would be easy, but, I'm having difficulties.  Any help would be appreciated.
MJ

A: It may be simple assuming you do have a view, as you say, that is sorted such that the document created last is the first document within each category.  In that case if you were to traverse that view you would simply need to retrieve the first document after each category, and set a value on one of the document's items.
For example,
Dim s as New NotesSession
Dim db as NotesDatabase
Dim view as NotesView
Dim nav As NotesViewNavigator
Dim viewEntry as NotesViewEntry
Dim docEntry as NotesViewEntry
Dim doc as NotesDocument

Set db = s.CurrentDatabase
Set view = db.GetView("My Categorized and Sorted View")
Set nav = view.CreateViewNav
Set viewEntry = nav.GetFirst  ' Should be your first category

While Not (viewEntry Is Nothing)

    Set docEntry = nav.GetNextDocument(viewEntry)  'The first document entry after the category
    Set doc = docEntry.Document
    doc.ReplaceItemValue("Some item", "This is the latest doc")
    doc.Save(false, false)
    Set viewEntry = nav.GetNextCategory(viewEntry)  'Jump to the next category

Wend


text:
Q: VAST (Vpaid) Clicks; second ClickTracking node I'm currently encountering a problem with a vpaid creative on different video players.
I'm using a flash vpaid creative hosted on my server. It includes the clickthrough urls (given via clicktag-parameters to the flash).
 nodes are specified in the VAST XML and should enable counting of clicks for the AdServer.
There's also one -node in the VAST XML, but according to the VPaid-Specs this might by ignored.
This seems to work fine when I test it on the Google IMA test page with chrome. However, I don't count clicks on some of the video players I'm running the ad on. This behaviour has started in June.
I'm also counting the clicks from within the flash, and the numbers are higher than those we're counting from the VAST (-Node).
The thing is, we're inserting two -Nodes in the VAST. Is it possible that the second one is discounted by some video players?
Kind regards,
der_seri

A: I would say that your assumption is correct. In my experience, a lot of players, including those who claim to be VPAID compliant, are actually not fully VPAID compliant and might not offer the full functionality they should do.
JW Player is one of the best in my opinion- have you tested on their player? If not, try it here: http://demo.jwplayer.com/ad-tester/
If that still does not work, post your VAST and I don't mind taking a look.


text:
Q: What is $\frac{d}{dx}(4\dot{y}^3)$ I have this question:

By solving the Euler-Lagrange equation, show that the geodesics are straight line

My attempt at solveing the question is attached below:

However i do not know to how to solve the equation $\frac{d}{dx}(4\dot{y}^3)$
My attempt at solving it gives:

A: As a forewarning, I am switching notation from $\frac{dy}{dx}=\dot{y}$ to $\frac{dy}{dx}=y'$ because a dot is usually used to denote a "time" (or parametric) derivative.
Make sure we are starting off with a valid Euler-Lagrange equation. In case you are unaware, it is easy to convince yourself that when minimizing length as the integral of a function $$f(x,y,y') = \sqrt{1+(y')^2}$$ it will be equivalent to minimize the integral of the square  $$f^2(x,y,y') = 1+(y')^2 .$$
The Euler-Lagrange equation we want to use is $$\frac{\partial f}{\partial y} - \frac{d}{dx}\bigg[\frac{\partial f}{\partial y'}\bigg]=0 \text{ .}$$
Applying this to our function $f$, we have
$$0 - \frac{d}{dx}\bigg[2y'\bigg]=0 $$ so clearly
$$ \frac{d}{dx}\bigg[2y'\bigg]=\frac{d}{dx}\bigg[2\frac{dy}{dx}\bigg]=2\frac{d^2y}{dx^2}=0 .$$
We are left with the second order ODE
$$\frac{d^2y}{dx^2} = 0$$
which models a line in the plane $y(x) = c_1 x + c_2 \text{ .}$


text:
Q: PHP : different behaviour of XSLT Processor in Windows WRT to Linux I've got this php snippet:
$xsltPath = $argv[1];
$xmlPath = $argv[2];

$xslt = file_get_contents($xsltPath);
$xml = file_get_contents($xmlPath);

$templateCMSObj = new \DOMDocument();
$templateCMSObj->loadXML($xslt);
$ekbXMLObj = new \DOMDocument();
$ekbXMLObj->loadXML($xml);
$proc = new \XSLTProcessor();
$proc->importStylesheet($templateCMSObj);
$html = $proc->transformToXML($ekbXMLObj);
echo($html);
exit;

Which simply applies an XSLT to a given XML document.
When I apply the below XSLT to the same XML doc I got a different behaviour of Windows wrt to Linux PHP version.
Here's php and libxml version detail:
Windows:
PHP 7.1.6 (cli) (built: Jun  8 2017 02:06:32) ( ZTS MSVC14 (Visual C++ 2015) x86 )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

XML Support => active
XML Namespace Support => active
libxml2 Version => 2.9.4
XMLReader => enabled
XMLWriter => enabled
XSL => enabled
libxslt Version => 1.1.29
libxslt compiled against libxml Version => 2.9.4
EXSLT => enabled
libexslt Version => 0.8.17

Linux:
PHP 7.0.32-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.32-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend Technologies
    with Xdebug v2.5.5, Copyright (c) 2002-2017, by Derick Rethans

XML Support => active
XML Namespace Support => active
libxml2 Version => 2.9.1
XMLReader => enabled
XMLWriter => enabled
XSL => enabled
libxslt Version => 1.1.28
libxslt compiled against libxml Version => 2.9.1
EXSLT => enabled
libexslt Version => 1.1.28

Here's is the XSLT code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://new.webservice.namespace">
    <xsl:output method="xml" version="1.0" indent="yes"/>
    <xsl:param name="searchPath" select="11"/>
    <xsl:variable name="slash" select="'/'"/>
    <xsl:variable name="dot" select="'.'"/>
    <xsl:variable name="open_bracket" select="'{'"/>
    <xsl:variable name="closed_bracket" select="'}'"/>
    <xsl:template match="/">
        <ns:flat_pallet>
            <xsl:attribute name="tipo"><xsl:value-of select="//ns:EKB_piatto/@tipo"/></xsl:attribute>
            <xsl:apply-templates select=".//ns:gruppo_logico/ns:versione/ns:contenuto/ns:riferimento_oi"/>
        </ns:flat_pallet>
    </xsl:template>

    <!--restituisco tipo del box e l'indice relativo a nel sottoalbero-->
    <xsl:template match="ns:gruppo_logico">
        <xsl:variable name="tipo">
            <xsl:value-of select="@tipo"/>
        </xsl:variable>
        <xsl:variable name="index">
            <xsl:number level="single" count="node()[@tipo=$tipo]" format="1"/>
        </xsl:variable>
        <xsl:value-of select="normalize-space($tipo)" disable-output-escaping="yes"/>
        <xsl:value-of select="$open_bracket"/>
        <xsl:value-of select="$index -1" disable-output-escaping="yes"/>
        <xsl:value-of select="$closed_bracket"/>
        <xsl:value-of select="$slash"/>
    </xsl:template>
    <!--quando sono in una unit risalgo i box progenitori-->
    <xsl:template match="ns:riferimento_oi">
        <xsl:variable name="tipoUnit" select="./ns:tipo"/>
        <xsl:variable name="index">
            <xsl:number level="single" count="node()[node()/ns:tipo=$tipoUnit]" format="1"/>
        </xsl:variable>
        <xsl:variable name="labelPath">
            <xsl:apply-templates select="ancestor::ns:gruppo_logico"/>
            <xsl:value-of select="$tipoUnit"/>
            <xsl:value-of select="$open_bracket"/>
            <xsl:value-of select="$index -1"/>
            <xsl:value-of select="$closed_bracket"/>
        </xsl:variable>
        <xsl:copy>
            <xsl:attribute name="labelPath"><xsl:value-of select="$labelPath" disable-output-escaping="yes"/></xsl:attribute>
            <xsl:attribute name="unitIndex"><xsl:value-of select="$index" disable-output-escaping="yes"/></xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="@*|node()">
        <!-- just copy all my attributes and child nodes, except if there's a better template for some of them -->
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--template per rimuovere nodi vuoti-->
    <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/>
</xsl:stylesheet>

And the XML Doc which gaves different results in win and linux
XSLT:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns:dettaglioFormEKBSOUT xmlns:ns="http://new.webservice.namespace">
    <ns:EKB_piatto>
        <ns:campo_GL>
            <ns:gruppo_logico tipo="Standard">
                <ns:versione id="1">
                    <ns:contenuto>
                        <ns:riferimento_oi>
                            <ns:tipo>Standard</ns:tipo>
                            <ns:natura_OI>
                                <ns:UNI>2.1</ns:UNI>
                            </ns:natura_OI>
                        </ns:riferimento_oi>
                    </ns:contenuto>
                    <ns:contenuto>
                        <ns:riferimento_oi>
                            <ns:tipo>Standard</ns:tipo>
                            <ns:natura_OI>
                                <ns:UNI>2.2</ns:UNI>
                            </ns:natura_OI>
                        </ns:riferimento_oi>
                    </ns:contenuto>
                </ns:versione>
            </ns:gruppo_logico>
            <ns:gruppo_logico tipo="Standard_due">
                <ns:versione id="1">
                    <ns:contenuto>
                        <ns:riferimento_oi>
                            <ns:tipo>Standard</ns:tipo>
                            <ns:natura_OI>
                                <ns:UNI>2.1</ns:UNI>
                            </ns:natura_OI>
                        </ns:riferimento_oi>
                    </ns:contenuto>
                    <ns:contenuto>
                        <ns:riferimento_oi>
                            <ns:tipo>Standard_due</ns:tipo>
                            <ns:natura_OI>
                                <ns:UNI>2.2</ns:UNI>
                            </ns:natura_OI>
                        </ns:riferimento_oi>
                    </ns:contenuto>
                </ns:versione>
            </ns:gruppo_logico>
        </ns:campo_GL>
    </ns:EKB_piatto>
</ns:dettaglioFormEKBSOUT>

Linux output
This is the desired output which actually results from applying XSLT on Linux:
<?xml version="1.0"?>
<ns:flat_pallet xmlns:ns="http://new.webservice.namespace" tipo="">
    <ns:riferimento_oi labelPath="Standard{0}/Standard{0}" unitIndex="1">
        <ns:tipo>Standard</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.1</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
    <ns:riferimento_oi labelPath="Standard{0}/Standard{1}" unitIndex="2">
        <ns:tipo>Standard</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.2</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
    <ns:riferimento_oi labelPath="Standard_due{0}/Standard{0}" unitIndex="1">
        <ns:tipo>Standard</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.1</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
    <ns:riferimento_oi labelPath="Standard_due{0}/Standard_due{0}" unitIndex="1">
        <ns:tipo>Standard_due</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.2</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
</ns:flat_pallet>

Windows output
This is the wrong result produces on Windows:
<?xml version="1.0"?>
<ns:flat_pallet xmlns:ns="http://new.webservice.namespace" tipo="">
    <ns:riferimento_oi labelPath="Standard{0}/Standard{0}" unitIndex="1">
        <ns:tipo>Standard</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.1</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
    <ns:riferimento_oi labelPath="Standard{0}/Standard{1}" unitIndex="2">
        <ns:tipo>Standard</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.2</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
    <ns:riferimento_oi labelPath="Standard_due{NaN}/Standard{0}" unitIndex="1">
        <ns:tipo>Standard</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.1</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
    <ns:riferimento_oi labelPath="Standard_due{NaN}/Standard_due{NaN}" unitIndex="">
        <ns:tipo>Standard_due</ns:tipo>
        <ns:natura_OI>
            <ns:UNI>2.2</ns:UNI>
        </ns:natura_OI>
    </ns:riferimento_oi>
</ns:flat_pallet>

The problem lies in the NaN put instead of relative index: it surely has to do with xsl:number element, but I can't figure out how to fix this...

Edit after accepted answer
By changing xsl:number count attribute to * instead of node() the xslt template works as expected on both Win and Linux.
Here's the updated code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://new.webservice.namespace">
    <xsl:output method="xml" version="1.0" indent="yes"/>
    <xsl:param name="searchPath" select="11"/>
    <xsl:variable name="slash" select="'/'"/>
    <xsl:variable name="dot" select="'.'"/>
    <xsl:variable name="open_bracket" select="'{'"/>
    <xsl:variable name="closed_bracket" select="'}'"/>
    <xsl:template match="/">
        <ns:flat_pallet>
            <xsl:attribute name="tipo"><xsl:value-of select="//ns:EKB_piatto/@tipo"/></xsl:attribute>
            <xsl:apply-templates select=".//ns:gruppo_logico/ns:versione/ns:contenuto/ns:riferimento_oi"/>
        </ns:flat_pallet>
    </xsl:template>

    <!--restituisco tipo del box e l'indice relativo a nel sottoalbero-->
    <xsl:template match="ns:gruppo_logico">
        <xsl:variable name="tipo">
            <xsl:value-of select="@tipo"/>
        </xsl:variable>
        <xsl:variable name="index">
            <xsl:number level="single" count="*[@tipo=$tipo]" format="1"/>
        </xsl:variable>
        <xsl:value-of select="normalize-space($tipo)" disable-output-escaping="yes"/>
        <xsl:value-of select="$open_bracket"/>
        <xsl:value-of select="$index -1" disable-output-escaping="yes"/>
        <xsl:value-of select="$closed_bracket"/>
        <xsl:value-of select="$slash"/>
    </xsl:template>
    <!--quando sono in una unit risalgo i box progenitori-->
    <xsl:template match="ns:riferimento_oi">
        <xsl:variable name="tipoUnit" select="./ns:tipo"/>
        <xsl:variable name="index">
            <xsl:number level="single" count="*[*/ns:tipo=$tipoUnit]" format="1"/>
        </xsl:variable>
        <xsl:variable name="labelPath">
            <xsl:apply-templates select="ancestor::ns:gruppo_logico"/>
            <xsl:value-of select="$tipoUnit"/>
            <xsl:value-of select="$open_bracket"/>
            <xsl:value-of select="$index -1"/>
            <xsl:value-of select="$closed_bracket"/>
        </xsl:variable>
        <xsl:copy>
            <xsl:attribute name="labelPath"><xsl:value-of select="$labelPath" disable-output-escaping="yes"/></xsl:attribute>
            <xsl:attribute name="unitIndex"><xsl:value-of select="$index" disable-output-escaping="yes"/></xsl:attribute>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="@*|node()">
        <!-- just copy all my attributes and child nodes, except if there's a better template for some of them -->
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--template per rimuovere nodi vuoti-->
    <xsl:template match="*[not(@*|*|comment()|processing-instruction()) and normalize-space()='']"/>
</xsl:stylesheet>

A: In the select attribute of xsl:number, use * instead of node().
When you use node(), that can be an element, text, comment, or processing instruction node.
When you use *, that's only an element. That makes more sense in your use of xsl:number.
See https://xsltfiddle.liberty-development.net/nc4NzRq/1 for a working fiddle. (Thanks @parfait!)


text:
Q: Generate dynamic form and store the data in Laravel For a part of my next project I'm looking for the following information.
I'm trying to make an application for something like scouts, all the supervisors will have a user account on the application and the supervisors will be able to manage the members of the scouts. I'm looking for a way to let the supervisor decide what information they would like to store about the member. This will then be converted to a form so they can easily add new members.
What is the best way to make a dynamic form and store the data in a database.
Thanks in advance!

A: Well there are many ways to do that, so I don't know if this is the best with the little information you give us about your "case scenario".
I'll do create this tables:
forms (hold the form basic info and supervisors reference)
forms_fields (with an Elquent relatinship tipy "belongsTo")
Check Laravel documentation on Eloquent here>


text:
Q: HTML in WooCommerce settings I need to append a default text block to each product description (same text for each and every product) in WooCommerce. So I've created simple plugin which adds new settings field as rich text editor (wp_editor) into "WooCommerce > Settings > Catalog" tab.
All works fine and I can enter/save plain text, but it strips any HTML tags. I believe tags are stripped by woocommerce_clean in settings-save.php
if ( isset( $value['id'] ) && isset( $_POST[$value['id']] ) ) {
 update_option($value['id'], woocommerce_clean($_POST[$value['id']]));
} elseif( isset( $value['id'] ) ) {
 delete_option($value['id']);
}

How can this be fixed without changing core code?

A: The woocommerce_clean function: return trim( strip_tags( stripslashes( $var ) ) ); is pretty much going to stip out any html. You may be able to use core WordPress sanitize and escaping functions, but no guarantee how WooCommerce is going to react.
Take a look at Data Validation docs on the WordPress Codex for other options.
Since your boilerplate text is the same on every product your simplest solution may be copy the default WooCommerce template(s) into your theme's directory and editing the file(s) as needed. Seems like overkill to write a user interface for this.
If you want to display this in the product 'Short Description' then the file would be ../wp-content/plugins/woocommerce/templates/single-product/short-description.php. Copy that file to your your theme's directory ../wp-content/themes/***your theme directory***/woocommerce/single-product/short-description.php
Once you've copied you can edit the file without worrying about your changes being overwritten when you update WooCommerce.
The docs on customizing the templates are at WooCommerce docs.
NOTE: If you want this in the Description tab you can use the file ../wp-content/plugins/woocommerce/templates/single-product/tabs/description.php


text:
Q: SQL Server composite key problem I have 2 tables:
create table numbers2
(
id1 int IDENTITY(1,1) not null,
id2 int not null,
primary key(id1, id2)
)

and table 2
create table ttt
(
id int identity(1,1) not null,
first_name varchar(50) null,
last_name varchar(50) null,
sex varchar(1) check (sex in ('m', 'f')) null,
number_id int not null,
id_id1 int not null,
id_id2 int not null,
primary key(id),
constraint fk_numbers_id1 foreign key (id_id1) references numbers2(id1)
on update no action
on delete no action
)

The problem is how to add constraint "fk_numbers_id1" so it will only reference one part of the composite key from table numbers2. Is it possible or there is other solution?

A: Create a unique constraint on numbers2.id1:
create table numbers2
(
id1 int IDENTITY(1,1) not null,
id2 int not null,
primary key(id1, id2),
unique(id1)
)

I would like to know why you chose to create the primary key over two columns, where the first column is already unique by itself. I'm sure this violates some kind of Normal Form rule but I can't remember which one.
If you did it in order to cover the data in both columns, then it is unnecessary to do that, just do this instead (assuming that the data in id1 is genuinely unique):
create table numbers2
(
id1 int IDENTITY(1,1) not null,
id2 int not null,
primary key(id1),
)
create index cover_id2 on numbers2(id2) -- no need to include clustered index columns in a covering index


text:
Q: mysql union order performance I have a MySQL union of 2 queries, with ORDER BY done on indexed columns. What is better performance wise, order by each of the union queries separately, or order by at the end of the union as I currently have it?
(SELECT pep.P_Surname, pep.P_FirstName, pep.P_ID, adm.Loc_ID AS lid
FROM lup_people pep
JOIN tr_adm adm ON pep.P_ID=adm.P_ID
WHERE (P_FirstName LIKE 'g%'
OR P_Surname LIKE 'g%')
AND pep.active = 'Y')

 UNION

(SELECT pep.P_Surname, pep.P_FirstName, pep.P_ID, vil.Loc_ID AS lid
FROM lup_people pep
JOIN tr_village vil ON (pep.P_ID=vil.P1_ID OR pep.P_ID=vil.P2_ID)
WHERE (P_FirstName LIKE 'g%'
OR P_Surname LIKE 'g%')
AND pep.active = 'Y')

ORDER BY P_Surname,P_FirstName LIMIT 50

VS
(SELECT pep.P_Surname, pep.P_FirstName, pep.P_ID, adm.Loc_ID AS lid
FROM lup_people pep
JOIN tr_adm adm ON pep.P_ID=adm.P_ID
WHERE (P_FirstName LIKE 'g%'
OR P_Surname LIKE 'g%')
AND pep.active = 'Y' ORDER BY P_Surname,P_FirstName LIMIT 50)

UNION

(SELECT pep.P_Surname, pep.P_FirstName, pep.P_ID, vil.Loc_ID AS lid
FROM lup_people pep
JOIN tr_village vil ON (pep.P_ID=vil.P1_ID OR pep.P_ID=vil.P2_ID)
WHERE (P_FirstName LIKE 'g%'
OR P_Surname LIKE 'g%')
AND pep.active = 'Y' ORDER BY P_Surname,P_FirstName LIMIT 50)

A: (1) You should use union all, unless you intend for duplicates to be removed by the union.
(2) The queries are different.  The first returns 100 rows.  The second returns 50 rows.
(3) You should not depend on the ordering of results from a union query.  If you want results in a particular order, then use an order by after the union.
(4) Quite possibly, the fastest approach is to use left outer join.  It would look something like:
SELECT pep.P_Surname, pep.P_FirstName, pep.P_ID,
       coalesce(adm.Loc_ID, vil.loc_id, vil2.loc_id) AS lid
FROM lup_people pep LEFT JOIN
     tr_adm adm
     ON pep.P_ID = adm.P_ID LEFT JOIN
     tr_village vil
     ON pep.P_ID = vil.P1_ID LEFT JOIN
     tr_village vil2
     ON pep.P_ID = vil2.P2_ID
WHERE (P_FirstName LIKE 'g%' OR P_Surname LIKE 'g%') AND pep.active = 'Y'
ORDER BY P_Surname, P_FirstName
LIMIT 50;

A: Based on the volume of data, it could go either way.  The issue you are faced with is this.  In your first query you are doing a select-from getting ALL POSSIBLE answers that qualify, after which, THEN the order by clause is applied and finally the limit.  So, if you have 1000's of qualified records, you are still plowing through them, ordering, then get the top 50.
The second one will AT LEAST, cut their respective result sets down to 50 from each leaving a max of 100 records.


text:
Q: float numbers in c [Xcode IDE] I have started to learn c language but the problem is that I'm confused about how to use float numbers. I am using Xcode as IDE. Here are the results that got me confused:
float x1 = 1.123456789123456789f;
double x2 = 1.123456789123456789f;
float x3 = 987654321.123456789f;
double x4 = 987654321.123456789f;

printf("x1 = %.20f\n", x1);
printf("x2 = %.20f\n", x2);
printf("x3 = %10.10f\n", x3);
printf("x4 = %10.10f\n", x4);

The output is:

x1 = 1.12345683574676513672
x2 = 1.12345683574676513672
x3 = 987654336.0000000000
x4 = 987654336.0000000000

The question is, why x1, x2 lose their float digits after 1.12345678? And why x3 and x4 are truncated?

A: The basic problem here is that floating point numbers only have a limited precision: they can only represent that many significant digits before they run out of space. It does not matter if those digits are before the decimal point or after it, the total number of significant digits matters. Note that this issue is not restricted to C, it can be seen in all languages/environments that use floating point numbers.
double should be able to store about twice as many digits as float, but all your floating point literals are float literals. Remove the f postfix on the double lines to actually use all the bits available for a double.

A: What you're missing is that you're putting each of your numbers through 2 base conversions, and x2 and x4 also through a widening type conversion.
First of all you have decimal literals, which the compiler converts to binary fractions of type float, which have a precision of 23 binary digits (equivalent to about 7.2 decimal digits) and cannot accurately represent most decimal fractions, even those that fit into their precision. Then x2 and x4 are assigned to double variables, but since everything that does not fit into 23 binary digits has already been cropped, they don't magically regain the precision that was present in the literals.
Then, you convert the binary fractions back to decimal via printf, and get the previously mention ca. 7.2 decimal digits correct, and everything after that reflects the representational rounding error created by the base conversion.
It's basically the same as if you try to convert 1/3 to a decimal fraction 0.333 and back to a proper fraction 333/1000 - hey, why isn't it 1/3?
Read the floating-point guide for more information.


text:
Q: Cannot extract data from XML file using XMLStarlet in the command line (namespace restriction) I try to extract data from a xml file (which I named output.xml) on the command line (and then, if I manage to do it, put it in a script).
I've seen that the better tool to do that is XMLStarlet. However xmlstarlet sel -t -m "/entry/content" output.xml doesn't work.
Note: I tried for xmlstarlet el output.xml to check the Xpath structure of the file and it works.That means that the tool sees the elements.

I saw that there are 2 conditions to make XMLStarlet work:
1- The XML file should be well-formed. Stackoverflow related link
So I applied this command to create a well-formed file:
xmlstarlet fo -R output.xml >> good-output.xml
2- XML is very picky about the default namespace. If the document has it, declare it before selecting the elements or delete all the occurences of "xmlns" in the document. Stackoverflow related link
So I did:
$ cat good-output.xml | sed -e 's/ xmlns.*=".*"//g' >> very-good-output.xml
HOWEVER, even performing these two steps, I have another error, and  don't know how to fix it... The terminal points to me the places I removed the namespaces and says "Namespace prefix app on collection is not defined". What I should do? With the namespaces it doesn't work and now it urges to put them again upon me...
Any help?
Screenshot of the original problem
Screenshot of the final problem

A: So this is the final solution to retrieve the content of a XML file with multiple namespaces:
xmlstarlet sel -t -m "//_:content" -c . good-output.xml

npostavs thank you for guiding me.
I believed the fact that my first attempt gave me the tag besides the desired content was a problem, but actually in my case no. If it is the case for someone else, this is how to proceed:
xmlstarlet sel -t -m "/_:entry/_:content/text()" -c . output.xml
OR
xmlstarlet sel -t -m "/_:entry/_:content" -v . output.xml
Simplified:
xmlstarlet sel -t -v "/_:entry/_:content" output.xml

A: Seems that the problems like this happens if the xml uses a different namespace. In these cases, one solution to overcome namespaces issues is to tell xmlstarlet the expected namespace value of the element:
xmlstarlet sel -N x='http://different.namespace.url/XMLSchema' -t -m '//x:YourElemHere' input.xml


text:
Q: Print contents of register to console in LC3 Assembly Say I have a value (eg. 1234) that I load into R0. How could I print this value to the console?

A: I'm assuming you would like to print a number out to the console but you're getting random characters if anything.
This happens when the LC3 tries to interpret your number as an ASCII character. Example: The number 8 in ASCII is the backspace character.
To make your program work you will need to add 48 (decimal) or x30 (hex) to your number before you can print it to the console.
.ORIG x3000
  AND R0, R0, #0    ; Clear R0
  LD R0, NUM        ; load our number into R0
  LD R2, ASCII      ; load the ascii offset into R2
  ADD R0, R0, R2
  OUT
HALT                ; Trap x25

NUM   .fill  x02    ; Our Number to print
ASCII .fill  x30    ; Our ASCII offset
.END

In your example you want to print off an array of characters like 1234. The concept for this is pretty similar but we'll need to work with pointers and a for loop.
.ORIG x3000
  AND R0, R0, #0    ; Clear R0
  AND R1, R1, #0    ; Clear R1
  AND R3, R3, #0    ; Clear R3
  LEA R0, NUM       ; pointer [mem]NUM
  ADD R1, R1, R0    ; Store the pointer address of R0 into R1
  LD R2, ASCII      ; load the ascii offset into R2

FOR_LOOP
  LDR R4, R1, #0    ; load the contents of mem address of R1 into R4
  BRz END_LOOP
  ADD R4, R4, R2    ; Add our number to the ASCII offset
  STR R4, R1, #0    ; Store the new value in R4 into [mem] address R1
  ADD R1, R1, #1    ; move our memory pointer down one
  BRnzp FOR_LOOP    ; loop again until we get an x00 char
END_LOOP

  PUTs              ; print our string starting from [mem]address in R0
HALT                ; Trap x25

ASCII .fill  x30    ; Our ASCII offset
NUM   .fill  x01    ; Our Number to print
      .fill  x02
      .fill  x03
      .fill  x04
.END


text:
Q: Restoring specific version of spreadsheet using the Google API Just like the title says, I'm trying to find a way to restore a spreadsheet to a specific version using the Google Sheets API v4 (or Google Drive API v3).
This is needed because of unit testing - I need one test to perform some actions (let's say delete a row) on a spreadsheet, assert the results and then reset the spreadsheet to its initial state so the next test can execute on the original spreadsheet.
So far I noticed that there isn't an option to do something similar in the Google Sheets API. As far as using the Google Drive API goes, I tried using revisions (getting a list of all revisions and deleting all revisions after the desired one), but to no avail.
I also tried capturing the request after clicking on the Restore this version button and found out there is a revisions/revert endpoint.
> Example:
> https://docs.google.com/spreadsheets/d/**spreadsheetId**/revisions/revert?includes_info_params=false

I actually managed to revert the version this way, but using Postman and using hardcoded values - which is bad.
Any advice on how to approach this?

A: The usual way to restore an older version from a document with Drive API is by deleting all later versions with Revisions: delete. But, as the referenced documentation indicates, "you can only delete revisions for files with binary content in Google Drive, like images or videos. Revisions for other files, like Google Docs or Sheets, and the last remaining file version can't be deleted". So there is no direct way to revert to a previous version with Drive API (Sheets API is not useful for this).
Workaround:
A possible workaround would be to do the following:

*

*Get the revision ID you want to restore via Revisions.list.

*Export the version you want to restore via Revisions.get and exportLinks, a property of the Revisions resource. You will have to choose the MIME type in which to export this version (see list of supported export MIME types). Update: You have to specify that you want to retrieve the field exportLinks by setting the parameter fields to exportLinks.

*Get the blob of this exported version.

*Using this blob, update the spreadsheet with Files.update.

You can see the code to do this in Google Apps Script in this answer. You would have to use the API directly and adapt this to C#, but the workflow is basically the same.
Reference:

*

*Revisions: delete

*Revisions resource

*G Suite documents and corresponding export MIME types

*Files.update


text:
Q: Building wheel for pandas (setup.py): finished with status 'error' I have Cygwin installed on my PC and I am trying to install pandas via the pip installer.
Below are some of the messages I get when installing pandas.
$ pip install pandas
Collecting pandas
  Using cached https://files.pythonhosted.org/packages/07/cf/1b6917426a9a16fd79d56385d0d907f344188558337d6b81196792f857e9/pandas-0.25.1.tar.gz
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/lib/python3.7/site-packages (from pandas) (2.8.0)
Requirement already satisfied: pytz>=2017.2 in /usr/lib/python3.7/site-packages (from pandas) (2019.2)
Requirement already satisfied: numpy>=1.13.3 in /usr/lib/python3.7/site-packages (from pandas) (1.16.2)
Requirement already satisfied: six>=1.5 in /usr/lib/python3.7/site-packages (from python-dateutil>=2.6.1->pandas) (1.12.0)
Building wheels for collected packages: pandas
  Building wheel for pandas (setup.py): started
  Building wheel for pandas (setup.py): finished with status 'error'
  Running setup.py clean for pandas
Failed to build pandas
Installing collected packages: pandas
  Running setup.py install for pandas: started

If anyone can suggest what I should do to get around this error, it would be greatly appreciated.


text:
Q: NO iOS 14.6 Simulator Found Anywhere I developed an app for a client in React Native. I fixed it for all the versions Apple said it didn't work on, except 14.6.
Apple is saying the app doesn't work on 14.6. However, I can't find the 14.6 Simulator anywhere!
I've also tried downloading Xcode 13 beta, but the Simulator versions skip 14.6 (it goes 14.5 and then 15.0). I've also tried it on the latest 12.5 version (12.5.1). Here's an image:

Please help.

A: @Adrian Bartyczak Except for the new contact information after AirTag is lost, iOS14.6 does not bring other new features. Obviously, this time iOS14.6 is for iOS14.5.1 users. You are sure that you can't complete the test on the 14.5 system.
i wish i can help you


text:
Q: Is there a method to create a sublist from the following list_A with the output as follows in python How to create a sublist from the list as [(INDEX, NUMBER), (INDEX, NUMBER)...]
FOR EXAMPLE
list_A = [0,1,2,3,4,5]
output = [(0,1),(1,2),(3,4),(4,5),(5)]

A: list_A = [0, 1, 2, 3, 4, 5]
output = [list_A[i:i + 2] for i in range(0, len(list_A), 2)]

You can do also using lambda function
import itertools
def grouper(n, it):
    it = iter(it)
    return iter(lambda: list(itertools.islice(it, n)), [])
list(grouper(2, list_A))

A: It's very much doable using list itself:
#Original list:
li = [1,2,3,4,5,6,7,8,9]

#How many values would we need to make combination of:
num = 2

li2 = [li[a:a+num] for a in range(len(li))]
print(li2)

Output:
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9]]

If you want to make list of list using 3 values, just change num to 3 and so on. I am pretty sure there will definitely be a numpy function or some other pythonic way to do that same though.


text:
Q: Turtles Get Stuck on Patch if asked to Face Patch How can I get turtles to directly walk towards a patch? In other components of the model, I direct them toward a specific scent, but I already have them walking towards the food scent in the look-for-food procedure, which is run before changing breed and returning to the nest. Right now, they reach the nest but then wander, and I want them to return directly to the food. I tried repeating the procedure, but that did not direct the leader breed towards the food at all; in fact, all turtles stopped performing the procedure. When I use face, as below, they simply get stuck at the food patch, and never return to the nest at all.
ask leaders
  [look-for-food
     fd 1
    return-to-nest
    recruit]
end

to recruit
ask leaders
  [facexy -41 -21
  fd 5]
end

A: First, the end is inside the code block. This can't be the code you are using, it would fail the syntax checker and wouldn't run at all. So you should probably update the code to show what you are actually running.
Regardless, you appear to have a misconception about how NetLogo 'thinks'. Each tick or timestep, the leaders do everything inside the code block. Assume there is one leader, it looks for food, then moves forward, then returns to nest to looks for food again, then asks all leaders (in this case itself only) to face a particular patch and then move forward 5 distance units. Instead, the code should be broken up and should contain what the leaders do within one timestep. For example, if they have not yet found food, then you probably want them to look for food and move towards the food. If they have found food, then you may have them returning to the nest.
Have a look at the Ants model in the NetLogo model library. I suggest you work through that model (and probably some of the tutorials listed in the Resources page on the NetLogo site) to fully understand how the model works.


text:
Q: Change background colour in web using java I'm not sure if the title is correct as I'm not familiar with all the naming technologies. :)
Anyway, I would like to ask if it is possible to change a background colour of a field from a webpage using java.  Based from what I'm working on:
name.xhtml
<p:inputText id="name"
    value="FirstName"
    maxlength="20" />
</p:inputText>

<p:commandButton id="changeColour" value="changeColour"
    actionListener="#{user.change}"
    update="name" >
</p:commandButton>

user.java
public final void change() {
    Some code here to change background colour???
}

Is this even possible? thank you..


text:
Q: Graphics.py Bouncing Cube I am trying to create a program that "bounces" a cube in a window up and down.  Everything is created properly but the cube will not bounce.
The code is as follows:
from graphics import *
import time # Used for slowing animation if needed
i=0

def create_win():
    win= GraphWin("Animation",500,500)
    cornerB1= Point(235,235)
    cornerB2= Point(265,265)
    Bob= Rectangle(cornerB1, cornerB2)
    Bob.setFill('blue')
    Bob.draw(win)
    win.getMouse()
    win.close()
create_win()

def main():
    cornerB1= Point(235,235)
    cornerB2= Point(265,265)
    Bob= Rectangle(cornerB1, cornerB2)
    center= Rectangle.getCenter(Bob)
    center_point= Point.getX(center)
    for i in range(500):
        Bob.move(0,5)
        if center_point<15:
            dy= -dy
        elif center_point>485:
            dy= -dy

main()

Any input would be greatly appreciated.

A: This seems to be too much code with too little planning.  Specific issues: you create Bob twice, once in each function -- the blue Bob you see isn't the Bob you're moving; too many numbers -- figure out your base dimensions and calculate everything else from them; you extract the center outside the loop so it never changes -- do it inside the loop so it's changing as Bob moves.
Below is a rework of your code that bounces Bob up and down as intended:
from graphics import *

WIDTH, HEIGHT = 500, 500

BOB_SIZE = 30
BOB_DISTANCE = 5

def main():
    win = GraphWin("Animation", WIDTH, HEIGHT)

    # Create Bob in the middle of the window
    cornerB1 = Point(WIDTH/2 + BOB_SIZE/2, HEIGHT/2 + BOB_SIZE/2)
    cornerB2 = Point(WIDTH/2 - BOB_SIZE/2, HEIGHT/2 - BOB_SIZE/2)

    Bob = Rectangle(cornerB1, cornerB2)
    Bob.setFill('blue')
    Bob.draw(win)

    dy = BOB_DISTANCE

    for _ in range(500):
        Bob.move(0, dy)

        center = Rectangle.getCenter(Bob)
        centerY = Point.getY(center)

        # If too close to edge, reverse direction
        if centerY < BOB_SIZE/2 or centerY > HEIGHT - BOB_SIZE/2:
            dy = -dy

    win.close()

main()


text:
Q: How to find the average value in list without considering dominant factors in python? im trying to find the average value in a list. but sometimes my list contains large numbers that could affect calculating the average number.
list = [215,255,210,205,450,315,235,250,450,250,250,250,210,450,210]

it would make sense that the average would range from 210 to 250, but number such as 450 and 315 could increase the average value. how do automatically remove dominant factors like the number 450 and easily find the correct average number?

A: The dominant factors you are talking about are called 'outliers' in data that are abnormal values(very high or very low) when compared with the rest of the dataset. You can use the concept of zscore to remove these outliers from your data
  from scipy.stats import zscore
  list1 = [215,255,210,205,450,315,235,250,450,250,250,250,210,450,210]
  score=zscore(list1)
  threshold=1 #should be 3 generally
  list1 = [value for index,value in enumerate(list1) if abs(score[index])<=threshold ]

You can change the threshold according to your wish & see the list1 you are getting finally to decide for the threshold(do try for a number of values ranging from 0-3).For more on zscore: outlier detection


text:
Q: Ajax call to webapi doesn't happen I'm following the this kudvenkat tutorial
I created the WebApi project and has the Get method.
public HttpResponseMessage Get()
{
   List<Student> students;
   List<StudentVM> studentsvm = new List<StudentVM>();
   using (SchoolEntities sc = new SchoolEntities())
   {
   students= sc.Students.ToList<Student>();
   }
        foreach (Student s in students)
        {
          StudentVM svm = new StudentVM { Sid = s.Id, Sname = s.Name };
          studentsvm.Add(svm);
        }
return Request.CreateResponse(HttpStatusCode.OK, studentsvm);
}

With URL request http://localhost:3735/api/values I get the data. I even have set a break point here. Hence when the above URL is refreshed, the break point hits.
Within the same project, I have created a html page and has the following code.

<button id="showemp" name="showbtn"> Show Employees</button>
<button id="clear" name="clearbtn">Clear</button>

But I get neither any error nor any response. I had gone through many stack overflow questions related to WebApi and Ajax calling. Most of the questions haven't been resolved and the some which are resolved have small mistakes which I have verified on my part.
Currently I'm using VS2012 with jquery 1.7.1
It's really appreciating if someone could point me out to what I'm missing.

A: Did you enable CorsAttribute? If not add it either globally or on the Get method
    [EnableCors(origins:"*",headers:"*",methods:"*")]
    public HttpResponseMessage Get()
    {
        //method body
    }


text:
Q: How does abstraction work practically? If a developer can navigate the code and see everything, then how does 'hiding' work in the real world? I get confused when I read 'you are hiding concrete classes by using an interface'. Since when the app is used by another guy, he can see the entire code (unless I expose web services only...that is a different aspect, not to mix here)?
I agree that interfaces and abstract classes help to nicely design code, but from what I understand , that's it. I can't understand how practically in real world we are hiding stuff from others or adding more security etc.

A: You have a misconception that the reason for "hiding" something is security. That is not at all what "hiding" means in this context. An interface "hides" the implementation details of a class in the same way a car's engine is "hidden" under the hood. Of course this doesn't stop you from looking at the engine if you want to see the car's internal workings, but the important points are that

*

*You don't have to look at the engine or understand it in order to use the car, and

*A car manufacturer doesn't have to make the engine work a particular way in order for the car to work as expected.

Likewise, by hiding the internal workings of a class, users of the class only need to understand how the class is meant to be used (i.e. its interface), and the developers of the class are free to change internal details of the class without annoying the users or breaking their code.


text:
Q: Storing regular expressions within a variable (std::string) I am trying to store a regular expression within a variable, i.e if we had a regular expression, \\d and a string, std::string str; then I would store the regular expression \\d within std::string str. From that I could then use str whenever I wanted to use that regular expression.
I tried something like this:
Boost::regex const string_matcher("\\d");
std::string str = string_matcher;

However I realized that it would not work. Does anyone have any ides of how I can store a regular expression?

A: std::string regex = "\\d";
boost::regex expression(regex);
bool ok = boost::regex_match(testStr, expression);

A: You already have your regular expression stored in a variable. You called it string_matcher.


text:
Q: coc.vim failing with :checkhealth command I'm trying to setup coc for nvim on my Windows os. I installed coc via vim-plug and have the coc.nvim config sourced in my main init.vim file. I recieve these messages when I open neovim and run :checkhealth
coc: health#coc#check                                                                                3 ========================================================================                                              4   - OK: nvim version satisfied                                                                                5   - ERROR: Unable to detect version of node, make sure your node executable is http://nodejs.org/                     6   - ERROR: Javascript entry not found, please compile coc.nvim by esbuild.                                            7   - ERROR: service could not be initialized                                                                           8     - ADVICE:                                                                                9       - Use command ":messages" to get error messages.                                                               10       - Open a issue at https://github.com/neoclide/coc.nvim/issues for feedback.                                    11
I have tried reinstalling node, going to coc.nvim directory and using npm install as well as yarn install (as directed to when I ran :messages after getting errors with :checkhealth). However when I ran yarn build (also directed to when I ran :messages) it said build was not a command of yarn. I've searched through other questions and github issues which have been solved by doing the above but none of it has worked here.


text:
Q: Building a time slider, not sure where to start So I want to create a time display similar to the image below.
I would like to create it dynamically without having to use an image, but I am falling short on the best way to do it.
Basically I want 100 points that will be resposive inside a div, so point 1 will start at 0% and point 100 will end at 100%.
I can figure out how to get the points at each multiple of 5 to vary in height.
For now I am just seeking a little guidance on where to start looking. I thought of using an SVG but I am not too well versed in it and I would like some input before spending hours trying to hammer in that solution.
In the next step I will need to change the color of a specefic point based on a slider below it (so if the slider is dragged to 70% width I need to target node 70 and chage its color)
Any help would be greatly appreciated.

A: You could checkout the jQuery UI slider (https://jqueryui.com/slider/#steps) to get you started. Likely you want to use the example that snaps to increments, then from there you can add css styles to make the slider look how you want it.
  <script>
  $( function() {
    $( "#slider" ).slider({
      value:100,
      min: 1,
      max: 100,
      step: 5,
      slide: function( event, ui ) {
        $( "#amount" ).val( "$" + ui.value );
      }
    });
    $( "#amount" ).val( "$" + $( "#slider" ).slider( "value" ) );
  } );
  </script>


text:
Q: Resolving "undefined reference" on pure virtual destructor of base class I am learning Object Oriented programming.  Here is a simple code snippet that I have written:
class Food {
protected:
    int id;
    FoodTypes type;
    string name;

public:
    Food(int id, FoodTypes type, string name) {
        this->id=id;
        this->type=type;
        this->name=name;
    }
    virtual ~Food() = 0;
};

class Dish: public Food {
protected:
    double cost;

public:
    Dish(int id, FoodTypes type, string name, double cost) : Food(id, type, name) {
        this->cost=cost;
    }
    void display() {
        cout<<id<<" "<<type<<" "<<name<<" "<<cost<<"\n";
    }
    ~Dish() {}
};

I get the error:

/tmp/ccW3e3PZ.o: In function 'Dish::~Dish()':
main.cpp:(.text._ZN4DishD2Ev[_ZN4DishD5Ev]+0x25): undefined reference to 'Food::~Food()'

Based on the solution mentioned here, I need to define the destructor of my base class (~Food), but IMO I cannot do that since I need it to be a pure virtual function (as suggested here).  If not for the destructor, there's no other function within the base class that can be delegated to be pure virtual (and the base class would no longer be abstract/interface).
So how do I resolve the error?  Thanks!


text:
Q: Increase RRD step We have situation with Zennos that collecting cycle was 30s and we have a lots of data already collected. Now we need to increase collection period to 300s.
Problem is that zenoss stop rendering graphs it you do it just like that. So we need to increase step to 300s in  RRD.
It there any option to do that and preserve old data and append it with new data?
I've already checked rrdtool options and don't see any option to do that.
Thanks
Dubravko

A: You'll have to dump the data from rrd into an XML file using rrdtool dump command. Then create a new rrd with the new step parameters and import the XML using rrdtool restore command.
It's not quite as easy as a "resize" command would be, but it keeps rrdtool lean and mean.
The downsize is you'll lose the 30s resolution from earlier collections.
Another option would be, if you really wanted to keep the 30s information, is to change the heartbeat (but keep the step size at 30s) when you create your new database (you'll still have to export, recreate, and import).
Hope this gives you enough direction. If not, let us know.
-r

A: file=sample.rrd
rrdtool dump $file | sed -e 's|<step>30</step>|<step>300</step>|g' | rrdtool restore /dev/stdin -f $file


text:
Q: Como especificar uma propriedade CSS em um único elemento para uma classe que se repete? Tenho um site Wordpress. No tema, preciso personalizar o height de uma única div da classe image_wrapper, porém quando faço a alteração, isso reflete nas outras divs da mesma classe espalhadas pelo tema.
Como posso definir o height nesse caso, sem que as demais divs sofram a alteração?
A div que preciso personalizar está contida nesta outra:

div.image_wrapper {
  height: 192px; }

Quando uso o CSS acima, outras divs de mesma classe são alteradas, como a seguinte:

Como é possível resolver? Não consegui usar a especificidade nesse caso.

A: Se você tem acesso ao código dessa div, pode adicionar uma outra classe própria para ela. Neste caso, só ela será alterada mantendo o estilo que já foi definido em .image_wrapper:
div.image_wrapper.outraclasse {
  height: 192px;
}

Exemplo:

div.image_wrapper.outraclasse {
  height: 192px;
}

.image_wrapper{
   display: block; width: 400px; height: 20px; background: red; margin: 5px 0
}

   Esta div é igual as outras

   Esta div é igual as outras mas tem uma alteração na altura

   Esta div é igual as outras


text:
Q: incomplete / partial Images are downloaded using node js I am downloading images from a site using node js in a standard way.
var download = function (uri, filename, callback) {
    request.head(uri, function (err, res, body) {
        console.log('content-type:', res.headers['content-type']);
        console.log('content-length:', res.headers['content-length']);

        request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
    });
};

But when I run this code in for loop, the images saved are corrupt. More to say, all the pixels are not downloaded. Only partial image is saved.
Is there a way to fix this issue?

A: Well, I found the solution to the problem. The reason was that before the image is completely written onto the disk, another thread starts and so on.
To fix this, I implemented the promises using Q-IO library.
var Apps = require("q-io/http");
var qfs = require("q-io/fs");

var download = function(uri, filename, callback){
Apps.read(uri).then(function(data){
    callback(data);
}, function(err){
    console.log('err: ' + err);
});
};

download('https://www.google.com/images/srpr/logo3w.png', 'test.jpg', function(data){
    console.log('done');
    qfs.write("test.jpg", data);
});

But instead of using for loop, I used self invoking function.


text:
Q: Algorithm problems, android java I've a problem but i really don't understand why. The problem is when i want to add an element in my ArrayList.
Here is my code :
    ArrayList<Integer> lesCasesCoches = new ArrayList<Integer>();
    lesCasesCoches.clear();
    Log.w("Test", "je beug pas" + idCasier);
    for (int f = 0; f < laCave.requeteIdCasier.size(); f++) {
        if (laCave.requeteIdCasier.get(f) == idCasier) {
            Log.w("Test", "size" + f);
            Log.w("Test", "id casier" + laCave.requeteIdCasier.get(f));
            Log.w("Test", "id case" + laCave.requeteIdCase.get(f));
            int casesAdd = laCave.requeteIdCase.get(f);
            Log.w("Test", "que vaut add" + casesAdd);
            lesCasesCoches.add(casesAdd);
            Log.w("test", "Cases cochés" + lesCasesCoches.get(f));
        }
    }

Here is my error log:
test: je beug pas2
test: size2
test: id casier2
test: id case5
test: que vaut add5

==> here the bug message
delvikvm: threadid=1: thread exiting with uncaught exception ( group=0x415072a0)
java.lang.indexOutOfBoundsException: Invalid index 2, size is 1

Sorry for my bad english.
Thank you very much for the time you spend for me

A: Change
Log.w("test","Cases cochés"+lesCasesCoches.get(f));

to
Log.w("test","Cases cochés"+lesCasesCoches.get(lesCasesCoches.size()-1));

A: I think this make exception error.
Log.w("test","Cases cochés"+lesCasesCoches.get(f));

change this.
Log.w("test","Cases cochés"+casesAdd);

A: Few things here:
1) why do you need to clear an Array you just created?
2) you access laCave.requeteIdCase and laCave.requeteIdCasier at the position f but f is only bound to laCave.requeteIdCasier.size(). That probably is crashing because requeteIdCase has lesser elements than requeteIdCasier (whatever those terms mean :) )

A: It probably happens because of this statement if (laCave.requeteIdCasier.get(f) == idCasier)
because if it's not true then for loop will go forward and increase f hence it won't match with
        lesCasesCoches.add(casesAdd);
        Log.w("test","Cases cochés"+lesCasesCoches.get(f));

so instead of getting f'th item you should get the last one
Log.w("test","Cases cochés"+lesCasesCoches.get(lesCasesCoches.size()-1));

A: The error is actually caused by logging:
Log.w("test", "Cases cochés" + lesCasesCoches.get(f));

Explanation:
test: je beug pas2
test: size2
test: id casier2
test: id case5
test: que vaut add5
java.lang.indexOutOfBoundsException: Invalid index 2, size is 1

From the debug log, you add the first Integer 5 from casesAdd into lesCasesCoches when f is 2. Since this is the first time you add the number, the size() of lesCasesCoches is 1. Then, when you call the problematic line, you're trying to access the third (from 0-based index) element of lesCasesCoches, resulting in IndexOutOfBoundsException.
The solution is to either remove the line if it's not really needed, or to use lesCasesCoches.get(lesCasesCoches.size() - 1) to get the last added Integer from lesCasesCoches.


text:
Q: Random binary matrix with two non-trivial constraints I need to generate a random matrix of K columns and N rows containing ones and zeroes, such that:
a) Each row contains exactly k ones.
b) Each row is different from the other (combinatorics imposes that if N > nchoosek(K, k) there will be nchoosek(K,k) rows).
Assume I want N = 10000 (out of all the possible nchoosek(K, k) = 27405 combinations), different 1×K vectors (with K = 30) containing k (with k = 4) ones and K - k zeroes.
This code:
clear all; close
N=10000; K=30; k=4;
M=randi([0 1],N,K);
plot(sum(M,2)) % condition a) not satisfied

does not satisfy neither a) nor b).
This code:
clear all; close;
N=10000;
NN=N;  K=30; k=4;
tempM=zeros(NN,K);
for ii=1:NN
ttmodel=tempM(ii,:);
ttmodel(randsample(K,k,false))=1;  %satisfies condition a)
tempM(ii,:)=ttmodel;
end
Check=bi2de(tempM);                    %from binary to decimal
[tresh1,ind,tresh2] = unique(Check);%drop the vectors that appear more than once in the   matrix
M=tempM(ind,:);                             %and satisfies condition b)
plot(sum(M,2))                                  %verify that condition a) is satisfied
%Effective draws, Wanted draws, Number of possible combinations to draw from
[sum(sum(M,2)==k) N nchoosek(K,k) ]

satisfies condition a) and partially condition b). I say partially because unless NN>>N the final matrix will contain less than N rows each different from each other.
Is there a better and faster way (that possible avoids the for cycle and the need of having NN>>N) to solve the problem?

A: First, generate N unique k-long permutations of the positions of ones:
cols = randperm(K, N);
cols = cols(:, 1:k);

Then generate the matching row indices:
rows = meshgrid(1:N, 1:k)';

and finally create the sparse matrix with:
A = sparse(rows, cols, 1, N, K);

To obtain the full form of the matrix, use full(A).
Example
K = 10;
k = 4;
N = 5;

cols = randperm(K, N);
cols = cols(:, 1:k);
rows = meshgrid(1:N, 1:k)';
A = sparse(rows, cols , 1, N, K);
full(A)

The result I got is:
ans =
    1   1   0   0   0   0   0   1   0   1
    0   0   1   1   0   1   0   0   0   1
    0   0   0   1   1   0   1   0   1   0
    0   1   0   0   0   0   1   0   1   1
    1   1   1   0   0   1   0   0   0   0

This computation should be pretty fast even for large values of K and N. For K = 30, k = 4, N = 10000 the result was obtained in less than 0.01 seconds.

A: You could use randperm(n) to generate random sequences of integers from 1 to n, and store the nonrepeated sequences as rows in a matrix M until size(unique(M,'rows'),1)==size(M,1). Then you could use M to index a logical matrix with the appropriate number of true values in each row.

A: If you have enough memory for nchoosek(K,k) integers, build an array of those, use a partial Fisher-Yates shuffle to get a proper uniformly random subset of N of those. Now, given the array of N integers, interpret each as the rank of the combination representing each row of your final array.  If you use colexicographical ordering of combinations, computing the combination from a rank is pretty simple (though it uses lots of binomial combination functions, so it pays to have a fast one).
I'm not a Matlab guy, but I've done things similar to this in C. This code, for example:
for (i = k; i >= 1; --i) {
    while ((b = binomial(n, i)) > r) --n;
    buf[i-1] = n;
    r -= b;
}

will fill the array buf[] with indices from 0 to n-1 for the rth combination of k out of n elements in colex order. You would interpret these as the positions of the 1s in your row.


text: Q: Member names cannot be the same as their enclosing type (auto-generated) I'm importing and consuming a SOAP service in my C# web application through Visual Studio. The error I'm getting is "[class name] Member names cannot be the same as their enclosing type". Here's the catch: this is happening in the code auto-generated by VS using the WSDL. I've read similar issues and I know it's a matter of just changing the class names to eliminate the conflict. In this case, it's a WSDL. So before I go rewriting several hundreds of lines of code, will the service still work if I rename the conflicting classes?


text:
Q: Best Database structure for storing RSS feeds I've been searching around trying to find an answer both here and google, although I've found some pointers I haven't quite found a solution.
If you have a simple RSS reader with a database, you might have a couple of tables for storing feeds (ignoring dealing with subscribers here):

*

*Feeds (feed-id, feed-title,
feed-url)

*Items (item-id, feed-id,
item-title, item-content)

This works in most cases but for many websites/web based applications you might have a main feed from the frontpage and then category feeds, if you take both into the above sort of system there's going to be a lot of replicated data due to the same post appearing in several rss feeds.
The two choices I've come up with are either ignore it and accept the duplicates or use a link table between the feeds and the items. But this also seems like quite a waste when probably 80% of the sort of feeds I'm looking to pull won't have multiple feeds which could create this replication.
Is there a better way of doing this/am I looking at this in completely the wrong way?
Update
Thanks to both for the answers, so the consensus seems to be that the saving on space is probably not significant enough to worry about and would be negated by the potential for unknown issues (such as mentioned by dbr).
Adding a link table or similar would probably increase the processing time as well so overall not worth worrying about too much. I had thoughts after reading the responses of linking content and removing duplicates only when the post is no longer in either RSS feed to save on space but again as Assaf has said, the space savings could make this a waste of time.

A: I would suggest you don't try to optimize away every possible copy of feed data at this stage of development (design, I presume). Concentrate on getting it working and when you're done, if you do some profiling and find that you can indeed save X% of storage if you use links or shared data between feeds, only then and if X is large enough to pay for the time it would take to optimize your DB would I suggest you implement any such more advanced schemes.

A: As Assaf said, I wouldn't worry about storing duplicated articles if they come from different feeds, for now at least. The complication it would add doesn't benefit the few kilobytes of space you'd save..
I suppose if you take a sha1 hash of the content, do SELECT id FROM articles WHERE hash = $hash and if something exists, simply have a "article_content_id" which if set points the articles content at another row... but, what if you have two articles:
id: 1
title: My First Post!
feed: Bobs site
content: Hi!
hash: abc
link: no
content_link_id:

id:2
title: My First Post!
feed: Planet Randompeople Aggregator
content:
hash: abc
content_link_id: 1

..this works fine, and you've saved 3 bytes by not duplicating the article (obviously more if the article was longer)
..but what happens when Bob decides to add adverts to his RSS feed, changing the content from Hi! to Hi!

 - but Planet Randompeople strips out all images. Then to update a feed item, you have to check each row that content_link_id-links against the article you are updating, check if the new item has the same hash as the articles that link against it - if it is different, you have to break the link and copy the old data to the linking-item, then copy the new content to the original item..
There's possibly neater ways to do that, but my point is that it can get very complicated, and you will probably only save a few kilobytes (assuming the database engine doesn't do any compression itself) on a very limited subset of posts..
Other than that, having a table of feeds and items seems sensible, and is how most other RSS-storing databases I've seen dealt with it..


text:
Q: Inner button with `position: absolute` will be placed outside a table Html:

        <button class="del">delete</button>

<button class="del">delete</button>

Css:
.container {
    position: relative;
    border: 1px solid red;
    height: 50px;
    width: 200px;
}

.del {
    position: absolute;
    top: 3px;
    right: 3px;
}

Why the button inside a div will be placed on the top right corner of the div, but the one inside a td will be placed outside the table?
How to fix it?
See active demo: http://jsfiddle.net/Freewind/d6Tug/

A: I think it has something to do with the display style of a td, which is table-cell. If you set it to display:block, it will work correctly.
Just add display:block to your .container style.
As freewind pointed out, it would be better to use inline-block if it is supported in your browser for td since td's are usually displayed in a row.

A: Giving an element position:absolute; places it relative to its containing block. Since a table cell is not considered a block container (unlike a div), it places it relative to the document body itself. top:3px; brings it 3px from the top border of the document and right:3px; moves it 3px from the right border.
http://reference.sitepoint.com/css/position


text:
Q: Is Spacy nlp(text) thread safe? Is the following thread safe in spacy?
nlp = spacy.load('en')
nlp(text)

A: Yes. See this thread (no pun intended...) for more information: https://github.com/explosion/spaCy/issues/172
If possible, instead of multi-threading the call to nlp, consider calling nlp.pipe which is a multithreaded call to the spaCy pipeline.
for doc in nlp.pipe(texts, n_threads=16, batch_size=10000):
    analyse_text(doc)

More info here: https://explosion.ai/blog/multithreading-with-cython


text:
Q: Transform differential equation $u'' +f(u) = 0$ into system of first order For $f \in C^1(\mathbb{R})$ let the following differential equation be given: $u'' +f(u) = 0$.
How can one transform this equation into a system of first order and give a non-constant first integral of this system?
I know that $f(u)= \omega^2 \sin(u)$ describes the mathematical pendulum and that we probably need this to transform the equation, but I'm not sure how!
I found a page which described the nonlinear pendulum, but it describes it by using a second order differential equation:

A: Let $v=u'$, so that $u'' + f(u) = 0$ becomes equivalent to the system $$\begin{cases}u' = v \\  v' = -f(u) \end{cases}$$This is a Hamiltonian system. Namely, if one thinks of $u$ as position and $v$ as momentum, then we have that $$\begin{cases} u' = \dfrac{\partial H}{\partial v} \\[1em] v' = -\dfrac{\partial H}{\partial u},\end{cases}$$where $H(u,v) = F(u) + v^2/2$, and $$F(u)= \int_{u_0}^u f(s)\,{\rm d}s$$By conservation of energy, if $t \mapsto (u(t),v(t))$ is a solution to the system, then $t \mapsto H(u(t),v(t))$ is a constant. Thus, if $t \mapsto u(t)$ is a solution to $u''+f(u)=0$, we have that $$\int_{u_0}^{u(t)} f(s)\,{\rm d}s + \frac{u'(t)^2}{2} = c$$for some constant $c \in \Bbb R$, for all $t$ in the domain of the solution.

A: $$\frac{d^2u}{dx^2}+f(u)=0$$ Switch variables and the equation becomes
$$\frac{\frac{d^2x}{du^2}}{\left(\frac{dx}{du}\right)^3 }=f(u)$$ Reduction of order $p=\frac{dx}{du}$ gives
$$\frac {p'}{p^3}=f(u)\implies -\frac 1{2p^2}=\int f(u)\,du+c_1$$
$$p=\frac{dx}{du}=\pm\frac 1{\sqrt{c_1+2\int f(u)\,du }}$$

A: A common rule of thumb is that if you have $m$ $n$th order systems, then it is the same as $m\times n$ $1$st order systems. If we start with:
$$u''+f(u)=0$$ we can make the substitutions:
$$z_1=u$$
$$z_2=u'$$
and we then get that:
$$z_1'=u'=z_2$$
$$z_2'=u''=-f(u)=-f(z_1)$$
which leaves us with the system:
$$\begin{cases}z_1'=z_2\\z_2'=-f(z_1)\end{cases}$$


text:
Q: Why does test asserts into a subscription pass without being in the async zone? When running tests in Angular2+ using Karma and Jasmine, and subscripting to observables, that subscription (as I understand) is run asynchronously, so the test should be wrapped into an async or fakeAsync.
But we don't use async not fakeAsync, the tests passes, so my question is: isn't the code into the subscribe used to be asynchronous? Why is the test passing? What is going on?
hello.component.ts
import { Component, Input, OnInit } from '@angular/core';
import {of} from 'rxjs';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit  {
  name: string;

  ngOnInit() {
    // Subscribing to sayName() to get a name
    this.sayName().subscribe(name => this.name = name);
  }

  sayName() {
    return of('Foo');
  }
}

hello.component.spec.ts
import { CommonModule } from '@angular/common';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import {HelloComponent} from './hello.component';

describe('HelloComponent', () => {
  let fixture: ComponentFixture<HelloComponent>;
  let component: HelloComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule
      ],
      declarations: [HelloComponent],
      providers: [
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should have foo name', () => {
    // Running out of async/fakeAsync
    // and asserting we got the name
    expect(component.name).toEqual('Foo');
  });
});

You can also check in Stackblitz this example.

A: subscribe() is a synchronous call. In your case during this call a subscription is created, values are emitted and the observer is called. Again: All of that happens while subscribe is being executed!
When you create an Observable with e.g. interval() the values will be emitted asynchronously. Everything before that still happens synchronously.
When you use the subscribeOn() operator then even the subscription would be created asynchronously.
Contrary to promises reactive streams are not asynchronous by default. And as explained before different parts of the whole process can be independently made asynchronous.
If you want to dive deeper into that topic I shamelessly recommend my article Concurrency and Asynchronous Behavior with RxJS. It's short ;)


text:
Q: Rails Lameness Filter? I've done some searching, and I haven't been able to find any kind of open-source lameness filter for rails.  Does anything like that exist?  I'm trying to curtail lame user generated content, in particular, all caps, improper capitalization, excessive exclamation marks, and excessive bold or italics.

A: Here is a ruby Bayesian Classifier which can be trained to block certain types of content.  It would take some creativity to apply directly to your problem.
Its a commercial service, but SocialMod is worth a mention.

A: I don't know of any existing ones, but it should be too hard to catch most of these with a set of regular expressions in a custom validation.  Improper capitalization is a hard one to catch because of proper names and acronyms.
before_validation :filter_lameness

def filter_lameness
  # reduce exclamation marks
    content.gsub!(/![!1]+/, "!")
  # Proper capitalization.
    content.gsub!(/(\.\s*[a-z])/, $1.upcase) # capital starts sentence
    content.gsub!(/([A-Z]{5,})/, $1.capitalize) # lowercases all but first letter in a string of capitals. Minimum length 5.
  # etc...
    return true # needed in case the last gsub matches nothing, otherwise validation returns nil and will fail
end

Personally I'd be tempted to keep track of users' infractions to the style guide and pin them with demerit badges after enough offenses, for public humliation.


text:
Q: Pass multiple elements to an each function function generalShowPopup(click_element, show_elements) {
  click_element.on("click", function(event) {
    show_elements.each(function() {
      $(this).show();
    });
    event.preventDefault();
  });
}

With the above function I intend to show an element when a certain link is clicked.
Calling the function like this (one second argument) works fine:
generalShowPopup($(".popup_link"), $(".popup") );

But how could I pass two elements to the second argument, i.e show two elements when a certain link is clicked?

A: Just use a comma, ,, inside the selector string, and there really is no reason to use .each():
generalShowPopup($(".popup_link"), $(".popup,.selecctor2, #selector3") );

No need to use each:
function generalShowPopup(click_element, show_elements) {
    click_element.on("click", function(event) {
        event.preventDefault();
        show_elements.show();
    });
}

A quicker way to write all this is:
$(function() {
    $(".popup_link").on('click', function(event) {
        event.preventDefault();
        $(".popup,.selecctor2, #selector3").show();
    });
});

A: $(".popup") is a jQuery Collection,
Just use .add() method:
generalShowPopup($(".popup_link"), $(".popup").add(".another") );


text:
Q: Optimize Javascript function for memory leaks Due to some reasons i am optimizing javascript functions and at this time i am investigating which i can optimize following code or not.
I have following array:
var usageArray = [5,10,20,10,15,18,19,20,21,24,23,28,29,27,10,10];

I want to push value to end of this array without changing on count of nodes and create array with following structure:
[[0, 5], [1, 10], [2, 20], [3, 10], [4, 15], [5, 18], [6, 19], [7, 20], [8, 21], [9, 24], [10, 23], [11, 29], [12, 27], [13, 10], [14, 10]]

I will pass new value each 10 second with following function:
function tUsage(value) {
    usageArray = usageArray.slice(1);
    usageArray.push(value);
    var i = [];
    for (var s = 0; s < usageArray.length; ++s) {
        i.push([s, usageArray [s]]);
    }
    console.log([i]);
    //Free Memory
    i = null;
    s = null;
}

Is there any way which i write this function in the better way, because fire this function each 10 seconds and want to remove its memory leaks.

A: As per the discussion above, your entire function can be reduced to a single Array.prototype.map call:

var usageArray = [5,10,20,10,15,18,19,20,21,24,23,28,29,27,10,10];

var newArray = usageArray.map(function (value, index) { return [index, value]; });
console.log(newArray);


text:
Q: cf_ct_date_input and leap year anyone using the cf_ct_date_input tag? If so are you having trouble with the leap year this year. Our calendar only goes through the 28th and I'm not sure how to get it to go through the 29th. Any help would be appreciated.

A: I'd say its buggy and doesn't cater for the proper leap year calculation.
Thus you are probably going to need to modify it yourself or find the developer.
This isn't one of those strange years, its a clear case of being divisible by 4
A year will be a leap year if it is divisible by 4 but not by 100. If a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400.


text:
Q: Выравнивание текста файла по центру Дан файл в котором текст выровнен по правому краю. Нужно выровнять по центру, с длиной строки 50 символов (в общем, не важно).
Использовал такую конструкцию:
filename = input("Введите имя файла: ")
with open(filename, 'r') as file:
    lines = file.readlines()
    for line_num in range(len(lines)):
        lines[line_num] = '{:^50}'.format(lines[line_num])
with open(filename, 'w') as file:
    file.writelines(lines)

После этого текст начинает плясать в разные стороны.

A: Мешает символ перевода строки. Нужно перед выравниванием его убрать и потом опять добавить:
lines[line_num] = '{:^50}'.format(lines[line_num].strip()) + "\n"

Увидел, что исходный текст был выровнен по правому краю (я-то проверял на обычном тексте без выравнивания). Тогда наверняка еще выравнивающие пробелы все портили. К счастью, для приведенного решения это неважно, потому что strip() удаляет и пробелы в начале строки.

A: На сколько я знаю
def center(string, length):
    l1 = (length - len(string))/2
    return '-'*l1 + string + '-'*l1

Где length - это ваше 50


text:
Q: How to run AngularJS 2 with Codeigniter 3 in Windows OS..? I downloaded AngularJS 2 'Hello World' program from the site and followed the procedures to run the program. I have successfully executed program in AngularJS 2 without Codeigniter 3.
But in Codeigniter 3 environment i don't know how to run 'Hello World' program.
I have the following questions:

*

*Path to run the commands like npm install and npm start in codeigniter 3.

*Where to place the folders and files like app,pakage.json, etc..?

*Is it correct to run the project in codeigniter..? Example: http://localhost:port/angular-2-codeigniter-3-project/controller
Help me to work this in codeigniter 3. And also notify me if i missed some procedures to run the program.

A: Have a look at https://blog.pisyek.com/create-todo-app-with-codeigniter-3-angularjs-part-2/
It is actually a good start to get the intergration working.
In reply to the solution(the answer needed to be expanded): optional is to create a restFul base in codeigniter to deliver the wanted data.
Build the components and elements using (example: angular-cli) and prefill the components with lorem ipsum values. After you have created a full angular application compile it to production and include the scripts to your views. I usually tend to use the template controller by Glenn Stovall because it is robust and dynamic to not overload the pages with unused js files.
I hope this helps you find your solution.


text:
Q: Why the Doppler Ultrasound beam needs to be looking directly down at a pipe So I was doing a question about "Doppler Ultrasound"
It states that a Doppler ultrasound uses soundwaves at a frequency much higher than what humans can hear. They can me used to measure the speed of fluid in underground pipes by reflecting high frequency sound waves (from 2-18 MHz) off moving liquid and analyzing the reflected waves.
The question is

One of the limitations of the Doppler Ultrasound is that the beam needs to be 'looking' as directly down the pipe as possible.
    Explain why:

I was thinking this is due to the Doppler machine which emits waves, which reflect of a liquid down the pipe. If the beam is misaligned, then the emitted waves from the machine could hit the walls of the pipe rather than a straight reflection from the machine to the liquid and back but I am unsure...
I was also thinking the change in frequency observed is dependent on the relative motion between he source and the observer. Therefore, only the component of the velocity directly towards or away from the machine will cause a Doppler shift hence it beam needs to be looking down to observe the doppler effect.


text:
Q: Form not picking up updated field value I am trying to encrypt a form using a PGP Javascript API before sending it.
The PGP part works, but the form does not send the js-modified value of the form's fields.
Here is the Javascript :
<script>
        function encryptForm() {
            var password = document.getElementById("form_password");
            var email = document.getElementById("form_email");

            email.setAttribute("type", "hidden");
            password.setAttribute("maxlength", "2000");
            password.setAttribute("type", "hidden");

            var form = document.forms[index];
            var password = form.elements["password"];
            var email = form.elements["password"];

            encrypt(email.value).then(function(encrypted_msg) {
                    email.value = encrypted_msg;
            });
            encrypt(password.value).then(function(encrypted_msg) {
                    password.value = encrypted_msg;
            });

            form.submit();

            return true;
        }

        function encrypt(msg) {
            if (msg.indexOf("-----BEGIN PGP MESSAGE-----") !== -1 && msg.indexOf("-----END PGP MESSAGE-----") !== -1) {
                return msg;
            } else {
                var key = `<?php printf($eassec->getPubkey('server')); ?>`;
                var publicKey = openpgp.key.readArmored(key).keys[0];
                return openpgp.encryptMessage(publicKey, msg).then(function(pgpMessage) {
                    return pgpMessage;
                });
            }
        }
        </script>

And the form element :
<form onSubmit="return encryptForm()" class="EASboxForm" method="post">
                                <input id="form_email" name="email" type="email" placeholder="email adress" required autofocus>
                                <input id="form_password" name="password" type="password" placeholder="password" maxlength="72" required>
                                <input name="action" type="hidden" value="connect">
                                    <input type="image" class="EASboxFormSend" src="resources/pics/icons/form_continue.svg" alt="Continue">
                            </form>

(You can test it live at [REDACTED] - the PHP part will show an error message if the sent data ain't a valid PGP message, if everything is correct the hashed password and the email will show up)

A: Since encrypt() is an asynchronous function, you have to wait for it to complete before submitting the form. You can use Promise.all() to wait for multiple promises to complete.
Promise.all([encrypt(email.value).then(function(encrypted_msg) {
    email.value = encrypted_msg;
  }),
  encrypt(password.value).then(function(encrypted_msg) {
    password.value = encrypted_msg;
  })
]).then(function() {
  form.submit();
});

You also need to return false from the encryptForm() function, to prevent the normal form submission.

A: What I can see is, function encrypt is an asynchronous function as per your implementation. But the execution flow of the javascript is top to bottom. when the code reaches the submit, the values may not be ready. Hence you may need to slightly change the flow of the program as shown below.
encrypt(email.value).then(function(encrypted_msg) {
  email.value = encrypted_msg;

  encrypt(password.value).then(function(encrypted_msg) {
    password.value = encrypted_msg;

    form.submit();
  });

});


text:
Q: find overlaps/range between two datasets using pandas or enumerate I am trying to do some interval range operations on two files with folowing conditions
check if chrom is equal, then check if my start and end of of co0rdinatefile is within or equal to start and end of gene_annotation file (condition if the strand is "+" the start and end will be for eg 10-20, if its "-" it will be 20-10) , if match print start end strand from coordinate and gene_id, gene_name from geneannotation file. (for representation purpose I have head annoataion file )
number of rows in annotation file ~50000
number of rows in coordinated file  ~200,000
gene_annotationfile
chrom     start       end             gene_id    gene_name strand
17  71223692  71274336  ENSMUSG00000085299      Gm16627      -
17  18186448  18211184  ENSMUSG00000067978  Vmn2r-ps113      +
11  84645863  84684319  ENSMUSG00000020530       Ggnbp2      -
 7  51097639  51106551  ENSMUSG00000074155         Klk5      +
13  31711037  31712238  ENSMUSG00000087276      Gm11378      +

coordinates_file
  chrom start   end strand
  1 4247322 4247912 -
  1 4427449 4432604 +
  1 4763414 4764404 -
  1 4764597 4767606 -
  1 4764597 4766491 -
  1 4766882 4767606 -
  1 4767729 4772649 -
  1 4767729 4768829 -
  1 4767729 4775654 -
  1 4772382 4772649 -
  1 4772814 4774032 -
  1 4772814 4774159 -
  1 4772814 4775654 -
  1 4772814 4774032 +
  1 4774186 4775654 -
  1 4774186 4775654
  1 4774186 4775699 -

desired output
 chrom, start, end,strand, gene_id, gene_name
 1      4427432 4432686 + ENSMUSG0001 abcd

Another problem is in some cases if there is a match it may map to to gene_id in that case i would like to write
 chrom, start, end,strand, gene_id, gene_name
 1      4427432 4432686 + ENSMUSG0001,ENSMUSG0002 abcd,efgh

my code so far:
 import csv

 with open('coordinates.txt', 'r') as source:
      coordinates = list(csv.reader(source, delimiter="\t"))

 with open('/gene_annotations.txt', 'rU') as source:
      #if i do not use 'rU' i get this error Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
      annotations = list(csv.reader(source, delimiter="\t"))

for index,line in enumerate(coordinates):

    for index2, line2 in enumerate(annotations):

        if coordinates[line][0] == annotations[line2][0] and coordinates[line][1] <= annotations[line2][1] and annotations[line2][2] >= coordinates[line][2] :
         print "%s\t%s\t%s\t%s\t%s" % (coordinates[line][0],coordinates[line][1],coordinates[line][2], annotations[line2][3], annotations[line2][4])
         break

error that I get
---> 15         if coordinates[line][0] == annotations[line2][0] and coordinates[line][1] <= annotations[line2][1] and annotations[line2][2] >= coordinates[line][2] :
16              print "%s\t%s\t%s\t%s\t%s" % (coordinates[line][0],coordinates[line][1],coordinates[line][2], annotations[line2][3], annotations[line2][4])
17              break

TypeError: list indices must be integers, not list

will pandas be a good approach for this?

A: I assume coordinates is a list of lists, like [[1,2],[3,4]] .
The line
for index,line in enumerate(coordinates):

iterates over coordinates, returning each line of coordinates as line and the index as index.
if coordinates[line][0] == annotations[line2][0] and coordinates[line][1] <= annotations[line2][1] and annotations[line2][2] >= coordinates[line][2] :

The error message means that you are using a list (line) for the index here. You likely wanted to use index instead of line:
if coordinates[index][0] == annotations[index2][0] and coordinates[index][1] <= annotations[index2][1] and annotations[index2][2] >= coordinates[index][2] :

Even better would be to just use line:
if line[0] == line2[0] and line[1] <= line2[1] and line2[2] >= line[2] :

see https://docs.python.org/2.7/reference/compound_stmts.html?highlight=for_stmt#grammar-token-for_stmt

A: There are tools dedicated this this such as bedtools intersect;
https://bedtools.readthedocs.io/en/latest/content/tools/intersect.html
And Bedops intersect;
https://bedops.readthedocs.io/en/latest/content/reference/set-operations/bedops.html