text:
Q: Using PHP iterators friends. I know, there are many questions here already on these iterators.
I've read something, and I'm not a beginner... but my mind is somewhat stuck on this. Please, help me to comprehend how I use iterators in practice.
Suppose, I have an ORM object that can select instances from database. And one instance contains fields and can insert, uodate etc. As usual.
I want to iterate through all objects of a type, but as there can be plenty of them, I prefer to select them by "pages". My code:
$limit = 100;
$offset = 0;
do
{
  $recs = $orm->select($filter, $sorting, $limit , $offset);
  $offset += $limit;
  foreach ($recs as $rec)
  {
    // doing something with record
  }
}
while (count($recs) == $limit);

I feel that iterator paradigm is what suits here, but what interface is better to implement in this case or maybe some base SPL class?
UPDATE
Ideally code above with iterator may look like:
$iterator = new ORMPagedIterator($ormobject, $filter, $sorting);
foreach ($iterator as $rec)
{
  // do something with record
}

E.g. all that page by page behavior is inside the iterator.

A: I would use an Iterator that iterates over another Iterator and asks for a next Iterator once it reaches the end of the previous Iterator...  ok, sounds a mo complicated than it actually is:
<?php
$limit = 100;
$offset = 0;

$iter = new NextIteratorCallbackIterator(function($i) use ($orm, $limit, &$offset) {
    printf("selecting next bunch at offset %d\n", $offset);
    $recs = $orm->select($filter, $sorting, $limit , $offset);
    $offset += $limit;
    if ($recs) {
        return new ArrayIterator($recs);
    }
    return null; // end reached
});

foreach ($iter as $rec) {
    // do something with record
}
?>

And here is a sample Implementation of that NextIteratorCallbackIterator:
<?php
class NextIteratorCallbackIterator implements Iterator {
    private $_iterator = null;
    private $_count = 0;
    private $_callback;

    public function __construct($callback) {
        if (!is_callable($callback)) {
            throw new Exception(__CLASS__.": callback must be callable");
        }
        $this->_callback = $callback;
    }

    public function current() {
        return $this->_iterator !== null ? $this->_iterator->current() : null;
    }

    public function key() {
        return $this->_iterator !== null ? $this->_iterator->key() : null;
    }

    public function next() {
        $tryNext = ($this->_iterator === null);
        do {
            if ($tryNext) {
                $tryNext = false;
                $this->_iterator = call_user_func($this->_callback, ++$this->_count);
            }
            elseif ($this->_iterator !== null) {
                $this->_iterator->next();
                if ($this->_iterator->valid() == false) {
                    $tryNext = true;
                }
            }
        } while ($tryNext);
    }

    public function rewind() {
        $this->_iterator = call_user_func($this->_callback, $this->_count = 0);
    }

    public function valid () {
        return $this->_iterator !== null;
    }
}
?>

UPDATE: Your ORMPagedIterator can be implemented using NextIteratorCallbackIterator as easy as:
<?php
class ORMPagedIterator implements IteratorAggregate {
    function __construct($orm, $filter, $sorting, $chunksize = 100) {
        $this->orm = $orm;
        $this->filter = $filter;
        $this->sorting = $sorting;
        $this->chunksize = $chunksize;
    }

    function iteratorNext($i) {
        $offset = $this->chunksize * $i;
        $recs = $this->orm->select($this->filter, $this->sorting, $this->chunksize, $offset);
        if ($recs) {
            return new ArrayIterator($recs);
        }
        return null; // end reached
    }

    function getIterator() {
        return new NextIteratorCallbackIterator(array($this,"iteratorNext"));
    }
}
?>


text:
Q: Can't figure out how to install ViewPager For the past hour, I've been looking at how to add support libraries to your build path so that I can learn how to use ViewPager. But for some reason, after I add the jars to my build path and clean the project, nothing new shows up in my palette and if I try to copy and past some XML code for a ViewPager in, it doesn't recognize it in the build path! I really have no idea what's going wrong here. Any advice would be greatly appreciated.

A: Can you post any screenshot or something? It'll be easier for everyone to help you fix the issue.
Anyway you will need to add android-support-v4.jar to use ViewPager. Usually when you add this jar to libs folder and build path, then you can add code to your xml file just like this (it also didn't show up in my palette):
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test.MainActivity" />

There's an easy way to check your issue.

*

*Create a new Android application in Eclipse/Android Studio

*When it asks you to create a activity or not, choose Tabbed Activity and then choose ViewPager in Navigation Style combo-box

*Once the project is successfully compiled, customize it the way you want or compare it to your own project to check if you're missing something. Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tracking mouse position of a jqplot vertical line chart I want to create a jqPlot line chart which has the ability to change orientation between vertical and horizontal orientation. I was able to achieve this using CSS rules, by rotating the div element containing the chart.
My work up to now: http://jsfiddle.net/GayashanNA/A4V4y/14/
But the problem is I also want to track the mouse-pointer and mouse clicks on points on chart after the orientation is flipped because i want to annotate those points. I am unable to do this when the chart is in vertical orientation. Can anyone suggest a method to do this? Or am i approaching the problem in a wrong way?
(Note: I am able to do this in horizontal orientation, you can observe it if you try to click on a point on the above chart.)
Thanks and help is much appreciated.

A: I've never used jqPlot, but I guess your problem is trying to use css rotate(), since the cursor plugin is using the mouse position to determine where to draw the lines, and element's size doesn't change when transformed by rotate(), it still have the same width and height values.
If you take a look at the code, you will see:
if (c.showVerticalLine) {
    c.shapeRenderer.draw(ctx, [[gridpos.x, 0], [gridpos.x, ctx.canvas.height]]);
}
if (c.showHorizontalLine) {
    c.shapeRenderer.draw(ctx, [[0, gridpos.y], [ctx.canvas.width, gridpos.y]]);
}

So it seems like the library is always drawing the lines based on mouse position over the original element, which of course, won't match the position after being transformed by rotate(), and XY coordinates are going to be transformed to YX after rotate().
I would try to change the size of your original element, though I don't know if the library lets you specify in which sides are the labels going to be drawn.

A: I finally found a solution for the problem. But i had to change jqPlot library to achieve this. To help anyone else who run in to the same problem, i'll put my solution here.
First i had to insert the following code in to the jqPlot class of the jquery.jqplot.js file, which is the core library.
function jqPlot() {
    //add the following code segment
    var verticallyOriented = false;
    this.setVertical = function(state){
        verticallyOriented = state;
    }
    //don't change other code that isn't mentioned here

    //now you have to change the logic in the getEventPosition function
    //to make sure the new orientation is detected
    function getEventPosition(ev) {
        //change the line starting with var gridPos = ...
        //to the following code segment
        //depending on the orientation the event position calculating algorithm is changed
        if(verticallyOriented){
            var gridPos = {x:ev.pageY - go.top , y:plot.eventCanvas._elem.height() - ev.pageX + go.left};
        } else {
            var gridPos = {x:ev.pageX - go.left, y:ev.pageY - go.top};
        }
        //no change to other code is needed
    }
}

You can view a working example here: http://jsfiddle.net/GayashanNA/yZwxu/
Gist for the changed library file: https://gist.github.com/3755694
Please correct me if i have done something wrong.
Thanks.


text:
Q: Nginx not redirecting to Django I am setting up a production server with Angular serving the front end and Django on the back. I got Nginx serving Angular properly but any requests to the backend dont go through and just time out.
I have Nginx serving Angular on port 80 and then Django on port 8800
This is the code I have in place for Django
server {
   listen 8800;
   server_name ADDRESS;
   location = /favicon.ico {access_log off;log_not_found off;}

   location = /static/ {
     root /home/ubuntu/django/dbsystem;
   }
   location = /media/ {
     root /home/ubuntu/django/dbsystem;
   }

   location = / {
     include proxy_params;
     proxy_pass http://unix:/home/ubuntu/django/dbsystem/dbsystem.sock;
   }
 }

This is the code I have in place for Angular
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;
    server_name _;

    location / {
            try_files $uri $uri/ /index.html;
    }
}

This is the code for Gunicorn
[Unit]
Description=gunicorn service
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/django/dbsystem/
ExecStart=/home/ubuntu/django/bin/gunicorn --access-logfile - --workers 3 -- bind unix:/home/ubuntu/django/dbsystem/dbsystem.sock dbsystem.wsgi:application

[Install]
WantedBy=multi-user.target

*

*If I go to ADDRESS it pulls up Angular which is expected

*If I go to ADDRESS/suburl it pulls up the appropriate Angular Route as expected

*If I go to ADDRESS:8800 it loads up the Django (Not found) page since its in debug mode which is expected

*If I go to ADDRESS:8800/suburl it waits a bit and goes into timeout which is the issue I am trying to solve. This is for both the /media route and all other routes. I dont have/use the static folder route I defined

A: There is a problem with location = in you nginx configuration. Please remove = and it would work.


text:
Q: uploadProgess() is not working $('#formName').on('submit', function(e){
    e.preventDefault();
    $.ajax({
        url: "file.php",
        type: "POST",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        beforeSend: function(){
            // do something
        },
        uploadProgress: function(event, position, total, percentComplete){
            // do something
        }
    })
    .done(function(data){
        // do something
    })
    .fail(function(data){
        // do something
    })
});

In above code, when actual data/statements are processed then beforeSend() & the uploadProgress() function are not working at all. Please help me understand the problem. Might the code structure is wrong or I'm missing few things within this code itsef.

A: fo reference like js seeenter link description here

$(function() {

    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });
});
<form action="file-echo2.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">

    <input type="submit" value="Upload File to Server">
</form>

0%

A: First of all, thank you all who responded to my question, I really appreciate that. Now, after coding and testing, testing and coding and on and on and on... I came up with a solution to my own problem. And as an opportunity, I would like to share that with you all. so here its is::

*

*First thing First - uploadProgress is not a parameter of .ajax() method, so it can't be used as I was trying to use it very first snippet.

*Well, what if we want to to use uploadProgress for any kind of work to be done like upload/download or whatever. So the answer to the question isxhr: function() that takes care of all the XMLHttpRequest() within the jquery.

So, hope it this information may help you in any case. If

YES

Do RATE this ANSWER :D - Have a Great Day!


text:
Q: Problem with an image I have a template for my project and I don't know very much about LaTeX.
It puts that for putting an image is:
\begin{figure}
\centering
% dummy figure replacement
\begin{tabular}{@{}c@{}}
\rule{.5\textwidth}{.5\textwidth} \\
\end{tabular}
\caption{\label{fig:example}A figure}
\end{figure}

but I think that in this text is missing a command to insert the image like this: \includegraphics[width=0.7\textwidth]{mifigure} but if I put that, it does´t work.
also if I put \includegraphics without width=0.7\textwidth, the image appear too big to the side of the document.
(my image is inside a folder and it is .png)
Now I have another problem related to this.
In main.tex
\documentclass{MScthesisITEM}
\DeclareGraphicsExtensions{.pdf,.jpg,.png}
\graphicspath{{./figs/}}

In example chapter4.tex
\begin{figure}
\centering
% dummy figure replacement
\begin{tabular}{@{}c@{}}
\rule{.5\textwidth}{.5\textwidth} \\
\end{tabular}
\caption{\label{fig:example}A figure}
\end{figure}

This shows a black image in the center of the document.
In my chapter.tex
\begin{figure}
\centering
% dummy figure replacement
\begin{tabular}{@{}c@{}}
\rule{.5\textwidth}{.5\textwidth} \\
\includegraphics[width=.5\linewidth]{circuitpacket}
\end{tabular}

\caption{ Explanation...}
\label{fig:comparison_circuit}
\end{figure}

I obtained the black image and my image after the black image. How can I erase the black image?

A: If your images are in the same directory in which the input file exist, the following code should work. Please make a try by replacing example-image-a with your-image-filename. And make sure you compile with pdflatex rather than latex followed by dvips followed by ps2pdf.
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}
\centering
\includegraphics[width=.5\linewidth]{example-image-a}
\caption{Hello Universe}
\label{fig:HelloUniverse}
\end{figure}
\end{document}

But if your images are in a sub directory subdir1, subdir2, etc, for example, then you need to specify the graphics path as follows.
\documentclass{article}
\usepackage{graphicx}
\graphicspath{{subdir1/}{subdir2/}}
\begin{document}
\begin{figure}
\centering
\includegraphics[width=.5\linewidth]{example-image-a}
\caption{Hello Universe}
\label{fig:HelloUniverse}
\end{figure}
\end{document}


text:
Q: Manejo de Threads en un DataGridView en VB .net Estoy actualizando automáticamente y manualmente un datagridview con datos cada cierto tiempo. Para esto, borro todas las filas y las inserto de nuevo manualmente con datos programados. No uso ninguna base de datos ni tabla.
El problema es que estoy con un thread para no bloquear la GUI, y desde ese thread estoy borrando y añadiendo las filas. Sin embargo, después de varias pasadas, el sistema me tira "NullReferenceException".
Éste es mi código:
     Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
                Dim wreturnCode1 As Integer = System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf RepeatAction), cancellation.Token)
        End Sub

        Private Sub RepeatAction(ByVal obj As Object)
            Dim token As System.Threading.CancellationToken = CType(obj, System.Threading.CancellationToken)
            FormTimer.Enabled = True
            AddHandler FormTimer.Elapsed, AddressOf AutoTaskRepo
       End Sub

       Private Async Sub AutoTaskRepo()
        FormTimer.Enabled = False
        DataGridView1.Rows.Clear()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        DataGridView1.Rows.Add()
        FormTimer.Enabled = True

   End Sub

Éste es el error:

Excepción no controlada del tipo 'System.NullReferenceException' en
  System.Windows.Forms.dll
Información adicional: Referencia a objeto no establecida como
  instancia de un objeto.

¿Algúna solución?
No puedo avanzar con esto.

A: Intenta con este código:
DataGridView1.update()
DataGridView1.refresh()

Después de hacer cualquier modificación al grid.
En algún punto el grid se queda sin los rows estas intentando acceder, o algo así, lo mejor será ir actualizándolo después de cada acción.


text:
Q: Make objects to move faster in lua issue I have created a game in lua. Everything seemed to work good in corona simulator. But when I installed the game on my device, he game begin to hang after 3-4 consecutive iterations. (Means when I clicked on 'replay' to play again, the game began to hang.
This is what I tried:
function animal()
local animal=display.newImage("animal.png")

    local z= math.random(1,1000)

      if z<=300
        then
        animal.x=330
          animal.y= centerY + 80

      elseif z<=650
           then
          animal.x= centerX + 60
          animal.y=centerY + 100

      else
          animal.x= 1180
          animal.y=centerY + 100
      end

        animal.trans=transition.to (animal, {time=1001, y=-150, alpha=1, onComplete = gameOver})
        animal: addEventListener ( "tap" , disapp )

function remove_listen_animal()
    Runtime: removeEventListener ( "tap" , disapp )
    return
end

function remove_animal()
    display.remove(animal)
end
end

local function disapp (event)
    local obj = event.target

    transition.cancel (event.target.trans)
    display.remove(obj)
    animal()

return
end

function gameOver()

    transition.cancel()
    remove_animal() --removes object from gameOver screen
    remove_listen_animal() --removes animal event listener
    scoreText.text=nil
    mainScreen() --This is the function invoked at very first when game is started. In order to restart the game,I re-invoked this function.

end

Now When I start the game,the first run goes perfect on device. But when game is over and I again tap the 'play' button to play, then game begins to hangs.
Help me with this please?
Also, I want the speed of movement [as in transition.to()] of object to be fast. Can this be reason of game hanging after 2-3 iterations?
P.S I think the problem is in gameOver function. Is there any way by which all running operations get killed/ended when gameOver function is invoked?
Because when I restart the game after closing it, again the first iteration runs fine, but later hangs again.
Help please?
Thanks

A: Are you using composer in your game? If not, composer will solve some problems about memory leaks when you used it right. Try this:
function remove_animal()
  display.remove(animal)
  animal = nil
end

And avoid making your functions visible in the global scope, always put local to it if that function is only needed in a certain scene.


text:
Q: How can we get the table count with specific date when rows adding day to day? Hi all please help me to get the result on date wise selection
For example I have table and rows on 14-08-2022
id name
1   A
2   B
3   C

and  rows on 15-08-2022
id name
4   D
5   E

and  rows on 16-08-2022
id name
6   F
7   G

If I select date  14-08-2022 i should get result
id name
1   A
2   B
3   C

If I select date 14-08-2022 to 15-08-2022 I should get result
id name
1   A
2   B
3   C
4   D
5   E

If I select date 15-08-2022 to 16-08-2022 I should get result
id name
4   D
5   E
6   F
7   G


text:
Q: Can't import maven into Eclipse - maven-compilier-plugin:2.3.2:compile I did see several posts about this issue, but they didn't work for me...
Here is my environment:
Eclipse Juno version: Juno Service Release 1
m2e: 1.4.0
maven: 2.2.1
I generated a HelloWorld sample with Maven and tried to import it into Eclipse by doing File -> Import -> Existing Maven Projects -> Browse -> select Hello World -> Next. However, it shows two errors:
maven-compilier-plugin:2.3.2:compile(1 errors)
maven-compilier-plugin:2.3.2:testCompile(1 errors)
I expended these two and similar notices as follows:
Execution default-compile, in/pom.xml
Execution default-testCompile, in/pom.xml


text:
Q: Command doesn't work in script, but works in shell I'm writing a script for using SSH "profiles", ~/scripts/ssh-profiled.sh
PROFILE=`cat ~/script/ssh-profiles/$1`
echo [ssh $PROFILE]
ssh $PROFILE

~/scripts/ssh-profiles/tummi
-i ~/Dropbox/security/key-nopass/key-nopass.pvt bart@example.com

When I run the script, it fails:
bart@bart-laptop:~$ script/ssh-profiled.sh tummi
[ssh -i ~/Dropbox/security/key-nopass/key-nopass.pvt bart@example.com]
Warning: Identity file ~/Dropbox/security/key-nopass/key-nopass.pvt not accessible: No such file or directory.
bart@example.com's password:

But this works:
bart@bart-laptop:~$ ssh -i ~/Dropbox/security/key-nopass/key-nopass.pvt bart@example.com
Linux tummi 2.6.32-24-server #39-Ubuntu SMP Wed Jul 28 06:21:40 UTC 2010 x86_64 GNU/Linux
Ubuntu 10.04.1 LTS

Welcome to the Ubuntu Server!

Is there an error/gotcha in my script?

A: Change 1st line to
eval PROFILE=`cat ~/script/ssh-profiles/$1`

For explanation see here

A: The ~ in your file needs to be the full home directory path, it's not getting expanded.

A: My guess is the "~/" is not being interpreted as expected when passed in that way. Try using an explicit full path.

A: What are the permissions on the .pvt file? If only you have read access, and no one can execute it, then your script might not be able to even see the file. That could be why you are getting the "...not accessible: No such file or directory." message.


text:
Q: Google Adwords multiple scripts in one page I need to put two (google adwords) scripts in same page. Is it safe to put two scripts at same page ?

The other adowrds conversion script

I just want to know if both scripts run fine simentaniously ? Can there be any problem on loading one script twice and declearing google_conversion_xxx variables twice ?
If not safe then what is other way around for this ?

A: Tip: Track multiple kinds of conversions
Do you want to track multiple kinds of conversions from the list above? Just set up a different conversion action for each type of conversion you want to track. For example, you can set up one conversion action to track purchases on your website, and another to track calls from your ads.
You can also set up multiple conversion actions for each conversion source. For example, say you want to track two different actions on your website: purchases and newsletter sign-ups. You'd set up two conversion actions: one for the purchases and one for sign-ups.
If you're tracking multiple conversion actions, you might want to use the "Include in 'Conversions'" setting to choose which conversions to include in your "Conversions" reporting column. Learn more


text:
Q: Solving a system of first order differential equations So, I have (another) problem with differential equations (from an optimal control problem). I am trying to solve the following system of DEs (is this even a system?):
$$ \lambda'(t) = r \lambda(t) + x' h(x(t)) \\ \lambda = g(x(t)) \\ \lambda(T) = 0, \quad x(0)=0 $$
with
$x: [0,T] \to \mathbb{R}_+$ and $\lambda: [0,T] \to \mathbb{R}$
So, I thought, the 2nd equation is really simple (and $g$ has nice properties, including being cont. differentiable), so I tried to just try to get one DE in $x'$ and replace $\lambda$ with $g(x)$ and $\lambda'$ with $\frac{d g(x(t))}{d t} = x'g'(x(t))$.
When I now try to solve the resulting initial value problem:
$$ x'(t) g'(x(t)) = r g(x(t)) + x'(t) h(x(t)), \quad x(0) = 0$$
So this is the point when I realized: something went wrong. I completely ignored $\lambda(T) = 0$ and when trying to solve an example I get a solution which seems to be for a problem without $\lambda(T) = 0$ (big surprise!), which is clearly wrong for a finite $T$.
So finally my question(s): What did I do wrong? And how can I fix it? Is there a general way to solve the initial value problem I stated at the beginning for nice $g$ and $h$?


text:
Q: Spring security dynamic authorization and authentication I founded this xml spring security configuration on the web in order to create a dynamic role authentication:
<bean id="filter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager">
     <bean class="org.springframework.security.access.vote.AffirmativeBased">
        <property name="decisionVoters" >
        <bean class="org.springframework.security.access.vote.RoleVoter">
            <property name="rolePrefix" value="ROLE_"/>
        </bean>
        </property>
     </bean>
</property>
<property name="securityMetadataSource" ref="dbFilterInvocationSecurityMetadataSource"/>
</bean>

I am trying to replace it with annotation and for this purpose i created this bean:
@Bean
public FilterSecurityInterceptor filterSecurityInterceptor(AuthenticationManager auth) {

    List<AccessDecisionVoter<?>> decisionVoters = new ArrayList<>();
    RoleVoter decisionVoter = new RoleVoter();
    decisionVoter.setRolePrefix("");
    decisionVoters.add(decisionVoter);
    FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
    filterSecurityInterceptor.setAuthenticationManager(auth);
    filterSecurityInterceptor.setAccessDecisionManager(
            new AffirmativeBased(decisionVoters));
    filterSecurityInterceptor.setSecurityMetadataSource(dbFilterInvocationSecurityMetadataSource);
    return filterSecurityInterceptor;
}

This is my DbFilterInvocationSecurityMetadataSource class:
@Component
public class DbFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource, InitializingBean{
private static final Logger logger = LoggerFactory.getLogger(DbFilterInvocationSecurityMetadataSource.class.getName());

@Autowired
private UUsersService userService;

@Autowired
UrlCache urlCache;

private HashMap<String, List<String>> urlRoles;

@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    FilterInvocation fi=(FilterInvocation)object;
    String url=fi.getRequestUrl();
    logger.debug("Request Url====>"+url);

    List<String> roles_=urlRoles.get(url);
    logger.debug("Ruoli associati all'url :"+roles_);
    if(roles_==null){
        return null;
    }
    logger.debug("------------------");
    String[] stockArr = new String[roles_.size()];
    stockArr = roles_.toArray(stockArr);
    return SecurityConfig.createList(stockArr);
}

@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
    return null;
}

@Override
public boolean supports(Class<?> clazz) {
    return true;
}

@Override
public void afterPropertiesSet() throws Exception {
    userService.getUrlRoles();
    this.urlRoles=urlCache.getUrlRoles();
    logger.debug("Oggetto ruoli/urls :"+urlRoles);
}

}

Now, all urls are intercepted from filter and roles associated to them but i'm not able to understand how to link roles of logged user with ones retrieved from url requested.
In my loadByUsername method implementation, i recover roles associated to loggedUser in this way:
    public PMAuthenticationUserDetails loadPMUserByUsername(String username) throws UsernameNotFoundException {
    PMAuthenticationUserDetails userDTO = null;
    try{
        // get anagrafica
        UUsers user = usersDao.findUserByUsername(username);

        if(user != null){
            // get role
            List<UAuthorities> authorities = userAuthorityDao.findAuthoritiesByUserId(user.getId());

            //get urls
            List<UResource> urls = authorityResourceDao.findUrlsByAuthorities(authorities);

            logger.info("L'utente con username: " + username + " esiste e ha n° " + authorities.size() + " ruoli associati.");

            /** per spring */
            Collection<GrantedAuthority> authoritiesDTO = new ArrayList<GrantedAuthority>();

            /** lista codici ruoli (Stringhe prive del prefisso spring "ROLE_" */
            List<String> codeAuthorities = new ArrayList<String>();

            logger.info("Elenco ruoli: ");

            for (UAuthorities item : authorities) {
                logger.info(AuthenticationType.PREFIX_ROLE + item.getAuthority());
                /**
                 * Quindi creiamo un oggetto di SimpleGrantedAuthority per passare quel ruolo in esso.
                 */
                authoritiesDTO.add(new SimpleGrantedAuthority(AuthenticationType.PREFIX_ROLE + item.getAuthority()));
                /**
                 * Aggiungo alla lista il codice del ruolo.
                 */
                codeAuthorities.add(item.getAuthority());
            }

            /**
             * Dopo valorizziamo l' oggetto user personalizzato che avrà il nome utente, le credenziali, ed
             * eventuali altri campi come e-mail ecc.
             */
            userDTO = new PMAuthenticationUserDetails(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authoritiesDTO);
            // set custom property
            userDTO.setUserId(String.valueOf(user.getId()));
            userDTO.setFirstname(user.getFirstname());
            userDTO.setLastname(user.getLastname());
            userDTO.setEmail(user.getEmail());
            userDTO.setAvatar(user.getAvatar());
            userDTO.setRoles(codeAuthorities);
        }else
            logger.error("L'utente con username: " + username + " >>> NON E' STATO TROVATO IN TABELLA.");

        return userDTO;
    }catch(Exception e ){
        logger.error("loadPMUserByUsername >>> " + e, e);
        return userDTO;
    }
}

I need something more in my configuration?
`


text:
Q: Drawing more than one object to JFrame I try to draw 2D objects in the same JFrame panel.
I wrote such a code, but to be honest, it doesn't work as I expected, I guess while adding the second object, it destroyed the previous one.
I was looking for the solution, but I couldn't find out anything :(
Is there anyone who can help me?
        public class Demo1 {

            public static void main(String[] args) {
                new Demo1();
            }

        public Demo1() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
                    TestPane objA = new TestPane(200, 300);
                    TestPane objB = new TestPane();

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(objA);
                    frame.add(objB);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }

        public class TestPane extends JPanel {
            int x = 0;
            int y = 0;
            int h = 0;

            public TestPane(int xa, int ya) {
                x = xa;
                y = ya;
            }

            public TestPane() {}

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(800, 800);
            }

            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                int width = x;
                int height = y;

                if ((x == 0) && (y == 0)) {
                    width = getWidth();
                    height = getHeight();
                }

                g2d.setColor(new Color(139, 69, 19));
                g2d.fillRect((width / 2) - 20, height / 2, 40, height / 2);

                g2d.setColor(Color.GREEN);
                int radius = 60;
                g2d.fillOval((width / 2) - radius, (height / 2) - (radius * 2), radius * 2, radius * 2);
                g2d.fillOval((width / 2) - radius, (height / 2) - radius, radius * 2, radius * 2);
                g2d.fillOval((width / 2) - (radius * 2), (height / 2) - radius, radius * 2, radius * 2);
                g2d.fillOval((width / 2), (height / 2) - radius, radius * 2, radius * 2);
                g2d.dispose();
            }
        }
    }

Update:
After those modifications, it works
JFrame frame = new JFrame("Testing");
            JPanel mainframe = new JPanel();

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainframe.add(objA);
            mainframe.add(objB);
            frame.getContentPane().add(mainframe);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

A: The answer is what user15358848 wrote. If you add it directly to a JFrame, they end up in CENTER, which can take only one component.
If you want to have more than one component in the CENTER area, just nest them in a JPanel (basically in everything derived from Container, but JPanel or subclasses is the most reasonable) and add that JPanel to the CENTER area.
Make sure to add a Layout to it, that matches your needs, so that e.g. the two Components are side by side each other or on top of each other.
The Default Layout for JPanel is FlowLayout. You can change it with setLayout(LayoutManager).
You should be able to find a lot of complete examples for that on the web, with those keywords. JFC / Swing offers lots of possibilities. Have fun!


text:
Q: Need to create a user application in python-Django framework where based on input data will insert or update in the database I am a newbie in python-Django and i have a requirement where i need to create  a template where there will be a text input name (id) and a drop down as OPS(view,insert,edit) and by giving the id and selecting view as ..it will check into the db and will show all the project details in the template.
For view:it will display all the records in the table.
For Insert:It will insert the records in the table based on the input parameters passed in the form.
For update:It will show all the fields and a user can edit and save it which will update the database from backend.
I wanted to know how to create a model which will link the existing database with that of this django for the table.So it can update and insert records through template.
Please help me on this

A: check out the official example (models)
models in the django orm look like this
from django.db import models

class MyModel(models.Model):
    foo = models.IntegerField()  # a field in the model

You will need to read the official documentation or check out other django applications.


text:
Q: Let's encrypt on Ubuntu Snappy Just got my first Ubuntu Snappy running on a Raspberry Pi 2 and would very much like to enjoy Let's encrypt on it. I got it working on my other web server, but feel that this might not apply on Snappy Core, right?
For example, Let's Encrypt provides a Python script for install of the certificates, but on Snappy the same files does not apply as normal about Apache2 and stuff, right?
Where to start.
Thanks,
Daniel

A: Right-- snaps need to include all of their dependencies, so for instance the ownCloud snap bundles its own Apache, its own MySQL, etc. This is doable, but it's something you'd have to support in the snap that bundles the web server.


text:
Q: Adding directories in hash AJAX My site uses a script to navigate through pages with AJAX. The home page url is for example this: http://example.com/#home, the actual home page is located in pages/page_home.php.
How can I add directories in the hash? This is my code.
<?php

if(!$_POST['page']) die("0");

$page = $_POST['page'];

if(file_exists('pages/page_'.$page.'.php'))
echo file_get_contents('pages/page_'.$page.'.php');

else echo '
404 - That page could not be found. Click here to return.
';
?>

My motive to do this is to make a conditions page so when a visitor clicks on the cookies link in /#conditions the URL changes to /#conditions/cookies which is neater.
EDIT: full code
var state = { 'page_id': 1, 'user_id': 5 };
var title = 'Hello World';
var url = '#conditions/cookies';

history.pushState(state, title, url);

var default_content="";

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    options.async = true;
});

$(document).ready(function(){

    checkURL();
    $('ul li a').click(function (e){

            checkURL(this.hash);

    });

    //filling in the default content
    default_content = $('#pageContent').html();

    setInterval("checkURL()",250);

});

var lasturl="";

function checkURL(hash)
{
    if(!hash) hash=window.location.hash;

    if(hash != lasturl)
    {
        lasturl=hash;

        // FIX - if we've used the history buttons to return to the homepage,
        // fill the pageContent with the default_content

        if(hash=="")
        $('#pageContent').html(default_content);

        else
        loadPage(hash);
    }
}

function loadPage(url) {

    url=url.replace('#','');

    $.post("load_page.php", page: location.hash.substring(1)), function () {
      history.pushState(null, '', '#conditions/cookies');
    });

    $.ajax({
        type: "POST",
        url: "load_page.php",
        data: location.hash,
        dataType: "html",
        success: function(msg){

            if(parseInt(msg)!=0) {
                $('#pageContent').html(msg);
            }
        }

    });

}

A: To add directories to the URL, you can use history API. To add a new directory, or change the # part:
var state = { 'page_id': 1, 'user_id': 5 }; // This is totally irrelevant.
var title = 'Hello World';                  // Some title/
var url = '#conditions/cookies';            // The main URL.

history.pushState(state, title, url);

And now, in your AJAX call, send the #hash value by sending:
data: location.hash                         // This sends condition/cookies to PHP.

So building your AJAX will be something like this:
$.post("page.php", page: location.hash.substring(1)), function () {
  history.pushState(null, '', '#conditions/cookies');
});


text:
Q: Testing significance of correlation between time series I would like to know if there are some methods (or better, some statistics or even better, some R functions) like in https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Inference or in the R function cor.test() which can be used to test the hypothesis $H_0: \text{corr}(X_t,Y_t)=0$ for 2 time series $(X_t)$ and $(Y_t)$ and especially for stationary time series (I'm aware of the spurious correlations one can have with non-stationary series, hence I know that we often need to take differences).
I already found many similar questions here but I feel like they only partially answer the question. Also, I feel quite lost between the approaches I know, like cointegration test, Granger causality test, pre-whitening and some papers I saw like this one or some other papers containing many complicated statistics like this one or this one and many others...
Finally, I would like to see answers giving a kind of survey of (some of) the possibilities we have, the tools we should/must use (in which case and/or in which order) and if possible, please indicate some R functions which would be helpful (of course, I know ccf() function).
I hope it's clear and I hope it's not too much demanding.
Edit: After thinking, I can ask the following questions:
1. How to test the significance of Pearson correlation between 2 stationary time series? This has been answered below by @taylor.
2. I have also the same question for Kendall correlation and for distance correlation. If possible (and if it exists), could you provide some R functions which perform these tests?
Last edit: Finally, I'll create a new question for this 2nd point, following the advice of @Juho Kokkala in his comment below.

A: Bartlett's theorem is useful for this. If $\{\mathbf{X}_{t}\}$ is a bivariate time series whose components are defined by
$$
X_{t1} = \sum_{k=-\infty}^{\infty} \alpha_k Z_{t-k,1}, \hspace{10mm} \{Z_{t1}\} \sim \text{IID}(0, \sigma^2_1)
$$
and
$$
X_{t2} = \sum_{k=-\infty}^{\infty} \beta_k Z_{t-k,2}, \hspace{10mm} \{Z_{t2}\} \sim \text{IID}(0, \sigma^2_2)
$$
where the two sequences $\{Z_{t1}\}$ and $\{Z_{t2}\}$ are independent, $\sum_k |\alpha_k| < \infty$,  and $\sum_k |\beta_k| < \infty$, then for all integers $h,k$, $h \neq k$, $\sqrt{n}(\hat{\rho}_{12}(h), \hat{\rho}_{12}(k))'$ is asymptotically Normal, with mean equal to the zero vector and covariance matrix equal to
$$
\left[\begin{array}{cc}
\sum_{j=-\infty}^{\infty} \rho_{11}(j)\rho_{22}(j) & \sum_{j=-\infty}^{\infty}\rho_{11}(j)\rho_{22}(j+k-h)  \\
\sum_{j=-\infty}^{\infty}\rho_{11}(j+k-h)\rho_{22}(j) & \sum_{j=-\infty}^{\infty} \rho_{11}(j)\rho_{22}(j)
\end{array}\right].
$$
In particular
$$
\sqrt{n}\hat{\rho}_{12}(h) \overset{D}{\to} \text{N}\left(0, \sum_{j=-\infty}^{\infty} \rho_{11}(j)\rho_{22}(j) \right),
$$
which means that you can still observe large cross-correlations for independent time series!
But, if you assume further that at least one of $X_{t1}$ and $X_{t,2}$ is white noise, then many of those summands are $0$ and
$$
\sqrt{n}\hat{\rho}_{12}(h) \overset{D}{\to} \text{N}\left(0, 1 \right).
$$
This is why prewhitening is done, which may or may not be necessary. Apply whitening filter(s) to the data will not change whether or not the series are independent, but it will give you a better standard error for the sample correlation at different lags. Under this assumption, you can look at cross correlations (in R with acf or ccf) and see if they're larger than $\pm \frac{2}{\sqrt{n}}$ (assuming $n$ is large).
Reference: https://www.amazon.com/Introduction-Forecasting-Springer-Texts-Statistics/dp/3319298526/ref=dp_ob_title_bk?dpID=41cwVafsUGL&preST=_SX218_BO1,204,203,200_QL40_&dpSrc=detail


text:
Q: Style the background of a dropdown I am trying to get rid of the white background behind the options in a dropdown menu, so far this is my code:
CSS:

select {
    margin: 50px;
    border: 1px solid white;
    background: transparent;
    width: 50%;
    padding: 5%;
    height: 50%;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}
select > option
{
color:transparent;
}
    .blueLabel
{
 background: linear-gradient(to right bottom,  #2D3C43 0%,#2D3C43 50%,#243137 50%,#243137 100%);
}

HTML:

<select>
    <option>option 1</option>
    <option >Kuku</option>
    <option>Yeah, why not</option>
    <option>I think is = 7</option>
</select>

Fiddle
I want it to be transparent. Problem is, no matter what i do it is still white, i can't get rid of it

A: You can fake it pretty close by using background-color:
select > option {
    background-color: blue;
}

Updated fiddle: http://jsfiddle.net/0s1moa4a/2/
If you actually want transparent option backgrounds, see this answer which suggests using a third-party control as a truly transparent background is impossible with pure CSS.

A: If you set the size property of the select element (along with background: transparent), you get this:

You can add event listeners so that the size property is changed only when the select box has focus.  You have to be careful with propagating events, and you need to blur the select box on click but not on focus:
var sel= document.querySelector('select'),
    inSelect= false,
    timer;

sel.addEventListener('focus', function() {
  this.size= this.options.length;
  clearTimeout(timer);
  timer= setTimeout(function() {
    inSelect= true;
  },500);
});

sel.addEventListener('blur', function() {
  clearTimeout(timer);
  inSelect= false;
  this.size= 1;
});

sel.addEventListener('change', function() {
  this.blur();
});

sel.addEventListener('click', function(event) {
  if(inSelect) {
    this.blur();
  }
  else {
    event.preventDefault();
    event.stopPropagation();
    return false;
  }
});

Working Fiddle

A: I didn't test this, but most elements seem to go transparent with this approach:
background-color:rgba(0,0,0,0);
Actually, that doesn't work. It appears that only opaque backgrounds can be rendered on selector option dropdown panes in CSS. That's kind of lame.


text:
Q: Author and Title I dont know how to make an author and title to look exactly like that in screen. Can someone help ?
I used this code but spaces between letters in word "zero" are to small
\documentclass[a4paper,12pt]{article}
\usepackage[MeX]{polski}
\usepackage[utf8]{inputenc}
\usepackage{indentfirst}

\begin{document}

\begin{center}
{\scriptsize Jan Brzechwa}\\{\Huge Z}       {\large E R O}
\end{center}

A: Here's a possible solution: with \textls[600] I set big letter spacing.
\documentclass[a4paper,12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[MeX]{polski}
\usepackage{indentfirst}
\usepackage{lmodern}
\usepackage{microtype}

\begin{document}

\begin{center}
\textsf{Jan Brzechwa}\\
\nointerlineskip
{\Huge\scshape\textls[600]{Zero}}
\end{center}

\begin{flushright}\lineskip=5pt
Toczyło się po drodze:\\
,,{\Huge Z drogi}, gdy ja przechodzę!\\
Ja jestem {\Huge sto tisięcy},\\
A może jeszcze {\Huge więcej}''.
\end{flushright}

\end{document}


text:
Q: Android ListView setId for each row How to set id for each row in ListView when using custom adapter?
TFragment:
public static TArrayAdapter adapter;
adapter = new TArrayAdapter(getActivity(), R.layout.t_list_item_adapter, new ArrayList<TString>());
    listview.setAdapter(adapter);

TArrayAdapter:
public View getView(final int position, View convertView, final ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    rowView = inflater.inflate(R.layout.t_list_item_adapter, parent, false);

    THolder holder = new TransactionHolder();
    holder.account = items.get(position);
    holder.name = (TextView) rowView.findViewById(R.id.tvName);
    rowView.setTag(holder);
    setupItem(holder);


text:
Q: How to write blocks (closures) in swift3 right way? I am trying to find how I can write this blocks in swift3, any help would be appreciated.
I am using obj-c PocketSDK in swift3 project.
https://github.com/Pocket/Pocket-ObjC-SDK
I can use this SDK fine with proper Bridge-Header settings, but still not sure how I can write blocks part.
obj-c
[[PocketAPI sharedAPI] callAPIMethod:@"get"
                       withHTTPMethod:PocketAPIHTTPMethodGET
                            arguments:arguments
                              handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error) {
                              }];

This is the type def in PocketSDK.
-(void)callAPIMethod:(NSString *)apiMethod withHTTPMethod:(PocketAPIHTTPMethod)HTTPMethod arguments:(NSDictionary *)arguments delegate:(id<PocketAPIDelegate>)delegate;

     typedef void(^PocketAPIResponseHandler)(PocketAPI *api, NSString*apiMethod, NSDictionary *response, NSError *error);

swift? (This shows error.)
    let arguments: [String: Any] = [
        "state": "unread",
        "count": 20
    ]

    PocketAPI.shared().callMethod("get", with: PocketAPIHTTPMethodGET, arguments: arguments) {
        (api: PocketAPI,
        apiMethod: String,
        esponse: [AnyHashable:Any],
        error: Error) in
    }

@Updated
I could avoid the compile error without type def, but still get the unrecognized selector if I put arguments. If I set nil in arguments, I don't get it though.  Anything wrong with the dictionary?
    var arguments = [String : Any]()
    arguments["count"] = 20
    arguments["state"] = "unread"

    PocketAPI.shared().callMethod("get", with: PocketAPIHTTPMethodGET, arguments: arguments) {
        (api,
        apiMethod,
        response,
        error) in
    }

Error.

-[_SwiftTypePreservingNSNumber length]: unrecognized selector sent to instance 0x174624540 2017-08-15 14:05:51.345611+0900
  Voicepaper2[1062:286998] * Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-[_SwiftTypePreservingNSNumber
  length]: unrecognized selector sent to instance 0x174624540'
  * First throw call stack:

A: Solved!  This was the final answer, thanks!
    let arguments: [String: Any] = [
        "state": "unread",
        "count": "20"
    ]

    PocketAPI.shared().callMethod("get", with: PocketAPIHTTPMethodGET, arguments: arguments) {
        (api,
        apiMethod,
        response,
        error) in
    }


text:
Q: Prove a.s. convergence of $(X_n)_n$ satisfying $E(X_{n+1} \mid F_n) \leq X_n+Y_n$ for $\sum_n Y_n<\infty$ I am have a problem with proving a convergence of a sequence of random variables in the given context:

Let $F_n$ be a filtration. Assume that $X_n$ and $Y_n$ are non-negative and integrable $F_n$-adapted random variables for $n\geq 0$.
Furthermore, I assume that:
$\mathbb{E}[X_{n+1} \mid F_n]\leq X_n+Y_n$ and that  $\sum_{n}Y_n < \infty$.
Under the above conditions, I should show that $X_n$ converges almost surely for $n\rightarrow \infty$.

My approach has been to define a variable $Z_n=X_n-\sum_{i=0}^{n-1} Y_i$, and to set this into the expression for the conditional mean of $X_{n+1}$, but this did not gave any result.
Anybody has an idea to this?

A: It follows from your assumption on the conditial expectation that
$$Z_n = X_n - \sum_{i=0}^{n-1} Y_i$$
is a supermartingale. If we define
$$T_k := \inf\left\{n \in \mathbb{N}; \sum_{i=0}^n Y_i \geq k\right\}$$
for fixed $k \in \mathbb{N}$, then $T_k$ is an $F_n$-stopping time. By the optional stopping theorem, the stopped process $(Z_{n \wedge T_k})_{n \in \mathbb{N}}$ is also a supermartingale. Moreover, the definition of $T_k$ and the non-negativity of $X_n$ and $Y_n$ entail that $Z_{n \wedge T_k} \geq -k$ for all $n \in \mathbb{N}$, and therefore
$$\sup_{n \in \mathbb{N}} \mathbb{E}(Z_{n \wedge T_k}^-) < \infty.$$
Applying the standard convergence theorem for supermartingales, we conclude that the limit $\lim_{n \to \infty} Z_{n \wedge T_k}$ exists almost surely, and so
$$\Omega_0 := \bigcap_{k \geq 1} \{\omega \in \Omega; \lim_{n \to \infty} Z_{n \wedge T_k}(\omega) \, \, \text{exists}\}$$
has probability $1$. Now if $\omega \in \Omega_0$, then $\sum_{n} Y_n(\omega)<\infty$ implies that we can choose $k \in \mathbb{N}$ large enough such that $T_k(\omega)=\infty$. As $\omega \in \Omega_0$ we thus know that
$$\lim_{n \to \infty} Z_{n \wedge T_k}(\omega) = \lim_{n \to \infty} Z_n(\omega) = \lim_{n \to \infty} \left( X_n(\omega)- \sum_{i=0}^{n-1} Y_i(\omega) \right)$$
exists. Using once more that $\sum_{i} Y_i(\omega)<\infty$, this shows that $\lim_n X_n(\omega)$ exists.


text:
Q: create youtube playlist from array of links hi can i make a php function where i can pass a array of youtube links and it creates a playlist in youtube for a certain user, i have read youtube docs but still can not figure out.
https://developers.google.com/youtube/2.0/developers_guide_php#Adding_a_Playlist_Video
on the doc it displays the following code.
    $newPlaylist = $yt->newPlaylistListEntry();
$newPlaylist->summary = $yt->newDescription()->setText('description of my new playlist');
$newPlaylist->title = $yt->newTitle()->setText('title of my new playlist');
// post the new playlist
$postLocation = 'http://gdata.youtube.com/feeds/api/users/default/playlists';
try {
  $yt->insertEntry($newPlaylist, $postLocation);
} catch (Zend_Gdata_App_Exception $e) {
  echo $e->getMessage();
}

A: I'm hardly an expert, but I think this is what you are looking for:
//Make a loop to go over all of the values within the array
     for ($i = 0; $i <= count($array); $i++){
$postUrl = $playlistToAddTo->getPlaylistVideoFeedUrl();
// video entry to be added
$videoEntryToAdd = $yt->getVideoEntry($array[i]);

// create a new Zend_Gdata_PlaylistListEntry, passing in the underling DOMElement of the VideoEntry
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());

// post
try {
  $yt->insertEntry($newPlaylistListEntry, $postUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}
}

The variable $array should obviously be a one dimensional array that contains the ytvideos 'IDs'. Hope that helped.


text:
Q: Prove that the number of edges is a multiple of 3 if each vertex has a degree that is either a multiple of 6 or 9 So if G is an undirected graph where the degree of each vertex is a multiple of 6 or 9 i have to show that the number of edges is a multiple of 3.
where I am having trouble, I said that if the number of edges is equally divisible by 3 then the number of edges is a multiple of 3.
I feel like this isn't enough....and I feel like I should be looking more closely at how the vertices have to be a multiple of 6 or 9 but I don't know how to relate this.
Just looking for hints and tips in the right direction; i feel like it's blatantly obvious but I can't see it

A: For any given graph $G = (V,E)$, if $m$ denotes $|E|$, then:
$$m = \frac12 \sum_{v \in V} d(v)$$
As each vertex has a degree that is either a multiple of $6$ or a multiple of $9$, then each vertex's degree is divisible by $3$. This means that their sum is divisible by $3$, hence so is $m$.

A: Using what is commonly referred to as the handshake lemma,
$$m = \frac12 \sum_{v \in V} d(v)$$.  Let $a_1$ denote the number of vertices of degree 6, and let $a_2$ denote the number of vertices of degree 9.  Since, by the first theorem of graph theory, there cannot be an odd number of odd degree vertices, $a_2$ must be even, say $a_2 = 2k$ for some $k$.  Then, $$m = \frac12 \sum_{v \in V} d(v)=\frac{1}{2}(6a_1+9a_2)=\frac{1}{2}(6a_1+18k)=3(a_1+3k)$$, and so $m$ is indeed divisible by 3.


text:
Q: Windows service popping calc in C# Error 216 0xd8 I coded this simple service -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace MySimpleService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Process p = new Process();
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "C:\\Windows\\System32\\calc.exe";
            psi.WindowStyle = ProcessWindowStyle.Normal;
            p.StartInfo = psi;
            p.Start();
        }

        protected override void OnStop()
        {
        }
    }
}

And when I installed it with sc.exe create test_service bitPath="<my_path>.exe",
I got an error message Error 216 0xd8.
I compiled the program on the same computer I ran the service on, any thoughts?


text:
Q: WPF Interface becomes unresponsive when clearing source of CollectionViewSource I have a WPF application where I communicate with a second application via TCP sockets. Each message sent and received has a given length and information, which is wrapped into an object.
After handling the message, this object is added to an ObservableList, which is (oneway) bound to a CollectionViewSource. This CollectionViewSource is the Itemsource of a Datagrid. Additionally, the CollectionViewSource has a filter which can be set with several toggleButtons. When the connection is closed, the list should be cleared for further use after reconnecting.
I tested this setup and especially the filtering up to a few thousand entries and it seems to work fine. Except if I clear the ObservableCollection, the whole interface becomes unresponsive, slow and setting the filter will spike the processing power used up to 60%, even for 10 objects in the list.
Clearing the ObservableCollection doesn't seem to update the Interface, only overwriting the Collection with a new object.
I also tried to change properties in XAML, like binding mode or read only, but this does change nothing.
<CollectionViewSource x:Key="telegramList"
                      Source="{Binding Path=LogManager.TList, mode=OneWay }"
                      Filter="telegramFilter">
</CollectionViewSource>

<DataGrid ItemsSource="{Binding Source={StaticResource telegramList}}" IsReadOnly="True" IsSynchronizedWithCurrentItem="False" x:Name="

Edit: Here is the LogManager, and the functions accessing the list. LogTelegram() can be called from either a Socket Callback, or directly from the main thread, before the message object is queued for sending.
public class LogManager : INotifyPropertyChanged
{
        private ObservableCollection<ImmutableTelegram> tList;
        public ObservableCollection<ImmutableTelegram> TList { get { return tList; } set { tList = value; NotifyPropertyChanged("TList"); } }

        public void logTelegram(Telegram512 telegram)
        {
            if (!Model.Instance.gui.Dispatcher.CheckAccess())
            {
                Model.Instance.gui.Dispatcher.Invoke(delegate
                {
                    logTelegramDelegate(telegram);
                });
            }
            else
            {
                logTelegramDelegate(telegram);
            }
        }

        private void logTelegramDelegate(Telegram512 telegram)
        {
            if (telegram.TELETYPE == Telegram512.Types.XX)
                TList.Add(new ImmutableTelegram(telegram));

            if(TList != null)
                TList.Add(new ImmutableTelegram(telegram));

        }

        public void clearTelegramLog()
        {
            TList = null;
        }

        public void createTelegramLog()
        {
            TList = new ObservableCollection<ImmutableTelegram>();
        }
}

Here is also the filter function and one state changed listener for a toggle button.
private void dataGridFilter(object sender, FilterEventArgs e)
    {
        var obj = e.Item as Telegram512;
        if (obj != null)
        {
            e.Accepted = true;

            if (obj.TELETYPE == Telegram512.Types.LF && this.lfToggle.IsChecked == false)
            {
                e.Accepted = false;
                return;
            }
        }
    }

private void lfToggle_Click(object sender, RoutedEventArgs e)
    {
        if(telegramDataGrid.ItemsSource != null)
            CollectionViewSource.GetDefaultView(telegramDataGrid.ItemsSource).Refresh();
    }


text:
Q: How to get IP Address of Server (Socket) in Android? I'm creating a simple chat program that connects two android devices and they can send simple message
I run the server with Socket on a port (1234 for example)
The problem is from the client i do not know the server IP Address. (and i dont want to enter it manually)
is there a way to find a server that is running on a specific port?or can i run the server on some specific static IP that i can give it to clients?
if not is there another way to communicate with android devices that works on Android 2.2+(don't want to use wifi direct) ?
Thanks in Advance

A: You can broadcast a udp message from the server specifying your ip in the message. Let the client receive the broadcast and use that msg as the ip address to connect to the socket. (PS : The broadcast receiver must b allowed to receive broadcasts). And you are done!

A: Assign one SERVER predominantly for getting details such as IP ADDRESS, PORT number,etc.. from all the clients.
Each client when activated will contact the SERVER to register itself first and will get the details(IP ADDRESS,etc) of other device to communicate.
Now they can start waiting for specific device.

A: On 4.1 you can use Mutlicast DNS for service discovery via the NsdManager (if you are on the same network). If you need this to work over the Internet/3G there is really no good way to do it. You could use Google Cloud Messaging (GCM) to notify clients about the server address, but in any case you will need one 'real' server on a stable address that all participants can reach.
http://developer.android.com/reference/android/net/nsd/NsdManager.html

A: InetAddress.getLocalHost(); doesnot work for me but ya below code work for me
DhcpInfo dhcp = mWifiManager.getDhcpInfo();
int dhc = dhcp.serverAddress;

String dhcS = ( dhc & 0xFF)+ "."+((dhc >> 8 ) & 0xFF)+"."+((dhc >> 16 ) & 0xFF)+"."+((dhc >> 24 ) & 0xFF);

dhcS contains IP address of server,I used for Wireless connection between multiple devices.

A: You can use this code
 connectionSocket.getRemoteSocketAddress();

A: No the port can never be fixed with a IP. It is always provided by the user. To know the IP address of the server automatically, you can run this program associated with the chat program.
public class Net {
  public Net() throws UnknownHostException {
    InetAddress ia = InetAddress.getLocalHost();
    System.out.println(ia);
    ia = InetAddress.getByName("local host");
    System.out.println(ia);
  }

  public static void main(String args[]) throws UnknownHostException {
    Net a = new Net();
  }
}

You run can this program by the help of a button which is associated with your chat program.


text:
Q: Collapsed Menu Not Working I have a web page that is built using MVC and .NET Core 2. So this page is generated from Razor.
When I run the page in Visual Studio and shrink my page down so that the screen is narrower it collapses the menu, and the hamburger menu expands the options.
However when it is deployed to my web host, the menu stops working. It collapses down but when clicking it it does not expand.
Any ideas?
The web page is located at https://www.techsportise.com/Account/Login and the code is below.
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Your Races - Techsportise - Free race timing for running clubs</title>
<link rel="stylesheet" href="/css/site.min.css?v=kHvJwvVAK1eJLN4w8xygUR3nbvlLmRwi5yr-OuAO90E" />
<link rel="stylesheet" href="/css/bootstrap-united.css" />
<link rel="stylesheet" href="/css/bootstrap-table.css" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

Help

API

                <form method="post" id="logoutForm" class="navbar-right" action="/Account/Logout">

                        Your Races

                        Your Account

                        <button type="submit" class="btn btn-link navbar-btn navbar-nav">Log out</button>

                <input name="__RequestVerificationToken" type="hidden" value="CfDJ8B_47xDwuwZKosoOrEvsIEc-7sACUmVXlDOlvKkWFf6tADFpx4HkVTmogPp-MODeiLleKz94PutshRuzq-Hb3iH-iPa86vzlYoBPig4JbC8_9oAWo8qaFCQGK4oXApQW1mmLKNAgFJs2jIJt7a2O8LA6eJiSShT5HxQ-VhHvspwn0YEOS6VoygnYCW331WEpjA" /></form>

Your Races

            New Race

        <form action="/Races" method="post">

            <input type="text" name="searchString">
            <input type="submit" value="Filter" />

            <input name="__RequestVerificationToken" type="hidden" value="CfDJ8B_47xDwuwZKosoOrEvsIEc-7sACUmVXlDOlvKkWFf6tADFpx4HkVTmogPp-MODeiLleKz94PutshRuzq-Hb3iH-iPa86vzlYoBPig4JbC8_9oAWo8qaFCQGK4oXApQW1mmLKNAgFJs2jIJt7a2O8LA6eJiSShT5HxQ-VhHvspwn0YEOS6VoygnYCW331WEpjA" /></form>

                        Title
                        Race Director
                        Email
                        Phone Number
                        Date
                        Time
                        Race Capacity
                        Current Entries
                        Entries
                        Results
                        Actions

                        My Race
                        My RD
                        rd@techsportise.com
                        01234 567890
                        04 June 2010
                        10:00
                        500
                        10
                        Entries
                        Results

                        Andover 10k
                        Matthew Warr
                        matt@techsportise.com

                        24 November 2017
                        09:00
                        100
                        2
                        Entries
                        Results

                        Hampshire Marathon
                        Matthew Warr
                        matt@techsportise.com

                        20 January 2018
                        09:30
                        5000
                        0
                        Entries
                        Results

                        Balksbury Hill Climb
                        Matthew Warr
                        matt@techsportise.com

                        22 April 2018
                        10:00
                        12000
                        0
                        Entries
                        Results

                        Valentines 5k
                        Matthew Warr
                        matt@techsportise.com

                        14 February 2018
                        07:30
                        150
                        0
                        Entries
                        Results

                        Techsportise Half Marathon
                        string
                        string
                        string
                        26 November 2017
                        04:39
                        0
                        0
                        Entries
                        Results

                        The Elite Race
                        Jon Warr
                        jon.mark.warr@gmail.com
                        07734190692
                        27 November 2017
                        05:00
                        20000
                        2
                        Entries
                        Results

                        We Love Jodie 10k
                        Jodie Warr
                        	jodiewarr@hotmail.com

                        04 November 2018
                        11:35
                        100
                        2
                        Entries
                        Results

                        Langport 10k

                        Simon Smith
                        Sismith1@hotmail.co.uk
                        07515541144
                        28 November 2017
                        07:15
                        1
                        1
                        Entries
                        Results

                        Chilly Hilly
                        hgkjg
                        jkhgkjh@kygkjh.com
                        123
                        31 December 2017
                        11:59
                        200
                        0
                        Entries
                        Results

About Us | Contact | Privacy Policy | Terms & Conditions

© 2017 - Techsportise

A: Thanks to VilleKoo and Orvar I found in my source that in Developer environment jquery was inlcuded but in production environment it wasn't. I have added it now.
_layout.cshtml
<environment include="Development">

    </environment>
    <environment exclude="Development">

        @**@

    </environment>

A: I can not see the jQuery file.You can try to add.

jquery-file.js <---


text:
Q: Comparison of wireless communication technologies: bluetooth vs wifi I would like to build a simple battery-powered board with temperature and humidity sensors. It should be able to be placed in different rooms of an appartment, and I want to be able to read the values remotely. Eventually I would like to equip all rooms with such board.
I haven't chosen any hardware yet, but I was thinking to connect the sensor(s) with a low-powered microcontroller, and some wireless interface. But considering the somewhat low distance (not more than 10m), the likely presence of wall, I am hesitating on the technology I should use for the wireless communication.
I considered the following technologies

*

*WiFi,

*Bluetooth.

Could anyone summarise the pros and cons of those three technologies? Or point me to a good review, which would help me choose the best for my needs?
Of course, if I am missing a very crucial technology, do not hesitate to point it out. Radio RF?
PS. I know that there are commercially available products for exactly such needs, but I would like to do it myself, for the experience it would bring me, and also because of possible extensions I could implement.

A: Have a look at Zigbee - this is basically what it is designed for. Bluetooth has very short range (won't work between rooms) and WIFI uses quite a lot of power comparatively (you'll need a bigger battery). Zigbee is designed to be somewhere in-between and also has the capability to create mesh networks to extend the range.

A: Wi-Fi is a IEEE 802.11 standard:
Pros:

*

*it is IP based communication

*you don't need build a gateway (I don't mean the router gateway) to transfer the information to the Internet.

*years of proven stack

*Strong security algorithms (AES-256, WPA2, etc.)

*Allows secure tunnels like TLS

Cons:

*

*Higher power consumption: It is probably not a good choice for a battery powered application unless you put your devices to sleep mode and wake up time to time to do measurements.

*WiFi stack is a heavy stack, it requires a better processor power to handle it (again cost and power)

*Higher cost

*WiFi uses beacon based communication, it constantly radiates (power consideration)

*It is majorly designed for an infrastructured mode, the nodes needs to be in the range of the AP in order to transfer your data. Ad-hoc mode is not well supported

Bluetooth: I am not much experienced on Bluetooth, the blueetooth's advantage would be that you can develop an application that you can use connect your phone directly to the devices to control. As I know, bluetooth is for peer to peer communication.
I would go for another standard under the same family of IEEE 802.15.4 ZigBee.
Pros:

*

*Low power

*Light stack

*Application layer compatibility (home automation stack should include what you are looking for)

*Beamless communication (no periodic signals)

*low cost¨

*well supported ad-hoc multi-hop toplogy

*Small packets, less overhead

*Security (AES-128)

Cons:

*

*You need a gateway to translate internet packets to ZigBee

You can use SoC solution that has ZigBee stack (RF core) + MCU, or you can use a MCU and attack a ZigBee module to run your application
All wireless standards are based on Radio Frequency (RF) waves, I don't know what standard you meant with the RF.


text:
Q: How did gdprscript.js get into the header of my Weebly site? When I view the source of my website, I am seeing this script inserted into my website.  However I cannot find the template where it is being added.

A: This javascript html tag is inserted automatically by Weebly's backend server itself.  It inserts it immediatly after the <head> element and before any items you have defined in your actual template file.
<script src="/gdpr/gdprscript.js?buildTime=1558379751&hasRemindMe=true&stealth=false"></script>

What does it do?
This code forces the display of the "This site uses cookies..." message that pops over the bottom part of the page.  It also handles the user's selection.
Why is it inserted if my site does not use cookies?
It is inserted because Weebly itself forces your site to use cookies.  It does this to enable its own collection of analytics on your homepage.
Does it slow down my site
Yes.  Code like this should be inserted after the site content.
Can it be removed?
You may be able have this removed by contacting Weebly directly.


text:
Q: Framemaker DITA pdf export creates new page for every DITA Topic I have created a Dita Map in Framemaker 12 containing some Topics.
When I build a pdf document with Dita Open Toolkit (which is supplied by Adobe), I get a pdf document which has a page break after each Topic.
I don't want a page break after each topic.
How can I change this behavior?

A: A lot depends on how you've structured your map. If each topicref is at the top level, then the implication is that you have a new "chapter" so you have to have a page break. If the topics are supposed to be ordered hierarchically, you need to nest the topicrefs and that will avoid the page break. So, if you have something that looks like this:
<topicref href="firsttopic.dita"/>
<topicref href="secondtopic.dita/>
<topicref href="thirdtopic.dita/>

You always get breaks between the topics. However, if what you really wanted was the first topic to be the parent of the other two, your map should look something like:
<topicref href="firsttopic.dita">
   <topicref href="secondtopic.dita/>
   <topicref href="thirdtopic.dita/>
</topicref>

The page break will come with whatever topic follows the reference to the first topic.


text:
Q: /dev/vda1 is huge, can't understand why (output screenshots When I run df -h, I get this:

The /dev/vda1 directory has 24G used. I'm trying to figure out which files take up the space. I tried du -shx /* | sort -rh and got this:

It lists /usr as the biggest with 2.8G inside. However it's 24G that are used, not 2.8G.
Using ncdu from inside /dev didn't help either:

What can I do to determine what takes up the 24G?
EDIT:
/# sudo ls -l /
total 108
drwxr-xr-x   2 root root  4096 Nov  7 06:24 bin
drwxr-xr-x   4 root root  4096 Nov 14 06:43 boot
drwxr-xr-x  10 root root  4096 Nov 14 01:23 Bots
drwxr-xr-x  16 root root  3580 Nov 15 00:10 dev
drwxr-xr-x 125 root root  4096 Dec  6 22:15 etc
drwxr-xr-x   3 root root  4096 Jun 28 16:30 home
lrwxrwxrwx   1 root root    33 Nov 14 06:43 initrd.img -> boot/initrd.img-4.4.0-169-generic
lrwxrwxrwx   1 root root    33 Nov 14 06:43 initrd.img.old -> boot/initrd.img-4.4.0-168-generic
drwxr-xr-x  21 root root  4096 Jun 28 15:09 lib
drwxr-xr-x   2 root root  4096 Nov 14 18:31 lib64
drwx------   2 root root 16384 Oct  4  2018 lost+found
drwxr-xr-x   2 root root  4096 Oct  4  2018 media
drwxr-xr-x   2 root root  4096 Oct  4  2018 mnt
drwxr-xr-x   4 root root  4096 Sep 24 18:55 opt
dr-xr-xr-x 126 root root     0 Nov 15 00:10 proc
drwx------  25 root root  4096 Dec  6 20:39 root
drwxr-xr-x  26 root root   940 Dec  6 22:25 run
drwxr-xr-x   2 root root 12288 Oct  1 06:34 sbin
drwxr-xr-x   2 root root  4096 Oct 20  2018 snap
drwxrwxrwx   2 root root  4096 Nov 14 18:28 sources
drwxr-xr-x   2 root root  4096 Oct  4  2018 srv
drwxr-xr-x   3 root root  4096 Nov 14 17:45 stuff
dr-xr-xr-x  13 root root     0 Dec  6 22:30 sys
drwxrwxrwt  10 root root 12288 Dec  6 22:35 tmp
drwxr-xr-x  10 root root  4096 Oct  4  2018 usr
drwxr-xr-x  13 root root  4096 Oct  4  2018 var
lrwxrwxrwx   1 root root    30 Nov 14 06:43 vmlinuz -> boot/vmlinuz-4.4.0-169-generic
lrwxrwxrwx   1 root root    30 Nov 14 06:43 vmlinuz.old -> boot/vmlinuz-4.4.0-168-generic

EDIT:
ncdu / gives this output:
--- / ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    2.4 GiB [##########] /usr
  888.3 MiB [###       ] /var
  847.5 MiB [###       ] /stuff
  823.6 MiB [###       ] /root
  548.1 MiB [##        ] /lib
  293.5 MiB [#         ] /Bots
  267.4 MiB [#         ] /opt
  246.4 MiB [#         ] /boot
   15.6 MiB [          ] /bin
   13.3 MiB [          ] /sbin
   10.6 MiB [          ] /run
    8.0 MiB [          ] /etc
  180.0 KiB [          ] /tmp
   20.0 KiB [          ] /home
e  16.0 KiB [          ] /lost+found
    8.0 KiB [          ] /snap
    4.0 KiB [          ] /dev
    4.0 KiB [          ] /lib64
e   4.0 KiB [          ] /srv
e   4.0 KiB [          ] /sources
e   4.0 KiB [          ] /mnt
e   4.0 KiB [          ] /media
.   0.0   B [          ] /proc
    0.0   B [          ] /sys
@   0.0   B [          ]  initrd.img.old
@   0.0   B [          ]  initrd.img
@   0.0   B [          ]  vmlinuz.old
@   0.0   B [          ]  vmlinuz

 Total disk usage:   6.2 GiB  Apparent size:   6.2 GiB  Items: 404555

EDIT:
# du -hsc .[!.]* *
du: cannot access '.[!.]*': No such file or directory
16M     bin
247M    boot
294M    Bots
4.0K    dev
8.1M    etc
20K     home
0       initrd.img
0       initrd.img.old
549M    lib
4.0K    lib64
16K     lost+found
4.0K    media
4.0K    mnt
268M    opt
du: cannot access 'proc/25571/task/25571/fd/4': No such file or directory
du: cannot access 'proc/25571/task/25571/fdinfo/4': No such file or directory
du: cannot access 'proc/25571/fd/4': No such file or directory
du: cannot access 'proc/25571/fdinfo/4': No such file or directory
0       proc
824M    root
11M     run
14M     sbin
8.0K    snap
4.0K    sources
4.0K    srv
848M    stuff
0       sys
180K    tmp
2.4G    usr
889M    var
0       vmlinuz
0       vmlinuz.old
6.3G    total

EDIT:
lsblk
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
vda     253:0    0   25G  0 disk
├─vda1  253:1    0 24.9G  0 part /
├─vda14 253:14   0    4M  0 part
└─vda15 253:15   0  106M  0 part /boot/efi


text:
Q: Target shows as hyperlink I tried to create a target, but for whatever reason, the target bit the "id" links to displays the text as a link which is not not a link, if you know what I mean (it's a header; it underlines and there's that pointer arrow to cursor change, but obviously it does not link anywhere because it is itself the target). How do I make this not happen? (Page: http://www.thesimplewardrobeblog.com/post/114843804438/how-to-develop-your-personal-style)
Thanks in advance, Richie
My code is as follows
LINK:

Skip to Workbook Below

TARGET:

Your Personal Style Workbook: Six Exercises To Help You Discover Your Personal Style

A: Put the ID in your
 tag. Do not create an  tag just for that. Like so:

Your Personal Style Workbook: Six Exercises To Help You Discover Your Personal Style


text:
Q: 'RuntimeError: Expected object of scalar type Long but got scalar' for torch.nn.CrossEntropyLoss() I'm using this loss function for xlm-roberta-large-longformer and it gives me this error:
    import torch.nn.functional as f
    from scipy.special import softmax

    loss_func = torch.nn.CrossEntropyLoss()
    output = torch.softmax(logits.view(-1,num_labels), dim=0).float()
    target = b_labels.type_as(logits).view(-1,num_labels)
    loss = loss_func(output, target)
    train_loss_set.append(loss.item())

when I try
b_labels.type_as(logits).view(-1,num_labels).long()

it tells me

RuntimeError: multi-target not supported at /pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15

What should I do?

A: Your target tensor should contain integers corresponding to the correct class labels and should not be a one/multi-hot encoding of the class.
You can extract the class labels from a one-hot encoding format using argmax:
>>> b_labels.argmax(1)


text:
Q: Problema javascript array estou enfrentando um problema com array javascript.
Estou utilizando o Google Charts e para popular o gráfico, é necessário um array contendo o nome e a participação.
function contentChart(){
var id = document.querySelectorAll('.id')
var nome = document.querySelectorAll('.nome')
var sobrenome = document.querySelectorAll('.sobrenome')
var participacao = document.querySelectorAll('.participacao')

var chartContent = [];
for (i = 0; i < id.length ; i++) {
    chartContent += `['${nome[i].innerText} ${sobrenome[i].innerText}', ${participacao[i].innerText}],`;
    /*var result = chartContent.push([`${nome[i].innerText} ${sobrenome[i].innerText}`, participacao[i].innerText],)*/
}
return chartContent }

A função acima cria uma variável e atribui os valores obtidos, dando quase certo. Porém, por retornar uma string dá error.
Retorno : "['carlos alberto', 1],['bahia folia', 2],"

Se vinhesse sem as aspas daria certo.
ex: ['carlos alberto', 1],['bahia folia', 2],

Error: jsapi_compiled_default_module.js:178 Uncaught (in promise)
  Error: Invalid row #1
      at Object.gvjs_ql [as arrayToDataTable] (jsapi_compiled_default_module.js:178)
      at drawChart (main.js:9)

A: Olha, não sei bem o que queres fazer, mas tem duas possibilidades que imaginei.
Preservar o conteúdo do chartContent e utilizar a função eval.
Mas deveria preservar o tipo da variável como Array e não transformando ela em um String.
Código alterado:
for (i = 0; i < id.length ; i++) {
    chartContent.push(eval(`['${nome[i].innerText} ${sobrenome[i].innerText}', ${participacao[i].innerText}],`));
}

Mas recomendo esta forma:
function contentChart() {
       const id = document.querySelectorAll('.id');
       const nome = document.querySelectorAll('.nome');
       const sobrenome = document.querySelectorAll('.sobrenome');
       const participacao = document.querySelectorAll('.participacao');

       return id.map((valor, i) => [`${nome[i].innerText} ${sobrenome[i].innerText}`, participacao[i].innerText]);
}

Considerações:

*

*Coloquei const porque as variáveis são imutáveis;

*Em vez do for, inseri o map. Ele é mais elegante e mais rápido que o forEach;

*Pelo que percebi a participação é sempre number, então retirei as aspas.

Bons estudos!


text:
Q: proving a non-zero polynomial $f$ has a point where it's not $0$ (on a field with infinite elements)
Let $k$ be a field with infinite elements. Let $0 \not = f \in k [x_1, ..., x_n]$. I want to prove that there exists $P \in k^n$ such that $f(P) \not =0.$

I think I could do it if I use induction on the number of variables or degree of $f$ or something, but it looks like it gets a bit messy, and I am sure there is a "slicker" proof. Could someone please tell me such a proof (that is not too messy) if there is one out there? Thank you very much!

A:
If $A$ is an integral domain and $f\in A[X]$ has infinitely many zeroes in $A$, then $f$ is the zero polynomial.

To see this, note that any zero $a\in A$ allows us to write $f(X)=(X-a)g(X)$ with $\deg g<\deg f$. Hence after factoring out $\deg f$ zeroes, we are lef with a degree zero factor, i.e., a constant: $f(X)=c(X-a_1)(X-a_2)\cdots (X-a_n)$. If we plug in yet another zero $a_{n+1}$, the right hand side is a product of $c$ and some non-zero factors. As $A$ is an integral domain, $f(a_{n+1})=0$ implies $c=0$, so $f=0$.
Now we can do a proof by induction: $k[X_1,\ldots,X_n]=A[X_n]$ where $A=k[X_1,\ldots,X_{n-1}]$ is an integral domain(!). So if $f\in A[X_n]$ is not the zero polynomial, there exists some $b_n\in k$ such that $f(b_n)$ is not the zero polynomial.
But spelled out, this means that $g(X_1,\ldots,X_{n-1}):=f(X_1,\ldots, X_{n-1},b_n)\in k[X_1,\ldots,X_{n-1}]$ is not the zero polynomial. By induction hypothesis, there exists $(b_1,\ldots,b_{n-1})\in k^{n-1}$ with $g(b_1,\ldots,b_{n-1})\ne0$, i.e., $f(b_1,\ldots, b_n)\ne 0$.


text:
Q: Array splitting seems not to be working , and also Maps and Lists refused to be populated Can someone please show me what is wrong with this block of code.
What I am trying to do is to create a phone-book that will receive the first input as the amount of entries the user want to enter, and the subsequent inputs will be the input of the phonebook details in
the form of a long string.
It will include the name of the person and the phone number, in a single line and then after the input, I will split the inputted values into two and store each as a key and value in a map.
But my code is not working.
What am I doing with the Lists is this:
The input from stdin will be a single string of the name and the phone number in a single line of input. So what I am trying to do is to split the long string of name and number into two(name and number), and store them both in a list, then when I want to populate the Map I will then call the index of the list where the number is situated and use it as the value, and also call the index of the list where the name is situated and use it as key in the Map.
I have tried using an array but there are problems when splitting the string. With this list now the splitted strings seems not to be saving in the list, probably because of iterations of the loops.
An insight will be helpful
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Testube {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int phoneBookSize = sc.nextInt();
        String[] names = new String[phoneBookSize];
        String[] numbers = new String[phoneBookSize];
        Map<String, String> phoneBook = new LinkedHashMap<>();
        String[] inputNameAndNumber = new String[2];
        String name;
        String number;
        List<String> keepStrings = new ArrayList<String>();
        for (int i = 0; i < phoneBookSize; i++) {

            for (int j = 0; j < 2; j++) {
                inputNameAndNumber = sc.next().split(" ");

                String holder = inputNameAndNumber[j];
                keepStrings.add(holder);
                // name = inputNameAndNumber[0];
                // number = inputNameAndNumber [1];

            }
            phoneBook.put(keepStrings.get(0), keepStrings.get(1));

        }
        System.out.println(phoneBook.entrySet());
    }

A: You should remove your jloop. It let you input your name and number twice to work correctly because of sc.next() is inside this loop.
The 2nd point is that your phonebook will only contains one entry because you always putting the same values. This is because your list is never cleared.
You may change your loop to:
// consume 'new line' after sc.nextInt()
sc.nextLine();
for (int i = 0; i < phoneBookSize; i++) {
    // note: change `next` to `nextLine`
    inputNameAndNumber = sc.nextLine().split(" ");
    name = inputNameAndNumber[0];
    number = inputNameAndNumber[1];
    phoneBook.put(name, number);
}

So in each iteration to populate your phonebook you're changing name and number by the next input.
Your input holds both name and number in one line like
Alex 123
Ben 456
Ed 789

A: The list keepStrings needs to be re-instantiated or cleared otherwise the objects would keep piling up in other indexes. The list will maintain its state (+ more objects further down the index) i.e. the objects on the index 0 and 1 will be the same until cleared or re-instantiated.
for (int i = 0; i < phoneBookSize; i++) {

            for (int j = 0; j < 2; j++) {
                inputNameAndNumber = sc.next().split(" ");

                String holder = inputNameAndNumber[j];
                keepStrings.add(holder);
                // name = inputNameAndNumber[0];
                // number = inputNameAndNumber [1];

            }
            phoneBook.put(keepStrings.get(0), keepStrings.get(1));

            keepStrings.clear();

        }

OR
for (int i = 0; i < phoneBookSize; i++) {

                for (int j = 0; j < 2; j++) {

                    keepStrings = new ArrayList<String>();
                    inputNameAndNumber = sc.next().split(" ");

                    String holder = inputNameAndNumber[j];
                    keepStrings.add(holder);
                    // name = inputNameAndNumber[0];
                    // number = inputNameAndNumber [1];

                }
                phoneBook.put(keepStrings.get(0), keepStrings.get(1));

            }

Though the first solution serves here better.


text:
Q: Hover em seletor :before Me deparei em uma situação, até sei como contornar, fazendo de outra forma, mas gostaria de saber, se é possível utilizar :hover em um elemento :before, tenho a seguinte estrutura:

  Informações da cidade

  Benefícios Fiscais

Onde, o elemento call-box, tem um seletor :before, na seguinte forma:
.call-box {
    float: left;
    font-family: 'LatoBold', arial, sans-serif;
    color: #909090;
    height: 52px;
    width: 150px;
    padding: 10px 0 0 62px;
    line-height: 16px;
    position: relative;
}
.call-box:before {
    position: absolute;
    content: '';
    left: 0;
    top: 0;
    border: 2px solid #00BF8B;
    height: 50px;
    width: 50px;
    -webkit-border-radius: 50%;
       -moz-border-radius: 50%;
            border-radius: 50%;
}

No hover do elemento call-box, gostaria de modificar o seletor :before, é possível?

A: Pfss, resolvido.
.call-box:hover:before {
  background-color: #00BF8B;
}

A: Sim, é possível da seguinte maneira: http://jsfiddle.net/jhwmxfrz/
.call-box:hover:before {
    background-color: #00BF8B;
}


text:
Q: The reverse/inverse of the normal distribution function in R To plot a normal distribution curve in R we can use:
(x = seq(-4,4, length=100))
y = dnorm(x)
plot(x, y)

If dnorm calculates y as a function of x, does R have a function that calculates x as a function of y?  If not what is the best way to approach this?

A: I'm not sure if the inverse of the density function is built in -- it's not used nearly as often as the inverse of the cumulative distribution function.  I can't think offhand of too many situation where the inverse density function is useful.  Of course, that doesn't mean there aren't any, so if you are sure this is the function you need, you could just do:
dnorminv<-function(y) sqrt(-2*log(sqrt(2*pi)*y))

plot(x, y)
points(dnorminv(y),y,pch=3)

A: The derivation of the inverse of the standard normal pdf is:

A: What dnorm() is doing is giving you a probability density function.  If you integrate over that, you would have a cumulative distribution function (which is given by pnorm() in R).  The inverse of the CDF is given by qnorm(); that is the standard way these things are conceptualized in statistics.


text:
Q: How to convert list to string How can I convert a list to a string using Python?

A: >>> xs = [1, 2, 3]
>>> " ".join(str(x) for x in xs)
'1 2 3'

A: Use ''.join:
xs = ['1', '2', '3']
s = ''.join(xs)

If the list contains integers, convert the elements to string before joining them:
xs = [1, 2, 3]
s = ''.join(str(x) for x in xs)

A: xs = ['L', 'O', 'L']
lol_string = ''.join(map(str, xs))


text:
Q: Core Data in XCTests I am using Magical Record in application.
I initialize
   - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [MagicalRecord setupAutoMigratingCoreDataStack];
}

and application usually do some stuff while internet connection is present.
I have tried to write an XCTest but I always receive SIGABRT:
   + (NSManagedObjectContext *) MR_defaultContext
   {
      @synchronized(self) {
      NSAssert(MagicalRecordDefaultContext != nil, @"Default context is nil! Did you forget to initialize the Core Data Stack?");
      return MagicalRecordDefaultContext;
       }
   }

I have investigate it and could see that magical record successfully initialized in AppDelegate.
I even tried
   - (void)setUp {
       [super setUp];
       [MagicalRecord setDefaultModelFromClass:[self class]];
       [MagicalRecord setupCoreDataStackWithInMemoryStore];
   }

   - (void)tearDown {
       [MagicalRecord cleanUp];
       [super tearDown];
   }

But no luck. Has anyone any ideas?

A: You will need to implement a few extra steps if your using Magic record. See here.


text:
Q: Make account stay connected with ZNC Is there a way to make my irc account stay connected when I've disconnected from ZNC?
The buffer feature in ZNC works perfectly, however I would like people to be able to query me, while my client is not runnning.
I'm running ZNC version 1.2.

A: Channels can be detached in two ways:
/detach #chan
/quote detach #chan

A simple join will reattach you:
/join #chan

Source: http://wiki.znc.in/Detaching


text:
Q: Gap between status and app bar when pressing back When I load my app, it looks fine as shown:

However when I tap into a ListItem and press the back button, a gap is created as shown:

Not sure what is causing this:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="0dp"/>
        </android.support.design.widget.AppBarLayout>

        <fragment
            android:id="@+id/car_nav_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/nav_transport" />

    </LinearLayout>

</layout>

And I am using Android JetPack's Navigation Controller
nav_transport.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/car_list_fragment">

    <fragment
        android:id="@+id/car_list_fragment"
        android:name="com.example.transportdirectory.fragments.CarListFragment"
        android:label="@string/cars_title"
        tools:layout="@layout/fragment_car_list">

        <action
            android:id="@+id/action_car_list_fragment_to_car_detail_fragment"
            app:destination="@id/car_detail_fragment"
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right" />
    </fragment>

    <fragment
        android:id="@+id/car_detail_fragment"
        android:name="com.example.transportdirectory.fragments.CarDetailFragment"
        android:label="@string/car_detail"
        tools:layout="@layout/fragment_car_detail">
        <argument
            android:name="vin"
            app:argType="string" />
    </fragment>

</navigation>

This is how I invoke the navigation
val direction = CarListFragmentDirections.ActionCarListFragmentToCarDetailFragment(vin)
            it.findNavController().navigate(direction)


text:
Q: Compare two screenshots doesn't work correctly-java i am trying to make two screenshots with 6 seconds difference, to see if there is some changes on the website.
But my code says me that the screenshots are always different, even if i test it without any changing on the screen.
what am i doing wrong?
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screensize = toolkit.getScreenSize();
Rectangle rectangle = new Rectangle(0,0,screensize.width,screensize.height);

Robot robot = new Robot();
BufferedImage image1 = robot.createScreenCapture(rectangle);
System.out.println("screenshot "+i+"");
Thread.sleep(6000);
BufferedImage image2 = robot.createScreenCapture(rectangle);
System.out.println("screenshot "+(i+10)+"");

int x1 = image1.getWidth();
    int x2 = image2.getWidth();
    if ( x1 != x2 ) {
        System.out.println( "Widths are different: " + x1 + " != " + x2 );
        return;
    }

    int y1 = image1.getHeight();
    int y2 = image2.getHeight();
    if ( y1 != y2 ) {
        System.out.println( "Heights are different: " + y1 + " != " + y2 );
        return;
    }

    for ( int x = 0; x < x1; x++ ) {
        for ( int y = 0; y < y1; y++ ){
            int p1 = image1.getRGB( x, y );
            int p2 = image2.getRGB( x, y );
            if ( p1 != p2 ) {
                System.out.println("Pixel is different at x/y " + x + "/" + y + ": " + p1 + " != " + p2 );
                return;
            }
        }
    }

    System.out.println( "Images are identical" );

A: I tried your code and my pixel is different because of a blinking cursor in Eclipse Console.
Then I had a problem with an animated icon (process explorer in task bar)
Finally it said Image identical.
Note : Mouse isn't part of the thing :

Creates an image containing pixels read from the screen. This image does not include the mouse cursor.


text:
Q: two abstract in article I need to include two abstracts (english and spanish) with their respective keywords, I am using the package apa6 but these only put the latest \abstract{} text.  How can I fix this?
\documentclass[jou,apacite]{apa6}
\abstract{El tema de la evaluación educativa ...}
\keywords{evaluación, aprendizaje, decreto 1290 de 2009.}
\abstract{ The issue of educational evaluation is one }
\keywords{assessment, learning, decree 1290 of 2009.}
\begin{document}
...
\end{document}