text:
Q: RewriteRule not working, 404 error obtained Using Apache/2.2.31, I created the following rule on my '.htaccess' file:
RewriteEngine on
RewriteRule ^([^/]+)/$ /do.php?label=$1 [L]

However, when accessing 'http://foo.com/whatever/', I get a 404 error message. I've checked my error log and:
[Mon Jun 27 11:12:15 2016] [error] [client 192.168.1.132] File does not exist: /path-to-web/whatever, referer: http://foo.com/

'http://foo.com' works ok, and 'http://foo.com/do.php?label=whatever' works ok as well.
I've checked phpinfo, and 'mod_rewrite' is loaded in Apache. Additionally, I tried to enable it via 'http.conf', but Apache tells me that "module rewrite_module is built-in and can't be loaded".
What am I doing wrong? This same '.htaccess' works ok in two other Apache servers.
I tried with "Options +FollowSymLinks -MultiViews" as well
Thank you very much


text:
Q: Differantiate devices with similar model and os version connected to computer with android studio I have 3 tablets with from the same model with the same android version.
I want to be able to differ between devices quickly.
I will just show the problem,

Is their a way to differentiate them on this combo box?
Thanks,
Ilan
UPDATE:
I have posted a bug google about this. I Its a problem for you to, vote for this bug here .

A: Try this in your device,
Homescreen -> press menu -> System settings -> applications -> development -> Device name

Here you can change the devices name which is shown in android studio.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WebSocket connection creates IOException I'm experiencing what 'appears' to be a unique problem. I have a Client/Server model now that takes input from a windows form and pushes it to a server that I've written from scratch, from where, it is supposed to get pulled to a webpage over a websocket.
I've just overcome the handshake and am effectively making a connection; however, my onMessage method does not seem to ever get hit ( regardless of how soon/late I send text to it ) and it SEEMS as if when it theoretically would trigger, something else happens...
When I send text from the client that is sending input TO the server, it delivers the first line and waits for the second. The server receives this input and writes it to all connected 'output' clients. This is meant to include my websocket. Here is where I'm getting lost. The first line gets 'written' ( according to the server ), but the 'onmessage' event never occurs. If I send a second line to the server, on attempting to write, the server throws an exception to the extent of "Unable to write data to the transport connection: An established connection was aborted by the software in your host machine." and the client triggers onclose.
Perhaps someone could offer some insight. Here is my websocket code:
<!DOCTYPE html>
<meta charset="utf-8" />

And its corresponding output:
Starting

Instantiated

Evented

CONNECTED

DISCONNECTED

Here is the server 'Write' method ( From a class I wrote and am inheriting from ):
public virtual void WriteLine(String Argument)
{
    if (this.ClientStream == null)
    {
        try
        {
            this.ClientStream = new NetworkStream(this.ClientSocket);
            this.WriteLine(Argument);
            return;
        }
        catch (Exception e)
        {
            throw new Exception("Exception encountered while writting to Client.\n" + e.Message);
        }
    }
    else if (this.OutputWriter == null)
    {
        try
        {
            this.OutputWriter = new StreamWriter(this.ClientStream);
            this.WriteLine(Argument);
            return;
        }
        catch (Exception e)
        {
            throw new Exception("Exception encountered while writting to Client.\n" + e.Message);
        }
    }
    else
    {
        try
        {
            this.OutputWriter.Write(Argument + "\r\n");
            this.OutputWriter.Flush();
            return;
        }
        catch (Exception e)
        {
            throw new Exception("Exception encountered while writting to Client.\n" + e.Message);
        }
    }
}

And Server 'Connect' method ( From my inherited class ):
public void Start()
{
    if (this.Server == null)
    {
        throw new Exception("Could not start TelnetServer.Listener, Server is null.");
    }
    else if (this.RunningThread == null)
    {
        this.RunningThread = new Thread(this.Start);
        this.RunningThread.Name = "TelnetServer.Listener:" + this.Port;
        this.RunningThread.Start();
        return;
    }
    else if (this.LocalAddress == null)
    {
        this.LocalAddress = IPAddress.Any;
        this.Start();
        return;
    }
    else if (this.NetworkListener == null)
    {
        this.NetworkListener = new TcpListener(this.LocalAddress, this.Port);
        this.NetworkListener.Start();
        this.Start();
        return;
    }
    else
    {
        this.RunningFlag = true;

        while (this.IsRunning())
        {
            try
            {
                Socket NewSocket = this.NetworkListener.AcceptSocket();
                this.Server.Connect(NewSocket);
                continue;
            }
            catch (Exception e)
            {
                this.Print("Exception encountered while creating new Client.");
                this.Print(e.Message);
                continue;
            }
        }
    }
}

If any more information is necessary, I'll be glad to elaborate. Please do note that I make a complete handshake in my 'final' class when I get a new connection, and the 'write' method in the final class sends the message down to the above mentioned write method.
Thanks again in advance.
[edit]
Added send frame; now it fails solid on the first message.
                if (HeaderFinished && HeaderSent)
                    base.WriteLine("\u0000" + Encoding.UTF8.GetBytes(Argument) + "\uffff");
                else
                    base.WriteLine(Argument);
[/edit]


text:
Q: Drupal 9.2 Login not working after logout My site upgraded from Drupal 8.x to Drupal 9.2.4 (PHP 7.4). Once logout then login was not working. No error or warning, just page refresh happened. I checked the cookie compared with my old version, one of the cookies was not set after first login and logout.
The below image session is not set for second-time login.
Missing session image

I am not sure this is the problem, maybe.

A: I had the same issue. I am using my own redirect in hook_user_login().
After update from Drupal 9.1 to Drupal 9.2 my redirect stoped working (no login and no redirect).
I found information on Drupal forum that 'redirect after login is breaking a basic contract of Drupal hooks, in that it is halting execution.'
On the same forum I found suggestion to save session before sending a response, so I tried this on my code:
$response = new RedirectResponse($url->toString());
$request = \Drupal::request();

// Save the session so things like messages get saved.
$request->getSession()->save();

$response->prepare($request);
$response->send();

Source: https://www.drupal.org/project/redirect_after_login/issues/3214949#comment-14138959


text:
Q: How to get Redux state before render for child component prop? I have a component that renders another component, and it depends on the currentUser state in Redux. However, upon initial load, the value is undefined. How do I enforce that the value is defined before proceeding?
The component with the state:
import { Grid, Typography } from "@material-ui/core"
import { makeStyles } from "@material-ui/styles"
import { useEffect, useState } from "react"
import DataScroll from "./navigation/DataScroll"
import Post from '../components/partsbin/Post'
import SidePanelCard from '../components/SidePanelCard'
import { getPosts } from "../gql/queries"
import { useSelector } from 'react-redux'
const theme = makeStyles({})

export default function HappeningNow(props: any) {
  const styles = theme()
  const { currentUser } = useSelector(({ uiState }: any) => uiState)

  const handleGetPosts = async (offset: number, limit: number) => {
    try {
      const data = await getPosts(offset, limit, null, currentUser?.uid || null)
      console.log('params being passed: ', offset, limit, null, currentUser?.uid)
      console.log('data returned', data)
      return data
    } catch(e) {
      return e
    }
  }

  return (
    <Grid container flexDirection="column">
      <Grid item>
        <Typography
          variant="h6"
          sx={{ fontWeight: "bold", textAlign: "center" }}
        >
          Happening Now
        </Typography>
      </Grid>
      <Grid item>
        <DataScroll ItemComponent={SidePanelCard} limit={12} getApiItems={(offset: number, limit: number) => handleGetPosts(offset, limit)} />
      </Grid>
    </Grid>
  )
}

As you can see, I'm setting currentUser via useSelector, but the query handleGetPosts is firing before currentUser is being defined. How do we guarantee that the value is set? Is it good practice to wrap a global state with local state? Is there a way to use useSelector in a useEffect? I'm not sure where to begin.

A: When you get the value currentUser  the component will re-render. So you may add a simple condition to check if currentUser  is available or not. Like,
{currentUser   && <DataScroll ItemComponent={SidePanelCard} limit={12} getApiItems={(offset: number, limit: number) => handleGetPosts(offset, limit)} />} .
Now handleGetPosts should get triggered only if currentUser  is set.


text:
Q: cython dict access results in segmentation fault I am trying to implement a simple cached method in cython. The compilation went through but read cache at run time crashes the program with segmentation fault.
Here is my cython hello.pyx file
# disutils: language = C++
# define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
cimport libc.stdint
cimport cython
cimport numpy as np
from libc.stdio cimport printf
from libcpp.unordered_map cimport unordered_map
from libcpp.pair cimport pair
from cython.operator cimport dereference

np.import_array()  # needed to initialize numpy-API

cdef class DemoClass:
    cdef readonly unordered_map[double, double[:]] cache

    def __init__(self):
        cdef unordered_map[double, double[:]] cache
        self.cache = cache

    cpdef double[:] demoMethod(self, double key):

        if self.cache.count(key) > 0:
            printf("second time")
            return self.cache[key]

        printf("First time")
        cdef double[:] result = cnp_empty(100)
        self.cache[key] = result

        return result

and here is what I tried to run in python
from hello import DemoClass

import numpy as np
demoObj2 = DemoClass()
print(demoObj2.demoMethod(0.0)) # <MemoryView of 'ndarray' object>
print(demoObj2.demoMethod(0.0)) # this results in Segmentation fault, no more messages

Which bit about the unordered map am I using wrong?

Edit: David's answer inspired me to try something else
from hello import DemoClass

import numpy as np
demoObj2 = DemoClass()
a = demoObj2.demoMethod(0.0)
print(a) # <MemoryView of 'ndarray' object>
print(demoObj2.demoMethod(0.0)) # this works fine now, because the reference to the memoryview is now kept, in python.

A: You cannot store a memoryview in an unordered map. A memoryview is a Cython-managed reference-counted type and the C++ unordered map doesn't know about the reference counting or initialization of the memoryview.
The Cython 3.0 alpha will diagnose this and emit an error message to stop you from doing it. But older versions of Cython won't.
An unordered map is not suitable for what you're aiming to do. A Python dict would be better (although it stores an "untyped" Python wrapper of the memoryview, so isn't ideal for speed). However, realistically you're probably better storing the raw Numpy arrays in the dict rather than the memoryviews of those arrays.

A: As answered by @DavidW, once the result memoryview is returned, if there is no python code which references it, python will do garbage-cleaning on the object, causing the cache to point to deleted data.
AFAIK, There are two ways to work around this.

*

*Use from cpython.ref cimport Py_INCREF to Py_INCREF to manually increase python reference to the memoryview result when caching. This means GIL is acquired.

*Instead of using memory_view, use libcpp.vector. This is not garbage-cleaned by python, so it doesn't need the reference inc and can be done without the gil.


text:
Q: Unexpected Python interpreter output I wrote an extremely basic python code which creates a file and appends 10 lines in it
>>> b = open("b.txt", 'w')
>>> for i in range(10):
...     b.write("line %d\n" %i)
...
7
7
7
7
7
7
7
7
7
7

Why are 7's outputted on the screen?

A: The '7's outputted to the console are the number of bytes written to the file, and are returned by the file.write function. See the docs here.
In addition, you should generally use the following format to handle files:
with open("b.txt", "w") as f:
    for i in range(10):
        f.write("line %d\n" %i)

This avoids having to manually close the file after you've finished with it.

A: This comes from the behavior of the interactive interpreter. You'll notice a similar effect if you write
>>> x = 5
>>> x
5

When you have a statement and don't set it equal to anything, the interactive interpreter will repr the output/return value and display it in the terminal. The return value for a file write command is the number of bytes written to the file.


text:
Q: Get whole language file array I'm newbie in laravel 4.0.

*

*How to get the whole array from lang/en/texts.php?

*Is there a Lang::getAll() method?

My goal is to generate keywords/description in my base controller, to fill them into the the meta tags and other places in the DOM in the master blade template. If my approach is completely wrong, please tell me!
Generating the keywords and description from an associative array is NOT the problem, but the lack of knowledge about the framework. And, I was googling for quite a time before ending up here...
Working with blade templates:
This is my BaseController:
class HomeController extends BaseController {

    protected $layout = 'layouts.master';
    private $keyWords = array();

    private function getKeyWords () {
        // ???

    }

    public function getIndex() {
        return View::make('home')
            ->with('errorcanvas', trans('texts.canvas'))
            ->with('errortextwebgl', trans('texts.webgl'))
            ...;
    }

    ...

}

I found something in the API:
Illuminate\Translation\FileLoader load() which loads the messages with a given locale
...

A: You can get the entire array with Lang::get().
$array = Lang::get('pagination'); // return entire array
$text  = Lang::get('pagination.next'); // return single item

A: Here's how yo can load them:
Route::get('test', function()
{
    $a = File::getRequire(base_path().'/app/lang/en/pagination.php');

    foreach($a as $key => $value)
    {
        echo "$key => $value<br>";
    }
});

If you need to load them all, you can use:
$languages = File::directories(base_path().'/app/lang/');

I had to find a way to create an language import command in my Glottos package: https://github.com/antonioribeiro/glottos.

A: Antonio answered loading of language file perfectly, but I don't like your approach.
It can be done much easier. Why not to do it this way?
// view file
<html>
  <head>
    <meta name="description" content="{{ trans('texts.description') }}">
    ...
  </head>
  ...
</html>

You do not need to send all the content thru controller, which makes your controller clean.

A: Lets say, a language file: lang/en/countries.php
return [
 'afg' => 'Afghanistan',
 'ala' => 'Aland',
 'alb' => 'Albania',
 'dza' => 'Algeria',
 'asm' => 'American Samoa'
];

Retrieving lines from the language file with Lang::get() method
$array = Lang::get('countries'); // return entire array
$text  = Lang::get('countries.afg'); // return single item

for Laravel 5.0 & above, You may also use the trans helper function, which is an alias for the Lang::get() method.
$array = trans('countries'); // return entire array
$text = trans('countries.afg'); // return single item

Find out more on Laravel docs...

A: you can actually use the helper function __('lang_file') as well.


text:
Q: how to convert an HTML table into an Excel spreadsheet I use laravel-excel version 3.1 .
my code is :
class UsersExport implements FromView
{
    private $users;

    public function __construct()
    {
        $this->users = User::query()->select('name' , 'family' , 'mobile' ,'national_code' , 'email' , 'registered_from')->get();
    }

    public function view(): View
    {
        return view('test', [
            'users' => $this->users
        ]);
    }
}

In my controller I called vies function:
return (new UsersExport())->view();

here I got a view (html page) not excel spreadsheet. what should I do?

A: You need to add use Exportable; in your UserExport class, then call return (new UsersExport())->download('something.xls');
P. S. It is not a good idea to write query in UserExport constructor. It would be better to get them before calling it, then pass to your new UserExport()


text:
Q: check constraint (or something better) The situation: there is a java application that reads data from a DB Oracle.   To simplify, the email field is currently read from a "USERS" table. Now I have to modify the application so that I can read more email addresses but I have no intention to modify all the dozens of already existing queries that refer to this table. The escamotage was to add a "EMAILS" table containing (in addition to PK "id_mailaddr")  only the "id_user" and "mail_address" fields. But because the data are not loaded only by the app but also by other users through the most diverse methods (Excel tables, queries "insert all", sql loader etc.) I have to impose the consistency condition at the database level. And here lies the problem! I do not know Oracle and Pl-sql. How can I write a "check" constraint to impose that, if the "id_user" of the email address that I insert in the new table was already existing in the "USERS" table, the email address that this "id_user" is matched in the table "USERS" must coincide with the matched one in the new table?
For example:
USERS                                     EMAILS
id_user  user       email                 id_mailaddr   id_user  mail_address
100      Smith      smith@yahoo.com       1             100      smith@yahoo.com        OK!
101      Brown      brown@gmail.com       2             101      brown@gmail.com        OK!
102      M.Scott                          3             105      scott@hotmail.com      NO!
103      J.Scott    scott@hotmail.com     4             103      j_scott@hotmail.com    NO!
104      P.Scott                          5             104      scotty@aol.com         OK!

A: Hope this trigger code helps -
drop table users;
drop table email;

CREATE TABLE users
    (id_user integer, userz varchar2(7), email varchar2(17))
;

INSERT ALL
    INTO users (id_user, userz, email)
         VALUES (100, 'Smith', 'smith@yahoo.com')
    INTO users (id_user, userz, email)
         VALUES (101, 'Brown', 'brown@gmail.com')
    INTO users (id_user, userz, email)
         VALUES (102, 'M.Scott', '')
    INTO users (id_user, userz, email)
         VALUES (103, 'J.Scott', 'scott@hotmail.com')
    INTO users (id_user, userz, email)
         VALUES (104, 'P.Scott', '')
SELECT * FROM dual
;

CREATE TABLE email
    (id_mailaddr int, id_user int, mail_address varchar2(19))
;

insert INTO email (id_mailaddr, id_user, mail_address)
         VALUES (3, 105, 'scott@hotmail.com');

insert INTO email (id_mailaddr, id_user, mail_address)
         VALUES (5, 104, 'scotty@aol.com');

create or replace trigger email_trig
after insert on email
for each row
declare
v_cnt integer := 0;
mail_adr varchar2(64);
e exception;
begin
    if inserting then
        select email, count(*) into mail_adr, v_cnt from users where id_user = :new.id_user group by email;

        if v_cnt = 0 or mail_adr <> :new.mail_address then
            raise e;
        end if;
    end if;
exception
    when others then
        raise_application_error(-20000, 'Error inserting new email:- '||:new.mail_address);
end;
/

A: If I understand correctly, you want to make sure that no id_user, mail_address combination gets inserted into the new EMAILS table that does not exist in the previously existing USERS table?
That only makes sense if it is an interim-design, because you will not be able to put more than one EMAIL record for any given USERS record.  (I am assuming rows in EMAILS must be unique.)
But, if that's the escamotage (+1 for that -- love it!), I think what you are talking about is a foreign key constraint:
alter table users add constraint users_id_email_u1
   UNIQUE (id_user, email);

alter table emails add constraint user_id_email_f1
   FOREIGN KEY ( id_user, mail_address) REFERENCES users  ( id_user, email);

This will ensure there are never any EMAILS rows that do not match what is in USERS.
However, it will not ensure the converse!  That is, there could be USERS rows that do not have the necessary row in EMAILS.  I don't think you asked about that case in your post, but I think that it may prove important to you.  So, I'd suggest that what you really want to do is:
CREATE OR REPLACE VIEW emails AS
  SELECT id_user, email mail_address
  FROM   users;

... and, possibly, this to handle inserts into the EMAILS "table"...
CREATE OR REPLACE TRIGGER emails_trg
  INSTEAD OF INSERT
  ON emails
  FOR EACH ROW
BEGIN
  UPDATE users
  SET    email = :new.mail_address
  WHERE  id_user = :new.id_user;
END;

Then, once all your queries are upgraded to use EMAILS, replace the view with a real table.


text:
Q: Use product view block in product list I am trying to use a block from catalog/product_view in catalog/product_list but I can't get the block to render. Below is the code that I'm trying to call from template/catalog/product/list.phtml.

<?php echo $this->getChildHtml('additional') ?>

A: The block alias name additional stands for the block Mage_Catalog_Block_Product_View_Attributes which is responsible for showing additional data related to a product in a product view page.
If you inspect further about the block, you can see that, this block is not rendered directly inside product view page. Instead it is added to a block group detailed_info and then uses this block group to show the additional block.
With that said, let us look what are the steps that you need to take care in order to add this block in a product list page.
1.Add the block in product list page via layout update
You can do this using local.xml file. This is how the code looks like
File : app\design\frontend\<package>/<theme>/layout/local.xml
<layout>
    <catalog_category_default>
        <reference name="product_list">
            <block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
                <action method="addToParentGroup"><group>detailed_info</group></action>
            </block>
        </reference>
    </catalog_category_default>
</layout>

This will add the product.attributes block to the product_list block, but which uses the feature of addToParentGroup. Due to this product.attributes block can be rendered in the same way it is rendering in a product view block.
2. Render the Child Groups of product_list block
Since we added product.attributes block as group child of product list, we need to show the block by looping through group childs. You can do this like this.
File : app\design\frontend\<package>/<theme>/template/catalog/product/list.phtml
....
<?php foreach ($_productCollection as $_product):
    ....
    <?php foreach ($this->getChildGroup('detailed_info', 'getChildHtml') as $alias => $html):?>
    <div class="box-collateral <?php echo "box-{$alias}"?>">
        <?php if ($title = $this->getChildData($alias, 'title')):?>

<?php echo $this->escapeHtml($title); ?>

        <?php endif;?>
        <?php echo $html; ?>

    <?php endforeach;?>
    ....
<?php endforeach; ?>

Here you can see that, we are added the group child rendering code inside the foreach loop which is responsible for looping through each products in a category product list.
3.Register the product in each loop
Now in order to make the product.attributes block work, we need to register and unregister for each product loop. Why would it need ? The answer resides in app\design\frontend\<package>/<theme>/template/catalog/product/view/attributes.phtml. You can see below code there.
$_product = $this->getProduct();

This call is actaully carrying out by Mage_Catalog_Block_Product_View_Attributes::getProduct(). The method look like this.
public function getProduct()
{
    if (!$this->_product) {
        $this->_product = Mage::registry('product');
    }
    return $this->_product;
}

As you can see, the method get the product from Mage::registry(). So it is important that, we need to Mage::register the product which is currently being in the product list loop.
So inside list.phtml, under the foreach loop of product collection, before calling the group child blocks, you need to do this registration. It looks somewhat like this.
 <?php foreach ($_productCollection as $_product):
     ...
     <?php
          Mage::unregister('product');
          Mage::register('product', $_product);
 <?php foreach; ?>

Hope that makes sense.


text:
Q: Iterating Over Xml using findall , Lxml I have the following xml :
<head>
  <body>
    <para>
      <Run>
        <Runprop>
           <highlight val="red"/>
        <break/>
        <text>
         Hello there
        </text>
        </RunProp>
      </Run>
      <Run>
        <break/>
      </Run>
      <Run>
         <text>
          See you there
         </text>
      </Run>
    </para> ..
  </body>
</head>

I want to extract all text with the highlight "red" value. Note that highlight tag is one level down to that of the text tag. And the conditions are:

*

*For every paragraph , add an extra space .

*If the break tag is encountered whilst iterating over parents of highlight tag , add a space.

*Extract text only corresponding to the highlight tag

What I have done is:
text=""                                #initialize an empty string
for p in lxml_tree.findall('para'): #itertate over each paragraph (all paragarpahs have the same tag name para)
    for r in p.findall("Run"):     #iterate over each run
         for a in r.iter(tag="highlight"): #search for highlight tag
            for b in a.iterancestors(): #go back to the parents
                if b.tag=="break":     #if break found
                   text+=" "           # add a space
                elif b.tag=="text":    # if text found
                   text+=''.join(b.text) #add text

The above doesn't seem to work as iterancestors travels all the way to the root node. How could i possibly iterate over the parents i.e. Runprop, break, and text?? I have implemented something similar to this for all the text and that worked..
Edit 1:
Just a flawed logic above , I would rather iterate over each Run in a paragraph , search for break first , then see if there's highlight within the Runprop and then extract text in the parent's sibling.

A: I have managed to fix it after some thoughts and getting an idea from anzel's answer.
text=""
for p in lxml_tree.findall('para'):   #iterate over paragraphs
    text+= " "                        #add spaces
    for r in p.findall("Run"):        #iterate over each run in para
         for a in r.findall("break"):  #search for break tag in it and add space if found
            text+= " "
         for b in r.findall('.//highlight[@val="red"]/../..//text'): #search for red highlight in that run and return text
             text+=''.join(b.text) # append text to main string

A: Since your xml has a positional pattern where <highlight>, <break /> and <text>, you actually don't need to go back to parent.
I'm going to use iter and getnext to achieve what you need:
from lxml import etree

html = '''
<head>
  <body>
    <para>
      <Run>
        <RunProp>
           <highlight val="red" />
        <break/>
        <text>
         Hello there
        </text>
        </RunProp>
      </Run>
      <Run>
        <break/>
      </Run>
      <Run>
         <text>
          See you there
         </text>
      </Run>
    </para> ..
  </body>
</head>'''

tree = etree.fromstring(html)

for node in tree.iter():
    if node.tag == 'para':
        node.text = '..your space here..' + node.text
        print node.text
    if node.tag == 'highlight':
        print node.values()
        if node.getnext().tag == 'break':
            print node.getnext().tag
            if node.getnext().getnext().tag == 'text':
                node.getnext().getnext().text = \
                    '..your space here..' + node.getnext().getnext().text
                print node.getnext().getnext().text
        elif node.getnext().tag == 'text':
            print node.getnext().text

..your space here....your space here..

['red']
break
..your space here....your space here..
         Hello there

to write the changes to a file:
etree.ElementTree(tree).write('output.xml', pretty_print=True)

cat output.xml
<head>
  <body>
    <para>..your space here..
      <Run>
        <RunProp>
           <highlight val="red"/>
        <break/>
        <text>..your space here..
         Hello there
        </text>
        </RunProp>
      </Run>
      <Run>
        <break/>
      </Run>
      <Run>
         <text>
          See you there
         </text>
      </Run>
    </para> ..
  </body>
</head>


text:
Q: Rails: can't migrate database When I'm trying migrate database with bundle exec rake db:migrate I get an error Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2). How can I fix it?

A: There may be different reasons. Either as vanda says your mysql server simply isn't running.
Or it placed the mysql.sock file in a different folder. In this case you can add the following line to config/database.yml:
socket: /var/run/mysqld/mysqld.sock

(Obviously the path must be the right one, this may differ between installs and you may have to find the right path first)


text:
Q: How read data by Dialogflow on Firebase I use dialog flow chatbot but when I try to bring books from DB firebase I should write the key !!
picture for DB
I want read all keys !
but the problem on code I must declare key to bring data the in this case (-LsDnHZFnJ1Iz5sGsRKu) like this
 function handlecat(agent){
   return admin.database().ref('Books/-LsDnHZFnJ1Iz5sGsRKu').once("value").then((snapshot) => {
     agent.add(`in ` + snapshot.child('title').val() );
   });
 }

how can I do it auto like loop!?
I use this code
admin.database().ref('Books').once("value").then((snapshot) => {
let books = snapshot.val();
books.forEach(function(element) {
    agent.add(element.child('title').val()); /// and I use element.title
});
});
}

but doesn't work !!

A: If you want all of the children of "Book", then you can get a reference to that path, call once() on it, and get the val() of the snapshot returned. This should give you an array of books. Something like this:
admin.database().ref('Books').once("value").then((snapshot) => {
  let books = snapshot.val();
});

This will be a JavaScript Array, so you won't need to re-fetch everything from the server. You can just access this using normal JavaScript methods, so if there is a "title" attribute in each book that you want, you can get it with something like
books.forEach( element => {
  console.log( element.title );
} );

But this could be very large if you have a lot of items in that array. And it may take a while to fetch and a lot of memory to store. If you are, there are various approaches to working with lists of data including using ordering and filtering methods such as orderByChild() and limitToFirst() depending on your needs.
Once you have this value, you also need to send it to the user, since it sounds like you're using Dialogflow. One issue is that you can't just call agent.add() for each item, since some of Dialogflow's integrations only support calling agent.add() once and this may create a long list of titles which won't be very usable in a chat agent. Think about ways to narrow this down to just one or a few titles that you may want to report back. So it might be something like this
if( books.length === 0 ){
  agent.add( `There are no books.` );
} else if( books.length === 1 ){
  agent.add( `There is one book named ${books[0].title}` );
} else {
  agent.add( `There are ${books.length} books including one named ${books[0].title}` );
}


text:
Q: What are the risks of running 'sudo pip'? Occasionally I run into comments or responses that state emphatically that running pip under sudo is "wrong" or "bad", but there are cases (including the way I have a bunch of tools set up) where it is either much simpler, or even necessary to run it that way.
What are the risks associated with running pip under sudo?

Note that this is not the same question as this one, which, despite the title, provides no information about risks. This also isn't a question about how to avoid using sudo, but about specifically why one would want to.

A: Using pip that way means you trust it to the level you allow it to make anything to your system. Not only pip, but also any code it will download and execute from sources you may not trust and that can be malicious.
And pip doesn't need all that privileges, only the write access to specific files and directories. If you can't use your system's package manager and do not want to go the virtual environment way, you may create a specific user that has write privilege to the python installation directory and use it for pip. That way you better control what can pip do and not do. And you can use sudo -u for that!

A: Besides obvious security risks (which I think are in fact low when you install software you know) mentioned in other answers, there is another reason. Python that comes with the system is part of this system and when you want to manage the system you use tools designated for system maintenance like package managers in the case of installing/upgrading/uninstalling software. When you start to modify system software with third party tools (pip in this instance) then you have no guarantee about the state of your system. Yet another reason is that sudo can bring you problems you wouldn't have a chance or have a very small chance to have otherwise. See for example Mismatch between sys.executable and sys.version in Python
Distros are aware of this problem and try to mitigate it. For example Fedora – Making sudo pip safe and Debian – dist-packages instead of site-packages.

A: The only thing "wrong" with sudo is that it, well, DOes as Super User ala root meaning you can potentially destroy an installation with the wrong command.  As PIP is a package maintenance for a particular program you would need such access anyhow to make changes...

A: When you run pip with sudo, you run setup.py with sudo. In other words, you run arbitrary Python  code from the Internet as root. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine. Prior to some recent fixes to pip and PyPI, an attacker could also run a man in the middle attack to inject their code when you download a trustworthy project.

A: There are a few reasons that haven't been mentioned by other users but are still important.
Lack of code review amongst pip packages
The first reason is that PyPI packages (packages that you can install via pip) are not monitored or code-reviewed like you may be used to with other package managers. There have been many cases of malicious PyPI packages being published and then downloaded by thousands of users before being removed. If you happen to download one of these malicious packages as root then you are essentially giving the malware access to your entire system. Though this isn't an every day occurrence, it is still an attack vector to be aware of. You can learn more about this by reading about the concept of least privileges.
Running pip as root interferes with system-level packages
The second, and more important reason, is that running pip with sudo or as the root user will interfere with system-level packages and can disrupt the functionality of your system. Piotr Dobrogost's answer briefly mentions the effects that package managers can have on the state of your system, but I think a more in-depth explanation will help people better understand why this practice can be harmful.
Take for example a Linux distro that ships with Python 3.6 and the Python package cryptography to perform cryptographic operations. For illustrative purposes, imagine that the cryptography package version 1.0.0 is used by the system to hash passwords and allows users to log in. If version 1.0.1 of the same package introduces a regression that the system doesn't account for and you upgrade the global cryptography package by running sudo pip3 install -U cryptography, you accidentally just broke the ability for users to log in system-wide by introducing a regression on system dependencies.
This is a contrived example and would actually be easier to track down than most, but it is certainly a possible scenario. In the real world you would most likely break something less important, but the lesson is the same. In some scenarios this example would be easier to undo because you would know exactly what you broke when everything instantly stopped working, but you could end up breaking something that is much harder to track down and you might not find out until much later when you have no recollection of what you changed.

Why would you want to run pip with sudo?
I haven't seen anyone address the final question in your post, so I'll address it here. There are a few reasons why someone would want to run pip with sudo, but they are far more rare.
The first reason that people would want to do it this way is because people are lazy and it's a fast way to force the system to install the package you need. Say that someone needs to install the coloredlogs package because they absolutely have to have their logs be colored right now and they don't know anything about having a secure system. It's often much easier for inexperienced users to add sudo to the beginning of everything when it doesn't work because "it just works" rather than learning why it didn't work the first time.
The second reason, and only legitimate reason that I can think of, is if an admin needs to patch something system-wide. Say that a vulnerability is introduced in pip version 20.0.0 and there is a hotfix that fixes the issue in version 20.0.1. The system administrator probably doesn't want to wait for the distro to patch this for them and instead wants to patch it right now to mitigate the issue. In this scenario I think it would be safe for the system administrator to use python3 -m pip install --upgrade pip to update their version of pip, but they would need to be cautious to ensure there are no unintended consequences.


text:
Q: Opengl 4 debug output does not work I am writing a game. I use ArchLinux most of time but I have tried to run my game on the Ubuntu 16.04 recently. On Ubuntu 16.04 there is a strange error: 1280. It is too difficult to find what causes the error so I wanted to see opengl's debug output but I don't see it too. I noticed one thing during shader validation - validation seems to be unsuccessful but the log is empty:
GLint status;
glValidateProgram(program_);
glGetProgramiv(program_, GL_VALIDATE_STATUS, &status);

if (status == GL_TRUE) {
    return;
}

// Store log and return false
int length = 0;

glGetProgramiv(program_, GL_INFO_LOG_LENGTH, &length);

if (length > 0) {
    GLchar infoLog[512];
    glGetProgramInfoLog(program_, 512, nullptr, infoLog);

    throw std::runtime_error(std::string("Program failed to validate:") + infoLog);
} else {
    throw std::runtime_error(std::string("Program failed to validate. Unknown error"));
}

This gives me Unknown error. Also the opengl's debug output can't be seen, however, user messages are written there successfully. Here is the code:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

int contextFlags = 0;
SDL_GL_GetAttribute(SDL_GL_CONTEXT_FLAGS, &contextFlags);
contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, contextFlags);

sdlWindow_ = SDL_CreateWindow(title.c_str(),
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        0,
        0,
        SDL_WINDOW_OPENGL
        | SDL_WINDOW_SHOWN
        | SDL_WINDOW_FULLSCREEN_DESKTOP
        | SDL_WINDOW_INPUT_GRABBED);

if (!sdlWindow_) {
    throw std::runtime_error("Unable to create window");
}

SDL_Log("Window created");

glContext_ = SDL_GL_CreateContext(sdlWindow_);
if (!glContext_) {
    throw std::runtime_error("Failed to init OpenGL");
}
SDL_Log("GL context created");

{
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (err != GLEW_OK) {
        throw std::runtime_error(std::string("GLEW Error: ") + reinterpret_cast<const char*>(glewGetErrorString(err)));
    }
}

if (glDebugMessageCallbackARB != nullptr) {
    SDL_Log("GL debug is available.\n");
    // Enable the debug callback
    glEnable(GL_DEBUG_OUTPUT);
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
    glDebugMessageCallback(_openglDebugCallbackFunction, nullptr);
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
    glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0,
                         GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Started debugging");
} else {
    SDL_Log("GL debug is not available.\n");
}

So the main question here is why I can't see the opengl's debug output. And, if it is possible, as an additional question, why does the shader validation fail without a log?

A: GLEW 1.x has some problems when beeing used in a core context (that's also why glewExperimental=true is needed). glewInit always generates an OpenGL error while loading the extensions. You don't get this error through the debug callback because the initialization of the callback happens after the point where the error happend.
You have kind of a chicken-egg problem here: You cannot setup the debug callback before initializing GLEW, but that's where you want to get the debug output from. I recommend calling glGetError() right after glewInit to get rid of the one error you know where it is coming from.


text:
Q: return view based on getimagesize - react-native I have the following piece of code:
getPhoto(item) {

Image.getSize( 'http://api/people/' + item.id + '/photo', ( width, height ) =>
{
  this.setState({ imageWidth: width, imageHeight: height });
  console.log('http://api/people/' + item.id + '/photo', + ' ' +  'width: ' + width)
},(errorMsg) =>
{
  console.log('http://api/people/' + item.id + '/photo', + ' ' + ' errorMsg: ' + errorMsg.code);
  this.setState({ imageError: errorMsg.code });
});

//console.log('http://api/people/' + item.id + '/photo', + ' ' + ' errorMsg: ' + this.state.imageError + ' ' + ' errorMsgIncludes: ' + this.state.imageError.includes('ERCTERRORDOMAIN0'));

return (
   <TouchableOpacity>
      <ListItem style={styles.listItem}>

        <FastImage
          style={styles.avatar}
          source={{
            uri: 'http://api/people/' + item.id + '/photo',
            priority: FastImage.priority.high,
          }}
          resizeMode={FastImage.resizeMode.strech}
        />

        <View style={styles.multiLineView} >
          <Text style={styles.name}>{item.id}</Text>
        </View>

      </ListItem>
    </TouchableOpacity>
)

}
The problem here is that the setstate does not persist outside of the success and error callbacks and hence i am getting inappropriate results.
How can i render a view from within those callback functions?
Thanks in advance for the help!!

A: I think you should refactor your code a little bit and move the get photo function logic to a new component
export default class Item extends React.Component{
    constructor(props){
       super(props);
       this.state={imageWidth: 0, imageHeight: 0}
     }
   // make the call for get size inside component did mount
   componentDidMount(){
      let item = this.props.item;
     Image.getSize( 'http://api/people/' + item.id + '/photo', ( width, height
       ) =>
      {
      this.setState({ imageWidth: width, imageHeight: height });
       console.log('http://api/people/' + item.id + '/photo', + ' ' +  'width:
     ' + width)
      },(errorMsg) =>
      {
        console.log('http://api/people/' + item.id + '/photo', + ' ' + ' errorMsg: ' + errorMsg.code);
        this.setState({ imageError: errorMsg.code });
      });
   }

   render(){
      // render the view you want here according to the component state
      switch(this.state.acondition){
         case 1:
         return a view or component you want ...
         etc ...
      }
   }
}

and then you can call the component and pass the item like this
import Item from './Item';

<Item item={item}/>


text:
Q: How to pass data to route with lazy loaded module? I am using Angular 12 and I have route path with lazy laoded module like this. I have no clue why passing roles in data object like this is not working. Wehn I am trying to read data in my AuthGuard, data object is empty. I would be grateful for any tips.
route path
      {
        path: RoutePath.Users,
        loadChildren: () => import('../users/users.module').then(m => m.UsersModule),
        canActivate: [AuthGuard],
        data: {roles: [UserRole.Admin, UserRole.SuperAdmin]}
      },

auth.guard.ts
   constructor(
      private store: Store,
      private router: Router,
      private activatedRoute: ActivatedRoute) {
  }

  public canActivate(): Observable<boolean> {
    console.log(this.activatedRoute.snapshot.data);
  }

A:  {
    path: RoutePath.Users,
    loadChildren: () => import('../users/users.module').then(m => m.UsersModule),
    canActivate: [AuthGuard],
    data: {roles: [UserRole.Admin, UserRole.SuperAdmin]}
  },

// Here I'm adding the canActivate function sample, you can access the data from ActivatedRouteSnapshot instance, here it is next
canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    console.log(next.data); // you can access the data from ActivatedRouteSnapshot instance, here it is next
    return false;
}


text:
Q: building a high scale java app, what stack would you use? if you needed to build a highly scalable web application using java, what framework would you use and why?
I'm just reading thinking-in-java, head first servlets and manning's spring framework book, but really I want to focus on highly scalable architectures etc.
would you use tomcat, hibernate, ehcache?
(just assume you have to design for scale, not looking for the 'worry about it when you get traffic type responses)

A: The answer depends on what we mean by "scalable".  A lot depends on your application, not on the framework you choose to implement it with.
No matter what framework you choose, the fact is that the hardware you deploy it on will have an upper limit on the number of simultaneous requests it'll be able to handle.  If you want to handle more traffic, you'll have to throw more hardware at it and include load balancing, etc.
The part that's pertinent in that case has to do with shared state.  If you have a lot of shared state, you'll have to make sure that it's thread safe, "sticky" when it needs to be, replicated throughout a cluster, etc.  All that has to do with the app server you deploy it to and the way you design your app, not the framework.
Tomcat's not a "framework", it's a servlet/JSP engine.  It's got clustering capabilities, but so do most other Java EE app servers.  You can use Tomcat if you've already chosen Spring, because it implies that you don't have EJBs.  Jetty, Resin, WebLogic, JBOSS, Glassfish - any of them will do.
Spring is a good choice if you already know it well.  I think following the Spring idiom will make it more likely that your app is layered and architecturally sound, but that's not the deciding factor when it comes to scalability.
Hibernate will make your development life easier, but the scalability of your database depends a great deal on the schema, indexes, etc.  Hibernate isn't a guarantee.
"Scalable" is one of those catch-all terms (like "lightweight") that is easy to toss off but encompasses many considerations.  I'm not sure that a simple choice of framework will solve the issue once and for all.

A: I would check out Apache Mina. From the home page:

Apache MINA is a network application
  framework which helps users develop
  high performance and high scalability
  network applications easily. It
  provides an abstract · event-driven ·
  asynchronous API over various
  transports such as TCP/IP and UDP/IP
  via Java NIO.

It has an HTTP engine AsyncWeb built on top of it.
A less radical suggestion (!) is Jetty - a servlet container geared towards performance and a small footprint.

A: The two keywords I would mainly focus on are Asynchronous and Stateless. Or at least "as stateless as possible: Of course you need state but maybe, instead of going for a full fledged RDBMS, have a look at document centered datastores.
Have a look at AKKA concerning async and CouchDB or MongoDB as datastores...

A: Frameworks are more geared towards speeding up development, not performance.  There will be some overhead with any framework because of use cases it handles that you don't need.  Granted, the overhead may be low, and most frameworks will point you towards patterns that have been proven to scale, but those patterns can be used without the framework as well.
So I would design your architecture assuming 'bare metal', i.e. pure servlets (yes, you could go even lower level, but I'm assuming you don't want to write your own http socket layer), straight JDBC, etc.  Then go back and figure out which frameworks best fit your architecture, speed up your development, and don't add too much overhead. Tomcat versus other containers, Hibernate versus other ORMs, Struts versus other web frameworks - none of that matters if you make the wrong decisions about the key performance bottlenecks.
However, a better approach might be to choose a framework that optimizes for development time and then find the bottlenecks and address those as they occur.  Otherwise, you could spin your wheels optimizing prematurely for cases that never occur.  But that probably falls in the category of 'worry about it when you get traffic'.

A: All popular modern frameworks (and "stacks") are well-written and don't pose any threat to performance and scaling, if used correctly. So focus on what stack will be best for your requirements, rather than starting with the scalability upfront.
If you have a particular requirement, then you can ask a question about it and get recommendations about what's best for handling it.

A: There is no framework that is magically going to make your web service scalable.
The key to scalability is replicating the functionality that is (or would otherwise be) a bottleneck.  If you are serious about making your service, you need to start with a good understanding of the characteristics of your application, and hence an idea of where the bottlenecks are likely to be:

*

*Is it a read-only service or do user requests cause primary data to change?

*Do you have / need sessions, or is the system RESTful?

*Are the requests normal HTTP requests with HTML responses, or are you doing AJAX or callbacks or something.

*Are user requests computation intensive, I/O intensive, rendering intensive?

*How big/complicated is your backend database?

*What are the availability requirements?

Then you need to decide how scalable you want it to be.  Do you need to support hundreds, thousands, millions of simultaneous users?  (Different degrees of scalability require different architectures, and different implementation approaches.)
Once you have figured these things out, then you decide whether there is an existing framework that can cope with the level traffic that you need to support.  If not, you need to design your own system architecture to be scalable in the problem areas.

A: If you are able to work with a commercial system, then I'd suggest taking a look at Jazz Foundation at http://jazz.net.  It's the base for IBM Rational's new products.  The project is led by the guys that developed Eclipse within IBM before it was open-sourced.  It has pluggable DB layer as well as supporting multiple App Servers.  It's designed to handle clustering and multi-site type deployments.  It has nice capabilities like OAuth support and License management.

A: As others already have replied scalability isn't about what framework you use. Sure it is nice to squeeze out as much performance as possible from each node, but what you ideally want is that by adding another node you scale your app in a linear fashion.
The application should be architected in distinct layers so it is possible to add more power to different layers of the application without a rewrite and also to add different layered caching. Caching is key to archive speed.
One example of layers for a big webapp:

*

*Load balancers (TCP level)

*Caching reverse proxies

*CDN for static content

*Front end webservers

*Appservers (business logic of the app)

*Persistent storage (RDBMS, key/value, document)

A: In addition to the above:
Take a good look at JMS (Java Message Service). This is a much under rated technology. There are vendor solutions such as TibCo EMS, Oracle etc. But there are also free stacks such as Active MQ.
JMS will allow you to build synch and asynch solutions using queues. You can choose to have persistent or non-persistent queues.


text:
Q: Hyper-V and WSL2 networks do not communicate I have a Windows 10 Pro (version 20H2) computer with the following situation:

The Host, the Hyper-V VMs and WSL2 all have Internet access, they all can communicate each other but wsl2 and the VMs cannot (the red arrows).
My problem is that I cannot ping or ssh wsl2 from a VM and vice versa.
The Hyper-V VMs use the "Default Switch" vNet: 172.29.96.1, netmask: 255.255.240.0, conn type Internal
WSL2 uses "WSL" vNet: 172.23.240.1, netmask: 255.255.240.0, conn type: Internal
There is a third vNet, named "nat", I can see using "ipconfig" but that is not listed in Hyper-V virtual switch manager: 172.25.128.1, netmask 255.255.240.0, conn type: ?
Can anyone help me?
Thanks

A: I eventually found a solution.
Basically all I need is to set up a port forwarding.
Have a look at here: https://github.com/microsoft/WSL/issues/4150


text:
Q: Unable to place images in the desired way in grid view I want to know how can I make a layout like the attached one.
Through grid layout I am able to achieve almost what I want but the images are not getting placed in this manner, please suggest what could be done in this case.
Shall I use some other view or what?


text:
Q: IBAction not getting called for my textfields inside the scroll view I am having a ScrollView which is a child of a View and then several textfields as children of
this ScrollView. I am trying to give IBAction to these textfields via nib and setting the
delegates of the textfields also via nib.The delegate method of UITextField gets called
without any problem,but the IBAction for the TextField is never called. My view hierarchy is
as follows
 UIView -->(TopMost Level )
   |
 ScrollView-->(Child of UIView)
   |
 Several TextFields-->(children of Scrollview)

All the TextFields are having the same IBAction. I am working on Xcode 4.5 and working on
ARC based project. Any help is greatly appreciated.

A: Finally I worked around and found a solution my self.
I was declaring IBAction with Touch Down Event which works perfectly fine if TextField is
inside the UIView not the ScrollView.
But when the TextField is inside the ScrollView , the IBAction for the TextField should be
declared with EditingDidBeginEvent.
I don't know the reason behind it though.


text:
Q: stm function won't stop running? I am trying to run a structured topic model on some documents, but I cannot get the stm to finish even with a trivial subset of the documents (I have about 5000 documents total, but I'm subsetting down to the first 20 just to test the code). In this stm, I'm not even trying to include covariates. I have a version of the text analysis done with LDA, and I'm just trying to confirm that the results are similar when using an stm without covariates. When I run the code below, I get this message on the console and it does not change:
Beginning Spectral Initialization
     Calculating the gram matrix...
     Finding anchor words...
    ..........
     Recovering initialization...
    ..
Initialization complete.

I've had to close out R entirely to get it to quit running. Here is the code:
test<- files[1:20, ] #the first 20 documents
met<- mytab[1:20,] #the first 20 rows of the df with the metadata for each document

corp<- corpus(test, text_field = "text")
dfm <- dfm(tokens(corp, remove_punct=TRUE),
           tolower=TRUE, stem=TRUE, remove_numbers = TRUE,
           remove=(c(stopwords("english"), 's', '$')))
dfm2<-dfm_subset(dfm, ntoken(dfm)>0)

# use quanteda converter to convert our Dfm
stmdfm <- convert(dfm2, to = "stm", docvars = met)
plotRemoved(stmdfm$documents, lower.thresh = seq(1, 80, by = 20))
out <- prepDocuments(stmdfm$documents, stmdfm$vocab, stmdfm$meta, lower.thresh = 3)

k <- 10
stmFit <- stm(out$documents,
              out$vocab,
              K = k,
              max.em.its = 150,
              data = out$meta,
              init.type = "Spectral",
              seed = 300)

Any thoughts on why this code will not produce results? I expect stm() to take a while, but I have left this running on just the 20 documents (which each average just a few hundred words in txt files) for over 30 minutes with no results.

A: The very simple answer was to reinstall the Rcpp package from scratch:
install.packages("Rcpp")
library(Rcpp)


text:
Q: can updates be automated without all the fuss? I would like to have the system automatically check for and install updates then shut down when I am done for the day.  perhaps an application or script.  I wrote bash scripts in 2000 but have no idea how to do one for gnome.

A: I'm not sure of a way to do this with regular updates, but you can definitely do it with security updates. In fact, Ubuntu does this by default.
If you are using vanilla Ubuntu, just open up the "Software and Updates" application, and click on the "Updates" tab, and set "Security Updates" to "Download and Install Automatically". You will also need to make sure you are subscribed to "Security and Recommended Updates".
As for shutting down the system automatically when you are done, there is no way to do that in vanilla Ubuntu, but you can certainly automatically put the system into "suspend" (sleep) mode after a certain about of time of inactivity (in fact, vanilla Ubuntu also does this by default). Just go into "Settings" > "Power" > "Automatic Suspend".


text:
Q: Change Combobox via Textbox Input VB.NET Hi I need some help over here... how do i change the display member of a ComboBox after i have entered a code in a textbox that it represent the combobox value??
example
Code: 02-001        Combobox: Provider X
if i change the code the provider combobox must change and if i change the provider combobox the code should change!.. i haven't found any help.. heres little code I remember
if e.keychar = chr(13) Then
    combobox.valuemember = textbox.text
    combobox.displaymember = me.stockdataset.selectprovider(@textbox.text)
end if

this code change the combo box display member but if I change the comobox by clicking it the code on the textbox doesnt change, to its corresponding code...??
please help
....the combo box is bound to the provider tables....

A: Change the selectedItem of your combobox when user press enter. But before, check that it is indeed in the provider list...
in the SelectionChanged handler of your combobox, set the textbox content to the value of the combobox.
Better each time use properties that uses propertychanged, and bind textbox and combobox's selectedItem to those properties.

A: This is wrong binding way....This is how you do it:
I have simulate your case by a simple form with a combobox and a textbox
and a datatable with 2 columns "Code" and "Description"
and here the Code (if you please, dont forget to mark my answer as Right):
Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            Me.KeyPreview = True'To Enable the Key events : KeyDown, KeyPress and KeyUp

            Dim dt As New DataTable("T")
            dt.Columns.Add(New DataColumn("Code"))
            dt.Columns.Add(New DataColumn("Description"))
            For i = 1 To 10
                Dim r As DataRow = dt.NewRow
                r("Code") = "Code" + CStr(i)
                r("Description") = "Desc" + CStr(i)
                dt.Rows.Add(r)
            Next

            With ComboBox1
                .ValueMember = "Code" ' This is case sensitive
                .DisplayMember = "Description" ' This is case sensitive
                .DataSource = dt
            End With

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub TextBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Click
        SetComoboValue()
    End Sub

    Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then SetComoboValue()
    End Sub

    Private Sub SetComoboValue()
        Try
            If Not String.IsNullOrEmpty(TextBox1.Text) Then
                ComboBox1.SelectedValue = TextBox1.Text
            End If
        Catch ex As Exception
            MsgBox("Ooops, Invalid code !!!")
        End Try
    End Sub
End Class

So when you enter "Code3" and hit Enter or Click the TextBox1, the ComboBox1 will display "Desc3"


text:
Q: Loop control using JAVA I saw the source code:
public class Test{
   public static void main(String[] args)
   {
    counting:
       for(int k = 0; k < 100; k++)
       for(int i = 0; i < 100; i++)
         if(i == 9) break counting;
   }
}

Now I implemented the loops as follows:
public class Test{
   public static void main(String[] args)
   {
      counting:
      for(int k = 0; k < 100; k++)
      {
         System.out.println(k);//to see how many times the outer loop runs
         for(int i = 0; i < 100; i++)
         {
             if(i == 9) break counting;
         }
     }
}

I got that the outer loop runs once and the inner will run 9 times if I am not mistaken.
I have come to the conclusion that this is nested loops that has flow control implemented. All I don't understand is what is the role of counting?

A: counting: is a label. When you call
break counting;

The code will jump to the end of the outer for loop.

A: It defines which loop is going to be stopped with the break statement. If you do not use a label, then the inner loop will be interrupted, but the outer one will continue normally.

A: The break statement by itself lets you break out of a single loop; in most cases this is enough, but there are situations when you must exit from several loops at the same time.
Adding a label to a loop from which you want to break out and referencing that label from a break statement lets you end several nested loops at the same time.
The code from your post is not a good illustration; a better use case is a search in multidimensional array. Let's say that you want to find a pair {row, col} such that array[row][col] == searchTerm. You can do it like this:
int row = -1, col = -1;
searching:
for(int r = 0 ; r != MAX_ROW ; r++) {
    for(int c = 0 ; c != MAX_COL ; c++) {
        if(array[r][c] == searchTerm) {
            row = r;
            col = c;
            break searching;
        }
    }
}

A: When you nested loop, if you want to break a for loop, you should define target to break, so you can you label to solve that.
for ex:
lb1:
for(int i = 0; i < 10;i++){
  lb2:
  for(int j = 0; j < 10;j++){
     for(int i = 0; i < 10;i++){
         if(a) break lb2; // this will break second loop
         if(b) break lb1; // this will break first loop
     }
  }
}

A: I hope you can understand!
public class Test {
    public static void main(String[] args) {
        counting: for (int k = 0; k < 100; k++) {
            System.out.println(k);
            for (int i = 0; i < 100; i++) {
                if (i == 9) {
                    System.out.println("I'm going to break!");
                    break counting;    // -----┐
                }                      //      |
            }                          //      |
        }                              //      |
        System.out.println("Broken!"); // <----┘
    }
}


text:
Q: Randomized HMTL5 Video Array Playing Only One Video I want to randomize a 179-video loop that is randomized anew each time the site is visited, but cannot get more than one video to play at a time.
{
    function getRandom(min, max) {
    if (min > max) {
        return -1;
    }
    if (min == max) {
        return min;
    }
    var r;
    do {
        r = Math.random();
    }
    while (r == 1.0);
    return min + parseInt(r * (max - min + 1));
}

function randomSrc(videoId) {
    console.log("randomSrc, " + videoId);
    var vid = $("#" + videoId);
    //var rndm = videoArray[getRandom(0, videoArray.length - 1)];
    var rndm = "001.webm";
    $(vid).attr("src", rndm).get(0).play();
    $(vid).get(0).addEventListener('ended', function () {
        randomSrc("v" + getRandom(1, 3));
    }, false);
}
var videoArray = ["001.webm", "002.webm", "003.webm", "004.webm", "005.webm", "006.webm", "007.webm", "008.webm", "009.webm", "010.webm", "011.webm", "012.webm", "013.webm", "014.webm", "015.webm", "016.webm", "017.webm", "018.webm", "019.webm", "020.webm", "021.webm", "022.webm", "023.webm", "024.webm", "025.webm", "026.webm", "027.webm", "028.webm", "029.webm", "030.webm", "031.webm", "032.webm", "033.webm", "034.webm", "035.webm", "036.webm", "037.webm", "038.webm", "039.webm", "040.webm", "041.webm", "042.webm", "043.webm", "044.webm", "045.webm", "046.webm", "047.webm", "048.webm", "049.webm", "050.webm", "051.webm", "052.webm", "053.webm", "054.webm", "055.webm", "056.webm", "057.webm", "058.webm", "059.webm", "060.webm", "061.webm", "062.webm", "063.webm", "064.webm", "065.webm", "066.webm", "067.webm", "068.webm", "069.webm", "070.webm", "071.webm", "072.webm", "073.webm", "074.webm", "075.webm", "076.webm", "077.webm", "078.webm", "079.webm", "080.webm", "081.webm", "082.webm", "083.webm", "084.webm", "085.webm", "086.webm", "087.webm", "088.webm", "089.webm", "090.webm", "091.webm", "092.webm", "093.webm", "094.webm", "095.webm", "096.webm", "097.webm", "098.webm", "099.webm", "100.webm", "101.webm", "102.webm", "103.webm", "104.webm", "105.webm", "106.webm", "107.webm", "108.webm", "109.webm", "110.webm", "111.webm", "112.webm", "113.webm", "114.webm", "115.webm", "116.webm", "117.webm", "118.webm", "119.webm", "120.webm", "121.webm", "122.webm", "123.webm", "124.webm", "125.webm", "126.webm", "127.webm", "128.webm", "129.webm", "130.webm", "131.webm", "132.webm", "133.webm", "134.webm", "135.webm", "136.webm", "137.webm", "138.webm", "139.webm", "140.webm", "141.webm", "142.webm", "143.webm", "144.webm", "145.webm", "146.webm", "147.webm", "148.webm", "149.webm", "150.webm", "151.webm", "152.webm", "153.webm", "154.webm", "155.webm", "156.webm", "157.webm", "158.webm", "159.webm", "160.webm", "161.webm", "162.webm", "163.webm", "164.webm", "165.webm", "166.webm", "167.webm", "168.webm", "169.webm", "170.webm", "171.webm", "172.webm", "173.webm", "174.webm", "175.webm", "176.webm", "177.webm", "178.webm", "179.webm"];
//var rndm = videoArray[getRandom(0, videoArray.length - 1)];
var rndm = "004.webm";
$("#v1").attr("src", rndm);
randomSrc("v1" + getRandom(1, 3));
this.removeEventListener("load", arguments.callee, false);
})

</script>

A: Ahem? first you set the source of #v1 to "004.webm", then hard-code the source for element with id #v11, #v12, or #v13 to "001.webm", there is absolutely no way this is ever going to work like this.
Instead try something like this
var videoArray = [ ... ];
function getRandom(...) { ... };

function randomize(videoId) {
    var vid = $('#' + videoId);
    function setRandom() {
        var index = getRandom(0, videoArray.length - 1)
        vid.attr("src", videoArray[index]).get(0).play();
    };
    setRandom();
    vid.bind("ended", function() {
        setRandom();
    });
};
randomize('v1');


text:
Q: jQuery slideUp().remove() doesn't seem to show the slideUp animation before remove occurs I have this line of JavaScript and the behavior I am seeing is that the selectedLi instantly disappears without "sliding up".  This is not the behavior that I expected.
What should I be doing so that the selectedLi slides up before it is removed?
selectedLi.slideUp("normal").remove();

A: The simplest way is calling the "remove()" function inside slideUp as a parameter like others have said, as this example:
$("#yourdiv").slideUp("normal", function() {
    $(this).remove();
});

It is a must to call it inside the anonymous function() to prevent remove() to be executed before the slideUp has ended. Another equal way is to use the jQuery function "promise()". Better for those who like self-explanatory code, like me ;)
$("#yourdiv").slideUp("normal").promise().done(function() {
    $(this).remove();
});

A: Using promises you can also wait for multiple animations to get finished, e.g.:
selectedLi.slideUp({duration: 5000, queue: false})
.fadeOut({duration: 3000, queue: false})
.promise().done(function() {
    selectedLi.remove()
})

A: You need to be more explicit: rather than saying "this" (which I agree should work), you should do this:
$("#yourdiv").slideUp(1000, function() {
    $(this).remove();
});

A: Might be able to fix it by putting the call to remove in a callback arg to slideUp?
e.g
selectedLi.slideUp("normal", function() { $(this).remove(); } );

A: selectedLi.slideUp(200, this.remove);


text:
Q: как изменить возвращаемый тип void на Future через onChange: static const int firstYearDiff = 40;

Future<DateTime?> buildCupertinoDatePicker({
  required BuildContext context,
  required ValueNotifier<DateTime> controller,
  String format = 'yyyy',
}) {
  return ValueListenableBuilder<DateTime>(
    valueListenable: controller,
    builder: (context, value, child) {
      return DatePicker.showDatePicker(
        context,
        minDateTime: DateTime(DateTime.now().year - firstYearDiff),
        maxDateTime: DateTime.now(),
        dateFormat: format,
        onChange: (dateTime, selectedIndex) {
          controller.value = dateTime;
        },
      );
    },
  );
}

вот сам код реализации пикера из библиотеки
void _showDatePicker() {
  DatePicker.showDatePicker(
    context,
    onMonthChangeStartWithFirstDate: true,
    pickerTheme: DateTimePickerTheme(
      showTitle: _showTitle,
      confirm: Text('custom Done', style: TextStyle(color: Colors.red)),
    ),
    minDateTime: DateTime.parse(MIN_DATETIME),
    maxDateTime: DateTime.parse(MAX_DATETIME),
    initialDateTime: _dateTime,
    dateFormat: _format,
    locale: _locale,
    onClose: () => print("----- onClose -----"),
    onCancel: () => print('onCancel'),
    onChange: (dateTime, List<int> index) {
      setState(() {
        _dateTime = dateTime;
      });
    },
    onConfirm: (dateTime, List<int> index) {
      setState(() {
        _dateTime = dateTime;
      });
    },
  );
}

A: Ты можешь использовать async и await в слушателе onChange, допустим:
onChange () async {
final param = await ...;
setState(() {
_dateTime = param });
}


text:
Q: Mac OS Python Install Messed Up I am trying to start on a python project, and I needed some data science libraries, and was directed to install Anaconda.
After installing it I realized I didnt want it, so I tried uninstalling it.
Now im trying to install a package with pip, but I guess pip is not installed, or my paths are all out of wack now, and im confused because python is in multiple places.
In /Library/Python I have a 2.6 and 2.7 folder, both containing only Extras.pth and README
In /usr/local/bin I have python2 python2-config python2.7 python2.7-config  pythonw2 pythonw2.7
This is apparently the Pipenv Environment? When i create a new project in PyCharm /usr/local/bin/python2.7 is the directory it wants to use.
And theres python in
/usr/local/opt/python
/usr/loca/opt/python2
/usr/local/Cellar/python/2.7.13_1/

My issue is when I want to install anything with pip i get
-bash: pip: command not found

When i run sudo easy_install pip i get
Searching for pip
Reading https://pypi.python.org/simple/pip/
Download error on https://pypi.python.org/simple/pip/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found!
Couldn't find index page for 'pip' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading https://pypi.python.org/simple/
Download error on https://pypi.python.org/simple/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found!
No local packages or download links found for pip
error: Could not find suitable distribution for Requirement.parse('pip')

Running which python gives /usr/bin/python
So now im confused on which python directory is which and how i can get pip to work again.
The only place i know that pip exists and works in my Homebrew install of /usr/local/Cellar/python/2.7.13_1/bin/pip
Can any one help me sort this out?

A: This might take some iterations to answer, but I'll try.
Unfortunately my reputation doesn't allow comments yet :(
First, I would check PATH environment variable:
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

In my case, the first thing in PATH is python 3.6 from python.org, then other standard paths.
I also have Extras.pth and README in /Library/Python/2.7/site-packages along with some other packages installed.
The python at /usr/bin/python should be the default python, installed with OSX.
Any other python you installed is going to be in /usr/local/bin. You can figure out what those are by doing a full listing to see where the symlinks point
$ ls -al /usr/local/bin/python*
lrwxr-xr-x  1 username  wheel  38 Jun 21 10:21 /usr/local/bin/python -> ../Cellar/python@2/2.7.15_1/bin/python
lrwxr-xr-x  1 username  wheel  45 Jun 21 10:21 /usr/local/bin/python-config -> ../Cellar/python@2/2.7.15_1/bin/python-config
lrwxr-xr-x  1 username  wheel  39 Jun 21 10:21 /usr/local/bin/python2 -> ../Cellar/python@2/2.7.15_1/bin/python2
lrwxr-xr-x  1 username  wheel  46 Jun 21 10:21 /usr/local/bin/python2-config -> ../Cellar/python@2/2.7.15_1/bin/python2-config
lrwxr-xr-x  1 username  wheel  41 Jun 21 10:21 /usr/local/bin/python2.7 -> ../Cellar/python@2/2.7.15_1/bin/python2.7
lrwxr-xr-x  1 username  wheel  48 Jun 21 10:21 /usr/local/bin/python2.7-config -> ../Cellar/python@2/2.7.15_1/bin/python2.7-config
lrwxr-xr-x  1 root  wheel  69 Aug  6 22:31 /usr/local/bin/python3 -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3
lrwxr-xr-x  1 root  wheel  76 Aug  6 22:31 /usr/local/bin/python3-config -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3-config
lrwxr-xr-x  1 root  wheel  71 Aug  6 22:31 /usr/local/bin/python3.6 -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
lrwxr-xr-x  1 root  wheel  78 Aug  6 22:31 /usr/local/bin/python3.6-config -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6-config
lrwxr-xr-x  1 root  wheel  72 Aug  6 22:31 /usr/local/bin/python3.6m -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6m
lrwxr-xr-x  1 root  wheel  79 Aug  6 22:31 /usr/local/bin/python3.6m-config -> ../../../Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6m-config
lrwxr-xr-x  1 username  wheel  39 Jun 21 10:21 /usr/local/bin/pythonw -> ../Cellar/python@2/2.7.15_1/bin/pythonw
lrwxr-xr-x  1 username  wheel  40 Jun 21 10:21 /usr/local/bin/pythonw2 -> ../Cellar/python@2/2.7.15_1/bin/pythonw2
lrwxr-xr-x  1 username  wheel  42 Jun 21 10:21 /usr/local/bin/pythonw2.7 -> ../Cellar/python@2/2.7.15_1/bin/pythonw2.7

In my case, I have installed Homebrew python 2.7.15 (anything starting with Cellar) and Python.org 3.6 (in /Library/Frameworks)
So... back to what you are trying to do.
If you want to run Homebrew python type python2 at the prompt.
If you want to run OSX python, type python.
If you want to run Homebrew as the default, just by typing python, you would have to add symlinks in /usr/local/bin similar to the first 2 lines in my listing, so that they are looked up in your path before /usr/bin (you would override the python command).
I'm not sure why your easy_install is failing, but which easy_install will probably tell you that this points only at the OSX python install version of easy_install also.
I hope that helps? Unfortunately I cannot replicate your error as I have pip installed already.


text:
Q: What is a good way to do a hotspot on a map So i have a map of the united states with 4 pins in 4 locations. The image is a png and I need to have a hover info box popup when the user hovers over one of the pins. Is there a standard way of doing this? I was reading online of image hotspots but i wasnt sure if anyone can point me into a clear direction...

A: It works just like a tooltip. Absolutely position a DIV over the area of the map you want to activate and hook up a tooltip event on mouseover.
There are plenty of scripts and plugn-ins for jQuery available that already do this.

A: As Diodeus wrote, just make "absolute" DIV's on top of the map. I can remember if the old MAP tag is supported in HTML5, but that allows to specify circle and polygon shaped areas too. I would still go for DIV solution though. Takes a little CSS knowledge, but is easy once you get it right.

A: Theres two ways to do it, an image map, and layering elements over the image using absolute positioning (ala facebook tagging)
Theres a plugin for JQuery which might be of interest.
JQuery MapHilight Plugin
And below is a tutorial to do it yourself, similiar to facebook picture tagging.
Tutorial using divs

A: Position a DIV either off the screen (my preference) or play with the Z-Index as described here.  Adjust on hover.
Here's another awesome example:
click me

A: There's a new jQuery plugin called MobliyMap that looks pretty good.  Here's the demo page.


text:
Q: Going out of vector limits but can't figure out where. Vector out of scope // Find smallest missing positive number
// Solve in O(n) time and O(1) space
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:

    void swap(int* a, int* b){
        int temp;
        temp = *a;
        *a = *b;
        *b = temp;
    }

    // move all non positive numbers to the left side of the vector
    int negativeToLeft(vector<int>& v){ // better name is seggregate!

        int j=0, i;

        for(int i = 0; i < v.size(); i++){
            // If number is negative then swap to left side of array
            if(v[i] <= 0){
                swap(&v[i], &v[j]);
                j++;
            }

        }
        // return the index from where the positive numbers start
        return j;
    }

    int firstMissingPositive(vector<int>& nums) {

        // move non positive to left
        int index = negativeToLeft(nums);

        // find the size of the positive segment of the vector
        int size = nums.size() - index;

        // traverse the vector
        for(int i = index; i < nums.size(); i++){

            // mark the index of the number as negative, if the number is within size
            if(nums[i] <= size){
                nums[abs(nums[i])] = -1 * nums[abs(nums[i])];
            }
        }
        if(index==0){
            nums[0] = -1;
        }

        for(int i = index; i < nums.size(); i++){
            // if the number at the index is positive then return the the index
            if(nums[i]>0){
                return i;
            }
        }

        return size + 1;
    }
};

 int main()
 {
     vector<int> g1{-1, -2, -3, -4};

     Solution m;
     cout << m.firstMissingPositive(g1);
 }

Error:
Line 924: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:9

I can't figure out where exactly an out of scope vector is being called. Any help would be much appreciated!


text:
Q: Python trig functions not returning matched results I came across something rather interesting while I am playing around with the math module for trigonometric calculations using tan, sin, and cos.
As stated is all math textbooks, online source, and courses, the following is true:

tan(x) = sin(x) / cos(x)

Although I came across some precision errors while using the three trig functions with the following:
from math import tan, sin, cos

theta = -30
alpha = tan(theta)
omega = sin(theta) / cos(theta)

print(alpha, omega)
print(alpha == omega)

>>> (6.405331196646276, 6.4053311966462765)
>>> (False)

I have tried a couple of different values for theta and the last digit of the results has been off by a tiny bit.
Is there something that I am missing?

A: This issue is because of the finite floating point precision (not all real numbers can be represented exactly and not all calculations with them are precise). An accessible guide is in the Python docs.
Using the default, "double precision" floating point representation, you can never hope for better than about 15 decimal place precision and calculations involving such numbers will tend to degrade this precision (the rounding error refered to in the above comment). In the same way, you get False from the following:
In [1]: 0.01 == (0.1)**2
Out[1]: False

because the Python isn't squaring 0.1 but the "nearest representable number" to 0.1, which is neither 0.01 nor the nearest representable number to 0.01.
D Stanley has given the correct way to test for "equality" within some absolute tolerance: (abs(a-b) < tol) where tol is some small number you choose to fit your expected precision.

A: As you have discovered, there is a level of imprecision when comparing floating point numbers.  A common way to test for "equality" is to determine a reasonable amount of difference you want to accept (commonly called "epsilon") an compare the difference between the two numbers against that maximum error:
epsilon = 1E-14

print(alpha, omega)
print(alpha == omega)
print(abs(alpha - omega) < epsilon)

A: First you should notice that the arguments of trigonometric functions are given in arc length, not in degree. Thus theta=-30 refers to an angle of -30*180/pi in degrees.
Second, the processor, and thus the calling math library, has separate internal procedures for the computation of tan and (sin, cos). The extra division operation loses 1/2 to 1 bit of precision, which explains the difference in results.


text:
Q: Using selenium in firefox Hello I want to click OK on a download popup window, however when I try
drive = selenium.selenium.selenium()
drive.choose_ok_on_next_confirmation()

It gives me an error AttributeError: type object 'selenium' has no attribute 'selenium'. I have alread tried setting the MIME type for preferences but it does not work.

A: How are you importing the selenium module?
A quick google search finds this page: Selenium RC with Python in 30 seconds. The code at the bottom of that page is a minimal example of how to get a selenium instance up and running.

A: it is unclear what you are using here exactly but assuming you are just using the selenium remote control you should be able to do
from selenium import selenium

followed by
sel = selenium("localhost", 4444, "firefox", "http://www.google.com")

or something similar.  you should really take a closer look at the documentation


text:
Q: Insert a copy of a node in a list (with condition) The exercise asks to insert a copy of a value x (which is also the value to search in the list), but only if the position is multiple of another value n. It is not specified whether the copy should be inserted before or after the x value.
My problem is that the copy is not inserted in all cases. I think the problem is that when I insert the new node, the counter of the list positions also counts this new value, reporting an incorrect result.
How can I solve the problem? Or am I making a mistake?
I'm learning. maybe my attempt is completely wrong and for this reason I ask for at least a decent explanation so that I can improve.
my code:
    struct data
{
    int d;
    struct data *next;
};

typedef struct data Node;

Node *newnode(void)
{
    return malloc(sizeof(Node));
}

Node *creat_list()
{
    Node *lis, *p, *last;
    int x;

    printf("\n insert data: ");
    scanf("%d", &x);

    if(x <= 0)
    {
        lis = NULL;
    }
    else
    {
        last = newnode();

        lis = last;
        last->d = x;
        last->next = NULL;

        printf(" insert data: ");
        scanf("%d", &x);

        while(x > 0)
        {
            p = newnode();
            p->d = x;
            p->next = NULL;
            last->next = p;
            last = p;
            printf(" insert data: ");
            scanf("%d", &x);

        }
    }
    return (lis);
}

void print_list(Node *lis)
{
    printf("\n List: \n");
    printf(" -> ");

    while(lis != NULL)
    {
        printf("%d", lis->d);
        printf(" -> ");
        lis = lis->next;
    }
    printf("NULL\n\n");
}

void insertCopy(int x, int n, Node **lis)
{
    int pos = 1;

    Node *p, *head;

    head = *lis;

    if ((head->d == x) && (pos % n == 0))
    {
            p = newnode();
            p->d = x;
            p->next = head;
            *lis = p;
    }

    if (head->next != NULL)
    {
        pos = 2;

        while(head->next != NULL)
        {
            if ((head->next->d == x) && (pos % n == 0))
            {
                p = newnode();
                p->d = x;
                p->next = head->next;
                head->next = p;
            }
            else
            {
                head = head->next;
            }
            pos++;
        }
    }
}

int main(void)
{
    Node *l1;

    int x = 1;
    int n = 3;

    l1 = creat_list();

    print_list(l1);

    insertCopy(x, n, &l1);

    print_list(l1);

    return 0;
}

Example:
Input:
2 3 1 6 1 2 2 6 1 5 0

gives
List:
2->3->1->6->1->2->2->6->1->5->NULL

With
x = 1, n = 3;

Expected Output is:
2->3->1->1->6->1->2->2->6->1->1->5->NULL

My Output is:
2->3->1->1->6->1->2->2->6->1->5->NULL

A: There are more problems in your code but the one you are asking for (according to your example) is that you only get one extra node while you expected two extra nodes.
Expected:
2->3->1->1->6->1->2->2->6->1->1->5->NULL

Actual:
2->3->1->1->6->1->2->2->6->1->5->NULL
                           ^^^
                        A node is missing here

The problem is the way you handle head when you insert the extra node.
Try to change this:
        if ((head->next->d == x) && (pos % n == 0))
        {
            p = newnode();
            p->d = x;
            p->next = head->next;
            head->next = p;
        }

into
        if ((head->next->d == x) && (pos % n == 0))
        {
            p = newnode();
            p->d = x;
            p->next = head->next;
            head->next = p;
            head=p->next;       // Add this line
        }

The problem with your original code was that you didn't move head correctly. Therefore the counter pos got out of sync with the original list.


text:
Q: The Developement Server Returned Error 500 First of all when I create a project and run it using:
react-native run-android

It works just fine but now when I have added some code for login screen it gives me this error:
Development Server Returned Error 500

I am new to React-native and I am not able to understand how to fix it, add to that I am not able to attach my debugger to visual Code so I don't need to run "RUN command" to test my app...
Can anyone help me?

*

*Error code 500

*Continuation of error code 500

*2nd Continuation of Error code 500

A: What does your metro bundler say? It'll be the thing that says "Loading dependency Graph... done"


text:
Q: LINQ - Iterate over a collection of dates and perform a calculation I have a collection of an object with a DateTime and an decimal property. All dates in the collection are unique and sorted to be sequential.
public class RateChange
{
    public DateTime EffectiveDate { get; set; }
    public decimal Rate { get; set; }
}

Assuming the first rate change is the start date and the end date is the current DateTime.UtcNow. How can i iterate over this collection and multiply the Rate * Days between each date and then sum the total of these results using LINQ only.

A: Something like this...
rateChanges
    .Zip(rateChanges
           .Skip(1)
           .Concat(new[]{
              new RateChange{
                    EffectiveDate = DateTime.Now.Date,
                    Rate = 0M //we never use this
              }
           }),
         (r1, r2) => r1.Rate * (r2 - r1).TotalDays)
    .Sum();

Due to the double iteration of rateChanges, it's probably best to ensure it's a materialized collection such as array or List<RateChange>


text:
Q: why does the vm_area_struct have start_code, end_code field? in linux, the vm_area_struct contains fields like start_code, end_code.
but a task has an mm_struct and that mm_struct has many vm_area_struct list.(see figure)
A task will have only one code area and data area, but why does the vm_area_struct has those start_code, end_code fields? Do the values belonging to the same mm_struct all have the same values for start_code and end_code?
(figure borrowed from http://esos.hanyang.ac.kr/tc/2015gradproject2/i/entry/2)


text:
Q: What is the meaning of the word 'should' in the following paragraph, and how does it function?
You might also be curious why the productsList variable is initialized as new list of strings at the start of the method, only for it to be overwritten by the code in the try block. This is a defensive mechanism that ensures that the productsList variable is always set to a meaningful value should the code in the try block fail for some reason. You will see an example of how such a failure might occur in Chapter 3.

A: Should in this usage basically functions similarly to if or in case.  You could rewrite the sentence in question as:

This is a defensive mechanism that ensures that the productsList variable is always set to a meaningful value if the code in the try block fails for some reason.

As far as how it functions as a part of speech, I believe it's the future subjunctive form of the auxiliary verb shall (i.e. should fail is the verb phrase)

A: To expand on Dusty's answer:
A more tentative version of
 if the code fails

is
 if the code should fail

In formal speech an writing, certain auxiliaries (principally 'had', 'were', and 'should', but occasionally 'could' and 'would' and rarely a few others) in an irrealis context can be inverted with the subject to get the same effect as the 'if':
 should the code fail
 had he but known
 were he to leave now

"Irrealis" means that the event or state of affairs has either not yet occurred, or is known not to have occurred when it might have.
"If he knows" and "if he knew" are realis: they are about present and past fact, which are either true or false, even though the speaker may not know which. These cannot be turned round in this way.
"If he should know", is an uncertainty about the future; and "if he had known" expresses a possibility which is known not to have happened; these are irrealis, and can be inverted as above.
As Dusty says, the verb is subjunctive (though in fact 'were' is almost the only distinctive subjunctive verb form in modern English); but I've never heard it called "future subjunctive".


text:
Q: How to convert 32 bit PNG to RGB565? How can I accomplish this? A programmatic solution (Objective-c) is great, but even a non-progarmmatic one is good.
I have pixelmator -> But that doesn't give you the option. I can't seem to do it with Preview either.
I have tried googling, but haven't been able to find a solution so far. The only tool I have been able to use to do this is TexturePacker, but that creates a sprite sheet.

A: You can use libpng to convert the PNG image to three-byte (8:8:8) RGB.  Then you can downsample to the 5:6:5 16-bit color values of RGB565.  If r, g, and b are the respective 8-bit colors (stored in an unsigned char type), then the 16-bit RGB565 value is:
((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)

You can improve a tad on this by rounding instead of chopping, being careful to not overflow the values.  You can also force the green value to be equal to the blue and red values when they are all equal in the original 8-bit values.  Otherwise it is possible to have colors that were originally gray inadvertently take on color after conversion.

A: Create Bitmap Context with color RGB565 using Quartz, paint your PNG on this context, save this bitmap context to file.

A: PNG does not support a RGB565 packing. You can always apply a posterize to the image (programatically or with ImageMagick or with any image editor), which amounts to discard the lower significant bits in each channel. When saving to PNG, you will still be saving 8 bits per channel (unless you use a palette), but even then you will get an appreciable reduction in size, because of the PNG compression.
A quick example: original:

after a simple posterize with 32 levels (equivalent to a RGB555) applied with XnView

The size goes from 89KB to 47KB, with a small quality loss.
In case of synthetic images with gradients, the quality loss could be much more noticiable (banding).

A: I received this answer from the creator of texture packer:
you can do it from command line - see

http://www.texturepacker.com/uncategorized/batch-converting-images-to-pvr-or-pvr-ccz/
Just adjust the opt and set output to .png instead of pvr.ccz
Make sure that you do not overwrite your source images.

A: According to Wikipedia, which is always right, the only 16-bit PNG is a greyscale PNG.  http://en.wikipedia.org/wiki/Portable_Network_Graphics
If you just add your 32-bit (alpha) or 24-bit (no alpha) PNG to your project as normal, and then set the texture format in Cocos2D, all should be fine.  The code for that is:
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565];


text:
Q: Issue with the solution to the following differential equation I have a function $u(x)$, and it satisfies the following differential equation:
$\frac{d^2 u}{dx^2} = \lambda u(u^2-b^2)$ where $\lambda$ and $b$ are just two positive real constants.
The Boundary conditions are:
$u(x = -\infty) = -b$  and $u(x= \infty) = b$. For simplification, $u(x = 0) = 0$ can be used.
The goal is to find $u(x)$.
My attempt:
Let, $g(u) = \lambda u(u^2-b^2)$
$\frac{d^2u}{dx^2} = g(u)$
$\implies \frac{du'}{dx} = g(u)$ where $u' = \frac{du}{dx}$
$\implies \frac{du'}{du} \frac{du}{dx} = g(u)$
$\implies u'\frac{du'}{du}  = g(u)$
$\implies u'du' = g(u) du$
$\implies u'du' = \lambda u(u^2-b^2) du $
Integrating both sides, we get,
$\frac{u'^2}{2} = \lambda(\frac{u^4}{4}-\frac{b^2u^2}{2}) + K $ where $K$ is a constant.
$\implies u' = \sqrt{\frac{\lambda}{2}(u^4-2b^2u^2)+K}$
$\implies \frac{du}{\sqrt{(u^2-b^2)^2-b^4+K}} = \sqrt{\frac{\lambda}{2}} dx$
When I put this in mathematica now, it gives me some elliptic function now. And I am not sure where to go from here.
In class, my professor gave us as a hint that $u(x)$ has something to do with $tanh(x)$, but I am very confused as to how to proceed from what I have.

A: Note that as $u\to const $ as $x\to \pm\infty$ we must have $u'\to 0$ as $x\to\pm\infty$. So let us start from the line you derived
$$\frac12u'^2 = \frac{\lambda}{4}u^2(u^2-2b^2) + K $$
Setting $u=b$ and $u'=0$ yields
$$K=\frac{\lambda}{4}b^4.$$
We now readily see that
$$\frac12 u'^2 = \frac{\lambda}{4}(u^2-b^2)^2.$$
Or equivalently
$$\left(\frac{u'}{u^2-b^2}\right)^2=\frac{\lambda}{2}.$$
For simplicity I will write $\lambda=2\mu^2$ (as $\lambda>0$) and thus we have
$$\frac{u'}{u^2-b^2}=\mu. $$
Note that we could have $\mu=\sqrt{\frac{\lambda}{2}}$ or $\mu=-\sqrt{\frac{\lambda}{2}}$. Integrating and applying the chain rule yields
$$\int \frac{du}{u^2-b^2} = \int \mu\,dx.$$
Making the substitution $u=bv$ we see that
$$-\frac{1}{b}\int \frac{dv}{1-v^2} = \int \mu\,dx$$
and thus
$$\textrm{arctanh } v = c-b\mu x\implies u=b\tanh (c-b\mu x)$$
where $c$ is an arbitrary constant. We see that the conditions $u(\pm\infty)=\pm b$ do not determine $c$, but in fact only dictate the sign of $\mu$ (which square root we take). It is clear we require $\mu=-\sqrt{\frac{\lambda}{2}}$. As $c$ is arbitrary we may define a new constant $\alpha$ such that
$$u=b\tanh \left(b\sqrt{\frac{\lambda}{2}}(x-\alpha)\right). $$