text:
Q: Appending query strings to URL
"Appending an url with appendages that were already in the previous url?"
  That's the most confusing title -- I know. But I can't think of a better way to explain it.

Maybe the below example will help.
I have URL 1: http://example.com/?value=xyz&stuff=abc
If someone clicks on a link within the page, can I pass along the appended values?
ie: http://www.example.org/?value=xyz&stuff=abc
Thanks and sorry for being such a noob.

A: These appendages you ask about is the actual so called query part of an URI:
<scheme>://<authority><path>?<query>

  foo://example.com:8042/over/there?name=ferret#nose
  \_/   \______________/\_________/ \_________/ \__/
   |           |            |            |        |
scheme     authority       path        query   fragment

Taken from: 3. Syntax Components (RFC 3986) https://www.rfc-editor.org/rfc/rfc3986#page-16

You then need a helper function that is append the (optional) <query> to an existing <scheme>://<authority><path> part. I ignore the <fragment> for this exmaple, as it would needed to be added at the end and I want to leave something as an exercise:
function href_append_query($href)
{
    $query = isset($_SERVER['QUERY_STRING'])
        ? '?' . $_SERVER['QUERY_STRING']
        : ''
    ;

    $query = strtr(
        $query, [
            '"' => '"',
            "'" => ''',
            '&' => '&'
        ]
    );

    return $href . $query;
}

And it's usage:
<a href="<?=href_append_query('http://step2.com/')?>Some link

This little function will ensure that the exisitng QUERY_STRING which can be obtained via $_SERVERDocs is encoded for HTML output.

A: If links are built with PHP, just append the original query string to them:
<a href="http://step2.com/?<?php echo $_SERVER['QUERY_STRING']; ?>">Some link

In JavaScript, just append the value of window.location.search to all the links you need to 'pass' the query string.

A: You could also use js/jquery to append the existing query string to each link on the page:
 $(function() {
    $('a').each(function() {
      link = $(this).attr('href');
      query = window.location.search;
      if (link.indexOf('?') !== -1 && query !== '') {
        query = query.replace('?','&');
      }
      $(this).attr('href',link+query);
    });
  });


text:
Q: Executable creation. Which path compatible Win10, Win7 and XP? Executable creation. Which path compatible Win10, Win7 and XP?
To create an executable file, this line of codes works on windows7 but does not work on XP =>
WriteAllBytes("C:\Program Files (x86)\File_Name.exe", My.Resources.File_Name)
On the other hand, the following line of codes runs on XP but does not work on Win7 =>
WriteAllBytes("C:\Program Files\File_Name.exe", My.Resources.File_Name)
What would be a compatible Win10, Win7 and XP SP3 path?
I tried the following environment variable, but it does not work =>
WriteAllBytes("%ProgramFiles%\File_Name.exe", My.Resources.File_Name)
Thank you for bringing me information on this subject.
WriteAllBytes("C:\Program Files(x86)\File_Name.exe", My.Resources.File_Name)

WriteAllBytes("C:\Program Files\File_Name.exe", My.Resources.File_Name)

WriteAllBytes("%ProgramFiles%\File_Name.exe", My.Resources.File_Name)

Depending on the different systems, the file is not created.

A: Use the Environment.GetFolderPath method to find the actual path (which may not be in the C: drive).
Note that you will need admin privileges to write to it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not getting android push notification messages from gcm I am developing an android application with push notification using GCM (step by step: http://developer.android.com/google/gcm/index.html)  but not all devices getting notifications from GCM server.
I debugged it and I saw that my 3d-party server sends the message successfully.
When i send to my Galaxy-S4 device I get the notification but in my Galaxy-S2 i don't get.
AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission android:name="com.example.gcm.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />

<receiver
        android:name=".gcm.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
             <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.freco" />
        </intent-filter>
    </receiver>
    <service android:name=".gcm.GcmIntentService" />

I think the other code its not necessary here because its works fine in Galaxy-S4.
What do you think is it ?

A: What's the package of your app, com.freco (as defined in the category of the broadcast receiver) or com.example.gcm (as defined in your permissions)?
You should use the package name of your app in both places. For some reason, this mismatch only causes problems in older Android versions. Newer versions work either way.

A: Looks like a copy paste error. In your manifest, change com.example to your actual package name


text:
Q: Is there a shortcut for SSMS pressing "Enter" If I press Enter then the cursor moves to the first indented line.
[]
[]
Is there a Enter like Shortcut to jump to the first position of the next line, like here.
[]
I tried already STRG + Enter, Shift + Enter but nothing worked.
Microsoft SQL Server 2019 (RTM-GDR) (KB4583458) - 15.0.2080.9 (X64)
Nov  6 2020 16:50:01

A: @allmhuran
Thanks for the tips. Here are the solution for the problem.
Now: If I press Enter i go the the new line (inside the Block) if I press STRG + Enter then i go to the new line (position 1 outside the identtion above)


text:
Q: How can I get a list of column definitions of the return type of a table returning function I am working on postgres 12. I have some functions defined that have TABLE(...) as return values. I know how to query the information_schema and/or pg_proc to get the list of arguments of the function given its name and schema. I would like to do something similar for the return type when it is a TABLE, that is, to find a query, that when the function returns a set of records, will return a list of the ordinal position and oid (or name) for the columns of the return table.
Is that possible?
EDIT: I know of pg_get_function_result() which returns the text of the return definition as it is written in the function definition but I would have to parse that and i wonder if there is a simpler way.

A: pg_proc.prorettype will contain the OID of the table's type, so you can use:
select prorettype::regtype::text
from pg_proc
where proname = 'your_function';

to get the name of the type - which is also the name of the table.
To get all the columns, you can join pg_proc with pg_class to get the table's oid and then use that to find the columns.
select col.attname, col.attnum, format_type(col.atttypid, col.atttypmod) as data_type
from pg_attribute col
where not attisdropped
  and attnum > 0
  and attrelid in (select tbl.oid
                   from pg_class tbl
                      join pg_proc p on p.prorettype = tbl.reltype
                   where p.proname = 'your_function_name_here')
order by col.attnum

If you need to get the column names returned by a function defined as returns table(), they are available in the array pg_proc.proargnames for those that are defined as "out" parameters through proargmodes
select t.column_name, t.arg_type::regtype::text, t.col_num
from pg_proc p
  cross join unnest(proargnames, proargmodes, proallargtypes) with ordinality as t(column_name, arg_mode, arg_type, col_num)
where p.proname = 'your_function_name_here'
  and t.arg_mode = 't'
order by t.col_num;


text:
Q: Calling javascript function when option is selected but need it inside the option itself How can I do when the option is selected the function will be called with the parameters that I pass? I can't put the javascript function on select itself because I'm using foreach to fill my option and I also need to get my parameter defends on one column on my query
Example:
<select name="request_type" id="request_type" class="form-control" required onchange="approval(<?php()?>)">
  <option value="">Select Request Type</option>
  @foreach($types as $type)
   <option value="{{ $type->id ?? ''}}" // if selected function call(true/false)>{{ $type->name ?? ''}}</option>
  @endforeach
</select>

after calling the @foreach there will I know the column im basing whether I will pass true or false on my function on javascript. Can anyone help me on this? The column itself is a boolean.
Thank you.
EDIT
I want to do this without using ajax. is there any other way?

A: Just trigger select change function on document ready, like mentioned in code. And for custom parameter in option add custom attribute in option like data-parameter and get value of that in change function. example

$(document).ready(function(){
    $('#dropdown-id').change()
})
function callFunction(dropdown){
  var selectedOption = $(dropdown).find('option:selected')
  var customParameter = $(selectedOption).attr('data-parameter')
  console.log(customParameter);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown-id" onchange="callFunction(this)">
  <option value="1" data-parameter="false">One</option>
  <option value="2" selected data-parameter="true">Two</option>
  <option value="3" data-parameter="abc">Three</option>
</select>


text:
Q: Insert custom block before "col-left-first" ( customer account panel ) Here's a screenshot to illustrate my question.
http://prntscr.com/ejyfd3
I want to insert a custom block title.phtml with a default title for all pages in Customer Account.
Where i trying customer.xml
http://prntscr.com/ejyl9l
Inside "root" reference, i put the <block type="core/template" name="customer_section_title" template="customer/account/title.phtml"/> but the block not show.
If i put the same code in "content" reference, it shows.
Any ideas?
I'm learning magento yet, not sure about some things


text:
Q: CSS 3 out of 4 custom fonts don't load I can't seem to make custom fonts load in Firefox 54.0 and Chromium  59.0.3071.86. Looking at the Network tab in Firefox's element inspection tool, I see no font being loaded/downloaded, same with Chromium.
Here's the relevant CSS: https://hastebin.com/raw/quyivirosa
And here's the HTML: https://hastebin.com/iciwavoyus.xml
I've checked, and the URLs to the fonts are all correct, so I have no idea why it refuses to work. What does work is the font in the navbar, but I'm guessing that one is being loaded locally, since it's installed on my system.
Is there something I've done wrong...? I've searched around, and could not find any solutions to my problem.

A: I found two errors in your css that, as soon as I fixed them, the fonts started working.
I changed
    @font-face {
        font-family: 'DejaVu Condensed'; !important
        src: url('/fonts/DejaVuSansCondensed.eot');
        src: url('/fonts/DejaVuSansCondensed.eot?#iefix') format('embedded-  opentype'),
            url('/fonts/DejaVuSansCondensed.woff2') format('woff2'),
            url('/fonts/DejaVuSansCondensed.woff') format('woff'),;
        font-weight: normal;
        font-style: normal;
    }

to
    @font-face {
        font-family: 'DejaVu Condensed' !important;
        src: url('/fonts/DejaVuSansCondensed-Bold.eot');
        src: url('/fonts/DejaVuSansCondensed-Bold.eot?#iefix') format('embedded-opentype'),
                url('/fonts/DejaVuSansCondensed-Bold.woff2') format('woff2'),
                url('/fonts/DejaVuSansCondensed-Bold.woff') format('woff');
        font-weight: bold;
        font-style: normal;
    }

On line two, !important should be inside the semicolon.
On line six, I removed the coma that is right before the semicolon.
Once fixed, the font face kicked in


text:
Q: Can someone help ? I have this answer of linear transformation.
Onto?
What we have in class that if $n=2$ and $m=3$ that clear $2<3$ ,$T$ will be not onto.
He said make three point u have with three variable $=(y,z)$ .then u will have one free variable that will be expressed by $x_1,x_2,x_3$...
I do it $x_1$ will free variable but I get very complicated answer,and does the question mean what the condition to be onto or 1-1?
last answer i have i do not make sure can some one help

A: If $b_1,b_2\in\Bbb R$, the equations
$$x_1+2x_2+3x_3=b_1\ ,\quad -x_1-4x_3=b_2$$
always have a solution.  Therefore $T$ is onto.


text:
Q: How to create multiple plots by looping through variables Consider the following MWE:
Ps = {P1, P2, P3}
f[betas_] := betas.betas

(*A) works as expected:*)
Plot[f[{P1, P2, P3}] /. {P1 -> 5, P2 -> 10, P3 -> 15}, {P1, 0, 10}]
Plot[f[{P1, P2, P3}] /. {P1 -> 5, P2 -> 10, P3 -> 15}, {P2, 0, 10}]
Plot[f[{P1, P2, P3}] /. {P1 -> 5, P2 -> 10, P3 -> 15}, {P3, 0, 10}]

(*B) does not work:*)
Table[Show[
  Plot[f[Ps] /. {P1 -> 5, P2 -> 10, P3 -> 15}, {Ps[[k]], 0, 10}]], {k,
   Length[Ps]}]

I try to get the three graphs in A) by looping through Ps in B), but can't get it running.

A: The error indicates that Ps[[k]] cannot be used as an iterator. A workaround:
Table[With[{p = Ps[[k]]},
  Plot[f[Ps] /. {P1 -> 5, P2 -> 10, P3 -> 15}, {p, 0, 10}]], {k, Length[Ps]}]


text:
Q: Not able to create ReactJS application npx create-react-app myapp
'CALL "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" prefix -g' is not recognized as an internal or external command,
operable program or batch file.
spawn C:\Program Files\MySQL\MySQL Server 5.7\bin ENOENT

A: Do you have create-react-app installed? If it is installed just run create-react-app myapp

A: Try yarn it's an alternative node package manager.
I had similar problems with npm
yarn create react-app app-name

A: Looks like there could be some fault in your node installation. But before that make sure your npm is of at least 5.2.0 or newer. To update it to the latest do npm install -g npm.
If it still doesn't work, you should remove any global installation of create-react-app and retry. At last, I'd try to reinstall Node if I were you.

A: Its seems link there is some error with your npm.
Try cleaning the cache by doing
npm cache clean --force

and after that run
npm cache verify

now try creating your reach app by typing
npx create-react-app myapp

Even after doing this won't work
do install latest npm again by doing
npm install npm@latest -g


text:
Q: hyperlink issue in Joomla I'm a neophyte programmer.  I've built a couple of sites with Joomla, and not had any problems. The site I'm working on now has an important hyperlink to a manufacturer's site, and I'm getting an error message:

This email address is being protected from spambots. You need JavaScript enabled to view it.&n=125958">

The link is to a third party site, and does have my email embedded in it, so that I get credit for sales derived from that link. The link works fine in a plain html page, but not in Joomla.
Any ideas would be appreciated.
Steven

A: Joomla core comes with email obfuscation plugins with defaults to enabled.  The purpose of which is to prevent spiders from being able to extract emails embedded in your site.  From administrator dashboard navigate to Extensions > Plugins Manager.  Search for and disable the Content - Email Cloaking plugins and test to see if the links works properly.
Again, this will expose any embedded email addresses in your site to scripts crawling for email addresses.  If this is the only email which would be presented in plain text as a result then the risk is limited considering the feature is hindering your minimization capabilities.


text:
Q: Postman PUT method not updating data Put method actually responds with 200 OK but data in db is not updating, i am using mongoDB.
Here is product.js file:
router.put('/products/:id', async (req, res) => {
    try {
        let product = await Product.findOneAndUpdate({_id: req.params.id}, {
            $set: {
                title: req.body.title,
                price: req.body.price
            }
        }, {upsert: true})

        res.json({
            success: true,
            updatedProduct: product
        })
    } catch(err) {
        res.status(500).json({
            success: false,
            message: err.message
        })
    }
})

Here is the image from postman, response is 200OK, but when i refresh and check mongoDB, data is still the same.
https://i.stack.imgur.com/asUoV.png
This is code from server.js file.
const express = require('express')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const dotenv = require('dotenv')

// importing user
const User = require('./models/user')

// env file
dotenv.config()

const app = express()

// connect mongoDB
mongoose.connect(process.env.DATABASE, (err) => {
    if(err) {
        console.log(err)
    } else {
        console.log('connected to database')
    }
})

// middleware
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

// require apis
const productRoutes = require('./routes/product')
const categorytRoutes = require('./routes/category')
const ownerRoutes = require('./routes/owner')

app.use('/api', productRoutes)
app.use('/api', categorytRoutes)
app.use('/api', ownerRoutes)

// Initial response
app.get('/', function(req, res, next) {
    res.send("Hello world");
})

app.listen(8080, (err) => {
    if(err) {
        console.log(err)
    }
})

A: router.put('/products/:id', async (req, res) => {
  try {
    const updatedProduct = await Product.updateOne({ _id: req.params.id},
    { $set: { title: req.body.title,price: req.body.price });
    res.status(200).send("updated successfully");}
    catch (err) {
    res.status(400).json({ message: err.message });
  }
});


text:
Q: Using subquery alias in case I'm having hard time using a subquery alias in one of my CASE, after spending my time in documentation I cant find the solution on my own.
 SELECT
    t1.cardcode as Kundennummer,
    t1.cardname,
    t3.groupname,

    (select
        sum(t11.doctotal)as sum24
    from
        oinv t11
    where
        t11.cardcode=t1.cardcode
        and t11.docduedate > dateadd(month, -24, getdate()) and t11.docduedate < dateadd(month, -12, getdate())
    )as Umsatz24,

    (select
        sum(t10.doctotal) as sum12
    from
        oinv t10
    where
        t10.cardcode=t1.cardcode
        and t10.docduedate > dateadd(month, -12, getdate())
    )as Umsatz12,
    case
        when t3.groupname = 'C' and Umsatz12 = 0
            then 'Dummy 0'
        when t3.groupname = 'C' and Umsatz12 > 0
            then 'Dummy 15'
        when t3.groupname = 'B' and Umsatz24 = 0
            then 'Dummy 15'
        else
            'Dummy 15/30?'
    end as 'Dummy'

from
(... some code)

Any idea how I could fix it?
Thanks in advance.

A: You can use CTE for this.
;WITH T AS
(
    SELECT
        t1.cardcode as Kundennummer,
        t1.cardname,
        t3.groupname,

        (select
            sum(t11.doctotal)as sum24
        from
            oinv t11
        where
            t11.cardcode=t1.cardcode
            and t11.docduedate > dateadd(month, -24, getdate()) and t11.docduedate < dateadd(month, -12, getdate())
        )as Umsatz24,

        (select
            sum(t10.doctotal) as sum12
        from
            oinv t10
        where
            t10.cardcode=t1.cardcode
            and t10.docduedate > dateadd(month, -12, getdate())
        )as Umsatz12
    from
    (... some code)
)
SELECT *,
 case
        when groupname = 'C' and Umsatz12 = 0
            then 'Dummy 0'
        when groupname = 'C' and Umsatz12 > 0
            then 'Dummy 15'
        when groupname = 'B' and Umsatz24 = 0
            then 'Dummy 15'
        else
            'Dummy 15/30?'
    end as 'Dummy'
 FROM T

A: I'd move the subqueries to the FROM clause and make this one query instead of two by using conditional aggregation:
select
  t1.cardcode as kundennummer,
  t1.cardname,
  t3.groupname,
  umsatz.umsatz24,
  umsatz.umsatz12,
  case
    when t3.groupname = 'C' and umsatz.umsatz12 = 0 then 'Dummy 0'
    when t3.groupname = 'C' and umsatz.umsatz12 > 0 then 'Dummy 15'
    when t3.groupname = 'B' and umsatz.umsatz24 = 0 then 'Dummy 15'
    else                                                 'Dummy 15/30?'
  end as dummy
from  (... some code)
left join
(
  select
    cardcode,
    sum(case when oinv.docduedate > dateadd(month, -24, getdate())
              and oinv.docduedate < dateadd(month, -12, getdate())
             then oinv.doctotal end) as umsatz24
    sum(case when oinv.docduedate > dateadd(month, -12, getdate())
             then oinv.doctotal end) as umsatz12
  from oinv
  group by cardcode
) umsatz on umsatz.cardcode = t1.cardcode;

A: You can use below approach.
you can execute and test the query here
select cc.CID,cc.CustomerName,cc.ContactName,cc.City,cc.Umsatz24,cc.Umsatz12,
 case
        when cc.City = 'London' and cc.Umsatz12 = 0
            then 'Dummy 0'
        when cc.City = 'London' and cc.Umsatz12 > 0
            then 'Dummy 15'
        when cc.City = 'Paris' and cc.Umsatz24 = 0
            then 'Dummy 15'
        else
            'Dummy 15/30?'
    end as 'Dummy'
from (
SELECT
    t1.CustomerID as CID,
    t1.CustomerName,
    t1.ContactName,
    t1.City,
    (select
        sum(t11.CustomerID)as sum24
    from
        Customers t11
    where
        t11.CustomerID=t1.CustomerID
        and t11.City = 'Paris'
    )as Umsatz24,

    (select
        sum(t10.CustomerID) as sum12
    from
        Customers t10
    where
        t10.CustomerID=t1.CustomerID
        and t10.City = 'London'
    )as Umsatz12
 from Customers t1
 ) cc


text:
Q: Bash: delete first line of stdin I've created a script for account creation that reads from a csv file, i do not need the first line in the csv as it has the titles for the colums, im trying to delete the first line using sed 1d $file, but it doesnt seem to work.
#!/bin/bash

FILE="applicants.csv"

sed 1d $FILE |while IFS=: read USERNAME PASSWORD SCHOOL PROGRAM STATUS; do

#------------------------------------------
groupadd -f $SCHOOL
useradd $USERNAME -p $PASSWORD -g $SCHOOL
if [ $? == 0 ]; then
echo
echo "Success! $USERNAME created"
grep $USERNAME /etc/passwd
echo
#------------------------------------------

else
echo "Failed to create account for $USERNAME"
fi

done < $FILE

here is the csv file
Full Name:DOB:School:Program:Status
JoseDavid:22-08-86:ACE:Bsc Computing:Unfinished
YasinAhmed:22-07-85:ACE:Bsc Networking:Complete
MohammedAli:21-04-84:ACE:Bsc Forensics:Complete
UtahKing:22-09-84:ACE:BSC IT:Unfinished
UsmanNaeem:21-09-75:ACE:BSC Computing:Complete

Here is a screenshot of the output
http://i.stack.imgur.com/R5zPN.jpg
is there anyway to skip the first line?

A: Try using tail -n +2 $FILE instead of sed.
You're reading from the unedited file with the redirect at the end: done < $FILE. Try changing that line to just done.


text:
Q: Log Factory error I am using Hibernate on Eclipse and continually get the following error message when I try to compile:

build.xml:39: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

I have the commons-logging.jar file inside my libs folder, and here is my classpath file:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
        <attributes>
            <attribute name="owner.project.facets" value="java"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v6.0">
        <attributes>
            <attribute name="owner.project.facets" value="jst.web"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
    <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
    <classpathentry kind="src" path="flex_src"/>
    <classpathentry kind="output" path="build/classes"/>
</classpath>

I even tried printing the class path from within the build.xml file, and the commons-logging.jar appears within there as well, with the correct directory. Here is my build.xml file for further reference:
<project name="project" default="main">
    <property file="build.properties" />
    <xmlproperty file="${project-root}/src/META-INF/persistence.xml" collapseAttributes="true" />
    <description>Generate CDB files</description>
    <target name="force">
        <property name="force.build" value="true" />
        <antcall target="mainInternal" />
    </target>
    <target name="main">
        <property name="force.build" value="false" />
        <antcall target="mainInternal" />
    </target>
    <target name="mainInternal">
        <antcall target="generateHibernateCfg" />
        <antcall target="compileEntities" />
        <antcall target="findAnnotations" />
        <antcall target="compileServiceInterfaces" />
        <antcall target="generateDTOs" />
        <antcall target="generateServices" />
        <antcall target="generateFlex" />
        <antcall target="generateBlazeDSConfig" />
    </target>
    <target name="generateHibernateCfg">
        <xslt in="${project-root}/src/META-INF/persistence.xml" style="${project-root}/cdb_build/src/hibernate.cfg.xsl" out="${project-root}/src/hibernate.cfg.xml" force="${force.build}" />
    </target>
    <target name="compileEntities">
        <path id="build.class.path">
            <fileset dir="${project-root}/WebContent/WEB-INF/lib" />
            <pathelement path="${classes-folder}" />
        </path>
        <pathconvert property="cp" refid="build.class.path" />
        <echo message="Classpath = ${cp}"/>
        <path id="srcfiles">
            <fileset dir="${project-root}/src">
                <include name="**/*.java" />
            </fileset>
        </path>
        <pathconvert property="srcfiles" refid="srcfiles" pathsep=" " />
        <script language="javascript">
            <![CDATA[
            var includes = "";
            var entitiesString = project.getProperty("persistence.persistence-unit.class");
            if (entitiesString) {
                var entities = entitiesString.split(",");
                for (entity in entities) {
                    if (entities[entity] != null && entities[entity] != "") {
                        includes += String(entities[entity]).replace(/\./g, '/') + ".java,";
                    }
                }
            }
            project.setProperty("entities.include", includes);
            ]]>
        </script>
        <mkdir dir="${project-root}/build/classes" />
        <javac includes="${entities.include}" srcdir="${project-root}/src" destdir="${classes-folder}" classpath="${cp}" debug="on" />
    </target>
    <target name="findAnnotations">
        <file name="annotated.xml" id="annotated.xml" />
        <echo file="annotated.xml" message="<annotated-types/>" />
        <path id="build.class.path">
            <fileset dir="${project-root}/WebContent/WEB-INF/lib" />
            <pathelement path="${classes-folder}" />
        </path>
        <pathconvert property="cp" refid="build.class.path" />
        <path id="srcfiles">
            <fileset dir="${project-root}/src">
                <include name="**/*.java" />
            </fileset>
        </path>
        <pathconvert property="srcfiles" refid="srcfiles" pathsep=" " />
        <path id="cfg-xml-path">
            <fileset file="${project-root}/src/hibernate.cfg.xml" />
        </path>
        <pathconvert property="cfg-xml" refid="cfg-xml-path" />
        <apt classpath="${cp}"
            compile="false"
            factory="com.farata.cdb.annotations.processor.CDBFullAnnotationProcessor"
            srcdir="${project-root}/src"
            sourcepath="${project-root}/src">
            <option name="com.faratasystems.cdb.annotations.file" value="annotated.xml"/>
            <option name="com.faratasystems.cdb.configuration.file" value="${cfg-xml}"/>
            <include name="**/*.java"/>
        </apt>
    </target>
    <target name="compileServiceInterfaces">
        <path id="build.class.path">
            <fileset dir="${project-root}/WebContent/WEB-INF/lib" />
            <pathelement path="${classes-folder}" />
        </path>
        <pathconvert property="cp" refid="build.class.path" />
        <path id="srcfiles">
            <fileset dir="${project-root}/src">
                <include name="**/*.java" />
            </fileset>
        </path>
        <pathconvert property="srcfiles" refid="srcfiles" pathsep=" " />
        <xmlproperty file="annotated.xml" collapseAttributes="true" />
        <script language="javascript">
            <![CDATA[
            var includes = "";
            var typeNamesString = project.getProperty("annotated-types.annotated-type.name");
            if (typeNamesString) {
                var annotationNamesString = project.getProperty("annotated-types.annotated-type.annotations.annotation.name");
                var annotationNames = annotationNamesString.split(",");
                var typeNames = typeNamesString.split(",");
                for (annotationName in annotationNames) {
                    if (annotationNames[annotationName] != null && annotationNames[annotationName] != "") {
                        if (annotationNames[annotationName] == "clear.cdb.annotations.CX_Service") {
                            includes += String(typeNames[annotationName]).replace(/\./g, '/') + ".java,";
                        }
                    }
                }
            }
            project.setProperty("entities.include", includes);
            ]]>
        </script>
        <javac includes="${entities.include}" srcdir="${project-root}/src" destdir="${classes-folder}" classpath="${cp}" debug="on" />
    </target>
    <target name="generateDTOs">
        <xmlproperty file="annotated.xml" collapseAttributes="true" />
        <path id="build.class.path">
            <fileset dir="${project-root}/WebContent/WEB-INF/lib" />
            <pathelement path="${classes-folder}" />
        </path>
        <pathconvert property="cp" refid="build.class.path" />
        <path id="srcfiles">
            <fileset dir="${project-root}/src">
                <include name="**/*.java" />
            </fileset>
        </path>
        <pathconvert property="srcfiles" refid="srcfiles" pathsep=" " />
        <xslt classpathref="build.class.path" in="annotated.xml" style="src/service-dto-all.xsl" out="tmp.txt" force="true">
            <param name="outputFolder" expression="${project-root}src" />
            <param name="force" expression="${force.build}" />
        </xslt>
        <script language="javascript" src="${basedir}/scripts.js">
            <![CDATA[
                var includes = getServicesDTOs();
                includes += getServicesDTOSubclasses();
                project.setProperty("entities.include", includes == ""? "none":includes);
            ]]>
        </script>
        <javac includes="${entities.include}" srcdir="${project-root}/src" destdir="${classes-folder}" classpath="${cp}" debug="on" failonerror="false" />
    </target>
    <target name="generateServices">
        <xmlproperty file="annotated.xml" collapseAttributes="true" />
        <path id="build.class.path">
            <fileset dir="${project-root}/WebContent/WEB-INF/lib" />
            <pathelement path="${classes-folder}" />
        </path>
        <pathconvert property="cp" refid="build.class.path" />
        <path id="srcfiles">
            <fileset dir="${project-root}/src">
                <include name="**/*.java" />
            </fileset>
        </path>
        <pathconvert property="srcfiles" refid="srcfiles" pathsep=" " />
        <xslt classpathref="build.class.path" in="annotated.xml" style="src/service-impl-all.xsl" out="tmp.txt" force="true">
            <param name="outputFolder" expression="${project-root}src" />
            <param name="force" expression="${force.build}" />
        </xslt>
        <script language="javascript" src="${basedir}/scripts.js">
            <![CDATA[
            var includes = getServices();
            includes += getServicesSubclasses();
            project.setProperty("entities.include", includes == ""? "none":includes);
            ]]>
        </script>
        <javac includes="${entities.include}" srcdir="${project-root}/src" destdir="${classes-folder}" classpath="${cp}" debug="on" />
    </target>
    <target name="generateFlex">
        <xmlproperty file="annotated.xml" collapseAttributes="true" />
        <path id="build.class.path">
            <fileset dir="${project-root}/WebContent/WEB-INF/lib" />
            <pathelement path="${classes-folder}" />
        </path>
        <pathconvert property="cp" refid="build.class.path" />
        <path id="srcfiles">
            <fileset dir="${project-root}/src">
                <include name="**/*.java" />
            </fileset>
        </path>
        <pathconvert property="srcfiles" refid="srcfiles" pathsep=" " />
        <xslt classpathref="build.class.path" in="annotated.xml" style="flex_src/flex-all.xsl" out="tmp.txt" force="true">
            <param name="flexOutputFolder" expression="${flex-output-folder}" />
            <param name="javaSrcFolder" expression="${project-root}src" />
            <param name="force" expression="${force.build}" />
        </xslt>
        <xslt classpathref="build.class.path" in="annotated.xml" style="flex_src/application-all.xsl" out="tmp.txt" force="true">
            <param name="javaSrcFolder" expression="${project-root}src" />
            <param name="testFolder" expression="${project-root}test" />
            <param name="force" expression="${force.build}" />
        </xslt>
    </target>
    <target name="generateBlazeDSConfig">
        <xmlproperty file="annotated.xml" collapseAttributes="true" />
        <path id="build.class.path">
            <fileset dir="${project-root}/WebContent/WEB-INF/lib" />
            <pathelement path="${classes-folder}" />
        </path>
        <pathconvert property="cp" refid="build.class.path" />
        <path id="srcfiles">
            <fileset dir="${project-root}/src">
                <include name="**/*.java" />
            </fileset>
        </path>
        <pathconvert property="srcfiles" refid="srcfiles" pathsep=" " />
        <script language="javascript" src="${basedir}/scripts.js">
            <![CDATA[
            generateRemotingConfig();
            generateMessagingConfig();
            ]]>
        </script>
    </target>
</project>

A: I think you might have to provide more details on your project structure. How did you package your project? (Does it contain an ear with ejb module packaged...)
Pretty obviously its a class loading problem. Or it is possible that the jar is not packaged with the final deployable archive. The easiest fix for your solution is to copy and paste the common-logging.jar file in to your server's lib directory. (for tomcat I believe its under catalina_home folder.. but I am not sure)

A: You seem to have posted the contents of Eclipse's .classpath metadata file, which defines the classpath that Eclipse uses when building your project within Eclipse, but you also mention using build.xml which implies you are also using Ant to build the project externally from the IDE.
Make sure your <javac> tasks in build.xml also refer to commons-logging.jar; the .classpath file will not be used by Ant unless you have somehow configured the build script to do so (possibly by generating build.xml from Eclipse).


text:
Q: Prism BindableBase.SetProperty() I am developing a ViewModel based on BindableBase.
This VM holds an instance of a domain model.
The VM exposes a property, say Name from which I want to not use local storage (i.e. storage in VM), but rather delegate to the model object's property.
I would like to use SetProperty(), but the storage reference cannot be a property.
Do I have to implement INotifyPropertyChanged my self ?
Is it at all a good idea to delegate to the model this way ?
Would it be possible to extend BindableBase (or team to add) to cover for this ?

A: So first you must chose how you will architect your VMs and Models.  As you mentioned, there are a few options.  The easiest and the way I recommend, is to just expose your Model as a property and then bind your View to the model properties:
public class MyViewModel : BindableBase
{
    private Person _myPerson;
    public Person Person
    {
        get { return _myPerson; }
        set { SetProperty(ref _myPerson, value); }
    }
}

If you don't want to do that and would rather wrap each individual model property, you would do it like this.
public class MyViewModel : BindableBase
{
    private Person _myPerson;

    private string _name;
    public string Name
    {
        get { return _myPerson.Name; }
        set { _myPerson.Name = value }
    }
}

Keep in mind, your Person model object still has to implement INPC.
EDIT:  If you don't have control over your models and need them to implement INPC, you could try to use IL weaving, or create a façade/decorator for your models and wrap them individually.
public class MyPersonFacade : BindableBase
{
    private Person _myPerson;

    private string _name;
    public string Name
    {
        get { return _myPerson.Name; }
        set
        {
            _myPerson.Name = value;
            OnPropertyChanged();
        }
    }
}

Then use this as your Model in your VM.


text:
Q: Calculate kappa score for multi label image classifcation I want to calculate kappa score for a multi label image classification problem.
I don't think sklearn supports this inherently because when i try this
import sklearn
sklearn.metrics.cohen_kappa_score(y_test, predictions)

i get
ValueError: multilabel-indicator is not supported

anyone has suggestions on how to do this?
My prediction matrix is of shape(845,8) with 0 and 1 in them.
My ground truth matrix is of shape (845,8) with 0 and 1 in them
My labels look like this
[0,0,1,0,1,0,1,0]

thanks in advance.

#######EDIT

please provide relevant code.Alteast a small snippet.

A: Cohen's kappa by definition does not support multiple labels
This is because Cohen's kappa is given by K = (po - pe)/(1 - pe)
where po = (TP + FN)/(TP + TN + FP + FN)
and   pe = (TN + FP)/(TP + TN + FP + FN)
As you can see it is calculated using Confusion matrix.You can construct a confusion matrix only for mutually exclusive labels(ex: [0,0,1,0,0,0,0,0]) and not for non exclusive labels(ex: [0,0,1,0,1,0,1,0])
If using Cohen's kappa is a priority i would recommend calculating it separately for each and every label and then averaging them.
Or else the best course of action here would be to use Krippendorff's Alpha
Krippendorff's alpha (also called Krippendorff's Coefficient) is an alternative to Cohen's Kappa for determining inter-rater reliability.
reference links: wikipedia , statisticshowto
Although Krippendorff's Alpha isn't available in sklearn library you can use it using this package krippendorff
import krippendorff
reliability_data = [[prediction matrix],[ground truth]]
print(krippendorff.alpha(reliability_data=reliability_data))

print([prediction matrix].shape,[ground truth].shape)

(845,8) , (845,8)
hope this helps

A: Krippendorff's Alpha
You can NOT use Cohen's Kappa for a multilabel agreement. The solution is to use Krippendorff's Alpha.
However, Krippendorff's Alpha can be used with many different data types and you need to remember that you have nominal data (i.e. classes).
Code
You can use the krippendorff package found here: https://github.com/pln-fing-udelar/fast-krippendorff
Notice that the alpha() function has a parameter level_of_measurement, which by default is interval, so you need to set it to nominal!
import krippendorff

reliability_data = [[predictions], [y_test]]

print(krippendorff.alpha(reliability_data=reliability_data,
                         level_of_measurement='nominal'))


text:
Q: Cannot connect to Twitter API from Postman I do not understand. I am doing everything I am supposed to.
I have created an app in Twitter, generate the OAuth info, and now I'm trying to make some requests from Postman. But I am getting this error every singe time:
{
  "errors": [
    {
      "code": 32,
      "message": "Could not authenticate you."
    }
  ]
}

I have tried several different ways, for example using the Oauth feature in Postman - as described in this answer, just using a plain Authorization header, etc. However nothing is working
Has anyone had a similar experience or know how to fix this?

A: I got it working with the following steps:

*

*I went to https://dev.twitter.com/oauth/tools/signature-generator where I typed in the query I wanted to make and then clicked Get OAuth Signature.

*

*Then in Postman, copy in the URL you generated an OAuth token for, and then copy the entire Authorization Header you generated.

*In Postman, click Bulk Edit and paste in the authorization header you copied

That's it.
Click Send


text:
Q: Does mount always require root privileges? I was under the impression that any sort of call to mount requires root privileges.
But recently I was told "You should instead create appropriate entries in /etc/fstab so that the filesystems can be mounted by unprivileged users"... which is counter to my experience using mount.
Anytime I have used mount I have needed to sudo it. (I have only used mount for mounting network drives. Specifically cifs type network drives.)
Does mount always require root privileges? If not:

*

*What kind of mount does and what kind of mount doesn't require sudo IN GENERAL?

*In my specific case I am doing mount -t cifs, how does one go about making this mount not require require sudo?

A: Mounting a filesystem does not require superuser privileges under certain conditions, the most common being that the entry for the filesystem in /etc/fstab contains a flag that permits unprivileged users to mount it, typically user. To allow unprivileged users to mount a CIFS share (but not automount it), you would add something like the following to /etc/fstab:
//server/share /mount/point cifs noauto,user 0 0

For more information on /etc/fstab and its syntax, Wikipedia has a good article here, and man 8 mount has a good section on mounting as an unprivileged user under the heading "[t]he non-superuser mounts".

A: The mount(8) man page has a section dedicated to this; in short, it comes down to adding the user or users option for that mount in /etc/fstab:

The non-superuser mounts.
Normally, only the superuser can mount filesystems. However, when fstab contains the user option on a line, anybody can mount the corresponding system.
Thus, given a line
 /dev/cdrom  /cd  iso9660  ro,user,noauto,unhide

any user can mount the iso9660 filesystem found on his CDROM using the command
 mount /dev/cdrom

or
 mount /cd

For more details, see fstab(5). Only the user that mounted a filesystem can unmount it again. If any user should be able to unmount, then use users instead of user in the fstab line. The owner option is similar to the user option, with the restriction that the user must be the owner of the special file. This may be useful e.g. for /dev/fd if a login script makes the console user owner of this device. The group option is similar, with the restriction that the user must be member of the group of the special file.

A: re: cifs mounts
Make sure you are entering the gid and uid with numeric values. I've had on issues with specifying these as their name values. This is despite the mount.cifs helper version being 5.1  (mount.cifs -V)
see

uid=arg
       sets the uid that will own all files or directories on the
       mounted filesystem when the server does not provide
       ownership information. It may be specified as either
       a username or a numeric uid. When not specified, the default
       is uid 0. The mount.cifs helper must be at version 1.10
       or higher to support specifying the uid in non-numeric form.
       See the section on FILE AND DIRECTORY OWNERSHIP AND PERMISSIONS
       below for more information.

//mynas/nasmedia /media/nasmedia cifs noauto,users,_netdev,credentials=/etc/.smbcredentials,iocharset=utf8,uid=1000,gid=1002,file_mode=0774,dir_mode=0775 0 0

worked well for non-root mounting, and allocating the correct uid and gid on the mountpoint.


text:
Q: Jenkins Slack Integration Test Connection Fails Can anyone provide any insight into how to debug why the Test Connection button in Jenkins fails.
We do have a webcontent filtering system and I'm assuming that because Jenkins runs as a local system account that it's not being permitted by that filter.
Aside from changing the filter to ALLOW all to Slack is there any other way to confirm it's a filter issue? Can I issue a test from a command line to see it's output etc...


text:
Q: The Mellin transform as a mapping from a Hardy space to a weighted space As far as I know, the following fact must be published somewhere, and I would like to find a reference.
The Mellin transform is defined by $f\mapsto\frac1{\sqrt{2\pi}}\int_0^\infty f(x)x^{s-1}\,dx$. The classical fact is that it is a unitary operator from $L^2(0, \infty)$ to the unweighted $L^2$-space on the critical line $\{\Re s=\frac12\}$. Also it is a unitary operator from the Hardy space $H^2$ on the half-plane $\{\Re z>0\}$ to the weighted $L^2$-space on the critical line with weight $e^{\pi t}+e^{-\pi t}$ if we write $s=\frac12+it$ for $s$ on the critical line; this is the fact I am interested in. To apply the Mellin transform to a function $f\in H^2$, one takes the above integral on $(0, \infty)$; the formula can be applied to functions that decrease exponentially near zero and infinity, such functions form a dense set.


text:
Q: R equivalent of Excel's "Sumif(s)" function across like columns I am fairly new to R (new to this site as well) and trying to understand how to aggregate data across columns in a situation where there is more than 1 identifier (in this case, two: PERSON_ID and PRODUCT_ID).
Please see my example below. To the right of the two identifiers within my data frame are five columns containing weekly sales figures. I need to aggregate the weekly data so that:
1: Week columns with the same name are summed (typically this is something I can easily accomplish in MS Excel using the sumif/sumifs function)
2: Any rows containing the same PERSON_ID and PRODUCT_ID combination are summed as well.
In this particular case, notice that the week of 6/2/2017 appears in more than one column. Meanwhile, PERSON_ID 0003603 appears twice for the same PRODUCT_ID, 3024.
PERSON_ID    PRODUCT_ID    6/23/2017   6/16/2017   6/9/2017   6/2/2017   6/2/2017
0003603      3024          10.000      5.000       4.000      3.000      2.000
0003603      3024          1.000       2.000       3.000      8.000      1.000
0007654      2111          8.000       3.000       2.000      1.000      0.000
0008885      3025          0.000       0.000       1.000      3.000      9.000
0950645      3024          6.000       5.000       4.000      3.000      2.000

My actual data frame contains in excess of 1 million records, so an approach using the data.table package would be ideal, as far as I can tell.
Can someone please shed some light on how to solve this particular problem in R?

A: melting your data (reshaping long) is the way to go. If I understand what you're after correctly, it's simply:
x = fread('PERSON_ID    PRODUCT_ID  6/23/2017   6/16/2017   6/9/2017    6/2/2017    6/2/2017
0003603 3024    10.000  5.000   4.000   3.000   2.000
0003603 3024    1.000   2.000   3.000   8.000   1.000
0007654 2111    8.000   3.000   2.000   1.000   0.000
0008885 3025    0.000   0.000   1.000   3.000   9.000
0950645 3024    6.000   5.000   4.000   3.000   2.000',
          colClasses = c('character', 'character', rep('numeric', 5L)))

xmlt =
  melt(x, id.vars = c('PERSON_ID', 'PRODUCT_ID'),
       variable.name = 'week', value.name = 'sales')

xmlt[ , week := as.IDate(week, format = '%m/%d/%Y')]

xmlt[ , .(total_sales = sum(sales)),
      keyby = .(PERSON_ID, PRODUCT_ID, week)]
    PERSON_ID PRODUCT_ID       week total_sales
#  1:   0003603       3024 2017-06-02          14
#  2:   0003603       3024 2017-06-09           7
#  3:   0003603       3024 2017-06-16           7
#  4:   0003603       3024 2017-06-23          11
#  5:   0007654       2111 2017-06-02           1
#  6:   0007654       2111 2017-06-09           2
#  7:   0007654       2111 2017-06-16           3
#  8:   0007654       2111 2017-06-23           8
#  9:   0008885       3025 2017-06-02          12
# 10:   0008885       3025 2017-06-09           1
# 11:   0008885       3025 2017-06-16           0
# 12:   0008885       3025 2017-06-23           0
# 13:   0950645       3024 2017-06-02           5
# 14:   0950645       3024 2017-06-09           4
# 15:   0950645       3024 2017-06-16           5
# 16:   0950645       3024 2017-06-23           6

A: We first define df as follows. Note that column names in R cannot start with a number and cannot have duplicates. R rectifies these by adding X at the front of column names that start with a number and appending .1, .2 etc. at the end of column names for duplicates.
df <- read.table(text = "
                 PERSON_ID    PRODUCT_ID    6/23/2017   6/16/2017   6/9/2017   6/2/2017   6/2/2017
                 0003603      3024          10.000      5.000       4.000      3.000      2.000
                 0003603      3024          1.000       2.000       3.000      8.000      1.000
                 0007654      2111          8.000       3.000       2.000      1.000      0.000
                 0008885      3025          0.000       0.000       1.000      3.000      9.000
                 0950645      3024          6.000       5.000       4.000      3.000      2.000",
                 header = TRUE, colClasses = rep(c("character", "numeric"), c(2,5)))

We can use dplyr (data manipulation), tidyr (tidy data) and lubridate (working with dates) packages to solve the problem.
library(dplyr)
library(tidyr)
library(lubridate)
library(rebus)
df %>%
  gather(DATE, SALES, -c(PERSON_ID, PRODUCT_ID)) %>%
  mutate(DATE = str_extract(DATE, pattern = repeated(DGT, 1, 2) %R% DOT %R%
                                            repeated(DGT, 1, 2) %R% DOT %R%
                                            repeated(DGT, 4, 4)),
         DATE = mdy(DATE)) %>%
  group_by(PERSON_ID, PRODUCT_ID, DATE) %>%
  summarise_at(vars(SALES), funs(sum)) %>%
  ungroup

The code is written in the following manner:

*

*The wide df is converted into a long format. This is to ensure that the rows in the dataframe are observations and the columns are variables.

*Format DATE variable to get rid of the prefix X and suffix .1 and coerce date class (month-day-year) to the variable.

*Group the dataframe by 3 variables, i.e. PERSON_ID, PRODUCT_ID, DATE

*Sum the SALES variable per group (as defined in the previous point)

If you want to convert it back to the wide format, you may add another line, i.e. %>% spread(DATE, SALES) at the end.


text:
Q: LLVM "source" package manager? To my understanding, the main advantage of a binary package manager is install speed, while the main advantage to a source package manager is cross-arch compatibility, so why not something in-between?
If packages were compiled down to LLVM and distributed from there, a package manager would be able to distribute it to multiple architectures, and possibly even completely different operating systems without needing tons of copies of the same software per architecture and OS while also not needing the ridiculous compile time of high-level languages. Is this viable, does something like it already exist, or is it kind of a useless idea?

A: Apple does something like that in the App store:

Bitcode
Bitcode is an intermediate representation of a compiled program. Apps
you upload to App Store Connect that contain bitcode will be compiled
and linked on the App Store. Including bitcode will allow Apple to
re-optimize your app binary in the future without the need to submit a
new version of your app to the App Store.

(https://help.apple.com/xcode/mac/current/#/devbbdc5ce4f)


text:
Q: C++ How to Save Elements in a Vector from a Function Consider the following code. In list1 I'm adding elements saved on the heap to a vector and printing. It works as expected. In list2 I'm adding elements onto the vector from a function which also allocates elements on the heap.
I understand I have to allocate Node on the heap in addNode as otherwise it would be deallocated when the function returns. However, via the final print statement I can see the nodes on the heap are still allocated, yet they don't show up in my vector.
#include <iostream>
#include <vector>

using namespace std;

/*
Simple node class for demo
 */
class Node
{
public:
  string val;
  Node(string value) { this->val = value; }
};

Node *addNode(vector<Node *> list)
{
  // allocate space for node on the heap so it isn't destroyed after function returns
  auto node = new Node("foo");
  // add pointer to node onto vector
  list.push_back(node);
  return node;
}

/*
Simple function for printing vector contents
 */
template <typename T>
void printVector(T d)
{
  cout << "Vector has size " << d.size() << " and elements: ";
  for (auto p = d.begin(); p < d.end(); p++)
  {
    cout << (*p)->val << ",";
  }
  cout << "\n";
}

int main()
{
  // make a new vector
  vector<Node *> list1;
  // add elements allocated on the heap
  list1.push_back(new Node("foo"));
  list1.push_back(new Node("foo"));
  list1.push_back(new Node("foo"));
  printVector(list1); // prints: "Vector has size 3 and elements: foo,foo,foo,"

  // make a new vector
  vector<Node *> list2;
  // add elements allocated on the heap from a function
  addNode(list2);
  addNode(list2);
  // save one of the nodes to a variable for demonstration
  auto node = addNode(list2);
  printVector(list2); // prints: "Vector has size 0 and elements:"
  cout << node->val << "\n"; // prints: "foo"

  return 0;
}

Can someone explain how to add elements to a vector from a function?

A: In addNode(), you are passing the vector by value, thus a copy of the caller's vector is made, and then you are adding the Node* to the copy, the original vector is unaffected.
You need to pass the vector by reference instead:
Node* addNode(vector<Node*> &list)

Same with printVector(). You are passing the vector by value, you are just not modifying the copy, but you should still pass the vector by (const) reference to avoid making a copy at all:
template <typename T>
void printVector(const T &d)

On a side note, you are leaking the Nodes you create.  You need to delete them when you are done using them:
int main()
{
  vector<Node*> list1;
  list1.push_back(new Node("foo"));
  list1.push_back(new Node("foo"));
  list1.push_back(new Node("foo"));
  printVector(list1);

  for(auto *p : list1)
    delete p;

  vector<Node*> list2;
  addNode(list2);
  addNode(list2);
  auto node = addNode(list2);
  printVector(list2);
  cout << node->val << "\n";

  for(auto *p : list2)
    delete p;

  return 0;
}

Better to use std::unique_ptr to manage that for you:
#include <iostream>
#include <vector>
#include <memory>

using namespace std;

...

Node* addNode(vector<unique_ptr<Node>> &list)
{
  list.push_back(make_unique<Node>("foo"));
  return list.back().get();
}

template <typename T>
void printVector(const T &d)
{
  cout << "Vector has size " << d.size() << " and elements: ";
  for (const auto &p : d)
  {
    cout << p->val << ",";
  }
  cout << "\n";
}

int main()
{
  vector<unique_ptr<Node>> list1;
  list1.push_back(make_unique<Node>("foo"));
  list1.push_back(make_unique<Node>("foo"));
  list1.push_back(make_unique<Node>("foo"));
  printVector(list1);

  vector<unique_ptr<Node>> list2;
  addNode(list2);
  addNode(list2);
  auto node = addNode(list2);
  printVector(list2);
  cout << node->val << "\n";

  return 0;
}


text:
Q: how to display news in a static block in home page what is the best free extension to show news scrolling on MAGENTO homepage. I have googled a lot but did not found any news or blog new extension

A: There is free extension available for that you can use any one of them
http://www.magentocommerce.com/magento-connect/news-5.html
http://www.magentocommerce.com/magento-connect/news.html
http://www.magentocommerce.com/magento-connect/medma-news.html
http://www.magentocommerce.com/magento-connect/news-extension-1.html


text:
Q: Data Science: Using Inferential Statistics to label train dataset Lack of High Schools in remote areas is a problem for students in developing country. Students in some locations are better than that in other. So, I have to find those locations. Now, the main problem is defining "BETTER". I have made some rules that will define the profile of a location.
Right now, I am concerned with the good students. So, what I have done is- 1. Used some inferential statistics to and made some rules to come up with the conclusion that Location A,B,C,etc are the most potential locations where you can put the high schools because according to my rules these locations contain quality students.
I did all of the things above to label the data because I required to define "BETTER" and label the data so that I can now use machine learning to learn the factors which makes a location a potential location so that if I give a data point from test data to the model, it will instantly tell if the location is better or not.
Overview of the method: For each location, I have these 4 pieces of information:

*

*total_students_staying_for_high_school_education(A), -

*total_students_leaving_for_high_school_education_in_another_place(B), -

*mean_grade_point_of_students_of_type_B,

*ratio (calculated as B/A),

For the location whose ratio > 1

*

*I calculated the chi-squared significance test to come up with a
statistic which would tell me if students are leaving that place in
significant amount than staying. I used ANOVA and then Tukey test to
compare means_grade points and then find combinations of pairs of
locations whose means vary and whose is greater than the others.

*I then wrote a python program with a custom comparator that first
compares if mean_grade of those points vary and returns the one with
greater mean. If the means don't vary, the comparator return the
location with the one whose chi-squared value is greater.

This is how, the whole process comes up with few suggestions of location and I call those locations: "BETTER".
What I am concerned about is-

*

*How do I verify if my rules are valid? Or do I even need to verify it?

*Most importantly, is mingling statistics with machine learning as described above an appropriate approach?Is there any major leakage in the method?

*Can anyone suggest a more general method?


text:
Q: Why is 1 cubic meter 1000 liters? Can anyone explain why $1\ \mathrm{m}^3$ is $1000$ liters?
I just don't get it.
1 cubic meter is $1\times 1\times1$ meter. A cube. It has units $\mathrm{m}^3$.
A liter is liquid amount measurement. 1 liter of milk, 1 liter of water, etc.
Does that mean if I pump $1000$ liters of water they would take exactly $1$ cubic meter of space?
I can't wrap my head around.

A: 1 liter is, by definition, 1 cubic decimeter, where 1 decimeter is 1/10 meter.
So $1000\,\mathrm{l} = 1000\,\mathrm{dm^3} = 1000\,(1/10\,\mathrm{m})^3 = 1000/10^3\,\mathrm{m^3} = 1\,\mathrm{m^3}$.

A: Originally:

*

*the metre was defined as 1/10,000,000th of the distance from the North pole to the equator at sea level;

*the litre was defined as 1/1,000th of a cubic metre;

*the kilogram was defined as the mass of a litre of water at freezing point.

Nowadays we have more precise standards, which don't rely on the density of water. But these relations are still very accurate.

A: Density = weight per unit volume (water density = 1 Gram per 1 Cubic centimeter)
i.e Density X 1 Centimeter cube = 1 Gram of water
   1 X 1 cc = 1 Gram

   1 x 1 cc X 1000 = 1 Gram X 1000

    1000 cc = 1000 Gram = 1000 Milli liter = 1 Liter

    1000 cc x 1000 = 1 Liter x 1000

    1 Cubic meter =  1000 Liter


text:
Q: Export a list of fields How can I export a list of all fields that are displayed on "Settings > Technical > Database structure > Fields" (web?debug#min=1&limit=80&view_type=list&model=ir.model.fields&action=15&menu_id=4) to csv or excel ?

A: Please Use Export Option In Action
Action --> Export.
Choose all line items in Tree view


text:
Q: 19 FOREIGN KEY constraint failed on Laravel I'm trying to write data to my SQLite database. I think there's an error at my migration file and the foreign keys.
I have tried to change names of the files, making the foreign key nullable and clearing Laravel's caches.
Are you familiar with the error that the error handler shows or could you point me towards a page that could help me understand what I'm doing wrong?
Thank you very much in advance.
Migration file:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSqrTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sqrs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id')->nullable();
            $table->string('qr_link');
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('sqr');
    }
}

Model file:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

// sQR stands for Saved QR-Code

class sqr extends Model
{
    protected $fillable = [
        'qr_link', 'user_id'
    ];
}

Controller that saves:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\sqr;

class saveController extends Controller
{
    public function save(Request $request)
    {
        $sqr = new sqr;
        $sqr->qr_link =     $request->qr_link;
        $sqr->user_id =     1;
        $sqr->save();

        return redirect('/');
    }
}

front end blade file:
<form method="post" action="/save">
        @csrf
       <input type="hidden" name="qr_link" value="{{ session('url') }}">
       <button class="btn btn-success">Save this QR</button>
    </form>

The error I'm getting is as follows:
SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed (SQL: insert into "sqrs" ("qr_link", "user_id", "updated_at", "created_at") values (images/1567444499.svg, 1, 2019-09-02 17:37:23, 2019-09-02 17:37:23))

A: @dparoli said in a comment of this post:
"Are you sure that you have an User with id = 1 in the database? – dparoli"
This was the answer to my question. Because there was nog user = 1 in the database, it crashed.


text:
Q: chartjs canvas to pdf coming out blurry I am using jspdf to convert chartjs canvases into a single pdf. But the outcome is very blurry.How do I fix this? I followed this to convert the canvas into pdf.

        <canvas class="selected" id="myChart1" width="100" height="75"></canvas>

        <canvas class="selected" id="myChart2" width="100" height="75"></canvas>

        <canvas class="selected" id="myChart3" width="100" height="75"></canvas>

$('#downloadPdf').click(function(event) {
    var PageHeight = $('.row').innerHeight();
    var PageWidth = $('.row').innerWidth();
    var pdfCanvas = $('<canvas />').attr({
      id: "canvaspdf",
      width: PageWidth,
      height: PageHeight
    });
    var scale = window.devicePixelRatio;
    var pdfctx = $(pdfCanvas)[0].getContext('2d');

    var pdfctxX = 0;
    var pdfctxY = 0;
    var buffer = 0;
    $("canvas.selected").each(function(index) {
      var canvasHeight = $(this).innerHeight();
      var canvasWidth = $(this).innerWidth();
      pdfctx.drawImage($(this)[0], pdfctxX, pdfctxY, canvasWidth, canvasHeight);
      pdfctxX += canvasWidth + buffer;
      if (index % 2 === 1) {
        pdfctxX = 0;
        pdfctxY += canvasHeight + buffer;
      }
    });
    var pdf = new jsPDF('l', 'pt', [PageWidth, PageHeight]);
    pdf.addImage($(pdfCanvas)[0], 'PNG', 0, 0);
    pdf.save('file.pdf');
});


text:
Q: Sinatra with Foreman not launching properly In trouble shooting a problem I've reduced it to the simplest possible scenario. Here's my code.
# dummyProcfile
web: bundle exec rackup dummyconfig.ru -p $PORT

# dummyconfig.ru
require File.expand_path('dummyapp', File.dirname(__FILE__))

run DummyApp

# dummyapp.rb
require 'sinatra/base'

class DummyApp < Sinatra::Base
  get "/" do
    "hello world"
  end
end

foreman start -f dummyProcfile
10:49:00 web.1  | started with pid 9211
10:49:00 web.1  | Puma starting in single mode...
10:49:00 web.1  | * Version 3.12.0 (ruby 2.6.0-p0), codename: Llamas in Pajamas
10:49:00 web.1  | * Min threads: 0, max threads: 16
10:49:00 web.1  | * Environment: production
10:49:00 web.1  | * Listening on tcp://0.0.0.0:5000
10:49:00 web.1  | Use Ctrl-C to stop

If I use a browser to open http://0.0.0.0:5000 it prints "file not found" in the browser window. If I run the app with rackup it works as expected:
rackup dummyconfig.ru
Puma starting in single mode...
* Version 3.12.0 (ruby 2.6.0-p0), codename: Llamas in Pajamas
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:9292
Use Ctrl-C to stop

What am I missing?


text:
Q: Custom alignment in richText cells Exceljs
"exceljs": "^3.9.0"

I need to create a spreadsheet with cells that have 2 different values that looks like this.
First value needs to be aligned left and second value needs to be aligned right.

My result right now is:

Here is my richText for the cells without "/"
    [
  {
    "font": {
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": "392.3 "
  },
  {
    "font": {
      "color": {
        "argb": "00c90a00"
      },
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": " -10%"
  }
]

And richText for cell with "/"
    [
  {
    "font": {
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": "392.3 "
  },
  {
    "font": {
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": " / "
  },
  {
    "font": {
      "color": {
        "argb": "00c90a00"
      },
      "size": 8,
      "name": "Arial"
    },
    "alignment": {
      "vertical": "middle",
      "horizontal": "distributed"
    },
    "text": " -10%"
  }
]

Is it possible to do what the first screenshot looks like?

A:
Is it possible to do what the first screenshot looks like?

Yes, that is possible, though you're not able to align text differently in the same cell. It isn't doable with Excel itself and thus definitely not with ExcelJS! There are hundreds of articles asking the question about Excel, but one quote hits the nail on it's head:

Unlike Word, Excel does not have the concept of paragraphs within a cell. Horizontal and vertical alignment apply to a cell as a whole.

Quote taken from the User Hansv MVP from this thread.
You can approach the project via different roads, depending on which suits you the most:

*

*Split the cells with the data. ExcelJS does has the .spliceRows() function, so you could use that (with RichText formatting on respective cells).

*You could implement the logic for writing from the get-go, i.e. implement one part of the data in one cell, the next part in the cell after that and so on. Afterwards you're able to color the border to the neighboring data to your background color, thus vanishing it.

*etc.
I highly suggest the second approach. In my opinion it should be the easiest solution as you can properly set up a "formatting logic" in the sense of being free with each values you're writing.


text:
Q: How do I set the ident string when using logging.SysLogHandler in Python 2.6? I have logging configured using logging.fileConfig(). I have a the root logger going to a handler that uses SysLogHandler('/dev/log', handlers.SysLogHandler.LOG_USER)
This all works perfectly well, and I see my log entries in /var/log/user.log
The question is how can I set the syslog ident string to something other than python? It appears the syslog module in the standard lib allows setting this when opening a log, but the logging handler doesn't offer this feature.
Would the solution be to subclass SysLogHandler and use the syslog library inside it's emit method? This is a unix only program, so using syslog directly doesn't pose a portability problem.

A:
This is a bit old but new information should be recorded here so people don't feel the need to write their own syslog handler.
Since Python 3.3, the SysLogHandler has a class attribute of .ident precisely for this purpose; the default for it is ''.
Example:
import logging
from logging.handlers import SysLogHandler

h = SysLogHandler(address=('some.destination.com',514), facility=SysLogHandler.LOG_LOCAL6)
h.setFormatter(
    logging.Formatter('%(name)s %(levelname)s %(message)s')
)
h.ident = 'conmon'

syslog = logging.getLogger('syslog')
syslog.setLevel(logging.DEBUG)
syslog.addHandler(h)

syslog.debug('foo syslog message')

A: Syslog implementations accepting RFC3164 messages should recognize first part of the message ("foo:" in the example) as TAG.

The MSG part has two fields known as the TAG field and the CONTENT
field.  The value in the TAG field will be the name of the program or
process that generated the message.

Python code..
import logging
from logging.handlers import SysLogHandler

h = SysLogHandler(address='/dev/log')
h.setFormatter(logging.Formatter('foo: %(message)s'))
logging.getLogger().addHandler(h)

logging.error('bar')

..will send this into syslog socket
connect(3, {sa_family=AF_UNIX, sun_path="/dev/log"}, 10) = 0
sendto(3, "<11>foo: bar\0", 13, 0, NULL, 0) = 13
close(3)

Which in turn, produces this in systemd's journal.
Dec 13 14:48:20 laptop foo[1928]: bar

Journal message details:
{
  ..
  "PRIORITY" : "3",
  "SYSLOG_FACILITY" : "1",
  "SYSLOG_IDENTIFIER" : "foo",
  "MESSAGE" : "bar",
  "_PID" : "1928",
}

It works with Py2.6, 2.7, 3.4, 3.5 and Systemd's syslog server. It may work with other syslog implementations as well (if they accept RFC3164) messages. This solution will probably break when python's SysLogHandler will default to newer RFC5424.

A: AFAIK, the ident string is an artifact of the syslog API, see this page. It's just using the C argv[0] which would of course be "python".
I'm surprised that you're getting this using SysLogHandler with a domain socket, as the message sent to syslog daemons across domain or TCP sockets is just a string with the priority in <angle brackets> followed by the formatted message and a NUL byte. There's no ident string specified by SysLogHandler, as it doesn't use the syslog API (which has some thread-safety issues in some versions, IIRC).

A: For Python 2.7, you could do something like this:
class MySysLogHandler(logging.handlers.SysLogHandler):
    def __init__(self):
        super(MySysLogHandler, self).__init__(address='/dev/log')
    def emit(self, record):
        priority = self.encodePriority(self.facility, self.mapPriority(record.levelname))
        record.ident = "My[" + str(priority) + "]:"
        super(MySysLogHandler, self).emit(record)

handler = MySysLogHandler()
handler.formatter = logging.Formatter(fmt="%(ident)s %(levelname)s: %(message)s")
logging.root.addHandler(handler)
logging.info("hello world")

This will produce in the syslog:
Sep  3 16:28:53 hostname My[14]: INFO: hello world


text:
Q: Why is java.sql.DriverManager.getConnection() still working after removing the SQLite database JAR? I'm having difficulties in Java with an SQLITE database provided in a separate JAR file.
Surprisingly, the sqlite database seems to be accessed even after removing the JAR file, exiting and restarting the program and even after rebooting the machine.
I'm using the Xerial driver sqlite-jdbc-3.7.2.jar (for org.sqlite.JDBC).
EDIT: very same issue with sqlite-jdbc-3.8.6.jar.
Xerial JDBC driver is published here:
https://bitbucket.org/xerial/sqlite-jdbc
I'm really puzzled. Is there some kind of persistent cache for this particular JDBC driver? or is it something I missed regarding JDBC in general?
CODE SAMPLE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqliteJDBCTest {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite::resource:jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite");
            System.out.println("connection = " + connection);

            statement = connection.createStatement();
            System.out.println("statement = " + statement);
            rs = statement.executeQuery(" SELECT * FROM nonexistentTable WHERE key = 'nonexistentKey'");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

The above code sample shows the first step of the problem: on the first run, DriverManager.getConnection(..) throwed an exception as expected:
$ java -jar sqliteJDBCTest.jar
java.sql.SQLException: failed to load jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite: java.io.FileNotFoundException: doesntexistJAR.jar (Aucun fichier ou dossier de ce type)
    at org.sqlite.Conn.open(Conn.java:92)
    at org.sqlite.Conn.<init>(Conn.java:57)
    at org.sqlite.JDBC.createConnection(JDBC.java:77)
    at org.sqlite.JDBC.connect(JDBC.java:64)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:270)
    at SqliteJDBCTest.main(SqliteJDBCTest.java:18)

But, since then, for each run I get the following output:
>java -jar sqliteJDBCTest.jar
    connection = org.sqlite.Conn@3fee733d
    statement = org.sqlite.Stmt@5acf9800
    java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: nonexistentTable)
            at org.sqlite.DB.newSQLException(DB.java:383)
            at org.sqlite.DB.newSQLException(DB.java:387)
            at org.sqlite.DB.throwex(DB.java:374)
            at org.sqlite.NativeDB.prepare(Native Method)
            at org.sqlite.DB.prepare(DB.java:123)
            at org.sqlite.Stmt.executeQuery(Stmt.java:121)
            at SqliteJDBCTest.main(SqliteJDBCTest.java:23)

In this example, the SQLException "SQL error or missing database" is not the error we're expecting!
Not only is the database missing, but even the JAR file supposed to contain it!
So how come getConnection() doesn't throw an exception in the first place?

A: Short answer: because of a bug in the Xerial JDBC driver.
When one requests the Xerial driver a connection by calling DriverManager.getConnection(jdbc:sqlite::resource:jar:file:<local_location_of_JAR>!/<name_of_database_file>), the driver creates a copy of the database file on the temporary directory specified by the Java system property java.io.tmpdir and then operates on this copy.
The problem is that when the original JAR is removed, the driver loads the copy the next time(s) one uses the same getConnection() call. For me, this is a bug; the driver should at least check that the (possibly remote) JAR file pointed to by the URL is still there...
Second problem (the one described in the CODE SAMPLE of this post): when the original JAR file doesn't exist, a "copy" of the (non-existent) database is created, and the next time(s) getConnection() is called with the same parameters, the driver directly returns a phantom connection to this empty database that was never found...
I submitted this story in a bug report on the Xerial JIRA website:
https://bitbucket.org/xerial/sqlite-jdbc/issue/158/drivermanagergetconnection-not-returning


text:
Q: How to POST extra parametre on twitter typeahead for CodeIgniter I'm using CodeIgniter with csrf protection enabled and Bootstrap 3 and twitter typeahead 0.9.3
I need to post my query with csrf key. I lost a day searching this. Tried beforeSend option but it doesn't work here is my code:
$('input[name="search"]').typeahead({
        name:"companies",
        remote:{
            url:"{/literal}{site_url('tender/search_suppliers')}/{literal}",
            beforeSend:function(jqXhr,settings){
                settings.type = 'POST';
                settings.data = { csrf_test_name: $.cookie('csrf_cookie_name')}
                settings.hasData=true;
                settings.hasContent=true;
                return true;
            }
        }

    });

This code is not posting and did not change type from GET to POST
SORRY for my english

A: I've run into the same problem RE: CSRF Protection in codeigniter and running any kind of ajax based function.
I added this function to my main site.js file that is loaded on all of my pages, and therefore gets included in all of my ajax calls:
$.ajaxSetup( data: { csrf_test_name: $.cookie('csrf_cookie_name') } );


text:
Q: Weird symbols on end when inserting text into a file I'm trying to make a simple program for inserting some text on specific position in existing text file. For example if is in file text.txt text "sample text", after running program should be in text.txt "saminserting textple text". But sometimes program inserts some Weird symbols to the end of text, so in this case I got "saminserting textple textX€" (where is for some reason "X€" on the end of text) and I can't figure out, why.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ( int argc, char *argv[] )
{

FILE *file;

 file = fopen("text.txt", "rb+"); //processed file
 if (file == NULL) return 0;

 char *test = "inserting text"; //text for inserting
 char *buffer;
 int size;

 fseek(file, 0L, SEEK_END);
 size = ftell(file);

 fseek(file, 3L, SEEK_SET);
 buffer = malloc(abs(3L - size) + 1);
 fread(buffer, abs(3L - size), 1, file);

 fseek(file, 3L, SEEK_SET);
 fwrite(test, strlen(test), 1, file);
 fwrite(buffer, strlen(buffer), 1, file);

 free(buffer);
 fclose(file);

 return 0;
}

I'll be grateful for any help.

A: buffer = malloc(abs(3L - size) + 1);
fread(buffer, abs(3L - size), 1, file);
...
fwrite(buffer, strlen(buffer), 1, file);

You never null-terminate buffer so you potentially write a different about to what you read. Do this instead. (But really, use size-3 or something nicer...)
fwrite(buffer, abs(3L - size), 1, file);


text:
Q: Documenting module/class/function bodies in Python Sphinx docs Is there a way with Sphinx documentation to output a function or class body (the code itself) with the autodoc feature? I'm using autodoc to much success. In addition to the docstrings getting pulled in to the documentation I want like a link to click for each function where it will show you the source... is that possible?
This is about what most of my documentation looks like now:
.. module:`foo.mymodule`

Title
===================

.. automodule:: foo.mymodule

.. autoclass:: MyModulesClass
    :members:
    :undoc-members:

A: If this still matters: The viewcode extension can do this, but needs the development version (1.0) of Sphinx

A: I don't believe so.  Autodoc is only for pulling the documentation out of the source code.


text:
Q: USAR FUNCTION CON PHP Estoy intentando definir una funcion que haga un update a la base de datos despues de un select. Pero al definirla, pareciera que no recibiera los parametros.
Lo estoy haciendo con ajax y y consulta la bd con php.
       include('../../control/parcel/db.php');

                     if (isset($_POST['id'])) {

                    $id = $_POST['id'];
                 $query = "SELECT * FROM reclute where id='$id'";
               $result = mysqli_query($connection, $query);

         if (!$result) {
                  die('Query Failed' . mysqli_error($connection));
                }

                $json = array();
           while ($row = mysqli_fetch_array($result)) {
               $json[] = array(
                 'id' => $row['id']
            );

                   function LeerNotificacion($id)
                 {
           $query2 = "UPDATE reclute SET estado=('leido')
                   where id='$id';";
                   $result2 = mysqli_query($connection, $query2);
                }
                 LeerNotificacion($id);
               }
                $jsonstring = json_encode($json);
             echo $jsonstring;
          }

me funciona si lo hago sin la function, pero quiero hacerlo con la function.
en ajax me da el error
   Uncaught SyntaxError: Unexpected token < in JSON at position 0
  at JSON.parse (<anonymous>)
   at Object.success (Datos_reclute.js:132)
  at c (jquery.min.js:2)
   at Object.fireWith [as resolveWith] (jquery.min.js:2)
   at l (jquery.min.js:2)
   at XMLHttpRequest.<anonymous> (jquery.min.js:2)


text:
Q: trouble handling strings with three or more '0' using pgloader I am loading large .csv files into a database and want to use pgloader because it is able to skip and log erroneous records. However I frequently get
ERROR PostgreSQL Database error 22021: invalid byte sequence for encoding "UTF8": 0x00
Which I first thought was due to 0x00 characters in my data. I tried different ways to remove these to no avail, until I noticed that some variables e.g. timestamps with three or more 0characters seem to be causing the problem. e.g. 17:46:30 +0000. Does anyone know how to handle this problem without changing my data? About 2/3 of my records have this problem. Ideally I am looking for a fix that allows me to import the data using the same procedure.


text:
Q: Available Guidelines for Interrupt Driven Processing Are there any available guidelines for the amount of code to have in a critical section of interrupt driven processing?
My personal rule of thumb is that the critical portion, (i.e. that between disable interrupts and enable interrupts), of any interrupt driven processing should be no more than about a dozen lines of code, (including those in any function/library/macro called), and that the processing should be as linear as possible.
I would expect something along the lines of:
disable_interrupts
if error_condition:
   set_error_flag
else:
   small_data_transfer
   set_ready_flag
enable_interrupts

However I have been asked to look into an existing project where some of the interrupts have  handlers where the call charts will not fit on a sheet of A1 (all in the critical section).
To clarify this is a "bare metal" project with no OS/Scheduler implemented - and all of the interrupt handlers start by disabling all interrupts - i.e. the original authors regarded every operation in every ISR as critical, (even the housekeeping is all inside of a disable/enable section).  There are a multitude of interrupts and hardware dependencies but as far as I can see some of the ISRs will be executing thousands of lines within the "critical" section.
I know that this is a problem and really needs to be completely rewritten but I can not find any standards, including MISRA, that I can point to rather than just saying "in my experience" - to convince the project management I need to point to some accepted standards.
So hence my question - Can anybody point me towards any standards or guidelines that I can use to back up my experience?  (Or of course am I totally wrong).

A: In general, the distribution of CPU time between ISR code and non-ISR code is very application-dependent.
If most of the work is being done in non-ISR code, then yes, you generally want to keep the ISRs as short as possible (but no shorter, to paraphrase a famous quote).
However, I have seen (and built) hard real-time DSP applications in which 90% of the work is done in the ISR, and the non-ISR code is only handling tasks that are not time-critical such as configuration, status and user interface.
Either approach is perfectly valid in deeply-embedded systems.

A: The general guideline is that critical sections should be as short as possible.
What you really need to do is account for the length of the critical section when you verify the schedulability of the task set. Doing that depends on how you are scheduling the tasks, but I think it could be as simple as adding the execution time of the critical section to the execution time of every lower-priority task.

A: I think you have to consider the execution time of the uninterruptible code wrt the fastest response time (latency) and variability of that time (jitter) you need from the microcontroller. It may not be intuitive what that is-- it may be something that is 'urgent' but not 'important'.
For example, a controller I designed some years back needed to deal with RS-232 inputs, to update the output using the control algorithm, to control the dual-slope ADC, to scan an LED display and keyboard (including debouncing), write to a slow EEPROM, and to control an electromagnetic beeper (and probably I couple of other things I've forgotten). Turned out the most critical response time was the beeper periodic interrupt (every 250usec), followed by the LED display, mostly for cosmetic reasons. So if 10% jitter in the beeper toggle was acceptable, that's 25usec of uninterruptable code (which wasn't many instructions, but enough to make certain things atomic). That particular processor supported nested interrupts, so IIRC I ended up making the periodic interrupt code re-entrant after the first section.
If you're deferring pending interrupts during long sections of code, it may be just fine, if your requirements for latency and jitter are fairly relaxed in relation to the execution time of the "critical portions".
My usual approach is to minimize the code execution time in ISRs and to get back as quickly as possible (perhaps stuffing things like debounced input event tokens into circular queues, set flags and get out). For example, if a complex control algorithm needs to be executed every 200msec with maximum 20msec jitter, I'd set a flag every 200msec in the timer interrupt and poll that flag outside the ISR.
Aside from meeting design requirements, reliability is enhanced by this approach.
As far as finding some kind of guideline that states this.. I suggest looking at some of the safety-critical software guidelines. You may not find it stated directly, but you may be able to infer it from other statements. UL1998 IEC 60730 etc. This FAA document states:

Interrupts and their effect on data must receive special attention in safety-critical areas. Analysis should
  verify that interrupts and interrupt handling routines do not alter critical data items used by other routines.

and

Of particular concern to safety is ensuring the integrity of safety critical data against being inadvertently
  altered or overwritten. For example, check to see if interrupt processing is interfering with safety critical
  data.

Both of which become more difficult as the size of the interrupt code increases.
Short (in relation to maximum jitter and latency) frequent interrupts can be analyzed as an effective decrease in processor speed rather than having to deal with worst-case stack-ups of long interrupts at the most critical times, which argues for fast execution as well as simple code within ISRs.

A: To me, avoiding nesting interrupts does not seem too bad or even absurd. In fact, nested interrupts may cause more problems than they solve.
I'm specifically referring to memory used to save/restore context when entering/exiting the ISR. Commonly on simple architectures each ISR will save all required context of the code it interrupted, for example on the processor's stack. When developing the software one needs to account for this memory.
If, for example, ISR A requires 10 bytes of context to be saved/restored, ISR B needs 15 and ISR C needs 12 bytes the calculation/estimation simply is:
Anywhere during the execution of non-critical sections any of the ISRs may be triggered. Now, if the ISRs are not allowed to be nested, the maximum memory required for the context is max( 10, 15, 12 ) = 15 bytes. If each of the ISRs may interrupt any other of those 3 ISRs, the worst case will be 10 + 15 + 12 = 37 bytes of context which need to be stored at the same time. So at every instant during execution (of non-atomic code), there must be at least enough memory available for those 37 bytes of context, vs. 15 in the non-nesting case.
Of course, the more ISRs join the "nesting game" the more the issue becomes visible.
If you have multiple tasks running concurrently and ISRs save context to the current stack of whatever code they're interrupting, you have to account for one worst-case context size per task.
This argument of course depends on the HW architecture you're using. It may not be applicable if the HW/Interrupt Controller is more advanced and has special features to handle context switching to/from ISRs.
Apart from that, complex ISRs tend to require more context data to be saved/restored than simple ones, so that small, concise ISRs are usually recommended because they provide multiple benefits:

*

*quick execution time, possibly yielding

*

*shorter critical sections and thus

*less jitter

*smaller context, resulting in

*

*less worst-case memory usage and (architecture-dependent)

*even less execution time (by not having to transfer as much state information from A to B to A)

In the end, if all ISRs are reduced to their minimum, like when only setting a flag, the question of whether or not to allow nesting ISRs may be answered clearly in favour of non-nesting because the benefit of nesting ISRs vanishes.


text:
Q: Combine materials/textures with alpha maps I have an object (brain) with a texture.
This brain-texture shall be overlayed/mixed with a heatmap that is integrating an alpha map. What I could archieve so far:

*

*The heatmap texture combined with the alpha map becomes an material

*The brain-texture combined with a pure heatmap-texture via Multiple transparent textures on the same mesh face in Three.js
The problem I have is the combination of both steps.
My brainmaterial step (combining heatmap and brain-texture)
brainTexture = new THREE.ImageUtils.loadTexture("/assets/textures/brain_tex.jpg");
  // uniforms
  uniforms = {
    color: { type: "c", value: new THREE.Color(0x0000ff) },
    texture: { type: "t", value: brainTexture },
    texture2: { type: "t", value: heatmapCanvasTexture }
  };
  brainMaterial = new THREE.ShaderMaterial({
    attributes: attributes,
    uniforms: uniforms,
    vertexShader: document.getElementById('vertex_shader').textContent,
    fragmentShader: document.getElementById('fragment_shader').textContent
  });

Fragmentshader I am using:
uniform sampler2D texture;
uniform sampler2D texture2;
uniform vec3 color;
varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vViewPosition;

void main() {
vec4 tc = vec4(color.r, color.g, color.b, 1.0 );
    vec4 tColor = texture2D( texture, vUv );
    vec4 tColor2 = texture2D( texture2, vUv );

    // hack in a fake pointlight at camera location, plus ambient
    vec3 normal = normalize( vNormal );
    vec3 lightDir = normalize( vViewPosition );

    float dotProduct = max( dot( normal, lightDir ), 0.0 ) + 0.2;

    //gl_FragColor = vec4( mix( tColor.rgb, tColor2.rgb, tColor2.a ), 1.0 ) * dotProduct;

    vec4 mix_c = tColor2 + tc * tColor2.a;
    gl_FragColor = vec4( mix( tColor.rgb, mix_c.xyz, tColor2.a ), 1.0 ) * dotProduct;

}

Result:
My alphamap step:
heatmapMaterial = new THREE.MeshBasicMaterial({
    map: heatmapCanvasTexture,
    side: THREE.DoubleSide,
    alphaTest: 0.5,
    alphaMap: THREE.ImageUtils.loadTexture("/assets/textures/heatmap_alphamap.jpg")
  });

Result:
How can I integrate the modified (by alphamap) heatmap-material into my brain-material (via shader programming?)?
To be clear: the brain-texture should be visible on the entire object but a specific part (alphamapped) should be mixed with a heatmap. So a specific region in the brain can have a heatmap overlay.
Desired result:

A: Something like this should work:
vec4 brain = texture2D( brainTexture, uv );
vec4 heatmap = texture2D( heatmapTexture, uv );
float alpha = texture2D( alphaTexture, uv ).r;
gl_FragColor = mix( brain, heatmap, alpha );

If you post your fragment shader I can try to be more specific.