text:
Q: How to store and fetch data systematically with using SharedPreferences? I have an app for listing movies. User should be able to list their favorite movies in the feed. I am doing that with using SharedPreferences. For list I am using ListView. However when I add new movie in list, it replaces with previous one.
This is ListActivity ,
public class ListActivity extends AppCompatActivity {

    ListView listView;
    ImageView listTitleImage;
    ImageView homeIcon;
    ImageView userListIcon;
    ImageView searchIcon;
    ImageView accountIcon;

    public static SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        listView = findViewById(R.id.listView);
        listTitleImage = findViewById(R.id.listTitleImage);
        homeIcon = findViewById(R.id.homeListImageViewList);
        userListIcon = findViewById(R.id.homeListImageViewList);
        searchIcon = findViewById(R.id.searchImageViewList);
        accountIcon = findViewById(R.id.accountImageViewList);

        sharedPreferences = getApplicationContext().getSharedPreferences("Save", Context.MODE_PRIVATE);

        String title = sharedPreferences.getString(String.valueOf(1),"No movie");
        String poster = sharedPreferences.getString(String.valueOf(2),"No poster");

        ArrayList<List> list = new ArrayList<>();

        list.add(new List(title,poster));

        ListAdapter listAdapter = new ListAdapter(this,R.layout.movie_list,list);

        listView.setAdapter(listAdapter);

    }
}

And this is where I store movie details.  'resultList' is the arraylist which I am using for getting data from api.
@Override
    public boolean onMenuItemClick(MenuItem item) {

        if(item.getItemId() == R.id.menuAdd){

            String title = resultList.get(pos).getTitle();
            String posterpath = resultList.get(pos).getPoster_path();

            sharedPreferences = context.getSharedPreferences("Save", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(String.valueOf(1),title);
            editor.putString(String.valueOf(2),posterpath);
            editor.apply();

            Intent intent1 = new Intent(context,ListActivity.class);
            context.startActivity(intent1);

            return true;

        }
        else if(item.getItemId() == R.id.menuShowDetails){

            int movieId = resultList.get(pos).getMovieId();
            Intent intent1 = new Intent(context, MovieDetails.class);
            intent1.putExtra("movie_id",movieId);
            context.startActivity(intent1);
            return true;

        }
        return false;
    }

A: the best solution is that you have to use SQLite database or room database for storing a list because it's easy to use and update every time if you want to update...
For Sqlite reference - https://www.javatpoint.com/android-sqlite-tutorial
for Room Database Reference - https://medium.com/mindorks/using-room-database-android-jetpack-675a89a0e942


text:
Q: Assign javascript variable to php variable How to pass javascript variable that came from select option to a PHP variable?
I want to set PHP variable depending on user selection.
I tried that code:

<form id="extended-search" >

        <select class="select" name="sex" id="sex">
            <option value="0">All</option>
            <option value="1">M</option>
            <option value="2">F</option>
        </select>

</form>
<?php
var_dump ($_REQUEST['selected']); //that print NULL don't know why!
?>

A: You are passing data in wrong format. Data is passed as an object. Please refer below.
 $("select[name='sex']").change(function () {
    var submitSearchData = jQuery('#extended-search').serialize();
    var selectedValue=$('#sex').val();
   jQuery.ajax({
    type: "POST",
    data: {'selected': selectedValue},
    url: "ajax.php",
    success: function (response) {
    // alert(submitSearchData);
    alert(response);
    }
   });
});

A: Is not possible in the same instance of time:
yourfile -> ajax -> yourfile (here is the value, but you can't see this in your current webpage except that instead of ajax, send post form)

A: I hope this will help you...
dataType: "html",
data: {'selected': selectedValue},

and then u can get it via $_POST/$_REQUEST array since you have set your type to post.

A: $_REQUEST is null because it is not related to the ajax request you send. Try this for example:
<?php
    if (isset($_POST["selected"])) {
    echo $_POST["selected"];
} else {
?>

        <form id="extended-search">

                <select class="select" name="sex" id="sex">
                    <option value="0">All</option>
                    <option value="1">M</option>
                    <option value="2">F</option>
                </select>

        </form>

<?php } ?>

EDIT:
I updated the script and tested it. You had some errors in your code. Hope this works for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convertir consulta select CROSS APPLY a LINQ Tengo una consulta de selección SELECT que implementa CROSS APPLY y tengo la necesidad de pasarlo a LINQ
Transact SQL Server
SELECT distinct(PC.ProductoCatalogoId),
P.Nombre + ' ' + PL.Product + ' ' + E.Nombre + ' ' + O.NombreOpcion AS   Descripcion,
    PC.PrecioVenta
FROM ProductoCatalogos AS PC
INNER JOIN Productos AS P ON PC.ProductoId = P.ProductoId
INNER JOIN EspecificacionCatalogos AS EC ON PC.ProductoCatalogoId = EC.ProductoCatalogoId
INNER JOIN EspecificacionProductos AS EP ON EC.EspecificacionProductoId = EP.EspecificacionProductoId
INNER JOIN Especificaciones AS E ON EP.EspecificacionId = E.EspecificacionId
AND E.EspecificacionId = 2
INNER JOIN Opciones AS O ON EC.OpcionId = O.OpcionId
CROSS APPLY (
    SELECT E.Nombre + ' ' + O.NombreOpcion AS 'Product'
    FROM ProductoCatalogos AS PC
    INNER JOIN Productos AS P ON PC.ProductoId = P.ProductoId
    INNER JOIN EspecificacionCatalogos AS EC ON PC.ProductoCatalogoId = EC.ProductoCatalogoId
    INNER JOIN EspecificacionProductos AS EP ON EC.EspecificacionProductoId = EP.EspecificacionProductoId
    INNER JOIN Especificaciones AS E ON EP.EspecificacionId = E.EspecificacionId
        AND E.EspecificacionId = 5
    INNER JOIN Opciones AS O ON EC.OpcionId = O.OpcionId

    ) PL
    WHERE P.Nombre LIKE '%ferr%'

LINQ, tengo el siguiente consulta no he podido avanzar mas porque no se como implementar CROSS APPLY en LINQ
public IEnumerable<ProductoCatalogo> SearchProduct(int colorId, int tallaId)
    {
        using (var context = new BusinessContext())
        {
            var result = from pc in context.ProductoCatalogos
                join p in context.Productos on pc.ProductoId equals p.ProductoId
                join ec in context.EspecificacionCatalogos on pc.ProductoCatalogoId equals ec.ProductoCatalogoId
                join ep in context.EspecificacionProductos on ec.EspecificacionProductoId equals ep.EspecificacionProductoId
                join e in context.Especificaciones on ep.EspecificacionId equals e.EspecificacionId
                join o in context.Opciones on ec.OpcionId equals o.OpcionId
        }
    }

Espero me puedan ayudar.
Saludos!


text:
Q: Contact form not delivering to my email I am using mail form and simple form to create a contact form for my website. I have used Mandrill as my email delivery service. Everything appears to be working fine according to my logs, but I do not get an email delivered to me when I do this.
MailForm::Notifier#contact: processed outbound mail in 359.2ms

Sent mail to example@gmail.com (787.8ms)
Date: Tue, 01 Dec 2015 13:20:59 -0500
From: "New ABA Conact Form Submission"
To: example@gmail.com
Message-ID: <message id>
Subject: My Contact Form
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

My Contact Form

Email:
  example@aol.com

Where I have 'example@gmail.com' is where my actual email is declared and it is entered correctly. I am working in a development environment. Do you guys know why I am not receiving the messages?


text:
Q: Integral $\int \frac{1}{\sqrt{1-2x-x^2}} \, dx$ I have simple integral that must be solved by substitution.
$$\int \frac{1}{\sqrt{1-2x-x^2}} \, dx = \int \frac{1}{\sqrt{2-(x+1)^2}} \, dx $$
After substitution $$u = x+1 $$
we get
$$\int \frac{1}{\sqrt{-u^2+2}} \, du $$
But i dont know how to continue. Thanks for any help.

A: Substitute $$\sqrt{1-2x-x^2}=tx+1$$ it is the so-called Euler substitution.

A: Try $\frac{u}{\sqrt{2}}=\cos({t})$ and use $\cos^2(t)+\sin^2(t)=1$.

A: Recall that
$$(\arcsin x)'=\frac1{\sqrt{1-x^2}}$$ and adapt to the given integral.

Use the change of variable $u=\sqrt2x$.

A: Now put $u=\sqrt{2}\sin\theta$


text:
Q: Display advanced custom field (ACF) value from custom post type taxonomy - wordpress In Wordpress I created a custom post type called "Sports" with a taxonomy called "sport_locations". Using the advanced custom field (ACF) plugin I created fields to show on taxonomy terms. I got everything to work, however I'm having trouble outputting the image I uploaded.
In ACF I have the option for the return value of the image to be: an object, url, or ID. Right now I have it set to object.
Below is the code I have so far. I'm writing this code inside of the single-sports.php . I created a foreach loop and only spitting out the terms associated to that specific sport.
When I do the var_dump I keep getting bool(false). Sorry for the extra commenting out in the code I was trying a bunch of different things and figured I'd leave it in my code as reference
post type = sports
taxonomy = sport_location
acf field = location_image (return value = object)
<?php
    $terms = get_the_terms( $post->ID , 'sport_locations' );
    //$LocImg = $wp_query->queried_object;

    // echo '
';
    // echo var_dump($LocImg);
    // echo '
';

    foreach ( $terms as $term ) {

    $term_thumb = get_field('location_image', 'sport_locations'.$term->term_id);

    echo '
';
    echo var_dump($term_thumb);
    echo '
';

        echo '
';

                echo'';
                //echo '';
                //echo 'term_id), "category"). '" class="img-responsive" />';
                //echo 'taxonomy . "_" . $LocImg->term_id ). '" />';
                echo '
slug .'/">'.$term->name .'
';

        echo '
';

    }
?>

A: There is supposed to be an underscore between the term name and the ID. So...
$term_thumb = get_field('location_image', 'sport_locations'.$term->term_id);

...should be...
$term_thumb = get_field('location_image', 'sport_locations_'.$term->term_id);

Alternatively, you can pass the term object...
$term_thumb = get_field('location_image', $term);


text:
Q: Finding the page id I'm not sure if I'm blind here, but short of digging directly into the database tables, where would I find the database id for a post or a page?

A: IDs always show in links in admin area, like /wp-admin/post.php?post=2164&action=edit
There are also some plugins that simplify this, quick search came up with Simply Show IDs.

A: Also, the status bar at the bottom of your browser is usually a convenient place to note the id when hovering over a link from within the admin

A: Another plugin that can do this (and one I use often) is "Reveal ID for admins" http://wordpress.org/extend/plugins/reveal-ids-for-wp-admin-25/

A: If you're a code geek, you might want to add <body <?php body_class('class-name'); ?>> and your body tag will show the page-id


text:
Q: Difference between execute current query and execute current script in oracle I need to complete multiple inserts in Oracle.
insert into  table_name (ID, code, date_t)
values (schema_name.SEQ$table_name.NEXTVAL, '232323232323'  , to_date('2020-09-01','YYYY-MM-DD'));
insert into  table_name (ID,  code, date_t)
values (schema_name.SEQ$table_name.NEXTVAL, '242424242424'  , to_date('2020-09-01','YYYY-MM-DD'));

I can't complete them when trying to use simple execute because it gives me an error: ora-00933 sql command not properly ended
But when I using execute as script it works fine.
The main problem is that I can't explain that to people how to complete that script in the console.
Maybe there are some other options to complete multiple inserts in Oracle?

A: Use INSERT ... SELECT:
insert into  table_name (ID, code, date_t)
WITH data (code, date_t) AS (
  SELECT '232323232323', DATE '2020-09-01' FROM DUAL UNION ALL
  SELECT '242424242424', DATE '2020-09-01' FROM DUAL
)
SELECT SEQ$table_name.NEXTVAL, code, date_t FROM data;

You could also use INSERT ALL; however, you have to jump through some hoops to get it to work with a sequence so I would suggest not using this option:
INSERT ALL
  WHEN rn = 1 THEN
    INTO table_name (id, code, date_t)
    VALUES (SEQ$table_name.NEXTVAL, '252525252525', DATE '2020-09-01')
  WHEN rn = 2 THEN
    INTO table_name (id, code, date_t)
    VALUES (SEQ$table_name.CURRVAL, '262626262626', DATE '2020-09-01')
SELECT LEVEL AS rn
FROM   DUAL
CONNECT BY LEVEL <= 2;


text:
Q: Notebooks or Desktop PCs for developers What are the pros and cons on this?
I am thinking on security, ease of replacement and maintainance, ...

A: This doesn't work for all cases since it requires a network connection, but I've been doing development/testing in a sandbox domain running entirely on virtual machines.  I have two virtual NICs on the dev machine spanning the sandbox and corporate network and sufficient resources to run Visual Studio comfortably.  So I just Remote Desktop in to work.
I've been impressed with the experience because I can easily revert to older snapshots if necessary (as I had to do recently when I forgot to turn off automatic updates).  As long as source files are checked in, there is nothing on the machine that needs to be persisted.
This doesn't fit all usage scenarios, but for ease of replacement and maintenance it's very good.

A: Before you consider any other points, first decide if you can justify the increased security risk from laptops.
If employees have laptops they can take home, there is significantly increased risk for either the hardware or data getting stolen or copied. Outside of your corporate network the machines are at a higher risk of infection for virii, spyware, etc. If they connect to the net in a public place they risk sending data in cleartext that should never be seen outside your company. And if the unthinkable happens and a laptop is physically stolen, there is a very small - but very real - chance of the source code to your company's entire code base getting in to the wrong hands.
I don't want to sound like the end of the world here, but letting your data leave the company premises is a major potential risk. There are ways to secure this (forcing data to go through a company VPN, etc), but those will take time and effort from you.

A: With reasonable laptops going so cheap nowadays, I would suggest that the middle way is the best: a powerful desktop for day-to-day operations and a laptop too for travel, work from home, VPN+RDP to the desktop from anywhere, etc.
This solution has better chances of keeping developers productive and data safe, since a stolen laptop will be less likely to have tons of information on it. Convenience will always erode security -- it is easier to keep everything nicely encrypted (TrueCrypt FTW!) on a side machine, that is not in constant use.

A: Notebooks: Developers can easily work at home (even after hours :-)

A: What I always liked about laptops for developers is all you need is an extra monitor to run dual, a huge benefit.
Most laptops come with 5400 RPM drives which just doesn't cut it and increases compiling time, so be mindful of the build. Sure you can lock the laptop down with drive encryption and other things, but they just make the developer whinny and they go out of their way to disable them.

A: I prefer a desktop for home and a desktop for work. This way, I can have dual monitors running. I know peeps say 'use the notebook display + an external', but that's not big enough / good enough, for me.
Security? Because it's not mobile, it's as secure as the location you work at. if anything, i won't loose it or break it (eg. drop it, etc).
Work from home? sure!! VPN + Remote Desktop to your machine.
Can u work at a cafe? nope :( Care factor though? zero :)
I love the new Macbook pro's and want one bad. But i couldn't do my programming on it because i'm greedy now and need 2x 24" LCD's. I can't go back. I've bitten the apple.
If u don't need 2x LCD's, then i would be all over a macbook pro for everything.
HTH :)

A: How about using a notebook connected to a big 19+ LCD at the office ?
You can get both the comfort of working with big monitor and the ease of carrying your computer anywhere you like.
I used to work with a dell XPS (switched to a macbook pro now) and connect it to a 19" samsung LCD at the office.

A: I think a high spec'd laptop is the way to go as long as it has a easy docking station when in the office or at home which easily connects to mulitple monitors and external keyboard and mouse.
Pros:

*

*You have a mobile dev environment.

*No synching for the developer from desktop to laptop to home etc.  They can just use their laptop everywhere.

*Developer has more freedom to work when ever and where ever they want if you company allows that.

Cons:

*

*Cost (more expensive hardware.  Laptop is more expensive of course, plus you need buy multiple extra monitors, keyboards, etc)

*Reliability (fixing a laptop can be more difficult than a desktop)

*Easy to lose / steal


text:
Q: How to add currency symbol without rounding value on asp.net page I have DiscountTotal variable with decimal type. Values are set on code behind the page, after page is loaded the values are rounded.
<%#DataBinder.Eval(Container.DataItem, "DiscountTotal","{0:C}")%>

Value 7610.3250D is being displayed as £7610.33. I like this to be displayed as £7610.32 or $7610.32 depending on logged in user. Current Culture settings are already there and i am only worry about rounding.

A: Try rounding with a MidpointRounding
decimal value = 7610.3250m;
string formattedValue = string.Format("{0:C}", decimal.Round(value, 2, MidpointRounding.ToEven));

A: Assuming that the underline datatype of your DiscountTotal property is System.Decimal, you could use this in order to provide the appropriated culture to the ToString method, so it can render the currency symbol based on the specified culture.
// For $, use en-US instead of en-GB.
// You must make this available in your session.
var sessionUiCulture = new System.Globalization.CultureInfo("en-GB");
...
...
<%# decimal.Round((decimal)DataBinder.Eval(Container.DataItem, "DiscountTotal"), 2, MidpointRounding.ToEven).ToString("C", sessionUiCulture) %>

Also, if you need this behavior across your application, the best way to accomplish this is by setting the property System.Globalization.CultureInfo.CurrentUICulture to the appropriated culture in your request pipeline, this way you don't have to worry about this.
Depending on what route you go, you should consider creating an extension method for this:
public static string ToCurrency(this decimal value)
{
    return decimal.Round(value, 2, MidpointRounding.ToEven).ToString("C");
}

So you could just do:
<%# ((decimal)DataBinder.Eval(Container.DataItem, "DiscountTotal")).ToCurrency() %>


text:
Q: Question regarding Cauchy sequence I am working on a problem in sequences. The theorem I am trying to prove requires the following implication. But I am not sure how to prove this. Kindly share your thoughts.
Let $(y_n)$ be a sequence which is not Cauchy but satisfies $\lim_{n\to\infty} d(y_n,y_{n+1})=0$. Then there exists an $\epsilon>0$ such that for every $n\in \mathbb N$, there exists an odd integer $q(n)\in \mathbb N$ and an even integer $p(n) \in \mathbb N$ with $n<p(n)<q(n)$, satisfying $d(y_{p(n)},y_{q(n)})\ge \epsilon$ and $d(y_{q(n)-1},y_{p(n)})< \epsilon$.
Thank you.

A: This is false as stated: we cannot make demands on the parity of the indicies $p(n)$ and $q(n)$. To see a counterexample, define $y_n$ as follows. For each $n$, write $n = 2k + r$ with $r \in \{0,1\}$ and define $\sum_{j=1}^{k} \frac{1}{j}$. Then $y_n$ satisfy that $\lim_{n \to \infty} d(y_n, y_{n+1}) = 0$ and the $y_n$ are not Cauchy as they are a sequence in $\mathbb{R}$ that does not converge.
On the other hand, for all $k$ odd, $y_k= y_{k-1}$ so for any integer $m$, $d(y_{m}, y_k) = d(y_m, y_{k-1})$, which rules out the desired feature for odd and even indicies from occuring for any $\epsilon > 0$.


text:
Q: Uncaught TypeError: $.ajax is not a function when trying to use gon.watch in cytoscape This is my code. It's part the configuration of a library for context menus, and get's triggered if I click on an item in the context menu. Then I see the error mentioned in the title.
{
  [...]
  onClickFunction: function (event){
    [...]
    gon.watch("nodes", {}, function(){})
  }
},


text:
Q: Write treble clef in tex? How to write treble symbol in Tex?
http://en.wikipedia.org/wiki/Clef

A: You may find the musixtex package useful. In the documentation you find more complex examples on how to use this package. Here just two small examples.
First
\documentclass{article}
\usepackage{musixtex}

\begin{document}
\begin{music}
\trebleclef
\end{music}
\end{document}

First result

Second
\documentclass{article}
\usepackage{musixtex}

\begin{document}
\begin{music}
\startextract
\Notes\ibbbu0h0\qb0e\tbbbu0\qb0e\tbbu0\qb0e\tbu0\qb0e\enotes
\zendextract
\end{music}
\end{document}

Second result

EDIT: Note that \begin{music} \end{music} is not necessary, I just recommend it, for it gives your code more structure and therefore makes it more readable.
Have Fun!


text:
Q: MUI React components not rendering Just started to learn react, and using the mui library.
I installed the MUI library with
npm install @mui/material @emotion/react @emotion/styled
I also installed the roboto font, and the icons.
Then i made a simple app that should just display MUI button.
App.js
import Button from '@mui/material/Button';

function App() {
  return (

Hello World!

      <Button variant="text">Text</Button>
      <Button variant="contained">Contained</Button>
      <Button variant="outlined">Outlined</Button>

  );
}

export default App;

Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

The three buttons have been copied directly from the library. When I run the app with npm start the page remains empty. The compilation is successful, there are no errors whatsoever. When i remove the buttons, the
 Hello World
 suddenly renders. When the buttons are left in the code, even the
 title disappears.
Why are the components not rendering?

A: Found the solution.
In my several attempts to get this to work I created multiple apps. Whenever I created the app using npm create-react-app I would then install the MUI library as described above.
The issue was that I did not cd to the app directory before installing the library. After changing directories the Buttons properly rendered.


text:
Q: Is the SqlDataReader.ExecuteReader skipped? I have the same problem as here :
Reader is not reading the data
the reader is never executed.
I am trying to read from a local db. what could it be? the db is not empty but i never receive the "hello from foo";
also it says that the reader doesn't have rows.
SqlConnection myConn = new SqlConnection("Data Source=(LocalDB)\\v11.0;Integrated Security=True");

SqlCommand comm = new SqlCommand("select * from employees;",myConn);

myConn.Open();
SqlDataReader reader = comm.ExecuteReader();

while (reader.Read())
{
    MessageBox.Show(reader[0].ToString())
    MessageBox.Show("hello from foo");
}
if (reader.HasRows)
{
    MessageBox.Show("reader.hasRows == true !");
}
else
{
    MessageBox.Show("reader.hasRows == FALSE !");
}

myConn.Close();

update:
i have changed the connection string to :" Data Source= my_server_name; Initial Catalog=employees; Integrated Security=True " now it works, thank you very much.


text:
Q: How can I go about diagnosing a poor performing Rails application running on mysql? I've taken over the maintenance of a Rails 2.3.4 application running on ruby 1.8.7 and mysql. The application is a modified Radiant CMS 0.8.1 site with custom extensions. Currently, the production environment is experiencing frequent periods of slow and sometimes no responsiveness. During these times I've noticed that the mysql CPU usage jumps through the roof. The web site has an international audience and at the time of it's creation scaling the site was not taken into consideration. Currently, the user base is at around 4600 and growing. What are some initial steps I can take to diagnose the poor performance in both Rails and mysql?
Thanks,
Mike

A: While not Rails-specific, I'd recommend using the MySQL slow query log and tracking those back to the queries your Rails application is sending (check log/production.log).

A: The last place I contracted used a tool called query_reviewer. It's a Rails plugin that in development mode analyzes every query and gives you warnings in the UI letting you know any possible issues. I liked it because you didn't have to switch back and forth between your app and log or other testing tools.
https://github.com/dsboulder/query_reviewer
Another helpful tool is New Relic - it's free for developing if you're just using it on your local. It analyzes more than just SQL, including view rendering and other potential efficiency issues.
http://newrelic.com/


text:
Q: Is it an anti-pattern to extract specific children to control where they are rendered? I am creating a reusable ContentHeading control that takes in an optional menu and submenu. Both the menu and submenu have very specific places I want them to render. The thing is, I need to give consumers of this component plenty of control over either menu to tailor it to the needs of their view.
Usually, I would just create two optional props for the component that can take in a Menu, and optionally render them where I need them if they are present. This works, but it looks a little messy declaratively, to me at least.
So I thought another possibility is to let them place the menus they want in their headers and assign them a specific key, and have render remove those from children and render them where I want, and all other children can be rendered as the heading.
Here's the code in question:
import * as React from 'react';

import { Grid, Menu, Header } from '../';

export interface ContentHeaderProps {
  heading?: string | React.ReactNode;
}

export class ContentHeader extends React.Component<ContentHeaderProps> {
  getComponent(children: React.ReactChild[], key: string) {
    return children.find((child: any) => {
      return (child.key && child.key === key);
    });
  }
  getHeadingComponents(children: React.ReactChild[]) {
    return children.filter((child: any) => {
      return !child.key || (child.key !== '.$menu' && child.key !== '.$submenu');
    });
  }
  render() {
    const children = React.Children.toArray(this.props.children);

    let heading;

    if (this.props.heading) {
      heading = this.props.heading;
    } else {
      heading = this.getHeadingComponents(children);
    }

    const menu = this.getComponent(children, '.$menu');
    const submenu = this.getComponent(children, '.$submenu');

    return (
      <div className="menu content">
        <Grid container padded="vertically">
          <Grid.Row>
            <Header
              floated="left"
            >
              {heading}
            </Header>
            {menu}
          </Grid.Row>
        </Grid>
        {submenu}
      </div>
    );
  }
}

And here it is in use:
<ContentHeader>
  <Menu key="menu">
    <Menu.Item>Test Menu</Menu.Item>
  </Menu>
  <Menu key="submenu">
    <Menu.Item>Test Submenu</Menu.Item>
  </Menu>
  Welcome!
</ContentHeader>

It works, but I'm not sure if this is an antipattern. I suppose the problem is that it's opaque what the capabilities of the component are.

A: This is not bad, in the end it's going to be all a matter of opinion and choice. If it works for you and you feel that it's maintainable, then that's fine.
However if I was to offer some guidance, what I would do is make those both be properties and where you then use the ContentHeader component, i'd create functions to return the items or store them in variables prior to there use and reference the variables.
<ContentHeader menu={this.createMenu()} subMenu={this.createSubMenu()}>
</ContentHeader>

The other option is that you could create the sub items as there own react components and pass in the component type as the value to the property and then use that component type, along with a list of items, to create the internal components by mapping over the list and creating the component.
The main value to all these is to increase test ability and reduce maintenance overhead.


text:
Q: Sort on two fields in MongoDB simultaneously I am currently developing a solution in MongoDB, where i have two different data schemas in the same collection. The problem is that some of the data has different field names. For example:
In one of the contracts a date is named: date_at, but in another type of contract it is just named date.
So the question is: How do i sort on one field, and if it is not present in the document, sort on the other instead?
Currently i am trying to make a query such as this:
db.collection('contracts').aggregate([
  {$project: {
    date_at: [ $ifNull: ['$date', null]
  }},
  {$sort: { date_at: -1 }}
]);

But it doesn't seem to work. Hopefully one of you will be able to help me. Thank you in advance.

A: $ifNull  is your solution :
taking the following documents set :
[
  {
    _id: 1,
    name: "c"
  },
  {
    _id: 2,
    name: "a"
  },
  {
    _id: 3,
    lastname: "b"
  },
  {
    _id: 4,
    name: "d"
  },
]

The following query will project name, or lastname if name doesn't exist, as name, and sort by name on second stage :
db.collection.aggregate([
  {
    $project: {
      name: {
        $ifNull: [
          "$name",
          "$lastname"
        ]
      }
    }
  },
  {
    $sort: {
      name: 1
    }
  }
])

Will result in :
[
  {
    "_id": 2,
    "name": "a"
  },
  {
    "_id": 3,
    "name": "b"
  },
  {
    "_id": 1,
    "name": "c"
  },
  {
    "_id": 4,
    "name": "d"
  }
]

$ifNull takes an array of 2 params : if first is null or not present, then use the second.

A: It sounds like you need to create a compound index.
A compound index consists of a single index which references multiple fields.
NOTE. It is important that the order of the fields in a compound index correspond to the order logic of your query's sort (see Sort Order).
Example:
Create compound index:
db.data.createIndex( { a:1, b: 1, c: 1, d: 1 } )

Find data with sort:
db.data.find().sort( { a: -1, b: -1 } )

More Info:
https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-on-multiple-fields
https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/


text:
Q: Change application.conf runtime? I want to set the database connection at run time for my Play project. I know that I can set a property run time with the following code:
@OnApplicationStart public class Bootstrap extends Job
{
   @Override public void doJob()
   {
     // now set the values in the properties file
     Play.configuration.setProperty("db.driver", dbDriver);
     Play.configuration.setProperty("db.url", dbUrl);
     Play.configuration.setProperty("db.user", dbUsername);
     Play.configuration.setProperty("db.pass", dbPassword);
   }
}

But when executing the code above the file is not actually changed, I think just in memory.
How can I set the database properties and force Play! to use this properties in order to connect to the right database onApplicationStart?
Thanks!
UPDATE 2012-01-29
Solution is possible via a plugin. In this plugin I have to override  onConfigurationRead() and apply the properties to the configuration file at that moment. I will try to post some code as soon as I have time for this.

A: By the time you change the properties, the DB plugin is already initialized. You need to write a plugin and overwrite the onConfigurationRead() method, then put your new settings there. Paly's dbplugin will init later on.

A: I faced with the necessity of programmatically obtaining values from aws secret manager in runtime before using that values in play framework configuration. You can override initial default values from application.conf and add new.
Work for play framework v2.7.3
import com.typesafe.config.ConfigValueFactory;
import play.api.Configuration;
import play.api.inject.guice.GuiceApplicationBuilder;
import play.api.inject.guice.GuiceApplicationLoader;

public class ExtendedGuiceApplicationLoader extends GuiceApplicationLoader {

    @Override
    public GuiceApplicationBuilder builder(Context context) {

        Configuration configuration = new Configuration(
            context.initialConfiguration().underlying()
                .withValue("db.default.username",
                     ConfigValueFactory.fromAnyRef("aws.secret.db.username"))
                .withValue("db.default.password",
                     ConfigValueFactory.fromAnyRef("aws.secret.db.password"))
        );

        return super.builder(
                new Context(context.environment(),
                            configuration,
                            context.lifecycle(),
                            context.devContext())
        );
    }
}

Don´t forget add this string to application.conf
play.application.loader="youpackage.ExtendedGuiceApplicationLoader"

A: Are you sure this is what you really intend to do?
Play offers the possibility to add different configurations in your application.conf
for example you could have:
db.url=mydefaulturl
%uat.db.url=uaturl
%prod.db.url=produrl
%prod1.db.url=prod1url

And then start the app with play start --%uat or play start --%prod


text:
Q: Applying the Open Mapping Theorem I have a problem answering this exercise that seems to me to be an application of the Open Application Theorem.
"Let $E, F$ Banach spaces and $T \in B(E, F)$ surjective, such that $T(B(0, r))$ is contained in a compact set for all $r> 0$. Show that $\dim E < \infty$."
Perhaps the result below (which I already know how to prove) will help in the resolution, but I can't make the adjustment.
"Let $N$ be a normed space with $\dim N = \infty$. Show that any subset that contains a non-empty open is not compact."
Any idea? Thanks in advance.

A: This is false. Let $E$ be any real Banach space and $T$ be a non-zero continuous linear functional on it. Then $T$ is surjective. The image of any bounded subset if $E$ is bounded in $\mathbb R$ and hence it is contained in a compact set. But $E$ need not be finite dimensional.


text:
Q: custom image in UIPicker I am trying to implement an image in a UIImagePicker that has only one component. I add an uimageview and a uilabel.  The catch is that the first row should NOT have an image as well as the 3rd row which I believe I have done right. My problem is that the images for each row are different so to solve this I have put them into an array of images and then based on what row is being passed in, I display the image. However; it is not working for me and seems to display the same image over and over. Can anyone tell me why? Thanks in advance!
imageNames= [[NSArray alloc] initWithObjects:@"9_stars.png", @"8_stars.png",@"7_stars.png",@"6_stars.png",@"5_stars.png",@"4_stars.png", nil];

/
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row
    forComponent:(NSInteger)component reusingView:(UIView *)view {

NSString *imageName= [imageNames objectAtIndex:theRow];
NSLog (@"the image name is %@", imageName);
NSLog (@"the current count is %d", theRow);

if(component == 0)
{
    if (row == 0 || row == 17)
    {

        UILabel *channelLabel = [[UILabel alloc] initWithFrame:CGRectMake(-80, 0, 320, 60)];
        channelLabel.text = [currentLottoNames objectAtIndex:row];
        channelLabel.textAlignment = UITextAlignmentLeft;
        channelLabel.backgroundColor = [UIColor clearColor];
        channelLabel.font = [UIFont boldSystemFontOfSize:20];
        channelLabel.backgroundColor = [UIColor clearColor];
        channelLabel.shadowColor = [UIColor whiteColor];
        channelLabel.shadowOffset = CGSizeMake (0,1);

        UIView *tmpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 60)];

        [tmpView insertSubview:channelLabel atIndex:0];
        return tmpView;

    }
    else {
        UIImage *img = [UIImage imageNamed:imageName];
        UIImageView *temp = [[UIImageView alloc] initWithImage:img];
        temp.frame = CGRectMake(120, 15,70, 27);

    UILabel *channelLabel = [[UILabel alloc] initWithFrame:CGRectMake(-80, 0, 320, 60)];
    channelLabel.text = [currentLottoNames objectAtIndex:row];
    channelLabel.textAlignment = UITextAlignmentLeft;
    channelLabel.backgroundColor = [UIColor clearColor];
    channelLabel.font = [UIFont boldSystemFontOfSize:20];
    channelLabel.backgroundColor = [UIColor clearColor];
    channelLabel.shadowColor = [UIColor whiteColor];
    channelLabel.shadowOffset = CGSizeMake (0,1);

    UIView *tmpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 60)];
   [tmpView insertSubview:channelLabel atIndex:0];
    [tmpView insertSubview:temp atIndex: 1];
    return tmpView;
}
   }
 }

EDITED CODE
 -(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row
    forComponent:(NSInteger)component reusingView:(UIView *)view {

NSString *imageName= [imageNames objectAtIndex:row]; // This is where the issue is I believe. What do I use to go through the whole image array?
NSLog (@"the image name is %@", imageName);
NSLog (@"the current count is %d", row);

if(component == 0)
{

       UILabel *channelLabel = [[UILabel alloc] initWithFrame:CGRectMake(-80, 0, 320, 60)];
        channelLabel.text = [currentLottoNames objectAtIndex:row];
        channelLabel.textAlignment = UITextAlignmentLeft;
        channelLabel.backgroundColor = [UIColor clearColor];
        channelLabel.font = [UIFont boldSystemFontOfSize:20];
        channelLabel.backgroundColor = [UIColor clearColor];
        channelLabel.shadowColor = [UIColor whiteColor];
        channelLabel.shadowOffset = CGSizeMake (0,1);

        UIImage *img = [UIImage imageNamed:imageName];
        UIImageView *temp = [[UIImageView alloc] initWithImage:img];
        temp.frame = CGRectMake(120, 15,70, 27);

    UILabel *channelLabel = [[UILabel alloc] initWithFrame:CGRectMake(-80, 0, 320, 60)];
    channelLabel.text = [currentLottoNames objectAtIndex:row];
    channelLabel.textAlignment = UITextAlignmentLeft;
    channelLabel.backgroundColor = [UIColor clearColor];
    channelLabel.font = [UIFont boldSystemFontOfSize:20];
    channelLabel.backgroundColor = [UIColor clearColor];
    channelLabel.shadowColor = [UIColor whiteColor];
    channelLabel.shadowOffset = CGSizeMake (0,1);

    UIView *tmpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 60)];

    [tmpView insertSubview:channelLabel atIndex:0];
    [tmpView insertSubview:temp atIndex: 1];
    return tmpView;
 }
 }

A: Your problem is "theRow" - its not even defined in this method. You should just put a placeholder string in the array - that is at position 0 and 17 just put @"". Now you can use "row" to index into your array and all will be well.
EDIT: So your code implies you have 18 rows, want to show an image in most rows, but do something different for rows 0 and 17. Thus, you need an array of size 18.
imageNames= [[NSArray alloc] initWithObjects:
@"", // row 0 unused
// 1 - 6
@"9_stars.png", @"8_stars.png",@"7_stars.png",@"6_stars.png",@"5_stars.png",@"4_stars.png", nil];
// 7 - 12
@"9_stars.png", @"8_stars.png",@"7_stars.png",@"6_stars.png",@"5_stars.png",@"4_stars.png", nil];
// 13 - 16
@"9_stars.png", @"8_stars.png",@"7_stars.png",@"6_stars.png",
// 17
@"" // not used
// keep adding
nil];

The concept is to insure that you always have the same number of objects in the array as you have rows.
You can add an assert at the start of this method:
assert(row < [imageNames count]);

which will cause an exception if what you believe to be true turns out not to be.


text:
Q: Is there a other way to reset fields I'm trying to create a reset spreadsheet function to clear the spreadsheet.
Now i use loops to define the values for each column. 'Dikte' Needs to be set to 6. And the first column needs to be false. clearContent clears everything. Is there a nicer way?
  var values = [];
  for (i = 0; i < 12; i++) {
    values.push([false,'','','','','6','0'])
  }
  var oldoak_data = SS.getRangeByName('oldoak_data').setValues(values);

A: Explanation:
Solution 1:

*

*You could get rid of the for loop by using map. This will give you some boost in performance since map is faster than the regular loops.

*Generally, since this approach overwrites the previous values, it is a good idea to clear the content before we set the new values.
Solution 2:

*

*Another idea would be to define a sheet object by its name. In my case Sheet1. Clear only the desired range, 'A2:E13' and set the values of the other two columns to 6 and 0 respectively. Not sure if this approach is faster, but it could be more efficient.

Solutions:
Solution 1:
function resetFields() {
  const SS = SpreadsheetApp.getActive();
  const rng = SS.getRangeByName('oldoak_data');
  const values = rng.getValues().map(r=>[false,'','','','','6','0'])
  rng.clearContent();
  rng.setValues(values);
}

Solution 2:
function resetFields() {
  const SS = SpreadsheetApp.getActive();
  const SH = SS.getSheetByName('Sheet1');
  const rngClear = SH.getRange('A2:E13');
  rngClear.clearContent();
  SH.getRange('F2:F13').setValue(6);
  SH.getRange('G2:G13').setValue(0);
}

Example sheet for Solution 2:


text:
Q: Jekyll different permalinks for posts than other pages I am using permalink: pretty for all of my site (static pages).
However for blog posts, I would like to use permalink: /blog/:year/:month/:day/:title/.
How do I set two different permalink styles?

A: My working solution, in _config.yml:
permalink: pretty
defaults:
  -
    scope:
      path: ""
      type: "posts"
    values:
      category: blog

Since the pretty settings prepends the category to the path, I set that all posts should have a category of blog.


text:
Q: how to insert list of values into datatable in spring hibernate I need to insert multiple rows of values into same table at a single submit.
In ajax
$("#btn_themDay").click(function(){
$("#themDay_validation").hide();
var no_row = Number($('#tbl_videoDetails').find("td.lastno").text());
var videoDetails_valid = true;
var name = new Array();
var land = new Array();
var area = new Array();
var District = new Array();
var thaluk = new Array();
var i;

for(i=1;i<=no_row;i++){     // validdation
    name[i]=$("#vodtitle"+i).val();
    land[i]=$("#vodtime"+i).val();
    area[i]=$("#voduploadImage"+i).val();
    District[i]=$("#vodurl"+i).val();
    thaluk[i]=$("#voddes"+i).val();

$.ajax({
    url: "savefull",
    type: "POST",
    data: {values:name},
    traditional: true,
    dataType: "json",
    cache: false,
    success: function (data) {

    }
});

return false;   // for testing return false

});
I catch the data in controller like this
    @RequestMapping(value="savefull",method=RequestMethod.POST)
    public @ResponseBody ThematicDay savefull(@ModelAttribute("Data") Data values){
        try{
            System.out.print("Value "+values+"        ");

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
        return null;

    }

But I don't know how to insert it in my dao using the hibernate query.

A: You can use Batch Inserts
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}

tx.commit();
session.close();

A: Firstly make a object which will be used for transferring the data in and out from db.
@Entity
@Table(name = "data_table")   // let the table name be "data_table"
public class PData {
@Id
@Column(name = "data_id")
private String id;

@Column(name = "xyz")
private String xyz;

public PData() {
    // Initialize
}

write getter and setters
}

Then create a repository which will communicate with the db. You can use JPA Repository for handling it.
public interface DataRepository extends JpaRepository<PData, String> {
@Query("from PData where data_id = ?1")
List<PData> findByKey(String data_id);
}

For saving the Data create an object of DataRepository and call save method passing the PData Object;
For example:
DataRepository dr = new DataRepository();
PData pd = new PData();
pd.setName("xyz");
pd.setId(id);
//set all the values
dr.save(pd);
// then save to db


text:
Q: ANN symbolic parameters My input parameters for the neural network contain symbolic data. I do not understand whether it is possible to submit data in this form or needed to normalize.
Is it not true? And how can I fix it?

A: Neural networks are not symbolic networks. They work only on the numeric data. If by "symbolic" you mean categorical (like "cat", "dog") then typical approach is to use one hot encoding. However, if by symbolic you mean actual symbolic (like "a+b-2^c", "a*b") then there is no specific way to go, and it is a problem-specific question, impossible to answer without exact specification of data and lots of research.


text:
Q: Database is in localhost of server. How to connect with it remotely My hosting site provided me phpMyAdmin on server's localhost. How to connect remotely to MySql using remote tool as Session Manager or MySql Workbench.
When i work database in my website i use hostname as localhost. So question is what to fill in hostname in workbench. I already tried hosting site ip address, but couldnt connect with database.
A screenshot

A: From the figure, you shared I can see you are using HeidiSQL software to connect with a remote MySQL server. Hostname/IP should be your hosting IP address provided by your hosting provider. You need to verify the port where your MySQL is running. Here you have set 3306 which is the default port. It could run on a different port. In the User and Password fields, you should use your username and password to login into your hosting server.


text:
Q: Fabric.js Images blurry I am using Fabric.js and jQuery UI for a drag and drop scene creator. When I drag and drop an image into the canvas the image becomes blurry/pixelated and appears to be zoomed in. I've been searching Stackoverflow and Google forever and can't find any solutions. I'd appreciate any suggestions on how to fix it!
Here is my code:
// HTML

<canvas id="scene"></canvas>

// Draggable setup

$('.scene-item').draggable({
    helper: 'clone',
    appendTo: 'body',
    containment: 'window',
    scroll: false,
    zIndex: 9999
});

// Drop Setup

var canvas = new fabric.Canvas('scene');

canvas.setDimensions({
    width: '800px',
    height: '500px'
}, {
    cssOnly: true
});
document.getElementById("scene").fabric = canvas;

canvas.on({
    'object:moving': function(e) {
        e.target.opacity = 0.5;
    },
    "object:modified": function(e) {
        e.target.opacity = 1;
    }
});

$('#scene').droppable({
    drop: function(e, ui) {
        if ($(e.target).attr('id') === 'scene') {
            var pointer = canvas.getPointer();
            fabric.Image.fromURL(ui.draggable[0].currentSrc, function (img) {
                console.log(img);
                img.set({
                    left: pointer.x - 20,
                    top: pointer.y - 20,
                    width: 52,
                    height: 52,
                    scale: 0.1
                });
                //canvas.clear();
                canvas.add(img);
                canvas.renderAll();
            });
        }
    }

});

This is what the images look like on and off the canvas:

Here is a demo jsfiddle.net/dmLr6cgx/1

A: I figured out the problem. I had to replace:
canvas.setDimensions({
        width: '800px',
        height: '500px'
    }, {
        cssOnly: true
    });

with
canvas.setHeight(500);
canvas.setWidth(800);
canvas.renderAll();

And now it works fine.


text:
Q: Never ending 'for' loop prevents my RStudio notebook from being rendered into a .md file I'm trying to calculate the Kolmogorov-Smirnov statistic in R. I have the following sample, which clearly comes from a random variable that follows a long-tailed distribution.

Download link

https://drive.google.com/file/d/1hIgqikX7p343zdyc-Goq34THUpsZA63n/view?usp=sharing

As you may know, the Kolmogorov-Smirnov statistic requires the calculation of the empirical cumulative distribution function and the presumed cumulative distribution function. For both calculations I take the following approach: first, I create a vector with the same length as the length of the sample, and then I modify each of the components of the vector so as for it to contain the empirical cdf (or presumed cdf) of the corresponding observation of the sample.
For the sake of illustration, I'll show you the code I wrote in order to calculate the empirical cdf.

I'm assuming that the data has been read and stored in a dataframe called data.

ecdf = vector("numeric", length(data$logueos))for (i in 1:length(data$logueos)) {ecdf[i] = sum (data$logueos <= data$logueos[i])/length(data$logueos)}

The code I wrote for the calculation of the presumed cdf is analogous to the preceding one; the only difference is that I set each component of the pcdf vector equal to the formula $P(X<=t)$ —where t is the corresponding observation of the sample— according to the distribution that I'm assuming.
The problem is that this 'for' loop never ends. If I force it to end by clicking RStudio's stop button it works: it makes the vector store what I want it to store. But, if I press Ctrl+Shift+k in order to render my notebook and preview it, the load gets stuck when trying to execute the first chunk encountered that contains one of those loops.

A: First of all, your loop is not endless. It will finish, eventually.
You start initializing a vector with as much elements as the number of observations (1.245.888, which is a lot of iterations). This vector is FULL OF ZEROS.
What your loop does is iterate while changing each zero with the calculus sum (data$logueos <= data$logueos[i])/length(data$logueos). Check that when you stop the execution, the first values of your vector will be values between 0 and 1 while the last values is going to be 0s (because the loop hasn't arrived there yet).
So, you will have to wait more time.
In order to make the execution faster, you could consider loop parallelization (because standard loops go sequentially, one by one, and if it's too much wait, parallelization makes it faster. For example, executing 4 by 4, depending of your computer capacities). Here you'll find some information about it: https://nceas.github.io/oss-lessons/parallel-computing-in-r/parallel-computing-in-r.html
Then, my proposal to you:
if(!require(foreach)){install.packages("foreach")}; require(foreach)
registerDoParallel(detectCores() - 1)

ecdf = vector("numeric", length(data$logueos))

foreach (i=1:length(data$logueos)) %do% {
  print(i)
  ecdf[i] = sum (data$logueos <= data$logueos[i])/length(data$logueos)
}

*

*The first line will download and load foreach library, that you
need for parallelization.

*detectCores() - 1 is going to use all the
processors that your computer has except one (to avoid freezing your
machine) for computing this loop. You'll see that is going to be
faster!

*registerDoParallel function is what tells to foreach how many cores use.


text:
Q: SQL Help for combining two queries I want to combine these two SQL queries into one. Any idea on how do I do it?
Select A, B, C
from table1
where condition1

select D
from table2
where table1.B=table2.E

(table2 has the mapping of column B of table1)
I just want to fetch A,B,C,D in a single select query. Any help would be appreciated.

A: INNER JOIN (read up on joins here http://www.w3schools.com/sql/sql_join.asp)
SELECT A, B, C, D
FROM table1 t1
INNER JOIN table2 t2 ON t1.B = t2.E
WHERE condition1

A: You could use a join:
select A, B, C, D
from table1
left join table2
on table1.B = table2.E
where condition1


text:
Q: Check for Internet connectivity in Angular2 (not Ionic) Cordova app We have created an Angular2 Cordova (not Ionic) app that makes many calls to backend services.
We would like the app to show a specific page (Component) if the user has no connection. We have that all built, however how do we sense the connectivity and then show the page?
The app is written in TypeScript, I was thinking I could add some code to the index.ts file to accomplish this, but the index.ts file doesn't understand the app's navigation to allow me to change the page.
I know I need the Cordova Network Information plugin and I know how to use that to check for connectivity, but the missing piece is hooking that up so that it can change the page (route to the appropriate component).

A: After you have install the Cordova Network Plugin this check every second:
setInterval(
    function(){
      if(!navigator || !navigator.network) return; //if is undefined

      if(navigator.network.connection.type == Connection.NONE){
            alert("nocon");
        }else{
            alert("yescon");
        }
    }, 1000
);

A: This plugin provides an implementation of an old version of the Network Information API. It provides information about the device's cellular and wifi connection, and whether the device has an internet connection.
cordova plugin add cordova-plugin-network-information

here is example for your
  module.controller('MyCtrl', function($rootScope, $cordovaNetwork) {

      document.addEventListener("deviceready", function () {

        var type = $cordovaNetwork.getNetwork()

        var isOnline = $cordovaNetwork.isOnline()

        var isOffline = $cordovaNetwork.isOffline()

        // listen for Online event
        $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
          var onlineState = networkState;
        })

        // listen for Offline event
        $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
          var offlineState = networkState;
        })

      }, false);
    });

for further information Please visit the reference link


text:
Q: Get current date and time from Google in Android I have some experience in Android application development. Now we developed an Android application where we need the exact date and time from Google or the internet. Already I test some code from Stack Overflow and from some other sites, but it did not work correctly. The app crashed. Can anyone help me?

A: Try this:
private long getTime() throws Exception {
    String url = "https://time.is/Unix_time_now";
    Document doc = Jsoup.parse(new URL(url).openStream(), "UTF-8", url);
    String[] tags = new String[] {
            "div[id=time_section]",
            "div[id=clock0_bg]"
    };
    Elements elements= doc.select(tags[0]);
    for (int i = 0; i <tags.length; i++) {
        elements = elements.select(tags[i]);
    }
    return Long.parseLong(elements.text() + "000");
}

Gradle:
compile 'org.jsoup:jsoup:1.10.2'

A: This is enough to get what you wanted:
Using the HttpGet, Client and Response, I manage to get a server's current time from the response Date Header. I can call this all the times I want and will get confident responses (Google is almost 100% available and I can trust on getting correct Date and Time)
try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            String dateStr = response.getFirstHeader("Date").getValue();
            //Here I do something with the Date String
            System.out.println(dateStr);

        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    }catch (ClientProtocolException e) {
        Log.d("Response", e.getMessage());
    }catch (IOException e) {
        Log.d("Response", e.getMessage());
    }

A: ou can get time from internet time servers using the below program
import java.io.IOException;

import org.apache.commons.net.time.TimeTCPClient;

public final class GetTime {

public static final void main(String[] args) {
    try {
        TimeTCPClient client = new TimeTCPClient();
        try {
            // Set timeout of 60 seconds
            client.setDefaultTimeout(60000);
            // Connecting to time server
            // Other time servers can be found at : http://tf.nist.gov/tf-cgi/servers.cgi#
            // Make sure that your program NEVER queries a server more frequently than once every 4 seconds
            client.connect("nist.time.nosc.us");
            System.out.println(client.getDate());
        } finally {
            client.disconnect();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

1.You would need Apache Commons Net library for this to work. Download the library and add to your project build path.
(Or you can also use the trimmed Apache Commons Net Library here : https://www.dropbox.com/s/bjxjv7phkb8xfhh/commons-net-3.1.jar. This is enough to get time from internet )
2.Run the program. You will get the time printed on your console.


text:
Q: Codeigniter4 redirect()->to() is not working On CI4, I'm trying to redirect the user to admin/login when the admin is not loggedin.
$this->session->isAdminLoggedIn is working as it should. But when I goto admin/index the user is not redirected and the statement echo __METHOD__; is being executed. What am I doing wrong?
<?php

namespace App\Controllers\Admin;

use CodeIgniter\Controller;
use App\Controllers\BaseController;

use Config\Services;

class Admin extends BaseController{

    protected $session;

    public function __construct(){
        $this->session = Services::session();
    }

    private function admin_login_check(){
        if ( !$this->session->isAdminLoggedIn ){
            $R2 = urlencode( current_url() );
            return redirect()->to('admin/login?r2='.$R2);
        }
    }

    public function index(){
        $this->admin_login_check();
        echo __METHOD__;
    }

}

A: As @ViLar starts to point out, it's how you're returning (or rather not returning) that Response object.
redirect()->to() does not perform a redirect immediately, on the spot, when called. It returns an object that in the end, must be returned by the Controller itself in order to work.
You are returning that object from admin_login_check() to index() but then completely ignoring it in index(); as such the Controller is never actually receiving or returning the object created by the call to redirect().
If you're going to return redirects from within nested function calls, you need to make sure that Response object returns all the way up that stack such that the initial Controller method called actually returns it as well.


text:
Q: "Invalid constraint: the type used for the constraint is sealed" is invalid I'm wish to use F#'s type inference to infer the types of my code simply by the methods/functions that are called.
This CAN be achieved quite nicely by using extension methods of the form...
[<Extension>]
type AttributeExtensions =
    [<Extension>]
    static member ``BroadcastOffset``<'a, 'b when 'a :> ``BroadcastOffset``<'b>> (this: 'a) =
        this.``

when I have code that reads
x.BroadcastOffset()

type inference will kick in and infers that x, must indeed be of type BroadcastOffset<'a>.
A small fly in the ointment though is F#'s own types for example, if I write
x.Value

F# will not infer its an Option<_>, thats understandable, but I can use the same extension trick to get there?
[<Extension>]
type AttributeExtensions =
    [<Extension>]
    static member Value<'a,'b when 'a :> Option<'b>> (this: 'a) =
        this.Value

and that SHOULD in theory mean
x.Value()

should trigger the inference of x being an Option<_>
sadly this ISNT the case, because F# rejects the extension method as an invalid constraint because Option<_> is sealed and thus 'a can only have 1 solution.
True 'a CAN only have 1 solution but, in my book that does NOT make the constraint invalid, it is perfectly valid, just trivial to infer, and because of this overzelous rejection, I am frustrated in making "Value" trigger type inference.
any ideas how to get around it? (apart from changing the F# compiler myself).
(I can of course define a function 'Value' instead, but my intention is to use F# to infer types from "methods", and extension methods fit the requirement where simple functions don't...I have my reasons)

A: I got compile errors using your code and then factored out what I think you are after into a function, then used the function in the extension. This allowed me to call .Value() and it work out that it was of type 'a option which is what I think you were after?
open System.Runtime.CompilerServices

let v (x : 'a option) = x.Value

[<Extension>]
type AttributeExtensions =
    [<Extension>]
    static member Value(this) = v(this)

let myFunc o = o.Value()


text:
Q: Serialization of Azure Service Bus BrokeredMessage I have a stateless RESTful service that will Peek & Lock off of an Azure Service Bus queue.  After it gets the message, it will forward the message on to a client who will process it.  The client may take longer than the lock timeout to process the message.
The client cannot talk to the queue directly and I would prefer to not add any state to the service.  Instead, I want to send enough information to the client such that they can send it back and the service can renew the lock on their behalf.
So, how do I serialize a BrokeredMessage such that I can renew the lock on it after deserializing it?
Alternatively, is there some way I can get a token for a BrokeredMessage such that I can renew the lock or delete the message from the queue using just that token (rather than the entire message)?

A: Per the Azure Service Bus REST API reference, the renew action requires the MessageId and the LockToken, both of which are available as properties on the BrokeredMessage object. You should be able to use those to fire off a REST request to renew your lock.

A: All you need to abandon a message is the lock token which is just a Guid so it serializes nicely.  Using the Azure Service Bus SDK (via NuGet) the following test will pass if run multiple times in a row on a queue with one message in it.  If you remove the queueClient.Abandon(lockToken) line then the test will fail on every run after the first until the lock times out (1 minute default).  This is because brokeredMessage is null since there are no messages available to be received as long as the one message in the queue has a lock taken out on it.
[Fact]
public void receive_lock_abandon()
{
    const String connectionString = "Endpoint=sb://stayupdated.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=X/LX7IFHLADiAMgn5zGoSlCYCriwa68An1hijB3rGXQ=";
    const String queueName = "TestQueue";

    var receiveClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
    var brokeredMessage = receiveClient.Receive(TimeSpan.FromSeconds(1));
    var serializedLockToken = brokeredMessage.LockToken.ToString();

    var lockToken = Guid.ParseExact(serializedLockToken, "D");
    var queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
    queueClient.Abandon(lockToken);
}


text:
Q: Prove by induction. If $a_1\geq a_2,a_2\geq a_3,...a_{n-1}\geq a_n$, then $a_1\geq a_n$ with equality iff all a's are equal.
My attempt at a solution:
Suppose n=2, if $a_1\geq a_2$. Clearly then $a_1 \geq a_2$, with equality if $a_1=a_2$ is true.
This is the step I'm not sure about
Then assume $a_1\geq a_{n-1}$, which implies that $a_1-a_{n-1}\geq0$. With equality when $a_1=a_{n-1}$
Also $a_{n-1}\geq a_n$ is given which implies that $a_{n-1}-a_n\geq 0$
We can then add these 2 inequalities $(a_1-a_{n-1})+(a_{n-1}-a_n) \geq 0$
We find that $a_1-a_n\geq 0$
Therefore, by induction
$a_1\geq a_n$, with equality iff all a's are equal.
I'm not sure if the second step works as I believe the property I'm trying to prove isn't really that $a_1 \geq a_n$ but that $a_1\geq a_2$ and $a_2\geq a_3$ implies $a_1\geq a_3$ and I assumed this property in the second step.
Appreciate any help/critique of my technique here.

A: I'll use '>' instead of using '≥', and also won't worry about sub-scripting, and use capitalization instead.
An induction step assumes that if a proposition predicated of n holds, then the same proposition predicated of the successor member S(n) holds also.  Or in other words, P(n) implies that P(S(n)), or "if P(n), then P(S(n))".  Here, the successor of n is just (n + 1).
Now, what is the proposition predicated of n here?
The proposition is the entire if-then statement that you posted.
Thus, changing from using the variable 'n' to 'k' to avoid confusion between the proposition itself and if-then the induction step, the induction step can get written as:
If "If A1 > A2, ... , A(k - 1) > Ak, then A1 > Ak" [this entire if-then part I call the first hypothesis], then "if A1 > A2 ... Ak > A(k + 1) [only the if  part of this I call the second hypothesis], then A1 > A(k + 1)".
Now, by the second hypothesis A1 > A2, ..., A(k - 1) > Ak.  Thus, by detachment and the first hypothesis, A1 > Ak.  Ak > A(k + 1) also holds by the second hypothesis.  Thus, (A1 - Ak) > 0 and Ak > A(k + 1).
Lastly, adding the inequalities eventually yields A1 > A(k + 1).
So, your technique had potential here.


text:
Q: Building a non-uberjar Docker image with leiningen I have a clojure project that depends on a Java library, that does not work, when it gets included in an uberjar. (It needs different XML descriptors using the same filename in different JAR files.)
Everything I find on using Docker with leiningen depends on building and packaging a uberjar. That's also how I built all clojure Docker images so far.
Is there any leiningen plugin out there, that understands to package a Docker image using several jar files like io.fabric8/docker-maven-plugin does?

A: Whenever packaging (uberjar, war) the big file that is created contains .class files and a directory structure. Where are these XML files supposed to be (class)loaded from? You can experiment with packing manually. After all it (whether uberjar, war or jar) is just a zip file.
When you know exactly the layout you need SBT is flexible enough to insure you can package from the many input jar files. Unfortunately lein plugins will do things like always overwrite duplicates, and you can't control the packaging behaviour. I can't remember exactly the inflexibilities, but I couldn't control how the packaging process went, what decisions were made.
For doing it manually I use a Linux something called Archive Manager, which I found to be much better than what I used when on Windows. Doing it manually may be all you need. The downside of SBT of course being that you have to learn it, which includes a bit of Scala.

It needs different XML descriptors using the same filename in different JAR files.

Just thinking about this, is it that you need to append the contents of each file that is in a different jar into the one file that is in the uberjar? You can try it out. If it works and you need to package up often enough that manually creating and renaming a zip file every time becomes a pain, then I believe that SBT will be your best bet.

I have to package my container with the original jar file and then reference this jar in the classpath when starting the application

The classloader loads classes rather than jars. It is the container's job to unpackage all the things you give it, such as .class files, (uber)jars, wars. Any program that dynamically loads from the classpath is loading either classes or resources (things like .xml files). I suppose a .jar file could be a resource, in which case you would put the jar file in the uberjar. So it is still possible to package it up.


text:
Q: Prototype $ and $$ with special characters Is there anyway by which i can use the $ or $$ utility selectors with arguments containing special characters?

$('my example')

$$('div.item1\item2')

I've tried using the standard escape sequence \ but am having no luck.

A: Arguments to those functions can contain ids of elements. As the spec says:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
  followed by any number of letters,
  digits ([0-9]), hyphens ("-"),
  underscores ("_"), colons (":"), and
  periods (".").

This implies that special characters within ids are not allowed.


text:
Q: Nature of covalent bonds in higher dimensional physics? In our 3+1 dimensional world covalent bonds occur because electron pair are shared between atoms. How many electrons are needed to form a covalent bond in a n+1 dimensional world?
The reason this is not entirely obvious is that there are more spin quantum numbers in a high-dimensional world. In our world there is just one spin, and hence two electrons with opposite spins are allowed to have otherwise equal quantum numbers, spreading out between the two atoms. Hence we end up with two electrons involved in the bond.
In a $n$ dimensional space there are $\lfloor n/2 \rfloor$ separate angular momenta, and it seems reasonable (but more complex to analyze properly) that there would be more spin quantum numbers. So does that mean that we could have not just 2-electron covalent bonds, but k-electron pair bonds (up to $k=n/2$)?  Or do we need $n$ electrons to make a covalent bond? Or even $2^{n/2}$ so each combination of spin quantum numbers is present?
(Ionic bonds appear much easier to model, although the rapid decay of electromagnetic attraction would make them weaker.)

A: What has been bothering me for some time is the binding of spherical harmonics to Cartesian coordinates in QM.  This gives an artificially constructed distinction between the first two electrons of the second and third shells and the remaining 6 electrons. Thereby there are solutions of spherical harmonics, which allows an equally distributed arrangement of 8 electrons. And this completely without additional dimensions.
Interestingly, the distribution of electrons in the Cartesian coordinate system leads to a geometric frustration. Although we are always looking for symmetries and equilibrium states.
I run the risk to lose the reader if I use the duplicity of spin and magnetic dipole and ask the reader to consider the distribution of the electrons also as the distribution of their magnetic dipoles. But please, try it only once.
If you distribute the 8 electrons of the second and third shell to two tetrahedra pushed into each other, you get a frustration-free geometry. This is possible if the magnetic dipoles of the electrons are aligned to the nucleus. The 4 electrons of the one tetrahedron are directed with the north poles inwards. The dipoles on the other tetrahedron are then of course directed inwards with the south poles.

This brings us back to Gilbert N. Lewis valence theory with his cubical atom.
Here is the corresponding spherical harmonic:


text:
Q: How to name two variables that have the same meaning but different types I have a method that parses a String and converts it to a boolean.
The legal values are "true" and "false".
boolean convertStringToBoolean(String text) {
  if (text.equals("true") {
    return true;
  } else if (text.equals("false")) {
    return false;
  } else {
    throw new IllegalArgumentException(text);
  }
}

When I use this variable, I get a naming problem.
void doSomething(String isSpecificReadString) {
  boolean isSpecificRead = convertStringToBoolean(isSpecificReadString);
  ...
}

The problem is that the parameter carries a meaning that I want to keep in its name.
The meaning doesn't change just because the type is changed.
So far, my solution has been to just suffix the type to the parameter.
But I don't like this solution.
What should I call the variables to solve this problem?

A:
So far, my solution has been to just suffix the type to the parameter.
  But I don't like this solution.

Strongly typed language as Java works in this way.
Variables cannot change their type at runtime.
You have to accept the language constraints.
Converted a data from a type into another type within a method may create this issue.
But your actual solution is rather fine.
The intention is clear and you kept a natural name for the target variable.
You indeed added the type suffix only for the input that will be converted (temporary/intermediary variable), not for the output that will be used in the next statement(s).

A: As inspired by Andy Turner, I can make two doSomething methods.
A method that takes a String and another that takes a boolean.
The String method can then call the boolean method.
As follows:
void doSomething(String isSpecificRead) {
  doSomething(convertStringToBoolean(isSpecificReadString));
}

void doSomething(boolean isSpecificRead) {
  ...
}


text:
Q: Node-webkit notification sound I've made a function for my node-webkit application to trigger a OS X notification. It works perfectly but I wonder if I can set a system or custom sound instead of the classic iPhone boing sound?
I've looked up the official notification API documentation from Mozzila (https://developer.mozilla.org/en-US/docs/Web/API/notification) and there is no sound option, however maybe node-webkit implanted that function (can't imagine they didn't) but if they did, I can't seem to find any documentation about it.
So my question is, is there a sound option for notifications in node-webkit?
function notif(title ,tekst, url){
    var notice = new Notification(title, {
        body: tekst
    });

    notice.onshow = function(evt) {
        setTimeout(function(){notice.close()}, 5000);
    }

    notice.onclick = function(evt) {
        gui.Shell.openExternal(url);
        setTimeout(function(){notice.close()}, 1000);
    };
}

A: The unwanted iPhone sound has been fixed/removed in a recent node-webkit pull request and is released.
As for generating my own sounds, I use a wrapper around the raw notifications object so that whenever I call the notification show command I also play a sound, as appropriate.
/**
 * Use composition to expand capabilities of Notifications feature.
 */
function NotificationWrapper(appIcon, title, description, soundFile) {

    /**
     * A path to a sound file, like /sounds/notification.wav
     */
    function playSound(soundFile) {
        if(soundFile === undefined) return;
        var audio = document.createElement('audio');
        audio.src = soundFile;
        audio.play();
        audio = undefined;
    }

    /**
     * Show the notification here.
     */
    var notification = new window.Notification(title, {
        body: description,
        icon: appIcon
    });

    /**
     * Play the sound.
     */
    playSound(soundFile);

    /**
     * Return notification object to controller so we can bind click events.
     */
    return notification;
}

To use it, we simply invoke it using the new keyword:
var myNotification = new NotificationWrapper(
    '#',    // image icon path goes here
    'node-webkit is awesome',
    'Especially now that I can use my own sounds',
    '/sounds/notification.wav'
);

myNotification.addEventListener('click', function() {
    console.log('You clicked the notification.');
});


text:
Q: Syntactic sugar for knowing if all array elements return true for specific method? In my Ruby program, I have an array of five strings, and I want to check if each one of the elements of that array match to a given requirement, for example:
a = ['', '', '', '']
a.inject(:blank?) # Will return true if (and only if) all elements of a are blank

I'm asking this question because Ruby has a pretty large standard API with a lot of pre-written syntactical sugar, which I want to know and don't want to reinvent.

A: There is a very concise way:
array.all? &:blank?

Study Enumerable and learn how to use Enumerators and you'll be speaking the most pleasant dialect of Ruby in no time.

A: Just an alternative way: if you have String#to_proc (search it because I would not post my own depository site in case being considered as ads), you can use a similar way you have:
a.inject(&'&& $1.blank?')
which is equivalent to
a.inject{ |sum,i|
  sum && i.blank?
}


text:
Q: Remove surrounding (table) layer if attribute=value (without direct attribute match!) im rather a beginner in XSLT, but have to solve the following and hope that maybe some of the bright minds from the StackOfJoel can help me:
i have some working xslt code (1.1! cant use 2.0) that transfers XHTML into XML, the new requirement is:

*

*a certain div-element (with a specific attribute-value) is always contained in a table; the div should be transferred into a new element (NUREQ), and all surrounding table structure should be removed

*any other table should be preserved, and any other div should not be cut out, but be transformed themselves, to yet different elements (text)!

The problem is: i can not match the attribute directly in a template match, because i have to make the attributevalue-match case-insensitive (i use translate - is there any other method i could use directly in the templatematch? I know about question# 13620725 but its solution doesnt apply afaik)
So, as you can see in the example code & data, i have to find ONLY those divs that have the attribute "class" set to 'req' (or 'REQ', or 'reQ', etc..), transform them into a separate new element 'NUREQ', and remove the surrounding table. But for any other div (without this specific attribute), do the standard transformation into  element, but keep the table!
As you can see, i use translate() to make it caseinsensitive, therefor i cant use it in the templatematch.
Of course my normal XSL is way longer, filters and transforms many other elements & attributes, but i distilled it down to the essence.
Has anyone got ideas and can help me with that?
One xhtml test data file:
<?xml version="1.0" encoding="UTF-8"?>

  <title></title>


text: Q: Desktop manager for XP(dual monitor) I have nvidia card. I am using two DVI ports for dual monitor. Now my requirement is I want to set some window to be open on specific monitor only. For that i have tried nview option. And it is get reset when we reboot machine with single monitor and when we connect second one all the output comes only in primary(single monitor which was connected earlier second one). I want to get the profile back after reboot with single and then dual monitor. Is there any other tool to do this?


text:
Q: How to view images in a Django template I am using Django 1.7 to upload images and view them on a template. For some reason, the images that I have uploaded are not being shown. I have verified that they are uploaded and the path is saved on the database. But when retrieving it from the template, I get nothing. I have the following code:
models.py
...
class Pet(models.Model):
    title = models.CharField(_("Title"), max_length=120)
    slug = models.SlugField(max_length=100, db_index=True)
    description = models.TextField(_("Description"), default='')
    ....
class PetImage(models.Model):
    pet = models.ForeignKey(Pet, related_name='images')
    title = models.CharField(max_length=200, null=True, blank=True)
    image = models.ImageField(upload_to="pet_images", null=True, blank=True)

forms.py
from django.forms.models import inlineformset_factory
from django.forms import ModelForm

from .models import Pet, PetImage

class PetForm(ModelForm):

    class Meta:
        model = Pet
        fields = ('title', 'description',)

PetImageFormset = inlineformset_factory(Pet, PetImage, fields=('image',), can_delete=False, extra=3)

views.py
...
def new_pet(request):
    form = PetForm()
    img_formset = PetImageFormset(instance=Pet())

    if request.method == 'POST':
        form = PetForm(data=request.POST)
        if form.is_valid():
            pet = form.save(commit=True)
            img_formset = PetImageFormset(request.POST, request.FILES, instance=pet)
            if img_formset.is_valid():
                img_formset.save()
                return redirect(pet)

    return render(request, "pets/new_pet.html", {
        'form': form,
        'img_formset': img_formset,
        'action': "Create"
    })

def view_pet(request, pet_slug, pet_id):
    pet = get_object_or_404(Pet, pk=pet_id)
    return render(request, 'pets/view_pet.html', {'pet': pet})

urls.py
from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^$', 'apps.pets.views.all_pets', name='all_pets'),
    url(r'^(?P<pet_slug>[-\w\d]+),(?P<pet_id>\d+)/$', 'apps.pets.views.view_pet', name='view_pet'),
    url(r'^new$', 'apps.pets.views.new_pet', name='new_pet'),
)

How can I view the images related to a pet on the template? This is what I've tried so far but the image is not shown:
view_pet.html

    {% for photo in pet.petimage_set.all %}

    {% endfor %}

A: Because your PetImage model's related_name for the Pet foreign key is "images", change the loop to
{% for photo in pet.images.all %}

Documentation on related_name


text:
Q: 'SELECT FOUND_ROWS()' returning a minimum of 1 when results empty I have a problem getting SELECT FOUND_ROWS() to return 0 when the result from MSQL query is empty.
I have the following function that calls getBasket();
function viewBasket(){
    include('classes/Orders.php');

    $BasketID = 10;
    $numRows=100;
    $data = Orders::getBasket( $numRows, $BasketID);

    $results['basket'] = $data['results'];
    $results['totalRows'] = $data['totalRows'];

    require( "templates/Basket.php" );
};

getBasket() builds the required results using LEFT OUTER JOIN and places into an array which is then returned to viewBasket().
public static function getBasket( $numRows, $BasketID ) {
    $order="Name ASC";
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

    $sql = "
SELECT SQL_CALC_FOUND_ROWS B.BasketID
                         , BP.ProductID
                         , BP.Quantity
                         , P.Name
                         , P.Price
                         , PT.NameType
                      FROM Basket B
                      LEFT
                      JOIN BasketProducts BP
                        ON B.BasketID = BP.BasketID
                      LEFT
                      JOIN Products P
                        ON BP.ProductID = P.ProductID
                      LEFT
                      JOIN ProductTypes PT
                        ON P.ProductTypeID = PT.ProductTypeID
                     WHERE B.BasketID = :BasketID
                     ORDER
                        BY $order
                     LIMIT :numRows;
";

    $st = $conn->prepare( $sql );
    $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
    $st->bindValue( ":BasketID", $BasketID, PDO::PARAM_INT );
    $st->execute();
    $list = array();

    while ( $row = $st->fetch() ) {
        $basket = new Orders( $row );
    $list[] = $basket;
    }

    // Now get the total number of articles that matched the criteria
    $sql = "SELECT FOUND_ROWS() AS totalRows";
    $totalRows = $conn->query( $sql )->fetch();
    $conn = null;
    return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}

My HTML then echos the totalRows value stored in $results by viewBasket();

You have <?php echo $results['totalRows']?> item<?php echo ( $results['totalRows'] != 1 ) ? 's' : '' ?> in your Basket

It works, but just wont send a 0 if the table is empty !
Thanks, Adam

A: I cannot reproduce the problem using php-5.6.3 and mysql-5.6 (default: myisam) under windows.
<?php
define('DB_DSN', 'mysql:host=localhost;dbname=test;charset=utf8');
define('DB_USERNAME', 'localonly');
define('DB_PASSWORD', 'localonly');
var_dump( getBasket(10, 1) );

function getBasket( $numRows, $BasketID ) {
    $order="Name ASC";
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    setup($conn); // boilerplate: creating empty, temp tables

    $sql = "
        SELECT
            SQL_CALC_FOUND_ROWS
            Basket.BasketID, BasketProducts.ProductID, BasketProducts.Quantity,
            Products.Name, Products.Price, ProductTypes.NameType
        FROM
            soBasket as Basket
        LEFT OUTER JOIN
            soBasketProducts as BasketProducts
        ON
            Basket.BasketID = BasketProducts.BasketID
        LEFT OUTER JOIN
            soProducts as Products
        ON
            BasketProducts.ProductID = Products.ProductID
        LEFT OUTER JOIN
            soProductTypes as ProductTypes
        ON
            Products.ProductTypeID = ProductTypes.ProductTypeID
        WHERE
            Basket.BasketID = :BasketID
        ORDER BY
            " . $order . " LIMIT :numRows
    ";

    $st = $conn->prepare( $sql );
    $st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
    $st->bindValue( ":BasketID", $BasketID, PDO::PARAM_INT );
    $st->execute();
    $list = array();

    while ( $row = $st->fetch() ) {
        $basket = new Orders( $row );
            $list[] = $basket;
    }

    // Now get the total number of articles that matched the criteria
    $sql = "SELECT FOUND_ROWS() AS totalRows";
    $totalRows = $conn->query( $sql )->fetch();
    $conn = null;
    return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}

class Orders {
    public $_data;
    public function __Construct(array $data) {
        $this->_data = $data;
    }
}

function setup($pdo) {
    $queries = array(
        "
            CREATE TEMPORARY TABLE soBasket (
                BasketID int
            )
        ",
        "
            CREATE TEMPORARY TABLE soBasketProducts (
                ProductID int,
                BasketID int,
                Quantity int
            )
        ",
        "
            CREATE TEMPORARY TABLE soProducts (
                ProductID int,
                ProductTypeID int,
                Price DECIMAL(10,2),
                Name varchar(64)
            )
        ",
        "
            CREATE TEMPORARY TABLE soProductTypes (
                ProductTypeID int ,
                NameType varchar(64)
            )
        "
    );
    foreach( $queries as $q ) {
        $pdo->exec($q);
    }
}

prints
array(2) {
  'results' =>
  array(0) {
  }
  'totalRows' =>
  int(0)
}

A: if($results['totalRows'] > 0){
echo $results['TotalRows'];
else{
echo '0';
}

an IF condition before echoing would do it.

A: Try to cast it:
return ( array ( "results" => $list, "totalRows" => (int)$totalRows[0] ) );

A: thanks to the input from @VolkerK and  @Phate01 I have solved the issue.
I cleared the BasketID set in the basket table if the row returned from basketProducts is NULL.  i.e. if I have removed the last row from products associated to that user, remove the cart session from Basket.
  $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
  $st = $conn->prepare ( "select BasketID FROM basketProducts WHERE BasketID = :basketID" );
  $st->bindValue(":basketID", $basketID, PDO::PARAM_INT );
  $st->execute();

  $row = $st->fetch();
  $conn = null;

  /**
  * If the row returned from BasketProducts DOES NOT include the customers $basketID
  * remove the row.
  **/
  if($row == 0){
      $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
      $st = $conn->prepare ( "DELETE FROM Basket WHERE BasketID = :basketID LIMIT 1" );
      $st->bindValue(":basketID", $basketID, PDO::PARAM_INT );
      $st->execute();

      $row = $st->fetch();
      $conn = null;
  }else{
    //do nothing
  }

@VolkerK, I had a quick read of that link and its gone over my head. Will read up tonight, but would you mind explaining how this might help me?


text:
Q: Eigenvalue properties Suppose that $A$ is a $3 \times 3$ matrix with eigenvalues $\lambda_1$ = 1, $\lambda_2$ = 2, and $\lambda_3$ = 3.
a - Find the eigenvalues of $B = A^2 − 2A + I$. (I is the $3\times 3$ identity matrix).
b - Find the eigenvalues of $B^2 − A^{−2}$
c - Find the eigenvalues of $C = (A − I)(A − 2I)(A − 3I)$. Is it true that $C$ is the zero matrix? Verify your answer.
I'm not sure how to solve these questions. How would I find $A^2$ or $2A $without knowing all of the elements of the $A$ matrix?
Are there properties of eigenvalues that can help me solve these, because I was never taught them.

A: Hint:
How you approach the problem depends a bit on what you already know. For the following, I assume that you know that given the fact that $\lambda_j$ are all distinct, that $A$ is diagonalizable.
So you have a basis $v_j$ such that
$A v_j = \lambda_j v_j$.
Given that the problem becomes rather simple. You just have to observe that the eigenvectors in your examples stay invariant (but the eigenvalues change)
As an example for (a)
$$B v_j = (A^2 -2 A+I) v_j = (\lambda_j ^2- 2 \lambda_j +1)v_j$$
and thus $B$ has the eigenvalues $\lambda_j ^2- 2 \lambda_j +1$.


text:
Q: The word "glee": How prevalent is the aspect of 'schadenfreude' in normal use? I wonder about the word "glee": It has hitherto been my impression that the word is typically used equivalent to danish "skadefryd" or german "schadenfreude"; ie. being pleased with someone else's misfortune. - But the reason I ask is that I'm in doubt if my impression might be wrong? The dictionary.com article does not mention any aspect of being pleased with someone else's misfortune at all, but simply states:

*

*open delight or pleasure; exultant joy; exultation.

Although far down on the page they quote British Dictionary:

*

*great merriment or delight, often caused by someone else's misfortune

It seems it's used in either sense, so my question is how prevalent (or not) is the aspect of 'schadenfreude' in the average native english language users understanding or perception of the word "glee"?
In examples such as "It is a person full of glee", or "They reacted with glee", or "They were gleeful of it" - and not giving any context, then would it be assumed by default (assuming that the 'schadenfreude' aspect of the word had not initially, as here, been given particular focus), as the immediate impression, simply that they are happy, and nothing else? Or implicitly also that it was propably due to someone's misfortune? (and might there be any difference in that respect, between the different examples?)

A: As @Evan said, Glee could certainly be used to describe someone's delight caused by another person's misfortune, but it does not inherently mean schadenfreude, at least not in the US.  Here's what the Oxford Dictionary (US) has to say:

Glee
NOUN
1 Great delight.
'his face lit up with impish glee'
2 A song for men's voices in three or more parts, usually
  unaccompanied, of a type popular especially c.1750–1830.
'Later, boys were paid to sing treble parts at meetings of glee clubs, and glees for SATB became more common.'

The latter definition, is apparently the source of the term glee club; something of which I was unaware.
In the British dictionary, however, the definition is slightly different:

Glee
NOUN
1 [mass noun] Great delight, especially from one's own good fortune
  or another's misfortune.
'his face lit up with impish glee'

So, I guess it depends on where you are.

A: I have heard it used where is to describe someone with a low level of responsibility or someone who is insane, as in the glee of irresponsibility or the glee of insanity.  I picture these people laughing out of control and at things that are destructive of others or to their misfortune.  An insane person might laugh uncontrollably after tripping someone, seeing someone injured, or the like.

A: From Vocabulary.com
Definitions of glee
noun great merriment
synonyms:gleefulness, hilarity, mirth, mirthfulness
see more
noun malicious satisfaction
synonyms:gloat, gloating
There is a negative view of glee.
If a child is very confused, they will sometimes show it in acting in a crazy gleeful laughter.  So we have all seen people being full of glee where it demonstrates lack of responsibility or craziness, some demonstrating full insanity.
Of course it is most often used in the sense of actually being joyful.


text:
Q: Walmart Inventory Update PUT API randomly returns 400 every once in a while I have been seeing this error popup every once in a while during inventory update process
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:errors xmlns:ns2="http://walmart.com/">
  <ns2:error>
    <ns2:code>2.GMP_INVENTORY_API</ns2:code>
    <ns2:field>Inventory</ns2:field>
    <ns2:description>Update failed even after retries</ns2:description>
    <ns2:info>Update failed even after retries</ns2:info>
    <ns2:severity>ERROR</ns2:severity>
    <ns2:category>DATA</ns2:category>
    <ns2:causes/>
    <ns2:errorIdentifiers/>
  </ns2:error>
</ns2:errors>

Is there a specific reason for this to happen ?

A: A 400 error is 'Bad Request'.  Usually that means the fault is on your end.
The first thing to do is check the requests you've been sending.  Logging them, especially the ones that result in an error, is a good idea.
Things to check:

*

*Try sending the same body again.  If you get the same error, then something is wrong with it.

*Check that the syntax is ok.  Use a validator.

*Check the backing data.  Can you notice any patterns to when it fails?  Only when 'SKU_1234' is included?  Are you sending a negative number for quantity?  Are there any unescaped special characters in your data?


text:
Q: Column 'mary' does not exist i'm doing a simple query here and it returns that column 'Mary' does not exist:
SELECT  telephone.telephonenumber as tel
FROM    person, telephone
WHERE   person.idperson = telephone.idperson
AND person.personname = 'Mary';

Can someone explain what can be happening? I don't want Mary as a column, but as a value.
Thanks in advance,
Gabriel

A: Make sure that you are quoting your string correctly.
From your snippet, I'd say that's the problem here since you're using something else than simple single quotes.

A: Use plain single quotes to delimit a string literal 'Mary' not smart quotes 'Mary'


text:
Q: Why forward and redirect in grails don't stop initial action execution? I read about forward and redirect in Grails and don't understant why the code bellow prints "foo".
See:
def bar = {
   redirect (controller: "public", action: "index") // same happens with forward
   println "foo" // prints this in console?? WHY?
}

In my opinion redirect/forward must skip current method execution...
Is this a bug or I understand the concept wrong?

A: Because these are just function calls - they can't exit from a calling function (your action). Just put return afterwards.


text:
Q: Indy, IdTCPSever sending data in utf=8 charset I have problem with conversion strings to utf-8.
I use standard Indy method for sending with conversion inside:
 AContext.Connection.IOHandler.writeln(Utf8Encode('ĄĘÓ'));

but the client reads them like '???' - 3f 3f 3f in hex (I checked it by using WireShark too).
I use Delphi XE and Indy 10.
Big thanks for any help.
~Artik

A: I found solution for my problem, I think the simplest by using code like below:
uses
  IdGlobal;

begin
  aContext.Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;
end;


text:
Q: How to use label names for prometheus alert expression? I want to send Prometheus alert if latency is beyond some 100s and based on the Severity label that I passed to gauge metric in instrumentation.
I tried the following
- alert: TestAppLatency
  expr:  LATENCY>100 or {{ $labels.SEVERITY }} == 'CRITICAL'

But I get the following error
could not parse expression: 1:32: parse error: unexpected left brace '{'
Where am I going wrong?

A: Maybe something like this:
- alert: TestAppLatency
  expr:  LATENCY{SEVERITY="CRITICAL"} > 100

Try reading https://alex.dzyoba.com/blog/prometheus-alerts for hints.