text:
Q: How to disable rsvp response from a created .ics file I'm working with ICS files sending by email to our customers. I'd like to disable the RSVP response to attendees (our customers). Does someone know how to disable it?

A: As per https://icalendar.org/iCalendar-RFC-5545/3-2-17-rsvp-expectation.html, use
RSVP=FALSE

or omit the RSVP.  The specification says the default is false.


text:
Q: How do I install ServiceStack without Nuget? I have Visual Studio 2008, and I want to try ServiceStack to make a REST web API. The problem is, Nuget generally can't be installed on VS2008. I have a zip with ServiceStack binaries but I am completely lost -- I just do not know where to put them and what else I might need to do. I am brand new to ServiceStack and haven't touched VS in 5+ years. I didn't know about Nuget until I was looking into ServiceStack.
Alternately, does ServiceStack work on a version of Visual Studio Express with which I could use Nuget to install it? I have read that Express doesn't support extensions, so I am guessing no. Let me know if I'm wrong.
Alternately, how do I get Nuget to work on VS2008? I found a webpage talking about it, but its instructions glossed over some key steps that I must not know about. I'm sure it would all make sense if I understood how it all worked, but I don't right now. I am a newbie and need all relevant specifics.
Alternately... well, any other thoughts?

A: Routinely we also publish deployed builds in the ServiceStack project /downloads. Currently the latest version is v3.9.28 which is what's on NuGet.
The /downloads on ServiceStack contains most of the project .dlls, what's not there are specific providers, e.g. OrmLite providers for alternate RDBMS's.
For these the best place to get them is in the NuGet zip packages deployed on NuGet. i.e. to get the OrmLite MySQL provider in OSX/Linux (or using gnu tools for Windows) you can just do:
wget -O ServiceStack.OrmLite.MySql.zip \
  http://packages.nuget.org/api/v1/package/ServiceStack.OrmLite.MySql/3.9.28

unzip ServiceStack.OrmLite.MySql.zip 'lib/*'

which will unzip the dlls in the local lib/ folder.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove the last bar from D3 bar chart? This may be a simple question, but if we have a bar chart which is built using D3.js then how can I remove just the last bar?

A: Something like this can remove the last bar
k = d3.selectAll("rect")[0];
k.pop().remove()

But the best way, would be to remove the last data set from the data array which makes the last bar.


text:
Q: Why the remainders of the division of a number by 2 results in the number in binary? For example 14, if you divide be 2 it equals 7 and the remainder = 0, then 7/2 = 3 with r = 1 then 3/2 = 1 and r = 1 then 1/2 = 0 with r = 1. If we take the r's and put them togheter 1110 is 14 in binary. I don't understand the intuition behind this, why does this work?

A: We can write any natural number $n$ as a sum of powers of $2$:
$$n = b_k 2^k + b_{k-1} 2^{k-1} + \cdots + b_{0} 2^0$$
where each $b_i, 0 \leq i \leq k$ is $0$ or $1$.
When we divide $n$ by $2$, we therefore see that the remainder is $b_0$. The result of the integer division is $b_k 2^k + b_{k-1} 2^{k-1} + \cdots + b_{1} 2^1$. Dividing again by $2$, we see in the same way as before that the remainder is $b_1$. This line of reasoning can be carried out for every subsequent division; the remainder of the $j$th successive division is $b_j$.

A: It should be clear that the remainder after the first division by $2$ finds the lowest digit - $0$ or $1$ depending on whether the number is even or odd.
Then think about how you might find the next lowest digit. That's like the ten's place in ordinary notation. If you have $1574$ that $7$ is what you get if you subtract the $4$, divide by $10$ (cancel the zero, move the decimal point one place left) and look at the new units digit.
So for binary, subtract the units digit ($0$ or $1$, whichever it happened to be) and divide by $2$ to shift left.
Keep going as long as you need to.

A: This is because of Horner's scheme for evaluating polynomials:
\begin{align}&a_nx^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}\dots+a_1x+a_0\\
={}(\dots(((&a_nx+a_{n-1})x+a_{n-2})x+\dots+a_1)x+a_0.
\end{align}
The successive divisions by $2$ yield
\begin{align}
14&=7\cdot 2+0\\&=(3\cdot2+1)\cdot 2+0=3\cdot2^2+1\cdot 2+0\\
&=\color{red}{((1\cdot2+1)\cdot2+1)\cdot 2+0}=(1\cdot2+1)\cdot2^2+1\cdot 2+0 \\ &=1\cdot2^3+1\cdot2^2+1\cdot 2+0
\end{align}

A: Might as well do it for an integral base $b>1$ instead of $2$.
For every integer $n\ge 0$ take the largest integer $q$ so that
$b q \le n$. Clearly $q \ge 0$, and $n - q b \ge 0$. Since $(q+1)b >n$, we have $n - q b < (q+1)b-  q b = b$. Therefore, $n -  q b \in \{0,1,\ldots, b-1\}$. This is the division with remainder. For every integer $n\ge 0$ there exists  integers $q\ge 0$ and $r \in \{0,1,\ldots, b-1\}$ so that
$$n = q b+ r$$  $b$ and $r$ with these properties are unique. $b$ is the quotient, and $r$ is the remainder of the division of $n$ by $b$.Note that $$0 \le q \le \frac{n}{b}$$
Take now an integer $n\ge 0$, denote $q_0=n$, and do successive divisions
$$q_0 = q_1 b + r_0 \\
  q_1 = q_2 b + r_1\\
  q_2= q_3 b + r_2 \\
  \ldots  \ldots\\
  q_{k-1} = q_k b + r_{k-1}\\
  q_k = q_{k+1} b + r_k$$
Since $0\le q_{k+1} \le \frac{q_k}{2}$, there exists a smallest $k\ge 0$ so that $q_{k+1} = 0$. From the above equalities we get
$$q_k = r_k \\
q_{k-1} = r_k b + r_{k-1}\\
q_{k-2}=(r_k b+r_{k-1})b + r_{k-2}= r_k b^2 + r_{k-1} b+ r_{k-2}\\
\ldots \ldots\\
q_0 = (r_k b^{k-1}+ r_{k-1} b^{k-2} + \cdots + r_2 b + r_1) b + r_0 = \\
=r_k b^k + r_{k-1} b^{k-1} + \cdots + r_1 b + r_0$$


text:
Q: how to combine data from two columns in aurelia slickgrid I have a aurelia slickgrid table with start date and end date and it is fine. Backend api response is in odata format. Now i want to make a new column called Status and status is calculated as :

        Activates on ${lic.DateStart}

        Ended on ${lic.DateEnd}

        Current License

        Cancelled on ${lic.DateEnd}

Basically, those fucntions above such as doesLicenseActivate are bunch of Moment.js function doing some date caclulations. My column looks like:
/* Define grid Options and Columns */
private defineMembershipGrid() {
    return this.columnDefinitionsMembershipHistory = [
       { id: "DateStart", name: "Start Date", field: "DateStart", formatter: Formatters.dateEuro, sortable: true, filterable: true, minWidth: 100, },
        { id: "DateEnd", name: "End Date", field: "DateEnd", formatter: Formatters.dateEuro, sortable: true, filterable: true, minWidth: 100, },
        { id: "Duration", name: "Duration", field: "Duration", formatter:  this.DurationFormatter, sortable: true, filterable: true, minWidth: 100, },
       // make a status column here
    ];
}

This is how it looks like:

And this is what i want to do, basically make a new Status column and it uses the values from first two columns (start and end date)

A: Just use a Custom Formatter, see Custom Formatter - Wiki it has the dataContext which is the item object of the entire row. You can use MomentJS to do your calculation and display "10 months" or "Current License" (I guess that last one would be a calculation and a switch/case). You can do anything you want in a Custom Formatter and it will be recalculated every time the grid re-render, if you change value of another cell it will also be recalculated. You might have problem to filter and sort though and in that case you might want to not show a filter and remove the sort.


text:
Q: parsing xml data return empty in php I'm trying to read below xml from PHP and return empty. What I'm doing wrong?
XML
<?xml version="1.0" encoding="utf-8"?>
<page>
  <settings>
    <ss_pageRef><![CDATA[1]]></ss_pageRef>
    <ss_pageType><![CDATA[juicebox]]></ss_pageType>
    <ss_navName><![CDATA[Gallery]]></ss_navName>
    <ss_navWeight><![CDATA[1]]></ss_navWeight>
    <ss_navShow><![CDATA[true]]></ss_navShow>
    <ss_indexShow><![CDATA[true]]></ss_indexShow>
    <ss_parentPage><![CDATA[0]]></ss_parentPage>
    <ss_pageTitle><![CDATA[New gallery page]]></ss_pageTitle>
    <ss_pageDescription><![CDATA[This is gallery one]]></ss_pageDescription>
    <ss_pageBody><![CDATA[
Enter page body text here.
]]></ss_pageBody>
    <galleryTitle><![CDATA[]]></galleryTitle>
  </settings>
</page>

PHP
$galleries = simplexml_load_file("../gallery/page.xml") or die ("no gallery found");

print_r($galleries);

echo $galleries->ss_pageDescription;

Print_r
SimpleXMLElement Object ( [settings] => SimpleXMLElement Object ( [ss_pageRef] => SimpleXMLElement Object ( ) [ss_pageType] => SimpleXMLElement Object ( ) [ss_navName] => SimpleXMLElement Object ( ) [ss_navWeight] => SimpleXMLElement Object ( ) [ss_navShow] => SimpleXMLElement Object ( ) [ss_indexShow] => SimpleXMLElement Object ( ) [ss_parentPage] => SimpleXMLElement Object ( ) [ss_pageTitle] => SimpleXMLElement Object ( ) [ss_pageDescription] => SimpleXMLElement Object ( ) [ss_pageBody] => SimpleXMLElement Object ( ) [galleryTitle] => SimpleXMLElement Object ( ) ) )

A: The reason it is not echo'ing anything is because <ss_PageDescription /> is nested within <settings />.
echo $galleries->settings->ss_pageDescription;


text:
Q: PyMongo: NatType ValueError on Bulk Insert to New Collection I am trying to use PyMongo to upload a mixed set of date and text data to a new collection in my remote MongoDB server.
However, I'm getting a error as a result of null values mixed in with dates—i.e. rows where there is a None value instead of a datetime.datetime() object.
As some background: The raw data is stored in a CSV file, which I'm reading into a pandas.DataFrame() using pandas.read_csv(). Once I have the data in pandas, I do some rudimentary cleaning before transforming the data into a list of dictionaries, which I then upload to the collection using the standard collection.insert_many() method.
Initially, the values in each row / document / dictionary are stored as strings. However, before uploading the data, I convert a number of date columns into datetime objects by calling datetime.datetime.strptime() on each value. Not every dictionary has these date fields populated, though. For these dictionaries, I simply use a None instead of a datetime object.
The resulting data that I'm trying to upload, then, is a list of dictionaries with a number of NoneType values mixed in, and when I call insert_many() I get this:
ValueError: NaTType does not support utcoffset.
I'm not familiar with utcoffset, and my attempts to research this have confounded me.
Has anyone run into this issue, or have suggestions on how to handle missing datetime data in PyMongo?
Here's my code:
import pandas as pd
import pymongo

source = '/path/to/data'
sampleData = pd.read_csv(source, dtype=str)

Date_Columns = [
    'date_a',
    'date_b',
    'date_c',
    'date_d'
]
cleanData = sampleData
for col in Date_Columns:

    # Convert the strings to datetime objects for each column.
    # If a value is null, then use a None object instead of a datetime.
    Strings = sampleData[col].values
    Formats = [dt.datetime.strptime(d, '%m/%d/%Y') if isinstance(d, str) else None for d in Strings]
    cleanData[col] = Formats

client = pymongo.MongoClient('XX.XX.XX.XX', 99999)
db = client['my_db']
c = db['my_collection']

# Convert the cleaned DataFrame into a list of dictionaries.
Keys = [key for key in sampleData.columns.values]
Data = [dict(zip(Keys, L)) for L in sampleData.values]

c.insert_many(Data)

And full traceback:
Traceback (most recent call last):
  File "/Users/haru/my_git/projects/pipeline/stable/sofla_permits_sunnyisles.py", line 738, in <module>
    setup_db()
  File "/Users/haru/my_git/projects/pipeline/stable/sofla_permits_sunnyisles.py", line 679, in setup_db
    c.insert_many(Data)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/collection.py", line 753, in insert_many
    blk.execute(write_concern, session=session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/bulk.py", line 513, in execute
    return self.execute_command(generator, write_concern, session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/bulk.py", line 338, in execute_command
    self.is_retryable, retryable_bulk, s, self)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1196, in _retry_with_session
    return func(session, sock_info, retryable)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/bulk.py", line 333, in retryable_bulk
    retryable, full_result)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/bulk.py", line 285, in _execute_command
    self.collection.codec_options, bwc)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/message.py", line 1273, in _do_bulk_write_command
    namespace, operation, command, docs, check_keys, opts, ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/message.py", line 1263, in _do_batched_write_command
    namespace, operation, command, docs, check_keys, opts, ctx)
  File "pandas/_libs/tslibs/nattype.pyx", line 59, in pandas._libs.tslibs.nattype._make_error_func.f
ValueError: NaTType does not support utcoffset

A: Most machines have their clocks set to utc, which is ideal. It's an integer value of seconds from a given date (sometime in the 70's, I believe). What this means is that your schedules for processes don't rely on local time, including the massive headache that is Daylight Savings.
UTC offset from US Eastern Standard is 4-5 hours (depending on daylight savings).
Looking at your error, this is a pandas error, and pandas.datetime does not play nicely with datetime.datetime. Convert it to a datetime string of the required precision. That should avoid this error.


text:
Q: Require is not define when I tried to send an email using nodemailer, after I insert these into my web project, and I get an error "require is not defined". Can I know how to solve it?
           var nodemailer = require('nodemailer');
            var transporter = nodemailer.createTransport({
                service:'gmail',
                auth:{
                    user:'xxx@gmail.com',
                    pass:'xxxxxxx'
                }
            });

            var mailOptions = {
                from:'xxx@gmail.com',
                to: 'xxx@gmail.com',
                subject:'Thanks for using!',
                text:'Thanks!'
            };

            transporter.sendMail(mailOptions,function(error, info){
                if(error){
                    console.log(error);
                }else
                console.log('Email sent: '+ info.response);
            });

A: I am assuming you are trying to do this on the frontend. Nodemailer is a package that is made to be run on a backend node.js server. You do not have node listed for the questions tags so that is why I am assuming this. If this is not the case then check out:
http://requirejs.org/docs/download.html
Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js
and take a look at this http://requirejs.org/docs/api.html


text:
Q: Getting the recurrence relation for Legendre polynomials by Leibnitz rule Exercise:
For each natural number $n$ define
$$\phi_n(x)=\frac{d^n}{d x^n}\left(x^2-1\right)^n$$
Derive the formulas
$$\phi_{n+1}^{\prime}(x)=2(n+1) x \phi_n^{\prime}(x)+2(n+1)^2 \phi_n(x)$$
$$\phi_{n+1}^{\prime}(x)=\left(\left(x^2-1\right) \phi_n^{\prime}(x)\right)^{\prime}+2(n+1) x \phi_n^{\prime}(x)+(n+1)(n+2) \phi_n(x)$$
Hint. Attack the expressions
$$\frac{d^{n+2}}{d x^{n+2}}\left(x^2-1\right)^{n+1} \space\space   \frac{d^{n+1}}{d x^{n+1}}\left(x^2-1\right)^{n+1}$$
Mt attempt:
$$\frac{d^{n+2}}{d x^{n+2}}\left(x^2-1\right)^{n+1}=\sum_{k=0}^{n+2}\binom{n+2}{k} \frac{d^{k}}{d x^{k}}\left(x^2-1\right) \frac{d^{n+2-k}}{d x^{n+2-k}}\left(x^2-1\right)^{n}$$
Obviously survives only $k=0,1,2$ - th terms
$$\frac{d^{n+2}}{d x^{n+2}}\left(x^2-1\right)^{n+1}=(x^2-1)\frac{d^{n+2}}{d x^{n+2}}\left(x^2-1\right)^{n}+2x(n+2)\frac{d^{n+1}}{d x^{n+1}}\left(x^2-1\right)^{n}+(n+2)(n+1)\frac{d^{n+1}}{d x^{n+1}}\left(x^2-1\right)^{n}$$
$$\phi_{n+1}^{\prime}(x)=(x^2-1)\phi_n^{\prime\prime}(x)+2(n+2) x \phi_n^{\prime}(x)+(n+1)(n+2) \phi_n(x)$$
$$\phi_{n+1}^{\prime}(x)=\left(\left(x^2-1\right) \phi_n^{\prime}(x)\right)^{\prime}+2(n+1) x \phi_n^{\prime}(x)+(n+1)(n+2) \phi_n(x)$$
I succeeded to get the second formula but coludn't find the first formula.
Could anybody help me, please?

A: To simplify notation, I write $\delta_n$ instead of $\frac{d^n}{dx^n}$ ; thus
$\phi_n(x)=\delta_n((x^2-1)^n)$. We then have
$$
\begin{array}{lcl}
\phi_{n+1}(x) &=& \delta_{n+1} ((x^2-1)^{n+1}) \\
 &=& \delta_{n+1} ((x^2-1)(x^2-1)^{n}) \\
 &=& \delta_{n} (2x(x^2-1)^{n}+(x^2-1)2nx(x^2-1)^{n-1}) \\
 &=& \delta_{n} (2x(x^2-1)^{n}+2nx(x^2-1)^{n}) \\
 &=& 2(n+1)\delta_{n} (x(x^2-1)^{n}) \\
\end{array}
$$
It follows that
$$
\begin{array}{lcl}
\phi'_{n+1}(x) &=& 2(n+1)\delta_{n+1} (x(x^2-1)^{n}) \\
 &=& 2(n+1)\sum_{j=0}^{n+1} \binom{n+1}{j} \delta_{j} (x) \delta_{(n+1)-j} ((x^2-1)^{n}) \\
 &=& 2(n+1)\sum_{j=0}^{1} \binom{n+1}{j} \delta_{j} (x) \delta_{(n+1)-j} ((x^2-1)^{n}) \\
 &=& 2(n+1)\bigg(x\delta_{n+1} ((x^2-1)^{n})+(n+1)\delta_{n} ((x^2-1)^{n})\bigg) \\
 &=& 2(n+1)\bigg(x\phi'_{n}(x)+(n+1)\phi_n(x)\bigg) \\
\end{array}
$$
which proves the first formula.


text:
Q: To get Xml index value based on node values XML OUTPUT
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     <HelpListResponse>
         <HelpList>
    <id>16639505</id>
    <name>HelpList_Old</name>
    HelpList/16639505
    </HelpList>
    <HelpList>
    <id>16641505</id>
   <name>Investments to Watch</name>
    HelpList/16641505
    </HelpList>
    <HelpList>
    <id>16640505</id>
    <name>HelpList_New</name>
    HelpList/16640505
    </HelpList>
    </HelpListResponse>

JAVA CODE for XML Parsing...
 xmlFile = new File("xmlFile.xml");
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(xmlFile);

I am parsing above xml document and storing it in doc object.
For instance, if i need to retrieve name value from first index (ie:"HelpList_Old"), then i use the below statement
doc.getElementsByTagName("name").item(0).getTextContent();
 => This helps me to print "HelpList_Old"

I need couple of things and I am not sure how to go about it…
1) I need to get index value based on the text content of xml. (eg: -  If I provide "HelpList_Old", then it should return me index = 0, similarly if i want to get the index of value "HelpList_New" it should return 2)
2) On same lines, if I  provide "HelpList_Old", then I want to print its corresponding  tag value, in this case  "16639505"
Let me know in case I am not clear with my question.
Thanks in Advance..


text:
Q: How to convert UTF-8 to String in Java I am stuck here because after making the convertion from byte to String I works with append method but if I want to use setText instead of append, I get no text shown on my phone. And I don't want to write text next to the last one.
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
        @Override
        public void onReceivedData(byte[] arg0) {
            String data = null;
             try {
                data = new String(arg0 , "UTF-8");
                    tvAppend(mostrarEntradaAnalogica, data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();

            }

        }
    };

public void tvAppend(TextView tv, String text) {
        final TextView ftv = tv;
        final String ftext = text;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ftv.append(ftext);
            }
        });

    }


text:
Q: Associate Ldap user to a group with Java I'm having problems to find how to associate a #Ldap user to a given group.
That is what I have tried:
    Attributes attrs = new BasicAttributes();

    BasicAttribute basicAttrs = new BasicAttribute("objectclass");
    basicAttrs.add("top");
    basicAttrs.add("person");

    BasicAttribute memberOf = new BasicAttribute("memberOf");
    memberOf.add("Managers"); // Tried with distinguished name too
    memberOf.add("Administrators"); // Tried with distinguished name too

    attrs.put(basicAttrs);
    attrs.put("cn", user.getLogin());
    attrs.put("name", user.getLogin());
    attrs.put("login", user.getLogin());
    attrs.put("mail", user.getMail());
    attrs.put("displayName", user.getDisplayName());
    attrs.put("memberOf", memberOf);

    try {
        ctx.bind("CN=" + user.getLogin() + "," + baseDn, null, attrs);
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I also tried to use the distinguished names like: "CN=Managers,OU=<system_name>,OU=Users,OU=<server>,DC=com", but didn't work.
I think it should be somewhere to reference the Ldap group.
But I got this error:
javax.naming.directory.InvalidAttributeValueException: Malformed 'memberOf' attribute value; remaining name 'CN=lcarvalho,OU=<system_name>,OU=Users,OU=<server>,DC=com'
at com.sun.jndi.ldap.LdapClient.encodeAttribute(LdapClient.java:951)
at com.sun.jndi.ldap.LdapClient.add(LdapClient.java:999)
at com.sun.jndi.ldap.LdapCtx.c_bind(LdapCtx.java:396)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_bind(ComponentDirContext.java:277)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.bind(PartialCompositeDirContext.java:197)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.bind(PartialCompositeDirContext.java:186)
at javax.naming.directory.InitialDirContext.bind(InitialDirContext.java:158)
...

This is all the stack trace besides my application lines.

A: If you're using OpenLDAP the memberOf attribute is maintained automatically by the memberOf overlay, and your application shouldn't write it at all. What you should be doing is adding the DN of the user to the uniqueMember or roleOccupant etc. attribute of the group he is joining. Then its DN will magically appear in his memberOf attribute.

A: Most probably your DN is wrong, because it seems you've specified one extra Organizational Unit instead of Domain Component:
"CN=Managers,OU=<system_name>,OU=Users,OU=<server>,DC=com"

should be:
"cn=Managers,ou=<system_name>,ou=Users,dc=<server>,dc=com"

In LDAP the Directory Structure starts with 2 domain components, which are a reversed company domain name (by convention).
In order for your code to work, you have to take into account the following:

*

*there's a schema "Person" that's loaded in your LDAP Server

*there's an attribute "MemberOf" defined in your "Person" schema

*"MemberOf" requires full DN as entry
I would also encourage you to take a look at UnboundID LDAP SDK.
Hope that helps.

A: The value of the memberOf attribute is wrong. The memberOf attribute is probably a distinguished name. LDAP clients should consult the schema (the base DN of which might be available in the root DSE) when in doubt about the syntax, ordering, or matching rules of an attribute.

A: I had the same problem. Check the value type of this attribute using any client of ldap (for example: Apache Directory Studio). If you try to replace attribute which type is String with int value it will thrown this error.


text:
Q: Why did Han Solo have to pay off Jabba? I know that the reason Han Solo picked up Luke and Ben Kenobi as passengers was because he owed some money to Jabba (and for that was later put in Carbonite since he didn't pay - Bad Move, dude!).
But was it ever stated in the movies what he owned Jabba the money for?

A: TL;DR: It was hinted at in the movies, and then explained in detail later in EU books (more specifically, Rebel Dawn - the 3rd book in the Han Solo trilogy).

In A New Hope, Greedo, while infamously chatting with Solo before Han shot him first he tried to shoot Han, says:

Greedo: Jabba's through with you! He has no use for smugglers who drop their shipments at the first sign of an Imperial cruiser.
Han Solo: Even I get boarded sometimes. Do you think I had a choice?

It doesn't provide any more details. (There's a chance that the Special Edition Han + Jabba scene has more info, but I will just pretend the Special Edition never happened)

In Rebel Dawn, the exact back-story of this is shown.
Han is (near the end of the book) one of Jabba's best (and favorite) pilots.
Jabba tells him to deliver some Glitterstim.
In the process, during the Kessel run, he is ambushed by some Imperials and forced to dump the contraband in the Maw when he discovers that boarding is imminent, when - after a record-setting run that set the famous "12 parsecs" record - he gets OUT of the black hole region only to find a second Imperial patrol waiting for him.

"Chewie, we ain't gonna be able to outrun these Imps," Han said. "And we're out-gunned. But we've lost that guy on our tail, at least for the moment. I think if we can get far enough ahead, we should go ahead and dump the load just inside the Pit..."

He hopes to pick up the drugs later, but when he finally has a chance to return, there's no trace of the shipment.
The extra candy is that this specific backstory ALSO includes the infamous "12 Parsecs Kessel Run" retcon!

Now the last Imperial ship was falling behind... and the Falcon was nearly out of the Maw.
... Moments later they were safe in hyperspace. Han slumped back in his seat. ... As he sagged in his seat, Han noticed something.
... Hans eyes narrowed. "Hey, this is weird," he said. "It says we actually shortened the distance we traveled, not just the time. Less than twelve parsecs!"
Chewie growled skeptically and rapped on the distance gauge with hairy knuckles, commenting that Han's wild piloting must have caused a short and the gauge was off.
"... But I did do it in under twelve parsecs ...." he thought stubbornly.

A: It's alluded to in the movie that Han had been smuggling cargo for Jabba, but had to jettison it when he thought he was going to be boarded by Imperial forces. The cost of the cargo is what he owed him.
EDIT :
DVK already posted the relevant quote from the conversation between Han and Greedo that appeared in the movie, but there is of course the controversial deleted scene where Han and Jabba meet. The original scene cast Jabba as a human, and was added back in later releases with a CGI Jabba taking his place. Whatever you may think about the scene, the script clarifies the point:

JABBA: Han, Han! If only you hadn't had to dump that shipment of
  spice...you understand I just can't make an exception. Where would I
  be if every pilot who smuggled for me dumped their shipment at the
  first sign of an Imperial starship? It's not good business.
HAN: You know, even I get boarded sometimes, Jabba. I had no choice,
  but I've got a charter now and I can pay you back, plus a little
  extra. I just need some more time.

A: From the original novel, which was alluded to in the movie, Han had dumped a shipment of "spice" while being pursued and eventually boarded by Imperials. Jabba wanted compensation (it's not like Lloyd's of London would have insured the shipment), and Han was pretty much broke except for his ship, which he persuaded Jabba to let him keep so he could work off the debt. Jabba agreed, obviously with some subtle hints as to his low level of patience.
It's unknown exactly what "spice" is in this universe, other than it was probably inspired by the Dune novels. It's likely just some sort of hallucinogenic plant-based drug, like marijuana or salvia, rather than having the "awareness spectrum" properties of the Dune universe.


text:
Q: Facebook App: What defines a "user"? I have a Facebook Application which is ready to be submitted to the Application Directory, but before I submit, it says " Your application must have at least 5 total users or 10 monthly active users before you can submit it to the Application Directory".
I have had many users navigate to the canvas page and use the iframe to browse the site and I also have many users that have "Liked" the Facebook App.
But it still says I have "0" users. So my questions is...what defines a user? How does that number increase?

A: It means average visiting of your site each month. This information is available in application Info page which can be accessed like this:
http://www.facebook.com/apps/application.php?id=xxxxxxxxxxxxxx
You need to replace xxxxxxxxxxxxxx with your application id (which can be figured out by going to http://www.facebook.com/developers and then choosing your application settings from there) and on that page will you see Information box which will tell you the number of average users visiting your site.
This number varies because it depends on how many users visit your site each month.


text:
Q: Why won't onclick event fire after setting new model to a grid with buttons? I have a grid with 2 buttons on each row, for edition and deletion. When I set a new model to the grid, the buttons won't fire the onClick event so I can handle it in the composer. I don't wanna bother using the MVVM pattern, I want to use the MVC pattern. I want to know how to make the buttons function after setting a new model to the grid.
Here is my ZUL File:
<?page title="ZK Application" contentType="text/html;charset=UTF-8"?>
<zk>
<window id="win" title="new page title" border="normal" apply="com.example.zk.controllers.ActorController">
<intbox id="txtActorId" visible="false" value="-1"></intbox>
<textbox id="txtFirstName"></textbox>
<textbox id="txtLastName"></textbox>
<button id="btnSave" label="Save"/>
<button id="btnClear" label="Clear" />
<button id="btnDeleteAll" label="Delete All"/>

<grid id="grdActors" model="${win$composer.actorsModel }">
    <columns>
        <column label="ID" />
        <column label="First Name" />
        <column label="Last Name" />
        <column/>
    </columns>
    <template name="model" var="actor">
        <row value="valor${each.actorId }">

            <button id="btnEdit${each.actorId }" label="Edit" >
                <custom-attributes actor="${each }" action="edit"/>
            </button>
            <button id="btnDelete${each.actorId }" label="Delete">
                <custom-attributes actor="${each }" action="delete"/>
            </button>
        </row>
    </template>
</grid>

</window>
</zk>

Here is my composer:
package com.example.zk.controllers;

import java.util.Date;
import java.util.List;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;

import com.example.zk.dao.ActorDAO;
import com.example.zk.entities.Actor;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class ActorController extends SelectorComposer<Component> {

    private static final long serialVersionUID = 1L;

    @WireVariable("actorDao")
    ActorDAO dao;

    @Wire
    Textbox textBox;

    @Wire
    Combobox cbxActors;

    @Wire
    Textbox txtFirstName;

    @Wire
    Textbox txtLastName;

    @Wire
    Intbox txtActorId;

    @Wire
    Grid grdActors;

    public List<Actor> getActors(){
        return dao.getAllActors();
    }

    public ListModel<Actor> getActorsModel(){
        return new ListModelList<>(getActors());
    }

    @Listen("onClick=#btnSave")
    public void saveActor(){
        Actor actor = new Actor((short) txtActorId.getValue().intValue(), txtFirstName.getValue(), txtLastName.getValue(), new Date());
        dao.saveActor(actor);
        refreshGrid();
        clearAll();
    }

    @Listen("onClick=#grdActors button")
    public void editActor(Event event){
        Actor actor = (Actor) event.getTarget().getAttribute("actor");
        if(((String) event.getTarget().getAttribute("action")).equalsIgnoreCase("delete")){
            deleteActor(actor);
            return;
        }
        txtActorId.setValue((int)actor.getActorId());
        txtFirstName.setValue(actor.getFirstName());
        txtLastName.setValue(actor.getLastName());
    }

    public void deleteActor(Actor actor){
//      Actor actor = (Actor) event.getTarget().getAttribute("actor");
        dao.delete(actor);
        refreshGrid();
    }

    @Listen("onClick=#btnDeleteAll")
    public void deletaAll(){
        dao.deleteAll();
        refreshGrid();
    }

    @Listen("onClick=#btnClear")
    public void clearAll(){
        txtActorId.setValue(0);
        txtFirstName.setValue("");
        txtLastName.setValue("");
    }

    public void refreshGrid(){
        grdActors.setModel(getActorsModel());
    }

}

A: In general, all event listeners are attached to model in MVC frameworks.
So if you replace the model, the listeners would still work in case of changes in old model.
You have to set all listeners again for the new model (and remove them from old model (which is done by framework in most cases)) to make it work properly.

A: The problem is, that your component (Window) is already created at the time you change the model. So zk don't call doAfterCompose and won't wire the components/event listners.
What should work, is fire the onCreate event of the Window in the constructor of the model (not tested)
Events.postEvent("onCreate", getSelf, null);

But it is bad practice in my opinion.
More correct would be, to manipulate the model.


text:
Q: Xcode 11.1 not installing new build with changes (iOS 13.1.2) After installing 11.1 I created a new project, removed the multi-window stuff that Xcode now gives you by default, and started developing a test app that uses Vision Framework.
By the time I got to the point where I needed to test on the device instead of the simulator, I was struggling to make my app work correctly. I finally realized that running the app on my phone required me to delete the app and run a fresh install or the changes wouldn't be pushed to the device. This continues to be a problem. Even a new print statement won't be shown in the debugger output unless I go through the rigamarole of deleting the app and running fresh. Subsequent changes still use the initially installed build regardless of the number of times I clean/build/run.
I've cleaned the project, build folder, derived data, Xcode cache, rebooted my Mac, rebooted my phone, reinstalled Xcode, obliterated and reinstalled Xcode again, all with no success.
Anyone else with this issue? What am I missing?!

A: Ok, after two days of trying to fix this, it turns out to be some kind of Apple bug on iOS 13 (surprise, surprise).
Here's what I did/found:

*

*I tried running on another device and was able to see changes on subsequent runs.

*Back on the original test device, the issue still exists (Xcode issue ruled out)

*I had a couple other test apps that were signed with the same development cert on the device, so I deleted those too.

*Running the app from Xcode again prompted me to go to settings to trust the developer certificate

*Changes and updates are now pushed to the device on each run from Xcode.
TLDR:
If you happen to run into a similar issue, try deleting other development certificate apps you have on your device and re-trust the certificate.


text:
Q: postgres lo_unlink not deleting objects Im little bit new in postgres, but I have problem related with disk space. now I have 2GB free space, I need to delete some of largeobjects. Situation is like this:
I have table espbidocuments that stores OID with ID to pg_largeobject table where is stored my files. pg_largeobject now is 87,201,636,352 bytes size and I need to shrink. I tried deleting references from espbidocuments, so LO will be orphans, then I ran function lo_unlink(oid) and get result 1, so I think that my files are deleted, but still when I selecting from pg_largeobject table, I get that they exist in that table and pg_largeobject table size is not lesser, size is the same. I cant do vacuum because tables size is 80+GB and free space is ~2GB... how remove those darn largeobject?


text:
Q: Where is the path to the downloaded jars file when Grails is resolving dependencies Grails resolves dependencies and downloads some jars. But I can't find where the downloaded file path.
And the command locate also can't find these jars.
My Operator System is Ubuntu 16.04

A: It should be under ~/.gradle/caches/modules-2/files-2.1


text:
Q: How to selectively map aesthetics (convex hulls) to ggplot2? I'm trying to overlay convex hulls on-top of noisy data. I only want the hulls on the main clusters (and not the red outliers).

How would I plot every other hull while plotting all the points?
In my workaround attempt, I accidentally made all the outliers disappeared. Additionally, the shapes (21-25) were distorted when plotting my actual data in a Shiny app.
Would this be solved by tinkering when building the stat, or by editing the mapping?
Requirements: I'd also like to keep things to ggplot2 since this will all be wrapped up in a ShinyApp, and the hulls will be plotted if the user clicks on a checkbox. The number of cluster varies per graph, but the first one is ALWAYS the outlier.
Data Generation
library(dbscan)
library(ggplot2)
data("DS3")
DS3_cl <- hdbscan(DS3, minPts = 25)
DS3_comb <- DS3
DS3_comb$cluster <- as.character(DS3_cl$cluster)

Graph functions/parameters
cols <- c('#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#a65628','#f781bf','#999999','#ffff33')
cols_2 <-  c(NA,'#377eb8','#4daf4a','#984ea3','#ff7f00','#a65628','#f781bf','#999999','#ffff33')

StatChull <- ggproto("StatChull", Stat,
                     compute_group = function(data, scales) {
                       data[chull(data$x, data$y), , drop = FALSE]
                     },
                     # Do the outlier removal around here?
                     required_aes = c("x", "y")
)

stat_chull <- function(mapping = NULL, data = NULL, geom = "polygon",
                       position = "identity", na.rm = FALSE, show.legend = NA,
                       inherit.aes = TRUE, ...) {
  layer(
    stat = StatChull, data = data, mapping = mapping, geom = geom,
    position = position, show.legend = show.legend, inherit.aes = inherit.aes,
    params = list(na.rm = na.rm, ...)
  )
}

Plots:
plot_1 <- ggplot(data = DS3_comb, aes(X, Y, color = cluster)) +
  geom_point(alpha = 0.4) +
  scale_color_manual(values = cols) +
  theme_bw()

plot_2 <- plot_1 + stat_chull(fill = NA)

Workaround Attempt:
plot_3 <- ggplot(data = DS3_comb, aes(X,Y, fill = cluster, color = cluster)) +
  geom_point(shape = 21, alpha = 0.4) +
  scale_fill_manual(values = cols) +
  scale_color_manual(values = cols_2) +
  theme_bw()

Sources consulted:

*

*R : pass Graph as parameter to a function

*https://cran.r-project.org/web/packages/ggplot2/vignettes/extending-ggplot2.html

*stat_function and legends: create plot with two separate colour legends mapped to different variables

*

*Just started reading, but could be problematic with Shiny: https://github.com/rstudio/shiny/issues/1431

A: Just subset the data for that layer. For example
plot_1 + stat_chull(fill = NA, data=subset(DS3_comb,cluster!=0))


text:
Q: How to disable irritating beeping sound in PowerShell sometimes I run grep (aka select-string) that has string that occurs too often, then PowerShell goes crazy, sometimes I manage to kill it with Ctrl+C, but even then I have to endure irritating beeping sound for 30 + seconds... can this be disabled also without killing terminal where it is running?

A: Open your PowerShell profile, or type:
if (!(Test-Path $profile)) {New-Item -Type File -Path $profile -Force}

to make a profile if one doesn't exist.
Then add Set-PSReadlineOption -BellStyle None to the profile to turn the sound off.
(that sound drives my dog insane, it was sapping my will to live)

A: This powershell is the SC equivalent that was already answered.
Get-Service Beep | Stop-Service -PassThru | Set-Service -StartupType Disabled


text:
Q: XML Element with attribute by using Java annotations I can create an XML element in Java by using the annotation javax.xml.bind.annotation.XmlElement
@XmlElement(name="foo")

that produces the following XML element
<foo/>

Now, I want to create the following tag:
<foo attr="attrval"/>

How can I do that by using annotations?


text:
Q: Partial Derivative Chain Rule on a Vector Valued Function I found this question on a past exam, but I am having a hard time figuring it out since the material was only briefly mentioned in class, without any examples, and is not present in the class notes.
Let $f:\mathbb{R}^2\rightarrow\mathbb{R}$ be twice continuously partially differentiable and let $g:\mathbb{R}^2\rightarrow\mathbb{R}^2$ be defined by $g(x,y)=(x^2-2y^2,xy^2)$. Let $F(x,y)=(f\circ g)(x,y)$. Use the chain rule to express $\frac{\partial^2F}{\partial x\partial y}(x,y)$ in terms of the partial derivatives of $f$.
I'm sure I'll understand the chain rule for vector valued functions once I see an example like this.

A: $F(x,y)$ = ($f($$x^2$-2$y^2$), $f$(x$y^2$)). This now boils down to a problem using the single variable calculus chain rule. So, $\partial{F} \over\partial{y}$ $=$ ($df \over dy$(${f}$($x^2 - 2y^2$)($-4y$), $df \over dy$($f$($xy^2$)($2xy$)). Next, $\partial^2{F} \over \partial{x} \partial{y}$ $=$ ($df \over dx$($df \over dy$($f$($x^2 - 2y^2)$(-4$y$)),($df \over dx$($df\over dy$($f$($xy^2$)$)($2xy$)$ + ($df \over dy$(f($xy^2)$)($2y$)))


text:
Q: Problema al importar SweetAlert Android Studio Intento implementar SweetAlert a mi código
implementation 'com.github.f0ris.sweetalert:library:1.5.2'

pero al momento de sincronizar me arroja el siguiente error:
INFO: API 'variantOutput.getProcessResources()' is obsolete and has been
replaced with 'variantOutput.getProcessResourcesProvider()'.

It will be removed at the end of 2019.

For more information, see https://d.android.com/r/tools/task-configuration-
avoidance.

To determine what is calling variantOutput.getProcessResources(), use -
Pandroid.debug.obsoleteApi=true on the command line to display more
information.

Affected Modules: app

Estoy usando compileSdkVersion 29. ¿Alguien podría decirme como solucionar esto por favor?


text:
Q: Images through the URL doesn't display import java.awt.*;
import javax.swing.*;

public class O2BIntro extends Open2Beat {

    private JLabel screenGraphic;

    private ImageIcon introBackground;
    private ImageIcon titleImage;
    private ImageIcon startButtonImg;
    private ImageIcon settingButtonImg;
    private ImageIcon buttonSelectedImg;

    public O2BIntro() {
        introBackground = new ImageIcon(this.getClass().getResource("../img/wp2537453-dj-background-hd.jpg"));
        titleImage = new ImageIcon(this.getClass().getResource("src/img/open2BeaTTitle.png"));
        startButtonImg = new ImageIcon(this.getClass().getResource("src/img/MenuImg_Gamestart_KR.png"));
        settingButtonImg = new ImageIcon(this.getClass().getResource("src/img/MenuImg_Preference_KR.png"));

    }

    public void paintIntro() {

        screenGraphic = new JLabel(introBackground,JLabel.CENTER);
        screenGraphic.setBounds(0, 0, DisplayBasic.myScreenWidth, DisplayBasic.myScreenHeight);
        add(screenGraphic);
    }

}

So, this is my current part of code. I tried to load my images from /src/img/, but it still doesn't display anything. How should I edit my code? Which kind of framework or component should I use to display properly?


text:
Q: Creating alias (or something similar) that activates when cd into a specific folder Is it possible to create aliases when I enter a certain folder?
What I want:
I use composer a lot (a PHP package manager), which installs binaries in ./vendor/bin. I would like to run the binaries directly from ..
For example:
/path/to/project
 | - composer.json     // dictates dependencies for the project
 | - vendor            // libs folder for composer, is created by composer
 |    | - bin          // if lib has bin, composer creates this folder
 |    |    | phpunit   // binary
 |    |    | phinx     // binary
 |    | - somelib1     // downloaded by composer
 |    | - somelib2     // downloaded by composer

Is it possible to get this to work:
> cd /path/to/project
> phpunit

And get phpunit to execute?
Something like "sensing" the composer.json file and dynamically find the binaries in ./vendor/bin and then do something like alias="./vendor/bin/<binary-name> $@" automatically?

I use OS X 10.9 and the boxed in Terminal app.

A: You can override cd, trap my_function DEBUG to run something on every command, or add a command into PS1 or PROMPT_COMMAND.
These have different behaviour and caveats, and I can't recommend doing any of them for this use case (after having used each of them at some point). They are bad solutions to X-Y problems.
An alternative which is much less likely to break things horribly is to create a custom function to do both things:
cdp() {
    cd "$@" && phpunit
}


text:
Q: compute a xi-xj matrix in numpy without loops (by api calls) How to compute a xi-xj matrix in numpy without loops (by api calls)?
Here's what to start with:
import numpy as np
x = np.random.rand(4)
xij = np.matrix([xi-xj for xj in x for xi in x]).reshape(4,4)

A: You can take advantage of broadcasting to subtract x as a column vector from x as a flat array and produce the matrix.
>>> x = np.random.rand(4)

Then:
>>> x - x[:,np.newaxis]
array([[ 0.        ,  0.89175647,  0.80930233,  0.37955823],
       [-0.89175647,  0.        , -0.08245415, -0.51219825],
       [-0.80930233,  0.08245415,  0.        , -0.4297441 ],
       [-0.37955823,  0.51219825,  0.4297441 ,  0.        ]])

If you want a matrix object (and not the default array object) you could write:
np.matrix(x - x[:,np.newaxis])

A: By reshaping the array, you can use the minus operator to calculate what you want
import numpy as np
x = np.random.rand(4)
x = x.reshape(-1,1)
xij = np.matrix(x.T - x)

A: Another alternative is to use np.subtract.outer:
In [35]: x = np.random.rand(4)

In [36]: np.matrix([xi-xj for xj in x for xi in x]).reshape(4,4)
Out[36]:
matrix([[ 0.        ,  0.45365177,  0.07227472, -0.05824887],
        [-0.45365177,  0.        , -0.38137705, -0.51190064],
        [-0.07227472,  0.38137705,  0.        , -0.13052359],
        [ 0.05824887,  0.51190064,  0.13052359,  0.        ]])

In [37]: -np.subtract.outer(x, x)
Out[37]:
array([[-0.        ,  0.45365177,  0.07227472, -0.05824887],
       [-0.45365177, -0.        , -0.38137705, -0.51190064],
       [-0.07227472,  0.38137705, -0.        , -0.13052359],
       [ 0.05824887,  0.51190064,  0.13052359, -0.        ]])

(Note that the result is a numpy array, not a matrix.)


text:
Q: Past continuous use for something that's accomplished
The girl said, "Oh I thought Danny was giving me his scarf because it was so special, but he gave me it because he doesn't support United any more!"

Why past continuous here? Is it because it is a regret? It is not a continuous action, it is completed because the girl has the scarf.

A: This is easier to understand if you think of how this would be expressed in the present tense.
In Present-day English the present continuous is often preferred to the simple present in speaking of unique, individual actions because the simple construction is felt to imply repeated, habitual practise. Thus, if the girl were speaking of the gift as it was occurring, she would not say:

Danny gives me this because it is so special.

although that is entirely acceptable, and three or four generations ago might even have been the most natural way of saying it. Instead, she would say

Danny is giving me this because it is so special.

In your example, she uses the continuous form because she is recalling what she thought at the time; in effect she is 'quoting' herself. The past continuous is a 'backshifted' present continuous. It is only when she realizes her mistake after the fact that she shifts to the simple past, which as you say expresses a completed action.

A: We use the past continuous to describe a scene in the past. — It was raining. The wind was blowing. —
We use the past continuous to describe an event that was in progress at a specific moment in the past. — At 7:30 this morning, I was waiting for the bus. —
We use the past continuous and the past simple together to describe a sudden event that interrupted a longer one. — While I was having lunch, my cousin phoned.

A: This sentence is a little weak on grammar, though it does still sound like spoken English, where grammar can be estimated and not seem strange unless it is written down.
If I had written this, it would have been: The girl said "Oh! I thought Danny had given me his scarf because it was so special, but he gave it to me because he doesn't support United anymore!"
"Was giving": in the past, had been in the process of giving. Brings to mind what he was thinking while he did the action, and that it was the action in process that is important.
"Had given": in the past, has already been done. Brings to mind what she thinks just after she was given the scarf.


text:
Q: How to export a python-highcharts chart for use in flask or django? It's really all in the question but I'm using python-highcharts to build something like this jsfiddle example for inclusion in a Python Flask app. I can get it to work in the Jupyter notebook from where I can save it to an html file or export it as an iframe or div code block. But I can't get any of these to work in the flask html page. The inclusion block in the flask page looks like:

{% if result != None %}

{% endif %}

and the relevant header parts:

I've managed to get it working with pandas-highcharts but in this way I can't send tooltip formatting javascript functions via the dict-to-json-to-browser path... so a solution to either issue would be great.
J.

A: First off:
Writing JS functions in the HTML can (almost) always be prevented!
One of the first principles you should stick to is to separate your static files. More on that here.
You should only pass the variable into your script using Jinja2/DjangoTemplatingLanguage tags like this, and write all your javascript functionality in your separate .js file, which is then imported along with other scripts, by your example:

This way you have nice code separation and it is also (somewhat) more safe.
Which leads us to the problem at hand; importing...
So secondly:
HighCharts needs jQuery to be implemented before it can work. That is probably your problem.
To import jQuery include this to your header:


text:
Q: Excel: Get value from cell indirectly for an offset formula My formula looks like that:
=OFFSET(supergraph!$Q$15;0;0;1;15)

The formula works fine but now I want to get the value of a cell for the supergraph!$Q$15 term.
In my cell I write for instance "X" and I want the term mentioned above to look like supergraph!$X$15, depending on the value of the cell. So in my cell i just write one single letter which should be combined with the number 15 -> X15.
Is it anyhow possible to extract the value from the cell and integrate it in my formula?

A: You can use the INDIRECT formula in your OFFSET formula to achieve this like below:
=OFFSET(INDIRECT(supergraph!$Q$15&3),1,0)

If you have "X" in supergraph!$Q$15, then the output will be =OFFSET(X3,1,0)


text:
Q: Copying column info in C++ I have to copy column info from a database to a struct, the problem is that it takes over 5000 iterations and is very slow. Is there any better way?
The code used is in the .h file:
struct sFieldDef
{
CString m_strQualifier;
CString m_strOwner;
CString m_strTableName;
CString m_strColumnName;
int  m_nDataType;
CString m_strTypeName;
long m_lPrecision;
long m_lLength;
int m_nScale;
int m_nRadix;
int m_nNullable;
};

The code used in the .cpp file:
sFieldDef sTempField;
CColumns rsColumns(m_pDatabase);
rsColumns.Open(CRecordset::snapshot);

while( !rsColumns.IsEOF() )
{
sTempField.m_strQualifier=rsColumns.m_strQualifier;
sTempField.m_strOwner=rsColumns.m_strOwner;
sTempField.m_strTableName=rsColumns.m_strTableName;
sTempField.m_strColumnName=rsColumns.m_strColumnName;
sTempField.m_nDataType=rsColumns.m_nDataType;
sTempField.m_strTypeName=rsColumns.m_strTypeName;
sTempField.m_lPrecision=rsColumns.m_lPrecision;
sTempField.m_lLength=rsColumns.m_lLength;
sTempField.m_nScale=rsColumns.m_nScale;
sTempField.m_nRadix=rsColumns.m_nRadix;
sTempField.m_nNullable=rsColumns.m_nNullable;
pArrFiels->Add(sTempField);
rsColumns.MoveNext();
}

A: You seem to be copying and storing everything in an array of structs, where each struct has identical members with the corresponding record. Usually we use arrays through iterators. So why not provide an iterator to your record-set and avoid copying altogether? You could roughly start like this:
template <typename RS>
class rs_iterator
{
   RS& rs;
public:
   rs_iterator(RS& rs) : rs{rs} { }
   const RS& operator*() { return rs; }
   rs_iterator& operator++() { return rs.MoveNext(), *this; }
   // ...
}

So you not only provide a convenient and standard interface to an array-like data source like a record-set, but you can use it directly in STL-like algorithms requiring bidirectional iterators.
If your CRecordset supports random access, then so would your iterator, easily. Otherwise, random access provision by itself is a good reason to copy (e.g. to sort columns).


text:
Q: Passing ID from url to MVC Controller (AngularJS) I'm new to AngularJS, trying to pass the ID from the url to MVC controller JSON method and then return the JSON to the angular scope.
Here is my MVC Controller:
public ActionResult Client(int clientid)
{
    return View();
}

public JsonResult GetClient(string clientid)
{

    ClientDao clientDao = new ClientDao();

    Client client = clientDao.getClientById(int.Parse(clientid));

    return new JsonResult { Data = client, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

And here is my Angular .js file:
var app = angular.module('myapp', ['ngRoute']);

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/Home/Client/:clientid', {
            controller: 'ClientCtrl'
        })
         .otherwise({
             redirectTo: "/Home/Index"
         })
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
});

app.controller("ClientCtrl", function ($scope, $http, $routeParams) {
    // alert($routeParams.clientid);
$http({
    url: "/Home/GetClient/",
    params: {clientid: $routeParams.clientid},
    method: "get"
})
    .then (function (response) {
        $scope.client = response.data;
    })
});

The problem is that the parameter clientid in the $routeParams is always undefined. How should I fix this ?
Update: Here's how my link looks like: http://something.com/Home/Client/20

A: The way you defined your action in the MVC controller, assuming that the default Route is the only one defined, it expects your url to look like http://something.com/Home/Client?clientid=20
Solutions:

*

*Rename clientId to id

*Add another route in AppStart/RouteConfig that has a clientid param

*Use attribute routing and define your route like [Route("getclient/{clientid}")]


text:
Q: Can you create a title case function in Vega-Lite? is there a way to create or add a title case function in Vega-Lite? I've tried using this Vega Documentation and am currently using a "hacky" way to get Title Case with a replace function, but I'd like to use a more sustainable/acceptable way for getting this done. Below is the current code I'm using, which is temporarily okay but not sustainable:
{"calculate": "replace(replace(replace(replace(replace(replace(datum['classification'],'_',' '),'_',' '),'_',' '),'all','All'),' r',' R'),' j',' J')","as": "Classification"}


text:
Q: How to split string in list Original list:
lines = [['Name0, Location0', 'Phone number0'], ['Name1, Location1', 'Phone number1']]

I want to get new list as below:
newLines = [['Name0', 'Location0', 'Phone number0'], ['Name1', 'Location1', 'Phone number1']]

I tried code below but it is not work (How to split elements in list?):
for line in lines:
    for token in line.split(', '):
        result.append(token)
print(result)

How to make it work?

A: You should know there are two nested list, so there should be two nested for loop to iterate the list. And you should use another for loop to iterate the split() result. The code may be like this:
lines = [['Name0, Location0', 'Phone number0'],
         ['Name1, Location1', 'Phone number1']]
result = []
for line in lines:
    result.append([])
    for fields in line:
        for token in fields.split(', '):
            result[-1].append(token)
print(result)

The output:
[['Name0', 'Location0', 'Phone number0'], ['Name1', 'Location1', 'Phone number1']]

A: You would have to iterate the strings in the sub-lists first before you can split each of the strings into tokens:
[[token for tokens in line for token in tokens.split(', ')] for line in lines]

This returns:
[['Name0', 'Location0', 'Phone number0'], ['Name1', 'Location1', 'Phone number1']]

A: First you need to loop through the inner array as well, as it looks like you'll be getting an error for trying to split a list. As the split will be actioning on this line:
['Name0, Location0', 'Phone number0']

So you need another loop to action on the strings like:
result = []
# loop the array
for line in lines:
    # If you want to keep the inner arrays, reset each loop
    current = []
    # Now loop the inner array
    for item in line:
        for token in item.split(', '):
            # Add the items to an array
            current.append(token)
    # Add these inner arrays to the larger array
    result.append(current)

A: Try This
lines = [['Name0, Location0', 'Phone number0'], ['Name1, Location1', 'Phone number1']]

newLine = []

for line in lines:
    temp = []
    for element in line:
        temp.extend(element.split(', '))
    newLine.append(temp)


text:
Q: xlCategory error in vba I have a graph that has dates on the x-axis with minimum and maximum values using Excel VBA.
Set rng = ActiveWorkbook.Worksheets("Project Data").Range("A5:A202")

minimum = Application.WorksheetFunction.Min(rng)
maximum = Application.WorksheetFunction.Max(rng)

With ActiveSheet.ChartObjects("Initiation").Chart
    With .Axes(xlCategory)
        .MinimumScale = minimum
        .MaximumScale = maximum
    End With
    With .Axes(xlValue, xlPrimary)
        .MinimumScale = 0
        .MaximumScale = 100
    End With
End With

The second internal "With" using "xlValue" works fine.
The first internal "With" using "xlCategory" causes a runtime error: Method "MinimumScale" of object "Axis" failed.
I cannot figure out what the problem is.  Does anyone know what is is?
Thanks much.

A: Correct these lines accordingly
Dim minimum As Double: minimum = Cdbl(Application.WorksheetFunction.Min(rng))
Dim maximum As Double: maximum = Cdbl(Application.WorksheetFunction.Max(rng))

As per your code, the method fails because of the type mismatch. minimum and maximum are declared without Dim which makes them variant rather than double datatype and your method according to MSDN is Read/write Double.
Add Option Explicit in your VBA editor so that you will get a compiler error rather a runtime error. This means that you will alerted if there is a missing dim.
Add Option Explicit only once in your code. It has to be outside outside of your subroutines.


text:
Q: Could not find RubyGem i18n I'm relatively new to Rails and Ruby, but when I try do rails -s or rails -v I get this error
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:777:in `report_activate_error': Could not find RubyGem i18n (>= 0.6.4, ~> 0.6) (Gem::LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:211:in `activate'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:246:in `activate'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:245:in `each'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:245:in `activate'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:246:in `activate'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:245:in `each'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:245:in `activate'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:1056:in `gem'
from /usr/local/rvm/gems/ruby-2.1.1/bin/rails:22
from /usr/local/rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15

Not sure what's causing it, or how I can fix it.
EDIT
After trying bundle install I get this error:
Gemfile syntax error compile error
on line 73: syntax error, unexpected ':', expecting $end
gem 'thin', group: [:production]
              ^

Line 73 in my Gemfile
gem 'thin', group: [:production]

EDIT 2
Gemfile Gist

A: The syntax is off. Just use this
group :production do
  gem 'thin'
end


text:
Q: Error while generating dynamic URL: The reference to entity "retURL" must end with the ';' delimiter <force:recordData aura:id="recordLoader" recordId="{!v.recordId}" targetFields="{!v.simpleRecord}" fields="CaseNumber" />
{!v.simpleRecord.CaseNumber}
{!v.recordId}

    <lightning:button label="Attach file">
        Attach file
    </lightning:button>

Failed to save CustomAttachmentRelatedList.cmp: c:CustomAttachmentRelatedList:17,118: ParseError at [row,col]:[18,118] Message: The reference to entity "retURL" must end with the ';' delimiter.: Source

I'm getting the above error not sure what is wrong in my URL.
My Expected URL looks like:

https://garvitasb2bsc--4hdev.cs60.my.salesforce.com/p/attach/NoteAttach?pid=5003C000003bdmt&parentname=0114054744&retURL=%2F5003C000003bdmtQAA where '500..' is case id, '001' is the case number.

A: You cannot nest the merge fields. URL must be generated inside the single merge field {!}, and inside you can concatenate the variables and string. Following would be the psuedo code and the query parameters must be separated by ampersand sign (&):
{!'/p/attach/NoteAttach?pid=' + v.recordId +
    '&parentname=' + v.simpleRecord.CaseNumber +
    '&retURL=%2F'+ v.recordId }

Note the ampersand (&) is probably reserved character, replace that with &.


text:
Q: Apply a CSS rule for a specific button that belongs to a class I have for example a web page that displays blog posts. Each blog posts has a 'comment' button and a 'like' button. When the user likes a post I want to apply a CSS style for that particular button. I have tried in many ways for example using "getElementsByClassName" to get the class of the button but it applies the rule for all the buttons. So if I have 5 blog posts all of them appear to be liked when I just like one of them. This is my JS code:
Template.post.events({
"click .like":function(event) {
 var likeButton1=document.getElementsByClassName('like');
 $(likeButton1).addClass('likeClick');
 var nrLikes=parseInt(this.likes);
 blogPosts.update(
   this._id,{
     $set:{"likes":nrLikes+1}
  }
);
}
});

And this is my html code:
<input class="like" type="submit" name="like" value="Like"/>

Basically I need the instance of that particular clicked button, how do I do this? Thanks in advance!

A: document.getElementsByClassName returns a HTMLCollection. You can iterate over this collection and use array methods by doing
Array.prototype.forEach.call(HTMLCollection,callBackFunction)

Inside the callback function you can add an event listener to add the class on the element on click on it.
Below is a snippet which may be useful.
classList.add will add a new class to the existing element

var likeButton1 = document.getElementsByClassName('like');
Array.prototype.forEach.call(likeButton1, function(el) {
  el.addEventListener('click', function() {

    this.classList.add('likeClick')
  })
});
.likeClick {
  color: green
}
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />
<input class="like" type="submit" name="like" value="Like" />

A: Instead of selecting all the elements with the class like, try targetng the specific element that received the click event (using the event object you're passing into your "click . like" handler). This assumes the event in this case represents an event object that has a target property, of course.
var likeButton1= event.target; // this will be the element that received the `click`
$(likeButton1).addClass('likeClick');

A: It sounds like you want to use a CSS psuedo class. That is how you can style a button that has been clicked or visited. This can all be done in your css file.
Example css file:
input .like {
  (some css styling)
}

input .like:visited {
  (different css styling)
}

You can also use link, hover, and active psuedo classes. Here's the reference:
https://www.w3schools.com/css/css_pseudo_classes.asp

A: use this jQuery Code
 $('.class_name').each(function () {
       $(this).addClass('likeClick');
    });


text:
Q: Rationale for taking second derivative in least squares estimation? I am reading DeGroot and he talks about how to derive the b0 and b1 coefficients using LS estimation.  I understand everything except the last part where he talks about taking the second derivative of the cost function.  What is the rationale for doing this?  Is this to check if we are at minimum or maximum or is there more to it than that?  I thought the cost function is convex.

A: Recall from single-variable calculus that th derivative of a function being zero does not guarantee that point to be a minimum. Indeed, the point could be a maximum (e.g., $f(x)=-x^2$) or neither a maximum nor a minimum (e.g., $f(x)=x^3$). The second derivative shows us if the point is a minimum or not.
There is similar logic in multivariable calculus related to the second and mixed partial derivatives in the Hessian matrix.
Therefore, just because we found a point where the loss function has a derivative of zero does not mean that the point must be a minimum. Checking the higher-order derivatives in the Hessian matrix confirms that the point is indeed the desired minimum.

A: There are first and second order conditions of minimum of the function at a point $x$:
$$F.O.C.: f'(x)=0\\S.O.C.: f''(x)>0$$
It's in basic calculus curriculum in high schools.


text:
Q: Techniques Regarding Improving Performance of Mac OS X I am a Windows user and used to use:

*

*ccleaner for managing installed application

*ccleaner for managing registries of windows

*disk defragmentation, ChekDisk, for disk (built-in Windows)

*ccleaner for clearing my all history at a single shot.

*I would use boost xp to manage xp.

*Similarly, I would increase the virtual memory from options for faster performance.

I was explaining here - that If I am a windows user I do above things to manage my OS properly.
I want same here for Mac OS X.
I would like to find out your techniques regarding managing Mac OS X.
One technique per answer please & if possible please give brief description.

A: You really don't need to do all that at all.
Since most OS X applications don't install by putting files all over the drive, you can generally uninstall an app simply by deleting it from the /Applications or ~/Applications folder.  The rare application that needs one should include an uninstaller (and again, this is rare).
There is no registry to manage.
HFS+ doesn't require manual defragmentation.
You're best letting the OS manage the virtual memory (as you indeed are in most XP configs as well).
If you're looking for something like BoostXP to manage lots of hidden settings, etc, try OnyX.

A: http://noahlittle.wordpress.com/2008/01/08/macintosh-maintenance-basics-from-typical-mac-user-podcast/
http://www.thexlab.com/faqs/maintainingmacosx.html

i think the only periodic maintenance most people do is "Repair disk permissions" and "Verify Disk" using Disk Utility.  One one mac, that wouldn't go, so i had to do a safe boot every few months (hold down Shift while booting)


text:
Q: staticfile is not working on other page, but index I am new to Python on Django. I am making a simple website, but I have a problem with staticfile. I can make it load boostrap and some images on static folder, but it just work correctly when it is in index page, if I click to other page, staticfile is not working anymore. This is my setting.py. pls tell me what I have to do to solve this problem, thanks
This is my setting.py:
STATIC_URL = '/static/'

STATIC_ROOT = '/static/static_root/'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    '/static/',
)

views.py:
def index(request):
    list_post_Anh = Blog.objects.filter(category_id=1).order_by('-posted')
    list_post_Uc = Blog.objects.filter(category_id=2).order_by('-posted')
    list_post_Ca = Blog.objects.filter(category_id=3).order_by('-posted')
    list_post_Us = Blog.objects.filter(category_id=4).order_by('-posted')

    context = {'listbloganh':list_post_Anh, 'listbloguc':list_post_Uc, 'listblogca':list_post_Ca, 'listblogus':list_post_Us}
    return render(request, 'index.html', context)

def view_post(request, slug):
    getpost = get_object_or_404(Blog, slug=slug)
    context = {'post':getpost}
    return render(request, 'content.html', context)

urls.py:
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'WebDuHoc.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'blog.views.index', name='index'),
    url(r'^baiviet/(?P<slug>[a-zA-Z0-9_-]+)/$', 'blog.views.view_post', name='content'),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

A: Hi I use this (I am new in Django but it works for me):
settings.py
"""
    Django settings for simplesite project.

    For more information on this file, see
    https://docs.djangoproject.com/en/1.7/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.7/ref/settings/
    """

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    import os
    import simplesite
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    TEMPLATE_DIRS = (
                     os.path.join(os.path.dirname(__file__), "templates").replace ('\\','/'),
    )

    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '8x*)8mtzd86&634n=kt!gr=9m**916trc&wd*qb(4uvgpcad3n'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    TEMPLATE_DEBUG = True

    ALLOWED_HOSTS = []

    # Application definition

    INSTALLED_APPS = (
        'bootstrap3',
        'django_admin_bootstrapped.bootstrap3',
        'django_admin_bootstrapped',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'homepage',
        'simpleapp',
    )

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.locale.LocaleMiddleware',
    )

    # http://django-bootstrap3.readthedocs.org/en/latest/settings.html
    BOOTSTRAP3= {

                'base_url': '/static/bootstrap3',
                'css_url': '/static/bootstrap3/css/bootstrap.min.css',

    }

    SESSION_EXPIRE_AT_BROWSER_CLOSE = True

    ROOT_URLCONF = 'simplesite.urls'

    WSGI_APPLICATION = 'simplesite.wsgi.application'

    # Database
    # https://docs.djangoproject.com/en/1.7/ref/settings/#databases

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

    # Internationalization
    # https://docs.djangoproject.com/en/1.7/topics/i18n/
    # default language, it will be used, if django can't recognize user's language
    LANGUAGE_CODE = 'en-us'

    # list of activated languages
    LANGUAGES = (
        ('en', 'English'),
        ('it', 'Italian'),
    )

    TIME_ZONE = 'UTC'

    # enable django's translation system
    USE_I18N = True

    USE_L10N = True

    USE_TZ = True

    # specify path for translation files
    LOCALE_PATHS = (
        os.path.join(os.path.dirname(__file__), 'locale'),
    )

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.7/howto/static-files/
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "static"),
    )

    STATIC_URL = '/static/'

urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
                       url(r'^', include('homepage.urls')),
                       url(r'^admin/', include(admin.site.urls)),
                       url(r'^', include('simpleapp.urls')),
)

some.html
{% extends 'base.html' %}
{% load staticfiles %}
{%block content%}
...
  //here I call js files which I put in static folder

GO

...
{% endblock content %}

example of directory tree
MyProject
    -MyProject
        -settings.py
        -...
    -MyApp
        - ...
    -static
        -js
           -...
    -manage.py
    -...

Also look at THIS QUESTION.


text:
Q: Linq to Sql with ADO.Net Data Services I am considering using ADO.Net Data Services in a project for the purpose of getting data over to a Silverlight client.  I'd like to use the Data Services with my existing Linq To Sql classes and designer.  I probably could regenerate everything as ADO.Net entity objects, but I feel this would be a bad design for DRY reasons.
I'm new to ADO.Net Data services, so I've been reading up on it, but most of the articles I'm finding are pre-release so I've a got a few questions.
First, I've read that while you can use the data services with Linq to Sql, you can only use them for reading data, but not writing.  Is this still the case?
Second, I want to have permissions so only certain users can view certain tables.  I'm using a custom permission system that goes beyond Asp.net Membership and Roles.  Does ADO.Net Data Services provide a way to custom authorize access?

A: 1) Yes, at this time, ADO.net only has an implementation of IUpdateable for Entity Framework. but I'm pretty sure you can find free implementations out there for LinqToSQL (that's one of the first thing quite a few people did)
2) You can easily apply whateverauhtorization scheme you need by filtering down (or simply refusing access to) a given set through "QueryInterceptors". These are basically methods on your service that are applied whenever someone sends a query for a given set. That way you can apply a more restrictive filter based on the user's rights, or simply raise an exception


text:
Q: $S=\{a,b,c,d\}$ is a finite sample space. Let $A=\{a,b,c\}, B=\{b,c\}$, and $C=\{c,d\}$. Assume $P(A)=0.8, P(B)=0.5$ and $P(C)=0.4$. $S=\{a,b,c,d\}$ is a finite sample space.
Let $A=\{a,b,c\}, B=\{b,c\}$, and $C=\{c,d\}$.
Assume $P(A)=0.8, P(B)=0.5$ and $P(C)=0.4$.
Find $P(\{a\}), P({a,d})$ and $P(C \text{ and } {\sim} B)?$

A: Denoting $p_a$ for the probability $P(\{a\})$ (and likewise for $b,c,d$) we have the equalities:

*

*$p_{a}+p_{b}+p_{c}+p_{d}=P\left(S\right)=1$

*$p_{a}+p_{b}+p_{c}=P\left(A\right)=0.8$

*$p_{b}+p_{c}=P\left(B\right)=0.5$

*$p_{c}+p_{d}=P\left(C\right)=0.4$
These equalities enable you to find $p_a,p_b,p_c,p_d$.
Further observe that

*

*$P(\{a\})=p_a$

*$P(\{a,d\})=p_a+p_d$

*$C\cap B^{\complement}=\{d\}$ so that $P(C\cap B^{\complement})=p_d$


text:
Q: Converse of the first fundamental homomorphism theorem I have a question arising from the "Fundamental Homomorphism Theorem" as applied to groups (i.e. that the existence of a homomorphism $h: G\to H$ with kernel $J$ implies $H$ is isomorphic to the quotient group $G/J$).
As I understand it, Category Theory can be used to show that the rough converse is also true - i.e., that if a quotient group $G/J$ (where $J$ is a normal subgroup of $G$) is isomorphic to some group $H$, then there is a homomorphism $h: G\to H$ with kernel $J$.
Is this correct?
If so, is there a proof of the latter using only ideas from "standard" undergrad algebra?

A: This is the easy direction: there is a natural map $q: G\rightarrow G/N$, given by $g\mapsto gN$. If $i: G/N\cong H$, then $q\circ i$ is a surjective homomorphism from $G$ onto $H$ with kernel $N$.


text:
Q: disable column on post and user list I'm looking for the way to disable user column (posts and role) from users list. like you see in the picture

I'm also search how to disable column author on page list (in red on the picture)

A: You can use the manage_{$screen->id}_columns hooks for this.
To manage user columns we can use manage_users_columns which is passed an array of columns and whatever we don't want we can unset().
/**
 * Manage User Admin Display Table Columns
 *
 * @param Array $columns
 *      [cb]        => <input type="checkbox" />
 *      [username]  => Username
 *      [name]      => Name
 *      [email]     => Email
 *      [role]      => Role
 *      [posts]     => Posts
 *
 * @return Array $columns
 */
function wpseq_270133_users( $columns ) {

    unset( $columns['role'] );
    unset( $columns['posts'] );

    return $columns;
}
add_filter( 'manage_users_columns', 'wpseq_270133_users' );

Pages is a very similar fashion but instead of a users hook we need to specify pages:
/**
 * Manage Pages Admin Display Table Columns
 *
 * @param Array $columns
 *      [cb]        => <input type="checkbox" />
 *      [title]     => Title
 *      [author]    => Author
 *      [date]      => Date
 *
 * @return Array $columns
 */
function wpseq_270133_pages( $columns ) {

    unset( $columns['author'] );

    return $columns;
}
add_filter( 'manage_pages_columns', 'wpseq_270133_pages' );

There's also checkboxes under Screen Options to remove these columns for yourself whenever logged in, the above code will hide these columns from every role.


text:
Q: Sum two values on the previous row I have two columns in my dataframe: "Cust_ID" and "Fill_days". I need to add a column for "Adjusted Days", like this:

The idea: for every first row for "Cust_ID", the "Adjusted Days" value should be 0. For the following rows,
if previous row's "Fill_days" + "Adjusted Days" < 0 then 0, else previous row's "Fill_days" + "Adjusted Days".
If we need to do this in Excel. the following formula is used:
C2=0
C3=IF(B2+C2<0,0,B2+C2)
C4=IF(B3+C3<0,0,B3+C3)

I was able to write the code using pandas, however the code is slow.
How to do it in Spark? I use Spark 3.2.1.

A: First of all, you need a column for order. Spark does not know the order. All the rows can be at any position unless you have a column which can tell exact order. I have added the column "order".
Secondly, referencing the same column is not possible per se. You need a workaround. The following will collect date into a list for every "Cust_ID" and do operations only within this list. When it's done, explode the result using inline.
Input:
from pyspark.sql import functions as F
df = spark.createDataFrame(
    [(1, 1, 5),
     (1, 2, 2),
     (1, 3, 1),
     (1, 4, -9),
     (1, 5, -2),
     (1, 6, 9),
     (5, 1, -2),
     (5, 2, 1),
     (5, 3, -1)],
    ['Cust_ID', 'order', 'Fill_days'])

Script:
df = df.groupBy('Cust_ID').agg(
    F.aggregate(
        F.array_sort(F.collect_list(F.struct('order', 'Fill_days'))),
        F.expr("array(struct(bigint(null) order, 0L Fill_days, 0L Adjusted_Days))"),
        lambda acc, x: F.array_union(
            acc,
            F.array(x.withField(
                'Adjusted_Days',
                F.greatest(F.lit(0), F.element_at(acc, -1)['Fill_days'] + F.element_at(acc, -1)['Adjusted_Days'])
            ))
        )
    ).alias('a')
)
df = df.selectExpr("Cust_ID", "inline(slice(a, 2, size(a)))")

df.show()
# +-------+-----+---------+-------------+
# |Cust_ID|order|Fill_days|Adjusted_Days|
# +-------+-----+---------+-------------+
# |1      |1    |5        |0            |
# |1      |2    |2        |5            |
# |1      |3    |1        |7            |
# |1      |4    |-9       |8            |
# |1      |5    |-2       |0            |
# |1      |6    |9        |0            |
# |5      |1    |-2       |0            |
# |5      |2    |1        |0            |
# |5      |3    |-1       |1            |
# +-------+-----+---------+-------------+

For understanding, please analyze this answer, as it's not an easy task to explain it for the 2nd time.


text:
Q: Iterating within bounds of a 2D list (matrix) in python I would like to iterate over a 2D list. I understand that I can do this with:
for j in range(columns):
     for i in range(rows):
        print depth[i][j],

But is there a more beautiful way. I tried:
for (x in range(rows)) and (y in range(columns)):
     print(depth[x][y])

But this given me an IndentationError.:
Thanks
EDIT:
    what if i want to set bounds for x and y. Say I have a 4x4 matrix(using list to represent it). For a given element I want to get 3x3 matrix around it, but i want to remain within the bounds of the original matrix. Suppose I am at (3,1), taking x = range(3-2, 3+3) = [1,2,3,4,5] and y = range(1-2,1+3) = [-1, 0, 1, 2, 3] would take me outside the bounds of the original matrix.

A: You can use itertools.product, or write a double-loop generator-expression like:
for (i,j) in ( (i,j) for i in range(rows) for j in range(columns) ):
    print depth[i][j]

or
for d in ( depth[i][j] for i in range(rows) for j in range(columns) ): ...

also, if you don't actually need the indices, but only to iterate over the values of depth, you can do:
for row in depth:
   for v in row:
      print

and even if you do need the indices, it is more pythonic to use enumerate:
for row_index, row in enumerate(depth):
   for col_index, v in enumerate(row):
      print 'depth[%d][%d]=%s' % (row_index, col_index, v)

A: This can be done with:
for depth in (depth[x][y] for x in range(rows) for y in range(columns)):
    print depth

Edit:
If you want bounds you can use the min and max builtins :
for x in range( max(x_min,col-2), min(x_max,col+3) ):
    #do stuff


text:
Q: Vows callback testing in Node.js generating anonymous errors I am new to the continuation passing style of asynchronous computation used in Node.js applications, and I'm struggling to get a grip on some fairly basic code.
I am trying to write a library which will create an imap interface to imap.gmail.com, and I am trying to follow BDD with 'vows'.js' (with varying levels of success. I'm definitely not following the full red->code->green cycle that I should be, but it's hard to get started in a language that way).
The relevant test case looks like this:
var gmail = require('../lib/gmail.js'),
    vows = require('vows'),
    assert = require('assert'),
    fs = require('fs');

vows.describe('Basic interface tests').addBatch({
  'A GMailInterface object can': {
    topic: function() {
      var gm = Object.create(gmail.GMailInterface);
      var settings_file = 'test/test_settings.json';
      var settings = JSON.parse(fs.readFileSync(settings_file));
      var that = this;
      gm.connect(settings.email,settings.password,function() {
        that.callback(gm); // ERROR BEING GENERATED HERE
      });
    },
     // ACTUAL VOWS OMITTED - the following is just a test of the callback
    'find an email' : {
      topic: function(gm) {
        console.log(">>>",gm);
      },
    }
  }
}).export(module)

If I write a console.log message right above the line with "ERROR BEING GENERATED HERE", it will print. It will not if I put a message below it. The output of the test gives the following error:
node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: Uncaught, unspecified 'error' event.
    at EventEmitter.<anonymous> (events.js:50:15)
    at EventEmitter.emit (/Users/eblume/Repositories/my_stuff/gmail/node_modules/vows/lib/vows.js:236:24)
    at /Users/eblume/Repositories/my_stuff/gmail/node_modules/vows/lib/vows/context.js:31:52
    at Object.callback (/Users/eblume/Repositories/my_stuff/gmail/node_modules/vows/lib/vows/context.js:46:29)
    at Array.0 (/Users/eblume/Repositories/my_stuff/gmail/test/gmail_test.js:17:14)
    at EventEmitter._tickCallback (node.js:192:40)

The code in gmail.js is a bit too much to post here, but here is what I think is the relevant section - I can post more if you ask a question below.
gm.connect = function(username,password,cb) {
  var self = this;
  self.conn = new ImapConnection({
    username: username,
    password: password,
    host: 'imap.gmail.com',
    port: 993,
    secure: true
  });

  async.series([
    function(callback){self.conn.connect(callback); },
    function(callback){self.conn.openBox('[Gmail]/All Mail',true,callback);}
  ],
  function(err,results) {
    if (err) {
      die(err);
    }
    process.nextTick(cb);
  });
};

Where might I be going wrong? Thanks for any help!

A: I recommend reading up on how 'this' works. If nobody's been messing with it the 'that' of that.callback refers to the parent object which is labeled with a literal string as 'A GMailInterface object can' .
I suspect it's the this factor tripping you up. 'callback' should be defined as a method of the same object as the 'topic' method the way you have things set up and that doesn't strike me as the way it's meant to work.
'this' typically refers to nearest ancestor/parent object by default. It ignores wrapping functions unless they're used as constructors using the 'new' keyword in which case it indicates the object instance. In the case of event callbacks in the DOM (browser JS - not node.js which I don't know in-depth as far as events), it typically refers to the object that's had an event triggered on it.
There's no real kludge being fixed with that and self. We just tend to use those to be certain we're addressing the top object in cases where an object has aggregate objects.


text: Q: Is there such a term as "modern street food era"? I wonder if there is such a word as "modern street food era"? I do realize that street food was popular in ancient Rome and in Medieval Times, but can we just add the adjective "modern" to refer to our days when street food is so very popular?


text:
Q: how do you show functional dependency in an er diagram? how do you show functional dependency in an er diagram? My assignment says "All functional dependencies should be shown, even if all or some tables are already normalized".
Can someone help me with what this means?

A: Learn what a "functional dependency" (FD) is. Read a textbook or even Wikipedia. (Do not take information modeling advice from someone who doesn't know what a FD is.) You cannot actually determine a table's "candidate keys" (CKs) without knowing the FDs. (Ie its unique column sets that don't contain smaller unique column sets.) One CK can be picked as "primary key" (PK).
A FD is a kind of condition/constraint on a table/relation value or on a base table/relation (ie table/relation variable) that only holds such constrained table values. If a FD is present then typically a bunch of other related "implied" ones are too. So we usually find a "canonical cover" which is a set of FDs that imply all the original ones and the ones they imply but which cannot be made smaller. It captures all the relevant information concisely. If someone asks for the FDs of a table then they generally mean they want a canonical cover.
A FD is written as a source/determining column/attribute set followed by a rightward arrow followed by a target/determined attribute set. An ER diagram does not express FDs. (Certain FDs are implied by CKs though.) Use your ER diagramming tool's text annotations. (Naturally, ask the person requesting the FDs what they want.)
Normalization replaces a table/relation by smaller component tables/relations that natural join back to it. In general some of those FDs are no longer associated with any component. In practice given some tables/relations that arose from normalization there will be FDs that held in original tables that are relevant and hold in natural joins of those components even though they do not hold in any component. It is reasonable to document those. But then, there are lots of relevant constraints that ER diagrams cannot express, and some particular ones they can.


text:
Q: Resample PCM network stream to 8000Hz 8-bit mono via libsndfile sf_open_virtual function My goal is to take a PCM stream in Node.js that is, even for example, 44100Hz 16 bit stereo, and then resample it to 8000 Hz 8 bit mono to then be encoded into Opus and then streamed.
My thought was to try making bindings for libsndfile in C++ and using sf_open_virtual function for resampling on the stream. However:

*

*How can I reply to its callback function requesting a certain amount
of data (found here:
http://www.mega-nerd.com/libsndfile/api.html#open_virtual) if my
program is still receiving data from the network? Do I just let it
hang in a loop until the loop detects that the buffer is a certain
percent full?

*Since the PCM data is going to be headerless, how can
I specify the format type for libsndfile to expect?

Or am I over-complicating things totally?


text:
Q: Mac Equivalent to Windows CMD f8 In Windows if I entered several commands and built up a little history, I could execute previous commands by typing a prefix at the command line and pressing F8 (Windows Keyboard shortcuts) to cycle through all commands in my history matching that prefix. Is there any equivalent in MacOS?

By way of example If I sequentially executed these commands
dir .
echo IgnoreThis
dir /b %TEMP%
dir /s .
dir /b %USERPROFILE%
echo IgnoreThis

If I then entered
dir /bF8
I would first receive an autocompletion to
dir /b %TEMP%

and if I pressed F8 again it would autocomplete to
dir /b %USERPROFILE%

For another example if I instead entered
dirF8
For the first, second, and third times I pressed F8 I would get
dir .
dir /b %TEMP%
dir /s .

A: Add this to your ~/.inputrc:

# ↑
"\e[A":history-search-backward
# ↓
"\e[B":history-search-forward

# Try to stay at the same the cursor position when moving through the history.
set history-preserve-point on

The way this operation works is you first type your partial command prefix and begin pressing ↑ and ↓ arrows to begin cycling in reverse and forward respectively through the command history matches to your typed prefix.

A: You may find that the Mac shell (called BASH, one of many Unix shells) is quite a bit more powerful than the Windows DOS/Powershell prompt.
Briefly yes but autocomplete works very differently on the Mac and follows Unix shell conventions in place long before Windows/DOS was a gleam in Bill Gates eye.
The up and down arrows will scroll backwards and forwards through the commands you have already entered. And even if you quit out of terminal all that history is remembered across sessions. Well not back to the beginning of time but BASH remembers a substantial history of commands.
You can string multiple commands together with "&&" :
cd /users/steve/desktop && rem picture.jpg

That will CD to my user profile and then delete a file called picture.jpg
Books (literally) have been written on the BASH shell and a little searching around the internet will come up with quite a lot of information on navigating, using, programming/scripting. if you don't specify the BASH shell on macOS you'll get a lot of Linux results which are generally applicable but many of the commands are different.
If you are really interested in geeking out you can change to a different shell, there are several built-in, or another terminal program that has more features than the one that comes with macOS. Finding and using said options will be left up to you in the spirit of exploration.


text:
Q: Cartesian product of a list of tuples I would to generate the Cartesian product of a list of tuples.
I am starting with a flat text file whose data looks like this:
1 1
0 1
2 2
3 3
0 5
3 4
5 6
0 -3
-2 -2

I then get it to a point where I have a list of tuples and the values are integers (converted from strings):
from csv import reader

f = reader(open('e:\\ucsd\\big_data_analytics\\programs\\week_1\\pa1\\data.txt', 'r'))
flat_list = [item for sublist in list(f) for item in sublist]
res = [tuple(map(int, sub.split(" "))) for sub in flat_list]
print(res)  # [(1, 1), (0, 1), (2, 2), (3, 3), (0, 5), (3, 4), (5, 6), (0, -3), (-2, -2)]

At this point I would the Cartesian product of the tuples in 'res'.
I've used Cartesian product in this way:
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
shirts = [(color, size) for color in colors for size in sizes]
print(shirts)

I am not sure of how to get the Cartesian product of the list of tuples above.
It's the format that has me stumped.

A: This did the trick:
result = [(x, y) for x in res for y in res]


text:
Q: Мастер страница и Роуты в AngularJS. ASP.NET Core Пытаюсь переписать свое приложение на AngularJS. Сам сайт простой, нет практический ничего кроме котроллеров которые возвращают вьюхи. Теперь архитертура немного другая. В стартапе я определяю начальную страницу. Она уже не cshmtl а просто html. Она запускается без проблем.
Код стартапа где я убираю архитектуру МВС.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();

        }
        else
        {
            app.UseExceptionHandler("/Home/Error");

        }

        DefaultFilesOptions defoptions = new DefaultFilesOptions();

        var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(locOptions.Value);

        defoptions.DefaultFileNames.Clear();
        defoptions.DefaultFileNames.Add("app/pages/index/index.html");
        app.UseDefaultFiles(defoptions);

        app.Use(async (context, next) =>
        {
            await next();
            if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
            {
                context.Request.Path = "/index.html";
                context.Response.StatusCode = 200;
                await next();
            }
        });

        //var options = new RewriteOptions().AddRedirectToHttps();
        //app.UseRewriter(options);

        app.UseStaticFiles();
        app.UseSession();
        app.UseAuthentication();
        //app.UseMvc(routes =>
        //{
        //    routes.MapRoute(
        //        name: "areas",
        //        template: "{area:exists}/{controller=Home}/{action=Index}");

        //    routes.MapRoute(
        //        name: "default",
        //        template: "{controller=Home}/{action=Index}/{id?}");
        //});
    }

Далее я создал приминитивный контроллерJS и модуль
var app = angular.module("app", ['ngRoute']);

app.config(function ($routeProvider, $locationProvider) {
   $routeProvider
      .when('/Home', {
          templateUrl: 'app/pages/home/Home.html',
          controller: 'testController'
      });

});

Ну и сама страница Index которая нормально работает по умолчанию, но там есть хедер на котором просан роут(первый линк) как видете первая кнопка уже прописана как в роуте, но у меня нет перехода, получаю что такой страницы не существует. Как я только не писал. #! и # как угодно, роуты не пашут, может класс стартап я неправильно переопределяю? или каких-то библеотек не подключил?
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link href="/css/site.css" rel="stylesheet" />
    <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    <link href="/css/site.css" rel="stylesheet" />

    <meta name="google-site-verification"

страница хедера где ссылка на другую страницу. Первый линк /Home

                        страница

                        страница

                        страница

                        страница

                        Страница

                        Блог

                        Трейдерам