text:
Q: (Java) How can I store my x and y values to use them outside of for loops? I'm coding Conway's Game of Life on Processing 3 and I want to store x and y so that the squares don't change right away, but I don't know how to store it to use later. Any help is appreciated!
void keyPressed() {

  for (int x = 0; x < 30; x++) {

    for (int y = 0; y < 30; y++) {

     int numNeighbours = numNeighbours(x,y);

     if (cells[x][y] == true) {

       if (numNeighbours > 3 || numNeighbours <= 1) { //underpopulation or overpopulation

       }
     }

     else if (cells[x][y] == false) {

       if (numNeighbours == 3) {

       }
     }
}
}
}

A: Based on my understanding of your code (and the Game of Life), you don't need to store x and y.  What you actually need to do is to store the (x, y) pairs where the cell changes state.
You could do this by creating pairs and adding them to lists.
But a another idea is to use a second array representing the next generation of the game and put all of the new values there; e.g.
for (int x = 0; x < 30; x++) {
    for (int y = 0; y < 30; y++) {
        int numNeighbours = numNeighbours(x,y);
        if (cells[x][y] == true) {
            if (numNeighbours > 3 || numNeighbours <= 1) {
                cellsNext[x][y] = false;
            } else {
                cellsNext[x][y] = true;
            }
        }
        else if (cells[x][y] == false) {
            if (numNeighbours == 3) {
                cellsNext[x][y] = true;
            } else {
                cellsNext[x][y] = false;
            }
        }
    }
}

Note: that could be simplified / written better, but I have written it as above so that you can see clearly what I have done.


text:
Q: ValueError: time data '67:01' does not match format '%M:%S' I have a pandas dataframe with a TEXT column called Used which contains the duration in minutes:seconds for phone calls. I would like to convert this to a a duration format. The problem is some of the minutes are greater than 59 so giving an error:
time data '67:01' does not match format '%M:%S'

The code to convert this is:
df.Used.apply(lambda x: datetime.datetime.strptime(x, '%M:%S'))

Is there a simple way to convert this to a decimal minutes format? Something like 67.01666 for 67:01?

A: Based on the documentation for the datetime object you can have values for minutes only between to [0-60) range:

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints or longs, in the following ranges:

*

*0 <= hour < 24

*0 <= minute < 60

*0 <= second < 60

*0 <= microsecond < 1000000

So, there is no possible way to get rid of that error. if you want to convert this to a decimal minutes format, which I'm guessing is just a decimal you'll need to do it manually like so:
# Split the string, join it and cast it to float
df.Used.apply(lambda x : float(".".join(x.split(":"))))

Which outputs:
In [5]: df = pd.DataFrame([['87:01'],['911:11']],columns=['Used'])

In [6]: df.Used.apply(lambda x : float(".".join(x.split(":"))))
Out[6]:
0     87.01
1    911.11
Name: Used, dtype: float64

A: I used the following which seems similar to some of the answers above. Using split I made two dataframes, one for minutes and another for seconds which I converted to float and then combined them to form a decimal column in the original dataframe.
test_df = home_df.Used.str.split(':')
minutes_df = test_df.str[0]
seconds_df = test_df.str[1]
minutes_df = minutes_df.astype(float)
seconds_df = seconds_df.astype(float)
decmin_df = minutes_df + seconds_df / 60.
home_df['Duration'] = decmin_df

A: If you are storing duration , I would suggest that the correct way for storing durations would be Timedelta , not datetime (since a datetime always requires an year/month/day , etc. basically datetime is used to denote exact dates/times).
For that an quick/easy way would be to split the string based on : and then pass them separately to minutes and seconds argument of datetime.timedelta . Example -
df.Used.apply(lambda x: datetime.timedelta(minutes=int(x.split(':')[0]), seconds=int(x.split(':')[1])))

Demo -
In [15]: import pandas as pd

In [16]: df = pd.DataFrame([['67:01'],['11:11'],['59:59'],['09:08']],columns=['Used'])

In [17]: df
Out[17]:
    Used
0  67:01
1  11:11
2  59:59
3  09:08

In [18]: import datetime

In [19]: df.Used.apply(lambda x: datetime.timedelta(minutes=int(x.split(':')[0]), seconds=int(x.split(':')[1])))
Out[19]:
0   01:07:01
1   00:11:11
2   00:59:59
3   00:09:08
Name: Used, dtype: timedelta64[ns]

If you want it as float, you can also do it with a simple change -
df.Used.apply(lambda x: float(x.split(':')[0]) + float(x.split(':')[1])/60)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress - add item to 2 menus instead of main menu Sorry, I didn't know how to word the title better.
I have a theme with 3 menus, a header, a subheader and a footer. I wanted to add a link that would change depending on whether the user is logged in or not. I found this code:
function ca_wp_nav_menu_items($items, $args) {

// Make sure this is the Primary Menu.
if ($args->theme_location == 'header') {
// CSS class to use for
 item.
$class = 'menu-item';

if (is_user_logged_in()) {
$extra = '

'.__('Mi Perfil').'

';
} else {
$extra = '

'.__('Ingreso').'

';
}

// Add extra link to existing menu.
$items = $items . $extra;
}
// Return menu items.
return $items;
}

// Hook into wp_nav_menu_items.
add_filter( 'wp_nav_menu_items', 'ca_wp_nav_menu_items', 10, 2 );

This works perfectly, but I'd like to modify it so the same function works for the footer menu. What has to be modified for it to work? I guess an easy way would be to copy the function and change header to footer, but I'd like to keep it simpler by just having one function.

A: if ($args->theme_location == 'header' || $args->theme_location == 'footer') {


text:
Q: How to get a content of array file using PowerShell? I am a new with PowerShell, I want to read a text file. But my text file format has a head. This is the format looks like
Name
(One Tab) Jhonny/Male
(One Enter)
(One Tab)  Merry/Female

Class
(One Tab)  XI/AB
(One Enter)
(One Tab)  XII/AB

I want to read the content each head, like Name or Class. If I read head Name, It will return
Jhonny/Male
Merry/Female

Anyone can give me idea, please? Thanks a lot
This is what I try. But it does not work
$File = Get-Content -Path .\Data.txt
$Name = $File.Name
Write-Output $Name

A: You may use the following if we assume text under he headers are indented with white space:
$name = $false
switch -regex -file Data.txt {
    '^Name' { $name = $true; continue }
    '^\s' { if ($name) { $_.Trim() }}
    '^\S' { if ($name) { return }}
}

A: I think this can help. If you want to replace tab while printing you can do that with the replace command also in powershell.
$content=Get-Content -Path "E:\test.txt"
$contentHead="Name"
for($i=0 ; $i -lt $content.Count ; $i++){
    if($content[$i] -eq $contentHead){
        for($i=$i+1; $i -lt $content.Count; $i++){
            Write-Output $content[$i]
            if($content[$i][0] -ne "`t"){
                break
            }
        }
    }
}


text:
Q: How to use get object in controller laravel I have a function in controller to remove category and its image file. But i am not able to access the path property. I am getting this error Undefined property: Illuminate\Database\Eloquent\Collection::$path. It is returning path but i am unable to use it.
public function remove($id) {
    //$category = Category::find($id)->delete();

    $category_image = CategoryImage::where('category_id', '=', $id)->get(['path']);

    echo $category_image->path;

    //return back();
}

A: You can use first() if you need to get just one object:
$category_image = CategoryImage::where('category_id', '=', $id)->first();

if (!is_null($category_image)) { // Always check if object exists.
    echo $category_image->path;
}

When you're using get(), you're getting a collection. In this case you can iterate over the collection and get data from each object, or just use index:
$category_image[0]->path;

A: You get a collection, you have to loop throug the collection this way:
foreach ($category_image as $image) {
echo $image->path;

}


text:
Q: express.js async router and error handling I have an async function as a route handler, and i'd like to have errors handled as some kind of middleware. Here is my working attempt:
router.get(
  "/",
  asyncMiddleware(
    routeProviderMiddleware(
      async ({ y }) => ({
        body: await db.query({x: y})
      })
    )
  )
)

// This is the middleware that catches any errors from the business logic and calls next to render the error page
const asyncMiddleware = fn =>
  (req, res, next) => {
    Promise.resolve(fn(req, res, next))
      .catch(next)
  }

// This is a middleware that provides the route handler with the query and maybe some other services that I don't want the route handler to explicitly access to
const routeProviderMiddleware = routeHandlerFn => async (req, res) => {
  const {status = 200, body = {}} = await routeHandlerFn(req.query)
  res.status(status).json(body)
}

What I strive to is a way to make the route declaration cleaner - I don't want the 2 middleware wrappers there, ideally i'd like for the business logic function there only, and somehow declare that every route is wrapped in these.
Even combining the two middlewares together would be nice, but I didn't manage.

A: I use following approach:
Create asyncWrap as helper middleware:
const asyncWrap = fn =>
  function asyncUtilWrap (req, res, next, ...args) {
    const fnReturn = fn(req, res, next, ...args)
    return Promise.resolve(fnReturn).catch(next)
  }

module.exports = asyncWrap

All your routes/middlewares/controllers should use this asyncWrap to handle errors:
router.get('/', asyncWrap(async (req, res, next) => {
  let result = await db.query({x: y})
  res.send(result)
}));

At app.js, the last middleware will receive the errors of all asyncWrap:
// 500 Internal Errors
app.use((err, req, res, next) => {
  res.status(err.status || 500)
  res.send({
    message: err.message,
    errors: err.errors,
  })
})

A: Express 5 automatically handles async errors correctly
https://expressjs.com/en/guide/error-handling.html currently says it clearly:

Starting with Express 5, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error. For example:
app.get('/user/:id', async function (req, res, next) {
 var user = await getUserById(req.params.id)
 res.send(user)
})

If getUserById throws an error or rejects, next will be called with either the thrown error or the rejected value. If no rejected value is provided, next will be called with a default Error object provided by the Express router.

I have shown that in an experiment at: Passing in Async functions to Node.js Express.js router
This means that you will be able to just make the callback async and use await from it directly without any extra wrappers:
router.get("/", async (req, res) =>
  const obj = await db.query({x: req.params.id})
  // Use obj normally.
)

and errors will be correctly handled automatically.

A: Express permits a list of middlewares for a route and this approach sometimes works for me better than higher-order functions (they sometimes look like an overengineering).
Example:
app.get('/',
  validate,
  process,
  serveJson)

function validate(req, res, next) {
  const query = req.query;
  if (isEmpty(query)) {
    return res.status(400).end();
  }
  res.locals.y = query;
  next();
}

function process(req, res, next) {
  Promise.resolve()
  .then(async () => {
    res.locals.data = await db.query({x: res.locals.y});
    next();
  })
  .catch((err) =>
    res.status(503).end()
  );
}

function serveJson(req, res, next) {
  res.status(200).json(res.locals.data);
}

A: What you can do is add an error handlers after your routes. https://expressjs.com/en/guide/error-handling.html
app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

A: What I ended up doing is unifying the wrappers like this:
const routeProvider = routeHandlerFn => async (req, res, next) => {
  try {
    const {status = 200, body = {}} = await routeHandlerFn(req.query)
    res.status(status).json(body)
  } catch(error) {
    next(error)
  }
}

This wrapper is all any route would need. It catches unexpected errors and provides the route handler with the needed params.


text:
Q: How to prove that if $x$ is not invertible, then $Rx \neq R$? Let $R$ be an associative ring with identity and let $x \in R$ be an element that is not invertible. How can we prove that $Rx \neq R$? Here $Rx$ denotes the left ideal generated by $x$.

A: As Robert Israel said, the correct statement is "if $x$ is not invertible, then $Rx \neq R$ or $xR \neq R$", and this is easy to prove by the contrapositive: if $Rx = R$ and $xR = R$, then there are $y, z \in R$ such that $xy = 1$ and $zx = 1$, and it is easy to conclude that $y = z$, hence $x$ is invertible.


text:
Q: Ingesting json dump in AWS RDS I made a django application and want to use an sqlite3 db for local development and a Amazon MySql RDS DB for production. My webserver is running on an EC2 Instance.
I have exported the data from the sqlite3 db to a json object using python manage.py dumpdata > datadump.json
Is there a way to import this JSON into a MySql DB in RDS or should I tackle this problem in a different manner?
Thanks in advance :)


text:
Q: Excel VBA - extraordinary WinHttpRequest.Open error for only a few of url Checking some URLs with
Function SiteStatus(ByVal URL As String, SiteStatusText As String) As Long

    Dim oHttp As New WinHttp.WinHttpRequest

    oHttp.Option(WinHttpRequestOption_EnableRedirects) = False

    oHttp.Open "GET", URL, False
    oHttp.Send

    SiteStatus = oHttp.Status
    SiteStatusText = oHttp.StatusText

End Function

generally works fine. Only a few URLs throw a VBA error -2147012744. The Server is giving an invalid or unknown response.
Some URLs in real work, I can open them with SHDocVw library, and some not, - that makes no difference.
for instance:
http: //s2.excoboard.com/Courthouse_Steps_Mavens/150601/1831324

or
http: //www.geld-und-leben.com/anleitung/

or
http: //globalnews.ca/news/3025046/justin-timberlakes-illegal-voting-booth-selfie-is-under-review/

I wanna check the status of these sites although.
How?
What's the point?

A: i know that this is old, but here is some VBA code that works.
some of the values for oHttp.Option came from http://www.808.dk/?code-simplewinhttprequest
Sub test()

    ' add reference to Microsoft WinHTTP Services

    Dim URL As String
    URL = "http://globalnews.ca/news/3025046/justin-timberlakes-illegal-voting-booth-selfie-is-under-review"

    Dim oHttp As WinHttpRequest
    Set oHttp = New WinHttpRequest

    oHttp.Open "GET", URL, False

    oHttp.Option(WinHttpRequestOption_UserAgentString) = "http_requester/0.1"
    oHttp.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = &H3300            '  ignore all err, 0: accept no err
    oHttp.Option(WinHttpRequestOption_EnableRedirects) = True
    oHttp.Option(WinHttpRequestOption_EnableHttpsToHttpRedirects) = True

    oHttp.send

    Do While True
        DoEvents
        If oHttp.Status Then Exit Do
    Loop

    Debug.Print oHttp.Status

End Sub


text:
Q: 2 buttons in a horizontal LinearLayout - how to spread them out? I am following the Android Programming: The Big Nerd Ranch Guide book and have a very newbish question:
In my first app named GeoQuiz - how to move the right button to the very right of the screen (and still keep the sizes of the buttons at wrap_content):

My layout file can be seen an GitHub as activity_quiz.xml and here is an excerpt:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="de.afarber.geoquiz.QuizActivity" >
....
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button" />

    </LinearLayout>
....
</LinearLayout>

A: Try this please
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="de.afarber.geoquiz.QuizActivity" >
....
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/true_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/true_button" />

    <Button
        android:id="@+id/false_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="@string/false_button" />

</RelativeLayout>
....
</LinearLayout>

A: Try this way,hope this will help you to solve your problem.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="de.afarber.geoquiz.QuizActivity" >

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button" />
        <View
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button" />

    </LinearLayout>
</LinearLayout>

A: I hope this will be helpful for you:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="de.afarber.geoquiz.QuizActivity" >

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="3">

    <Button
        android:id="@+id/true_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/true_button"
        android:layout_weight="1" />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_weight="1"
        android:visibility="invisible"/>
    <Button
        android:id="@+id/false_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/false_button"
        android:layout_weight="1" />

</LinearLayout>

A: I would recommend creating two more horizontal layouts within the earlier horizontal layout and giving each a weight of 0.5. You can then place the true and false button at the center of the horizontal layout. The code is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"

android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="de.afarber.geoquiz.QuizActivity" >

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:gravity="center" >

   <Button
       android:id="@+id/true_button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/true_button" />

       </LinearLayout>

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:gravity="center">

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button"/>

        </LinearLayout>
</LinearLayout>

I hope this helps as the size of your button will remain as wrap_content and you can spread your buttons out.
Although you could easily solve your problem using relative layout I would strongly advise you against using relative layouts as they may create problems when the resolution of the screen is changed


text:
Q: ado open xlsx file classic asp I am trying top open an xlsx file using classic ASP and ADO
The connection string is below. But it produces an error. What am I doing wrong?
Driver=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Derek Cohen\Documents\!!websites\demographix\surveys\AKGW-YHSN\pu_VTGDVVJZ_56_4088906840162.xlsx;Extended Properties=Excel 12.0;HDR=Yes;IMEX=1;

Microsoft OLE DB Provider for ODBC Drivers error '80004005'

[Microsoft][ODBC Driver Manager] Data source name too long

A: Microsoft.ACE.OLEDB.12.0 is a provider so your connection string isn't valid. Try the following:
Dim objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Provider = "Microsoft.ACE.OLEDB.12.0"
objConn.ConnectionString = "Data Source=C:\Users\Derek Cohen\Documents\!!websites\demographix\surveys\AKGW-YHSN\pu_VTGDVVJZ_56_4088906840162.xlsx;Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1;"""
objConn.Open

A few connection string examples for the Excel 12


text:
Q: Persistent "Sticky" Headers within a div with height and overflow I've been researching this a bit and can't seem to find the right answer.
I have this codepen example that I put together using an example from CSS-Tricks.
Persistent headers "Sticky headers"
It works fine as is, but I want to set the properties of the container div #page-wrap from:
#page-wrap {
   width: 500px;
   margin: 0 auto;
}

to
#page-wrap {
   width: 500px;
   height: 300px;
   background: red;
   overflow-y: auto;
   margin: 0 auto;
 }

The result is that the functionality "breaks". I understand that the javascript sets the browser window as the container, but I'd like to "pin" or "bind" the sticky headers to the top of #page-wrap container instead the browser window .
Here is the JS:
    function UpdateTableHeaders() {

    $(".persist-area").each(function() {

    var el = $(this),
      offset = el.offset(),
      scrollTop = $(window).scrollTop(),
      floatingHeader = $(".floatingHeader", this)

    if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
      floatingHeader.css({
        "visibility": "visible"
      });
    } else {
      floatingHeader.css({
        "visibility": "hidden"
      });
    };
  });
}

// DOM Ready
$(function() {

  var clonedHeaderRow;

  $(".persist-area").each(function() {
    clonedHeaderRow = $(".persist-header", this);
    clonedHeaderRow
      .before(clonedHeaderRow.clone())
      .css("width", clonedHeaderRow.width())
      .addClass("floatingHeader");

  });

  $(window)
    .scroll(UpdateTableHeaders)
    .trigger("scroll");

});

Here is the full HTML:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>Persistent Headers</title>

Header 1

Pellentesque habitant morbi tristique senectus et netus et malesuada   fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

Header 2

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

Header 3

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

Header 4

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

etc...

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus

`


text:
Q: Highlight selected points in a plot I need to change color to selected points dynamically in my plot.
clicks = {}; insert = 0;
Column[{
   ListPlot[Button[Tooltip@#, If[insert < 5 && ! MemberQ[clicks, #],
      AppendTo[clicks, #]; insert++;]] & /@ N@data, ImageSize -> 300], "\n\t",
    Row[{"clicks = ", Dynamic[clicks // TableForm]}],
    Row[{Button["Del L1", If[Length[clicks] >= 1, insert--; clicks = Delete[clicks, 1]]]}]}
]

I managed how to get x/y clicked, but not how to highlight it.

A: clicks = {}; insert = 0;
data = RandomReal[100, {50, 2}];

You can add the points in clicks using Epilog:
Column[{ListPlot[Button[Tooltip@#,
        If[insert < 5 && ! MemberQ[clicks, #], AppendTo[clicks, #];
         insert++;]] & /@ N@data, ImageSize -> 400,
   Epilog -> Dynamic[{ Directive[Opacity[.7, Red], PointSize[Large]], Point@clicks}]],
   "\n\t",  Row[{"clicks = ", Dynamic[clicks // TableForm]}],
   Row[{Button["Del L1", If[Length[clicks] >= 1, insert--;
      clicks = Delete[clicks, 1]]]}]}]

Alternatively, you can Style the points in clicks and add them to the list of points to be plotted:
Dynamic@Column[{ListPlot[Join @@
   {Style[#, Directive[Opacity[.5], Orange, Magnification -> 2]] & /@ clicks,
    Button[Tooltip[#], If[insert < 5 && ! MemberQ[clicks, #], AppendTo[clicks, #];
            insert++;]] & /@ N@data}, ImageSize -> 400,
    BaseStyle -> PointSize[Large]], "\n\t",
   Row[{"clicks = ", Dynamic[clicks // TableForm]}],
   Row[{Button["Del L1", If[Length[clicks] >= 1, insert--;
       clicks = Delete[clicks, 1]]]}]}]


text:
Q: custom style for mobile submenu I'm trying to change the look of my site's submenu on mobile devices;
my theme already has a special style on mobile, my problem is it doesn't seem to work by media query
So I made my mobile menu including a styling for a dropdown submenu which shows when tested on small screen sizes but when I check my site on my phone, the default submenu which blends in from the right as animation shows. I don't know what to put in my css to change that or if it's somewhere else that I need to put changes. The theme is Twenty Nineteen and my page is https://demokratietalk.at
In the original css I found this code, which describes what happens but as mentioned before I don't know how it only targets mobile devices:
.main-navigation .main-menu .menu-item-has-children.off-canvas .sub-menu.expanded-true {
  display: table;
  margin-top: 0;
  opacity: 1;
  padding-left: 0;
  /* Mobile position */
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  position: fixed;
  z-index: 100000;
  /* Make sure appears above mobile admin bar */
  width: 100vw;
  height: 100vh;
  max-width: 100vw;
  transform: translateX(100%);
  animation: slide_in_right 0.3s forwards;
  /* Prevent menu from being blocked by admin bar */

A: Have you tried using media queries in your css? For a mobile device, you can use the below to wrap around all the custom css you want for your phone.
@media screen and (max-width: 600px) {
  css {
    Your customer CSS goes here
    }
}

Check out the link from w3 school for more help - https://www.w3schools.com/css/css3_mediaqueries_ex.asp


text:
Q: Adding more buttons to a banner, and adjusting the top margin I am using code from bootstraps main site to create a button banner. I would like to know how to add more buttons to this while keeping its width the same. Also other than style="margin-top: 10px;" how can i adjust the banner?
Bootstrap site: http://getbootstrap.com/components/

    <button type="button" class="btn btn-default">Left</button>

    <button type="button" class="btn btn-default">Middle</button>

    <button type="button" class="btn btn-default">Right</button>


text:
Q: Why does my NSToolbar not get the icon/text/icon+text options? I have an NSToolbar with some items in it.  In most NSToolbars on macOS, when you right-click, you get the choice of icon, text, or icon+text.  These 3 choices also appear as a popup menu, in the bottom-left corner of the Customize sheet.
In my app, I don't get this.  Instead, in the context menu, I get the option "Use Small Size".  In the customization panel, instead of the popup menu, I have a (terribly placed!) checkbox, "Use small size".
What causes an NSToolbar to get "Use small size", rather than the icon/text/icon+text choices?

A: Are you by any chance doing [self.window setTitleVisibility:NSWindowTitleHidden]; to move the toolbar up into the title bar area?
If that's the case, toolbars are limited to icons only in this case.


text:
Q: How to get latest sdist link from PyPI I want to get sdist url for meta.yaml in conda build recipe. It needs to get a specific version or latest version from URL. as I do it using Github actions for CI/CD I need to retrieve a source link of either specific version or the latest version automatically.
Now the link is like this: https://files.pythonhosted.org/packages/40/e7/sha-256-of-file/file I need something reliable like https://hosting/package/release/file
I need to know a more reliable way to retrieve either the latest sdist or sdist of a specific release. Is there any way to do that or I need to go another way?
Is there a PyPi source download link that always points to the lastest version?
This question doesn't work for me by far as I don't seek to install it in python. I need that to include it in meta.yaml recipe for conda-build.
meta.yaml looks like this:
{% set version = "0.1.1rc3" %}

package:
  name: blablablah
  version: {{ version }}

source:
  url:
  sha256: f3832918bc3c66617f92e35f5d70729187676313caa60c187eb0f28b8fe5e3b5

build:
  noarch: python
  number: 0
  script: python -m pip install --no-deps --ignore-installed .

requirements:
  host:
    - python
    - pip
    - numpy==1.16.5
    - cython
  run:
    - python

test:
  imports:
    - blablablah

about:
   here are information about the package

I don't know where to get this file as code updates hourly and manual upgrade is not possible.

A: If you know the exact project name and version, you can use the following URL structure:
project_name = "..."
version = "..."
url = f"https://files.pythonhosted.org/packages/source/{project_name[0]}/{project_name}/{project_name}-{version}.tar.gz

e.g.
https://files.pythonhosted.org/packages/source/p/pip/pip-20.0.1.tar.gz
If you don't know the latest version, you can use the PyPI JSON API to get it:
>>> import requests
>>> resp = requests.get('https://pypi.org/pypi/pip/json').json()
>>> resp['info']['version']
'20.0.1'

Note: there is no guarantee that a source distribution for a given version exists, although it is likely.


text:
Q: How to access the local path of a downloaded image Scrapy here is how i am downloading Images.Now i had create one more pipline to insert my scraped data.
class CmindexPipeline(ImagesPipeline):

    def get_media_requests(self, item, info):

        for image_url in item['image_url']:
            yield scrapy.Request(image_url)

    def item_completed(self, results, item, info):
        image_paths = [x['path'] for ok, x in results if ok]
        if not image_paths:
            raise DropItem("Item contains no images")
        item['image_paths'] = image_paths
        print("From Images Items", item)
        return item

class MysqlPipline(object):
    def process_item(self, item, spider):
        print("From Process Items",item['image_path'])

here is my settings.py
ITEM_PIPELINES = {'cmindex.pipelines.CmindexPipeline': 1,'cmindex.pipelines.MysqlPipline':2}
IMAGES_STORE ='E:\WorkPlace\python\cmindex\cmindex\img'
IMAGES_THUMBS = {
    '16X16': (16, 16)
}

But unfortunately sill i am not able to access item['image_paths'] in process_item.it raise error
KeyError: 'image_paths'

If anyone know what i am doing wrong please suggest me.

A: The process_item method is called before item_completed, so it does not have the image_paths yet.
If you want to access the image_paths, you will have to do it inside item_completed, or write another pipeline that is placed after the image pipeline.


text:
Q: Infinispan 12: CLI with self-signed certs I setup infinispan 12 with self-signed certs and SSL/TLS configuration.  I have default on port 11222 and hotrod on 11322.
The application starts up with no problem and connect to 11322 with no problem.
I start up cli.bat and pass the truststore and password on command line.  I try to connect by doing a connect https://DN:11222 and it gives a Received fatal alert: handshake_failure error.
The DN is the same DN name used for resolution in the application for hotrod which worked with no problem on port 11322.  Using the same DN on the cli.bat CLI command prompt line fails on port 11222.  The only way I can get this working for cli.bat is I have to add a SAN to my truststore and the problem is resolved.
Why do I need a SAN for cli.bat to work on SSL/TLS connection?

A: I assume you are using
cli.bat -t truststore.pfx -s secret -c https://DN:11222

Would it be possible for you to share the server configuration ?
I'm afraid I do not know what you mean by SAN (I assume it is not a storage area network).


text:
Q: Error messages when adding code to function.php or trying to delete inactive plugin files Error message below:
Warning: Cannot modify header information - headers already sent by (output started at /home/content/79/7603579/html/listings/wp-content/themes/OIB theme/functions.php:519) in /home/content/79/7603579/html/listings/wp-includes/pluggable.php on line 897
EDIT: Code around functions.php line 519:
    <?php echo $value['desc']; ?>

    <?php break;
case "section":
    $i++; ?>

<img src="<?php bloginfo('template_directory')?>/functions/images/trans.gif" class="inactive" alt="""><?php echo $value['name']; ?>

            <input name="save<?php echo $i; ?>" type="submit" value="Save changes" />

    <?php break;
   }
} ?>

And the fix, per comment below, removed this code:
function cpt_Search_category_Filter($query) {
   $post_type = array('post','business_sold');
   if ($query->is_search || $query->is_category) {
      $query->set('post_type', $post_type);
   };
      return $query;
};
add_filter('pre_get_posts','cpt_Search_category_Filter');

A: Your functions.php file is outputting instead of returning something, on line 519.
Can you post whatever code/functions are around Line 519?
EDIT:
You have a syntax error in your cpt_Search_category_Filter() function. You have a couple stray semi-colons after closing braces.
Change this:
function cpt_Search_category_Filter($query) {
   $post_type = array('post','business_sold');
   if ($query->is_search || $query->is_category) {
      $query->set('post_type', $post_type);
   };
      return $query;
};
add_filter('pre_get_posts','cpt_Search_category_Filter');

to this:
function cpt_Search_category_Filter($query) {
   $post_type = array('post','business_sold');
   if ($query->is_search || $query->is_category) {
      $query->set('post_type', $post_type);
   }
      return $query;
}
add_filter('pre_get_posts','cpt_Search_category_Filter');


text: Q: How to determine the distance of slipping in a toppling body? A body of known mass is connected to the top of a light rod which perpendicular to the floor. As the body starts to fall, the base of the rod slips before the edge of the mass comes in contact with the floor. Assuming that all variables are known (masses, height, friction coefficient, etc.), how would the distance of slipping before the mass comes in contact with the floor be calculated?


text:
Q: Gaussian estimate I am trying to find some $a\gt 0$ such that $$\int_{-2}^{2}\frac{1}{\sqrt{2\pi}}e^{-\frac{t^2}{2}}dt\leq e^{-a}$$ Any good method to do so?
I'm looking for an analytical argument rather than a numerical solution.
Edit: there was a typo in the integral.

A: with standard procedure you can see that
$$\int_{-\infty}^2 \phi(x)dx\approx 0.97725$$
thus you can find an approximated value for $a$, that is
$$a\approx0.023$$
and it is valid with $=$ instead of $\leq$

A: To make the problem general, you search for $a$ such that, for a given $x$,
$$\int_{-x}^{+x}\frac{1}{\sqrt{2\pi}}e^{-\frac{t^2}{2}}dt\leq e^{-a}$$ that is to say
$$\text{erf}\left(\frac{x}{\sqrt{2}}\right)\leq e^{-a}$$ First, we can solve the equation using some approximation. For example
$$\text{erf}(t)\sim \sqrt{1-\exp\Big(-\frac 4 {\pi}\,\frac{1+\alpha\, t^2}{1+\beta \,t^2}\,t^2 \Big)}$$ where
$$\alpha=\frac{10-\pi ^2}{5 (\pi -3) \pi } \qquad \text{and} \qquad \beta=\frac{120-60 \pi +7 \pi ^2}{15 (\pi -3) \pi }$$ so
$$a > -\frac 12 \log \Bigg[1-\exp\Bigg(-\frac{2 x^2 \left(\alpha  x^2+2\right)}{\pi  \left(\beta  x^2+2\right)} \Bigg)\Bigg]$$
Using $x=2$, this approximation gives $a >0.04673$ while the exact solution would be $a >0.04657$.
We can have much better using the second approximation I gave here.


text:
Q: Insert Method as part of an Array This method has been plaguing me for hours. It's part of an array of type X that should take any datatype.  This is the first time I've worked on a generic type array and a debugger as well.
The errors I'm getting from testing are:
expected: 'hello' but was 'null' and
0: ...ArrayOutOfBoundsException: 0

It also looks like the ArrayOutOfBoundsException handling isn't being thrown correctly either.
I have no idea what to do.  My remove function seems to be working fine.
public void insert( int index, X item )
{
    if ( index > 0 || index < length )
    {
        length++;
        X[] obj2 = (X[]) new Object[obj.length - 1];
        for ( int i = 0; i == index; i++ )
        {
            obj2[i] = obj[i];
        }
        obj2[index] = item;
        for ( int i = index; i == length; i++ )
        {
            obj2[i + 1] = obj[i];
        }
        obj = obj2;
    }

    else
    {
        throw new java.lang.ArrayIndexOutOfBoundsException("" + index);
    }
}

@Test
public void testInsert()
{
    XArray<String> b = new XArray<String>();
    b.add("hello");
    b.add("bye");
    b.insert(1, "adios");
    assertEquals("hello", b.get(0));
    assertEquals("adios", b.get(1));
    assertEquals("bye", b.get(2));
    assertEquals(3, b.size());

    b.insert(1, "buenos dias");
    assertEquals(4, b.size());
    assertEquals("hello", b.get(0));
    assertEquals("buenos dias", b.get(1));
    assertEquals("adios", b.get(2));

    b.insert(0, "hi");
    assertEquals(5, b.size());
    assertEquals("hi", b.get(0));
    assertEquals("hello", b.get(1));

    b.insert(4, "see ya");
    assertEquals(6, b.size());
    assertEquals("see ya", b.get(4));
    assertEquals("bye", b.get(5));
}

A: You have a few problems.
1) Assuming that length is an instance variable, which reflects the length of the obj array, then you actually want to do the following test:
if (index >= 0 && index <= length)

This tests to see if your new item index is either 0 or more, or is 1 greater than the maximum index in your current obj array (i.e., equal to the current array length). This does depend slightly on your expected contract I think it's reasonable to expect that you can "insert" at the end of the list, but you may have to restrict it to only inserting in the middle, and therefore only if there is another element. In this case you want
if (length > 0 && index >= 0 && index < length)

Note: you test &&, not || as you need all conditions to be true. If you wanted to do a more standard argument validity check at the beginning you could do:
    if (index < 0 || index > length)
      throw new java.lang.ArrayIndexOutOfBoundsException("" + index);

This has the benefit of removing the need for an else block and reducing your code nesting slightly.
2) You then increment this.length, but then you do new Object[obj.length - 1];, which makes no sense. I suspect you want to do:
  length++;
  @SuppressWarnings("unchecked")
  X[] obj2 = (X[]) new Object[this.length];

or better still:
  @SuppressWarnings("unchecked")
  X[] obj2 = (X[]) new Object[++length];

3) Your first loop does for ( int i = 0; i == index; i++ ), which should be:
for (int i = 0; i < index; i++)

This is because a loop condition statement doesn't test for the breakout condition (i.e. stop when this is true) but for the continuation condition (i.e. continue while i is less than index)
4) Your second loop does for ( int i = index; i == length; i++ ), and should do:
for (int i = index; i < length - 1; i++)

This is because your length has increased, but you are using i to refer to the original array indexes, not the larger array indexes.
All in all I think it looks like the code below.
The biggest issue here is probably your approach to the testing. You have several tests inside one mega-test. That doesn't help you isolate the individual errors and work out what is wrong with your method without breaking out the debugger (pun not intended, but I just saw it so I'll leave it). Ideally you shouldn't have to use the debugger if your unit tests are small, focused, and isolated. Examples of such tests are included at the end.
class XArray<X> {
  private int length;
  private X[] obj;
  public XArray() {
    this.obj = initBackingArray(0);
    this.length = 0;
  }
  private X[] initBackingArray(int length) {
    @SuppressWarnings("unchecked")
    X[] result = (X[])new Object[length];
    return result;
  }
  public X get(int index) {
    return this.obj[index];
  }
  public int size() {
    return this.length;
  }
  public void add(X item) {
    insert(length, item);
  }
  public void insert( int index, X item )
  {
    if (index >= 0 && index <= length)
    {
      @SuppressWarnings("unchecked")
      X[] obj2 = (X[]) new Object[++length];
      for (int i = 0; i < index; i++)
      {
        obj2[i] = obj[i];
      }
      obj2[index] = item;
      for (int i = index; i < length - 1; i++)
      {
        obj2[i+1] = obj[i];
      }
      obj = obj2;
    }

    else
    {
      throw new java.lang.ArrayIndexOutOfBoundsException("" + index);
    }
  }
}

Example tests:
@Test
public void testAddOnceWorks()   {
    XArray<String> b = new XArray<String>();
    b.add("hello");
}
@Test
public void testAddTwiceWorks()   {
    XArray<String> b = new XArray<String>();
    b.add("hello");
    b.add("bye");
}
@Test
public void testInsertOnEmptyWorks()   {
    XArray<String> b = new XArray<String>();
    b.insert(0, "hello");
}
@Test
public void testAddOnceInsertBeforeWorks()   {
    XArray<String> b = new XArray<String>();
    b.add("hello");
    b.insert(0, "hello");
}

A: First, your logic for bounds checking is incorrect.  Every value possible for index is either greater than 0 or less than length.  This causes the ArrayIndexOutOfBoundsException you are trying to create not to be thrown.  (It's possible Java may throw its own AIOOBE if you do access your array out of bounds.)
You should ensure that both conditions are met.  Use && instead of ||.
if ( index > 0 && index < length )

Also, when copying old elements to your new array, you need to realize that the for loop condition being true means "keep going", not "stop".  Keep looping while the index has not reached length yet.  Change == to <.
for ( int i = 0; i < index; i++ )

(A similar change is needed for the other for loop.)


text:
Q: Change speed of Sequential Transition via a Slider Java FX I have a Sequential Transition and I have a slider. The slider will be used to change the speed of the Sequential Transition (as the animation is playing). However, I am not too sure how to do this. I tried to use the slider to change the duration of the animation but it did not seem to work the duration just stayed at 0 and so the animation would not even play.
It would be great if someone could maybe show a small simplified example of my problem.
Thank you.
EDIT:
So binding the slider value to the rate property allows me to change the speed of animations efficiently. However I want my Slider value to start in the middle I tried:
animationSpeedSlider = new Slider(1, 4, 2);

But that did not work. I also tried to set the value manually like:
    animationSpeedSlider = new Slider(1, 4, 2);
    animationSpeedSlider.setValue(2);
That did not seem to work either, in both cases the slider value is still to the far left.
Also, I want the speed not to be 0 when it is at the far left which is why I put the lower bound to 1 but it seems to still stop the animation.

A: The only way of adjusting the animation speed without stopping the animation is via the  rate property: The cycle duration of the animation is devided by the value of the rate property to determine the effective cycle duration.
Example
@Override
public void start(Stage stage) throws Exception {
    Duration d = Duration.seconds(1);

    Rectangle rect = new Rectangle(50, 50);
    TranslateTransition t1 = new TranslateTransition(d, rect);
    t1.setToX(350);
    TranslateTransition t2 = new TranslateTransition(d, rect);
    t2.setToY(350);
    TranslateTransition t3 = new TranslateTransition(d, rect);
    t3.setToX(0);
    TranslateTransition t4 = new TranslateTransition(d, rect);
    t4.setToY(0);

    SequentialTransition transition = new SequentialTransition(t1, t2, t3, t4);
    transition.setCycleCount(Animation.INDEFINITE);
    transition.play();

    Pane pane = new Pane(rect);
    pane.setPrefSize(400, 400);

    Slider slider = new Slider(0.1, 4, 1);
    transition.rateProperty().bind(slider.valueProperty());

    stage.setScene(new Scene(new VBox(slider, pane)));
    stage.show();
}


text:
Q: ¿Como puedo guardar en base de datos múltiples registros a partir de un formulario? Estoy aprendiendo php y tengo idea de hacer un formulario en el que dinámicamente con JavaScript se puedan añadir nuevas filas , cada una de ellas sería una nueva fila en una base de datos MySQL:
<form  method="POST" action="index.php">
    <!-- Fila 1 -->
    <input type="hidden" name="nombreTabla" value="Colegios">
    <input type="text" name="alumnoID">
    <input type="text" name="fechaNacimiento">

    <!-- Fila 2 -->
    <input type="hidden" name="nombreTabla2" value="Colegios">
    <input type="text" name="alumnoID2">
    <input type="text" name="fechaNacimiento2">

    <!-- Una fila mas cada vez que se pulse el boton -->
    <input type="button" value="Añadir otro registro">

    <button type="submit"> Enviar </button>
</form>

La variable $_POST[] recibida en el servidor será un array asociativo con $key del nombre de cada input y su valor. Pero a partir de aqui me pierdo.
¿Como podria construir una consulta sql dinamicamente con php que inserte todos los registros?


text:
Q: YQL feed parsing troubles I use Yahoo YQL to parse the next feed: https://www.thiscomplexworld.com/tag/optimization-and-analytics/feed/.
The problem is that the parsing result changes randomly from time to time. Sometimes it returns status code 400, sometimes it parses this feed successfully with the same query: 2 results examples. (sorry for placing them on the same picture - I can't insert more that 2 links)
So the question is How to make it work?
Thanks in advance.


text:
Q: Error in android - SQLite I am trying to query my database to return the name entered into a text box. I have been able to view all the items in the database but i want to search for a name using a text box. When I enter the name and hit the search button, the log cat displays an error that "no such column: john: while compiling: SELECT name, gender, height, age, hair FROM details WHERE name= john ORDER by name.
 private void findRecords(){
    EditText find = (EditText)findViewById(R.id.nameSearch);
    EditText name = (EditText)findViewById(R.id.nameFound);
    EditText gender = (EditText)findViewById(R.id.genderFound);
    String s = find.getText().toString();
    //Long l = Long.parseLong(s);
    DatabaseClass hon = new DatabaseClass(this);

    String returnedName = hon.getName(s);
    String returnedGender = hon.getGender(s);

    name.setText(returnedName);
    gender.setText(returnedGender);

}

    public String getName(String s) {
    // TODO Auto-generated method stub
    String[] columns = new String[] {NAME_COLUMN, GENDER_COLUMN, HEIGHT_COLUMN, AGE_COLUMN, HAIR_COLUMN};
    Cursor c = sherlockdb.query(TABLE_NAME, columns, NAME_COLUMN +"="+ s, null, null, null, NAME_COLUMN);
    if (c != null){
        c.moveToFirst();
        String name = c.getString(1);
        return name;
    }
    return null;
}

Please kindly help

A: Replace:
Cursor c = sherlockdb.query(TABLE_NAME, columns, NAME_COLUMN +"="+ s, null, null, null, NAME_COLUMN);

with:
String[] args={s};
Cursor c = sherlockdb.query(TABLE_NAME, columns, NAME_COLUMN +"=?", args, null, null, NAME_COLUMN);

A: What kind of data is your column? I think that you forgot to put the literal jonh between ''.
You can try this:
SELECT name, gender, height, age, hair FROM details WHERE name='john' ORDER by name;

A: Try this:
Cursor c = sherlockdb.query(TABLE_NAME, columns, NAME_COLUMN +"='"+ s+"'", null, null, null, NAME_COLUMN);

Because you need String in 'john' format.


text:
Q: Cómo leo una cadena de texto, y añado espacios después de 3 caracteres? Tengo un problema. Dentro de una tabla, irán unos textos sacados de unas variables, cómo hago para leer 'x' número de caracteres y añadir unos espacios en blanco después?.
Ej.:
01. Escritura natural de idiomas.

Ej.: cómo debe quedar:
01.     Escritura natural de idiomas.

Cómo debo formular para añadir esos espacios tras leer dichos primeros caracteres? Gracias de ante mano!.
function generatePageLinks(text, isChapter, pageId) {
       // text = variable con cadena de texto de título.
    var $element = $(document.createElement('td')),
        $link = $("").text(text).attr('href', '#').attr('data-page-id', pageId);

    $element.append($('
').html(isChapter ? text : $link));
    //Mete dicho texto dentro de las etiquetas
    return $element;

}

Y esto es lo que crea en el html:
04. Contenido_solapas

Gracias al compañero de abajo, ésta ha sido la solución final, para poder manipular los espacios :)
$element.append('
');
$element.append($("

").html(isChapter ? text : $link));
return $element;

A: Lo he hecho buscando el primer espacio que me parece más sencillo que contar carácteres, a ver si te sirve:

   var str = document.getElementById("parrafo").innerHTML;
   var str2 = str.replace(" ", "     ");
   document.getElementById("parrafo").innerHTML = str2;

01. Escritura natural de idiomas.

A: Para hacerlo más automatizado, crea una función que reciba:

*

*El texto original a editar

*El punto de quiebre o posición en la que se añadirán los espacios.

*Cantidad de espacios a añadir.

function fillWithSpaces(text, breakpoint, spacesQty) {
  if(breakpoint < 0) { throw new Error("Invalid break position"); }
  let leftPart = text.substring(0, breakpoint);
  let rightPart = text.substring(breakpoint);
  [...Array(spacesQty)].map((i) => {
    leftPart += " ";
  });
  return leftPart + rightPart;
}

let originalText = "01. Escritura natural de idiomas.";
let customText = fillWithSpaces(originalText, 3, 5);
document.querySelector('pre').innerText = customText;

Actualización 2
Tu código se puede segmentar para mejor legibilidad. Simplemente crea los elementos td y a y
. Añade los atributos a a y de acuerdo a si es capítulo, añades solo el texto o el link respectivamente.
var element = document.createElement('td');
var link = document.createElement('a');

$(link)
  .attr('data-page-id', id)
  .attr('href', '#')
  .append('
')
  .find('pre')
  .append(text)
  .find('a');

var wrapper = $(element)
              .append('
')
              .find('div');
if(isChapter){
  $(wrapper).append(text);
} else {
  $(wrapper).append(link);
}
return element;

A: var str="01. Escritura natural de idiomas.";

var str2 = str.slice(0, 3) + "   " + str.slice(3);

El resultado:
01.    Escritura natural de idiomas.

str.slice devuelve los elementos seleccionados de una matriz, como un nuevo objeto de matriz, seleccionando los elementos desde los argumentos dados (0,3) para el primer caso y el segundo slice que
comienza del (3) hasta el fin

A: Con una expresion regular es bastante simple. El metodo replace te permite sustituir el fragmento de la cadena de caracteres.
Coincide los 3 primeros caracteres, agrega espacios y luego pon el resto de la cadena de entrada.

var spaces = '   ';
// En ES6 puedes usar
// var spaces = ' '.repeat(3);
var source = 'Lorem ipsum dolor amet';
var source2 = '01. Escritura natural de idiomas.'

var result = source.replace(/^(.{3})(.*)$/, '$1' + spaces + '$2');
var result2 = source2.replace(/^(.{3})(.*)$/, '$1' + spaces + '$2');

alert(result);
alert(result2);

A: Puedes utilizar javascript de esta manera:
var str = "Hello world!";
var res = str.substr(1, 4) + " ";//Un espacio en blanco

Resultado
ello

Espero que te sirva


text:
Q: Split Command - Choose Output Name I have a text file named myfile.txt. The file contains 50,000 lines and I would like to split it into 50 text files. I know that this is easy with the split command:
split myfile.txt

This will output 50 1000-line files: xaa, xab, and xac.
My question, how do I run split my text file so that it names the output files:
1.txt
2.txt
3.txt

...

50.txt

Seeking answers in python or bash please. Thank you!

A: Here is a potential solution using itertools.islice to get the chunks and string formatting for the different file names:
from itertools import islice

with open('myfile.txt') as in_file:
    for i in range(1, 51):
        with open('{0}.txt'.format(i), 'w') as out_file:
             lines = islice(in_file, 1000)
             out_file.writelines(lines)

A: its not exactly what you are looking for, but running
split -d myfile.txt

will output
x00
x01
x02
...

A: To generate test data in empty directory, you can use
seq 50000 | split -d

To rename in the way that you want, you can use
ls x* | awk '{print  $0, (substr($0,2)+1) ".txt"}' | xargs -n2 mv

A: Here's a funny one: if your split command supports the --filter option, you can use it!
If you call
split --filter=./banana myfile.txt

then the command ./banana will be executed with the environmental variable FILE set to the name split would choose to write the chunk it's processing. This command will receive on its standard input the chunk being processed. If this command returns a non-zero status code, then split will interrupt its operations.
Together with the -d option, that's exactly what you want. With the -d option, the name split will choose for the filenames will be x01, x02, etc.
Make a script:
#!/bin/bash

# remove the leading x from FILE
n=${FILE#x}
# check that n is a number
[[ $n = +([[:digit:]]) ]] || exit 1
# remove the leading zeroes from n
n=$((10#$n))

# send stdin to file
cat > "$n.txt"

Call this script banana, chmod +x it and let's go:
split -d --filter=./banana myfile.txt

This --filter option is really funny.

A: Here's an example of how you could split this file in bash:
split -l 1000 -d --additional-suffix=.txt myfile.txt

The -l argument determines the number of lines included in each split file (1000 in this case, for 50 total files), the -d argument uses numbers instead of letters for the suffixes, and the value we pass to the --additional-suffix argument here gives each file a .txt file extension.
This will create
x00.txt
x01.txt
x01.txt

etc.
If you wanted to change the 'x' portion of the output files, you'd want to add a prefix after the input file (e.g. myfile.txt f would create f01.txt, f02.txt, etc.)
Note that without --additional-suffix, your files will all lack filename extensions.
I've looked to see if there's a way to split a file and name them with only the suffix, but I haven't found anything.

A: A simple approach:
f=open('your_file')
count_line,file = 0,1
for x in f:
    count_line +=1
    if count%1000 == 1:
        f1 = open(str(file) + '.txt','w')
        f1.write(x)
        file +=1
    elif count_line%1000 == 0:
        f1.write(x)
        f1.close()
    else:f1.write(x)


text:
Q: one ViewController goes to another ViewController I want to implement following GUI on ipad.
when user start my application, I have a ViewController which has button on that, after user touched one button it will go to another View Controller.
My question is how to display a new ViewController in current ViewController.
Thanks

A: You need to define an IBAction in your header and connect your button to this action.
Then in your action, use:
/* also add - (IBAction) goToAnotherView: (id) sender; to your header */
- (IBAction) goToAnotherView: (id) sender {

    MySecondViewController *secondView = [[MySecondViewController alloc] init];
    [self.navigationController pushViewController:secondView animated:YES];
    [secondView release];

}


text:
Q: Can someone please tell me what is wrong with my seo friendly url htaccess code? It is producing an Error 500 - Internal server error
Thanks very much
Options -Indexes
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^tmp/public
    RewriteRule ^(.*)$ tmp/public/$1 [L]
</IfModule>

A: This pattern certainly will never match: !^tmp/public, read the documentation: it clearly states that %{REQUEST_URI} contains the absolute path, so including a leading slash. So your attempt to prevent an endless rewriting rule fails
Instead match against the absolut path in your condition:
Options -Indexes
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/tmp/public
    RewriteRule ^(.*)$ tmp/public/$1 [L]
</IfModule>


text:
Q: The type or namespace name 'DrawableGameObject' could not be found? I've been working on a XNA project for a class I'm taking. I had an issue with a class that I was making for the "Bad guys" which are snowmen (the class is called Snowman.cs). I cannot get the program to compile and it's driving me crazy. Someone helped me out with what I think is some solid code for the Snowman.cs class:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using CameraViewer;

namespace MGH10_Skybox
{
    public class Snowman : DrawableGameObject
    {
        private Camera cam = new Camera();

        Model snowMan;
        Matrix[] snowManMatrix;

        protected override void LoadContent()
        {
            //snowMan = Content.Load<Model>( "Models\\snowman" );
            snowManMatrix = new Matrix[snowMan.Bones.Count];
            snowMan.CopyAbsoluteBoneTransformsTo(snowManMatrix);
        }

        public void DrawSnowMan(Model model, GameTime gameTime)
        {
            foreach (ModelMesh mesh in model.Meshes)
            {
                Matrix world, scale, translation;

                scale = Matrix.CreateScale(0.02f, 0.02f, 0.02f);
                translation = Matrix.CreateScale(0.0f, 0.7f, -4.0f);

                world = scale * translation;

                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = snowManMatrix[mesh.ParentBone.Index] * world;

                    effect.View = cam.viewMatrix;
                    effect.Projection = cam.projectionMatrix;
                    effect.EnableDefaultLighting();
                }

                mesh.Draw();
            }
        }

        protected override void Draw(GameTime gameTime)
        {
            DrawSnowMan(snowMan, gameTime);
        }

    }
}

My issue is that I keep getting a compiler error that says "The type or namespace name 'DrawableGameObject' could not be found (are you missing a using directive or assembly reference?)".
I have tried doing all kinds of research on google and I get almost no results for DrawableGameObject, but anything that does talk about it (or at least says it in the page preview) usually ends up using DrawableGameComponent instead.
I've tried using DrawableGameComponent, but then I get even more compiler errors which lead me to believe that it truly is not what I'm looking for. Specifically, the error states that "DrawableGameComponent does not contain a constructor that takes '0' arguments" (which goes against how my class and its calls were constructed).
The one gleam of hope that I had was that 'DrawableGameObject' is supposedly a .net 4.0 class, and I had been using XNA 3.1 w/ Visual C# 2008 (which does not support 4.0 apparently). So I downloaded XNA 4.0 and Visual C# Express 2010 with high hopes that crashed and burned when I went to change the target Framework only to find the option completely grayed out (even when starting a completely new project).
All help is GREATLY appreciated.

A: It seems as though you will actually want "DrawableGameComponent" instead, as I couldn't find anything about a "DrawableGameObject" class.  The error you're getting when trying to inherit from DrawableGameComponent can be fixed by calling the base constructor with the appropriate parameter during your classes constructor, as shown below:
public Snowman(Game game) : base(game)
{
   //Whatever goes here!
}

"game" in the base constructor is supposed to be the Game object that the DrawableGameComponent is attached to.
Edit:
Based on your latest comment, I'd recommend adding this constructor to your class (that is, replace what I previously suggested with this constructor):
public Snowman(Game game, Model snowman) : base(game)
{
    this.snowman = snowman;
}

And in your Game1.cs, in your LoadContent function or wherever you're currently calling "snowMan = Content.Load ( "Models\snowman");", try this instead:
snowMan = new Snowman(this, Content.Load<Model>("Models\\snowman");

This will create a new Snowman instance with the "Model snowman" field initialized.

A: So... if you can't find the class, make your own!
Anywho, I guess DrawableGameObject was supposed to make it easy to update and draw different types of objects in the game engine, but if you're using it only for the snowman (which I would guess since you're not mentioning other code not working..) you might as well not have it!
So remove the inheritance for that class, and remove the override from those methods. Hide the DrawSnowMan method (i.e. make that private), and make the LoadContent and Draw public, and call them from respective methods in your Game class!
Also, I would suggest building in a mechanism to draw your snowman on different locations, or if you want to have multiple instances of the SnowMan class, move the Model somewhere else (they are gonna share it, so you could save some memory by not duplicating it unnecessarily).
Hope I helped some, although if you were looking for an answer that involved finding the DrawableGameObject class then sorry.


text:
Q: List files on ftp using cURL in Matlab I'm trying to get a directory listing of files on an ftp server using cURL commands within Matlab.  Currently I'm trying something like:
[s,w] = dos('curl "ftp://name:password@ftpurl/directory/"');

which correctly gets the data and stores it in the variable w.
To get a list of the files in that directory I could try to parse out the names from the 'w' variable, but that could get a little complicated.  Is there an easier way to obtain a list of the file names within the ftp directory, or do I have to go about trying to grab it out of the w variable?
Thanks!
EDIT
Using the -l command:
[s,w] = dos('curl "ftp://name:password@ftpurl/directory/"');

The resulting w looks something like:

0 0 0 763 0 0 2319 0 --:--:-- 2437FTPtest-D20110322-T022705.bot
FTPtest-D20110322-T022705.idx
FTPtest-D20110322-T022705.raw
FTPtest-D20110322-T022746.bot

So it looks much better, but since the first file doesn't have a line feed before, it may be a little more difficult.  Any ideas on how to get around this?
Thanks!

A: Try the -l (that's a lowercase L) option:

When listing an FTP directory, this switch forces a name-
                only  view. Especially useful if you want to machine-parse the
                contents of an FTP directory since  the  normal directory  view
                doesn't use a standard look or format.
This  option  causes  an  FTP NLST command to be sent. Some FTP
                servers list only files in their response to NLST; they do not
                include subdirectories and symbolic links.

(quote originates from http://curl.haxx.se/docs/manpage.html#-l)

A: How about use Matlab's built-in ftp support instead of shelling out to curl? See "help ftp".


text:
Q: Angular is modifying scope within method I have a method being called inside my scope which performs a calculation on the model that you pass through.
This is causing an infinite loop because Angular is modifying the original object, not the local copy of it in the method.
HTML

{{ todo.name }} {{ doSomething(todo) }}

JS
var app = angular.module('myApp', []);

app.controller('TodoController', ['$scope', function ($scope) {

    $scope.todos = [{
        name:      'Todo 1',
        someValue: 1
    }];

    $scope.doSomething = function (todo) {
        console.log(todo.someValue);
        todo.someValue += 1;
        return todo.someValue;
    };

}]);

See this in action here https://jsfiddle.net/pvkpj169/
If you open up the console while running this you will see that it causes an infinite loop.
How can I prevent Angular for modifying the original model within this scope? I want any changes made in here to be local to the method

A: Your doSomething() is making the model unstable by adding a new copy of your todo.
Use the following controller code:
var app = angular.module('myApp', []);

app.controller('TodoController', ['$scope', function($scope) {

  $scope.todos = [{
    name: 'Todo 1',
    someValue: 1
  }];

  $scope.doSomething = function(todo) {
    console.log(todo.someValue);
    var val = todo.someValue + 1;
    return val;
  };

}]);

A: If it was me I would get rid of the function completely and change:
{{ doSomething(todo) }}

to:
{{ todo.someValue + 1 }}

Angular will evaluate this for you in the view and the digests won't keep incrementing the object property value


text:
Q: Determine the number of ways to colour a 1 by n grid using the colours red and white if an even number of squares are to be coloured red. a) Determine the number of ways to colour a 1 by n grid using the colours red and white if an even number of squares are to be coloured red.
Note that n is greater than or equal to 1 and the number of red squares could be 0.
I know I must consider the cases of n being even and odd, and determine the sum, from zero to n of the squares being red, where the number of red squares is even. But I just want to make sure I haven't missed any arrangements by saying a) is $2^{n-1}$ when n is even and $2^{n-1}-1$ when n is odd.
b) Determine the number of ways to colour the squares using red, white and blue if an even number of squares are to be coloured red.
For this case, I can have arrangements including red only, white only, blue only, white and blue only, red and white only, red and blue only, and finally all three colours.
Thank you for any help provided.

A: For part (a): If $n$ is odd, then any arrangement will have either an even number of red squares or an even number of white squares (but not both). Reversing white and red if necessary gives an even number of red squares. So the answer in this case is one half of the total number of arrangements, or $2^{n-1}$.
If $n$ is even, then any arrangement has either an even number of both red and white squares or an odd number of both. But there is a bijection between the latter set and the former by switching the color of the last square. Thus in this case as well the total number of arrangements with an even number of red squares is $2^{n-1}$.
For the general case, part (b), suppose there are $c$ colors and you want to know the number of arrangements with an even number of red colors. Suppose first that the number of squares, $2n$, is even. For each $k$ from $0$ to $2n$ we first choose the number of arrangements with $2k$ red squares in $\binom{2n}{2k}$ ways, and then any arrangement of the remaining squares using $c-1$ colors. Then the total number of such arrangements is
$$\sum_{k=0}^n \binom{2n}{2k}(c-1)^{2n-2k}
= \sum_{k=0}^n \binom{2n}{2n-2k}(c-1)^{2n-2k}
= \sum_{k=0}^n \binom{2n}{2k}(c-1)^{2k}.$$
This can be seen to be an expansion of the formula
$$\frac{1}{2}(((c-1)+1)^{2n} + ((c-1)-1)^{2n})
= \frac{1}{2}(c^{2n}+(c-2)^{2n}).$$
In your case, with $c=3$, one gets for the number of arrangements with an even number of squares
$$\frac{1}{2}(3^{2n}+1).$$
For an odd number of squares, the computation is very similar, and the answer comes out to be
$$\frac{1}{2}(c^{2n+1}+(c-2)^{2n+1}).$$

A: In part (a) the answer is $2^{n-1}$ for all $n\gt0$, even or odd. You see, flipping the colour of the leftmost square changes the parity of the number of red squares, so there are just as many even as odd, so exactly half of the $2^n$ possible colourings have an even number of red squares.
(The following answer to part (b) is plagiarized from my answer to this related question.)
In part (b), flipping the leftmost non-white square from red to blue or blue to red changes the parity of the number of red squares. This argument would show that there are equal numbers of colourings with an even or an odd number of red squares, except that we've left out one colouring: ALL SQUARES WHITE. In this case there are no red squares, and $0$ is an even number, so even wins by one. That is, there are $\frac{3^n-1}2$ colourings with an odd number of red squares, and $\frac{3^n+1}2$ colourings with an even number of red squares.
More generally, if $k$ colours are available for the squares, then there are $\frac{k^n+(k-2)^n}2$ ways to colour the $1\times n$ rectangle with an even number of red squares, $\frac{k^n-(k-2)^n}2$ ways with an odd number of red squares, so the difference is $(k-2)^n$ in favour of even; see this answer.


text:
Q: Android Runtime permission in Cordova 3.6 App How to implement android runtime permissions in app that is using cordova 3.5

A: Android Runtime permission introduced from Android 6.0 (API level 23). It has no relation with cordova version.
In MainActivity.java of your Android platform, add this code after loadUrl(launchUrl);
if(Build.VERSION.SDK_INT >= 23)
{
    // Sample request for user permission runtime */
    ActivityCompat.requestPermissions(MainActivity.this,
            new String[] {
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE
            },
            100);
}

If you are working on android studio it will automatically import necessary packages like:
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;


text:
Q: How to center Textview inside Listview using RelativeLayout? ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.activity_haltestellen, R.id.tvHaltestellen, HaltestellenListe);
lvH.setAdapter(arrayAdapter);

this is how the stuff is set and .xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ListView
    android:id="@+id/lvHaltestellen"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >
</ListView>

<TextView
    android:id="@+id/tvHaltestellen"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"

    />

I get the StringArray from a database.
so how can center the tv inside the listview? realy bad thing

A: I'm not quite sure what do you want to do, but if you want to center the TextView inside the RelativeLayout then remove
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"

from TV and try adding something like android:layout_centarInParent="true", and in the relative layout change match_parent to wrap_contents

A: Try to add this one: android:layout_centerInParent="true"
<TextView
    android:id="@+id/tvHaltestellen"
    android:layout_centerInParent="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

A: You could anchor the TextView to the top and bottom of the ListView (and optionally left and right too, depending on the desired effect). That will make the TextView equally tall (and optionally wide), so use a center gravity to position the text in the middle.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/lvHaltestellen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/tvHaltestellen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/lvHaltestellen"
        android:layout_alignBottom="@+id/lvHaltestellen"
        android:layout_alignLeft="@+id/lvHaltestellen"
        android:layout_alignRight="@+id/lvHaltestellen"
        android:gravity="center" />

</RelativeLayout>

If you're planning to add a background colour to the TextView, you'll need to wrap it inside another transparent container (e.g. a FrameLayout), to avoid the colour from obscuring what's displayed in the list. Something like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/lvHaltestellen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/lvHaltestellen"
        android:layout_alignLeft="@+id/lvHaltestellen"
        android:layout_alignRight="@+id/lvHaltestellen"
        android:layout_alignTop="@+id/lvHaltestellen" >

        <TextView
            android:id="@+id/tvHaltestellen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@android:color/black" />
    </FrameLayout>

</RelativeLayout>

Alternatively, if you decide to make the ListView fill up the whole height of the RelativeLayout, you don't need to anchor the TextView to the list anymore. As already pointed out by @user1796624, you can then just center the TextView.
As per your earlier comment on someone else's answer:

the textview is shown inside the listview.

I understand what you're trying to say here, but please do realize that the TextView does not sit inside the ListView, but rather floats on top of it.


text:
Q: How to make a drag and drop LineChart using JavaFX? I need to create a line graph to allow me to drag it in different coordinate axes, when dragged backward the graph should show data that have already been painted.
"Currently I have some graphs showing real-time data, I receive this data via sockets, then I want to be able to pause the graph and dragging back to see the data that have already been shown."

A: I'm not experienced with Javafx, so I apologise if this misses the mark.
I have made something similar in the past using my own component and a JScrollPane. You can make a "scrolling savvy" client, allowing you to render the history as the user drags the graph backwards. If you make your client Scrollable, you have full control on how it responds. While this isn't javafx specific, there is a javafx panel, so I can't see a reason this wouldn't work, assuming comparability with light weight swing components.
Oracle introduce it here: http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html#scrollable


text:
Q: Getting error in using expected_conditions in python + selenium I have been using python and selenium for automation and here is the error I am getting frequently.
WebDriverException: Message: u'An invalid or illegal string was specified'

I am not sure what is wrong. This error occurs in the following line of my code:
wait = WebDriverWait(self.driver, 10)
wait.until(expected_conditions.element_to_be_clickable(By.CSS_SELECTOR,"a:contains(Sign In)"))

Please help!

A: The problem is that a:contains(Sign in) is not valid CSS.
If you want to do CSS, a[href*='Sign In'] might do the trick, but it looks like you're clicking on a link, so the best solution is to do By.LINK_TEXT,"Sign In"


text:
Q: Else condition not executed due to try catch I have a scenario in which, when we click on save two process can occur. It can show some messages or else the page can crash. I have added an if condition for the crash and mentioned the other process if the application does not crash as else condition. I have written a code like this to handle the crash.
try {
    if (driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div[1]/span[1]")).isDisplayed()){
        System.out.println("Critical Error Occured.");
        driver.close();
    } else{
    String msg = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div/div/div[1]/div/div[2]/div/div[1]/span")).getText();
    if (msg.equals("User already registered")){
        driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
        System.out.println(msg);
        driver.close();
    } else if (msg.equals("Admission number already exist.")) {
        driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
        System.out.println(msg);
        System.out.println("Please change the admission number.");
        driver.quit();
    } else if (msg.equals("Saved Successfully.")){
        driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
        System.out.println(msg);
    }
    }
}catch ( org.openqa.selenium.NoSuchElementException e){
    System.out.println("No Such Element Exception.");
}

Since the page crashes rarely, while executing the control goes to catch and so the else conditions for the first if condition is not executed. Is there any solution for this?

A: Do separate try-catch blocks inside the sections of the if or use a finally block for code you always want to execute.
You have two separate issues, the first is the findElement within the conditional. To handle that you need to do the find separately then do the if.
Element elem = null
try {
    elem = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div[1]/span[1]"));
} catch (org.openqa.selenium.NoSuchElementException e) {
    System.out.println("No Such Element Exception.");
}

Then after that you need to handle it within the else
if (elem != null && elem.isDisplayed()){
    System.out.println("Critical Error Occured.");
    driver.close();
} else{
  try {
    String msg = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/div[1]/div[1]/div/div/div[1]/div/div[2]/div/div[1]/span")).getText();
    if (msg.equals("User already registered")){
        driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
        System.out.println(msg);
        driver.close();
    } else if (msg.equals("Admission number already exist.")) {
        driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
        System.out.println(msg);
        System.out.println("Please change the admission number.");
        driver.quit();
    } else if (msg.equals("Saved Successfully.")){
        driver.findElement(By.name("dnn$ctr5995$View$btnOk")).click();
        System.out.println(msg);
    }
  } catch ( org.openqa.selenium.NoSuchElementException e){

  }
}

A: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
May-be you're looking for the  finally clause, aren't you ?

A: Finally clause can solve your problem. Its best practice to include must  execute code in Finally clause


text:
Q: How to export DT table to html and preserve all functionality? I'm able to export a DT table generated in R/RStudio to HTML using the htmlWidget:saveWidget method. However, the FixedColumns feature is not preserved and becomes very narrow when a term is entered in the search bar.
xyz_search_dt <- datatable(
  xyz_search_table_d,
  rownames = FALSE, extensions = 'Buttons',
  options = list(autoWidth = TRUE,
                 extensions = 'FixedColumns',
                 options = list(dom = 't',scrollX = TRUE,
                                fixedColumns = TRUE),
                 columnDefs = list(list(width= '200px',
                                        targets = "feedback")),
                 dom=('Bfrtip'), buttons = c('excel'),
                 pageLength = table_rows,
                 searchHighlight = TRUE),
  filter = list(position="top"))

htmlwidgets::saveWidget(xyz_search_dt, "xyz_search_dt.html")

A: The solution that I found and seems to work well is to address the widget sizing policy after the fact.
dow_search_dt[["sizingPolicy"]][["defaultWidth"]] <- "100%"
htmlwidgets::saveWidget(dow_search_dt, "dow_search_dt.html")

Reference:

*

*How to resize HTML widget using saveWidget in htmlwidgets R (reopened question)?

A: You can try this. I use the mtcars dataset and everything works well.
xyz_search_dt <- DT::datatable((mtcars),
                           rownames = FALSE,
                           extensions = 'Buttons',
                           options = list(autoWidth = TRUE,
                                          extensions = 'FixedColumns',
                                          options = list(dom = 't',
                                                         scrollX = TRUE,
                                                         fixedColumns = TRUE),
                                          columnDefs = list(list(width= '200px',
                                                                 targets = "feedback")),
                                          dom=('Bfrtip'),
                                          buttons = c('excel'),
                                          #pageLength = table_rows,
                                          searchHighlight = TRUE),
                           filter=list(position="top"))

htmlwidgets::saveWidget(xyz_search_dt, "xyz_search_dt.html")

OUTPUT:


text:
Q: correcting navigation between VCs in existing app I have a fairly simple app thats a game for small children. There is a main screen and 5 separate levels. 3 of the 5 levels are made up of more than one VC where actions take place in the first VC in that row then code calls a modal segue to the next one in the line and so on till it reaches the end of the row and a modal segue is called linking back to the main screen. The levels that have only one VC just perform actions then segue back to the main VC.
Every segue in the app in modal.
Also every page (VC) has a home button that will segue to the main page if pressed
I set this all up in the StoryBoard and visually everything works as Id expect but when adding sound I realized that there seems to be a major problem.
If I now understand correctly (and maybe I dont) modal segues dont actually replace the current VC with the newly requested one but rather slide the newly requested one over top the original and make it the visible display.
Currently I go from main to level 1. Level 1 does some stuff and plays some sounds that repeat via a timer. If I segue back to main visually everything is fine except the sounds being played by the timers in level 1 VC continue to play and xCdoe give me the following error quite a few times
2013-01-21 22:16:07.901 TTBetaDev[678:c07] Warning: Attempt to present <MainMenuViewController: 0x7e02f40> on <BonusViewController: 0x7ecbfa0> whose view is not in the window hierarchy!

Below is a screenshot of my storyboard in case I havent explained the layout well enough.
How should this be set up to allow the navigation I would like? A what steps will I need to take to apply that to the what I already have built in the storyboards? Or will I have to re-do all my storyborad work?
I tried apples VC documentation but I couldnt understand what relates to what Im trying to do.
COuld someone please help explain this to me

A: You have segues going forwards AND backwards. You shouldn't do this.
e.g. Look and Main and VC 2.
You have a segue going from Main to VC 2. This means that Main will present VC 2 as a modal view controller.
When Main does this though it is still on the stack underneath VC2.
Then you have a segue from VC2 to Main. This means that VC2 will create a new Main and present it modally too. If you continue using the app you will have multiple instances of main and all the other VCs and memory consumption will rocket.
What you need to do is delete ALL the segues that go backwards. (i.e. like the one from VC2 to Main)
Then when you want to get back to main from VC2 you have to dismiss VC2.
i.e.
in Main...
//present VC2
[self performSegueWithIdentifier:@"VC2Segue" sender:nil];

//dismiss VC2
[self dismissViewController:vc2ViewControllerInstance];

or in VC2...
//dismiss VC2 from itself
[self dismissViewController:self];

The main thing though is that you can't use segues to go backwards.
TL:DR
Nothing should segue INTO Main. Any segues that go into the left hand side of main should be deleted and dealt with properly.


text:
Q: Отношение ManyToMany внутри одной модели в JPA? Столкнулся с проблемой описания сущности и связей таблицы.
Есть 2 таблицы:

*

*Первая - users (user_id, username)

*Вторая user_friendship (id, first_user_id, second_user_id) с двумя внешними ключами на первую:
first_user_id, second_user_id - ссылаются на users.user_id
Не могу даже представить как описать энтити и джоины, даже не знаю с какой стороны начать.
Вопрос: как описать сущности и какие связи будут (ManyToMany)?
Использую Spring boot data

A: Классический случай many-to-many с самим собой.
@ManyToMany
@JoinTable(name = "user_friendship",
    joinColumns = @JoinColumn(name = "first_user_id", referencedColumnName = "user_id", nullable = false),
    inverseJoinColumns = @JoinColumn(name = "second_user_id", referencedColumnName = "user_id", nullable = false))
private Collection<User> friends;


text:
Q: Find all the positive integers $m$ such that $p_{m}≥2m$ Find all the positive integers $m$ such that $$p_{m}≥2m$$
where $(p_{m})$ is the sequence of prime numbers
I have no idea to start.

A: We have $p_n\ge n\log(n)\ge 2n$ for all $n\ge 8$. This follows from the standard estimates, e.g., see here.

A: Note that $7 < 2\cdot 4$, while $11 > 2\cdot 5$, and every prime after that is odd.

A: @Dietrich Burde's answer does the hard part, of proving the high-$m$ behavior.
However, the correct answer to the problem is
$$
m \in \{1 \cup \{n | n \geq 5 \}$$


text:
Q: Qt proper connect() calling I have a problem regarding connect() method, non of these below calls work:
connect(tutorial->back, SIGNAL(clicked()), this, SLOT(exit_button_clicked()));
connect(tutorial->back, &QPushButton::clicked(), this, &MyMainWindow::exit_button_clicked());

The first one does not call exit_button_clicked() and the second one tells me that clicked() must be static(in Clion) and does not compile .back is an QPushButton and tutorial is an custom QWidget class. It is important to implement this method by calling custom function (for further use). Can anyone show me the right way to implement this??
UPDATE:
the problem was with my CMakeLists.txt, I added set(CMAKE_AUTOMOC ON) and Q_Object macro to my classes and it works fine now.

A: In the first case, there must be something wrong with your exit_button_clicked() slot. It should be a simple member function with slots specifier taking void and returning void in a class with Q_OBJECT macro. If the connection fails, it writes the error at run-time to the console (probably through qDebug()).
In the second case, it's clear that you have extra () after the function names. Taking the addresses of the functions looks like this:
connect(tutorial->back, &QPushButton::clicked, this, &MyMainWindow::exit_button_clicked);

&QPushButton::clicked() tries to call the function and take an address of a return value, which of course fails at compile-time, because QPushButton::clicked is not static.
I hope this clarifies it. Looking into documentation wouldn't do any harm neighter.

A: I presume, your exit_button_clicked() is declared as a private or public function (not as a slot). Qt custom signals and slots have to be declared in a proper way. For example, you have your class Tutorial:
class Tutorial : QWidget {
    Q_OBJECT
    // Your class members go here.
    // Add this slot declaration:
    private slots:
        void exit_button_clicked();
}

(Note the slots keyword next to the private).
Slots can also be public or protected, as you wish.