text:
Q: woocommerce retriving category name as div class? ok I am trying to retrive the category name of a woocommerce product displayed in a wordpress loop and use it as the class for a li also inside the loop i've tried this:

<?php while (have_posts()) : the_post(); ?>

                        <li class="<?php echo $product->get_categories(); ?> box">
                            <a href="<?php the_permalink(); ?>"><?php echo the_post_thumbnail(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                            <a href="<?php the_permalink(); ?>"><span href="<?php the_permalink(); ?> " class="amount price" data-original="<?php echo get_woocommerce_currency(); ?><?php echo $product->get_price(); ?>" data-price="<?php echo $product->get_price(); ?>" title="Original price: <?php echo $product->get_price(); ?>"><?php echo get_woocommerce_currency(); ?><?php echo $product->get_price(); ?>
                            <a href="<?php the_permalink(); ?>?add-to-cart=<?php echo $post->ID ?>" class="pbutton">Add to Cart

                    <?php endwhile; ?>

this being the part i'm trying to retrive the class with:
<li class="<?php echo $product->get_categories(); ?> box">

but it just outputs this:

which does retrieve the category but also screws with the markup  breaking the loop.
I've also tried this:
<li <?php post_class('box'); ?>
but because woocommerce uses taxonmys it retrives the tags but not the product category.
any help is much appriciated
Kind regards
Chris

A: It's not quite as easy as making a single call - get_categories() is designed to show an HTML representation of the product categories. The product categories are actually a custom taxonomy, so you have to use get_the_terms() to get at it.
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ){
    $category_id = $term->term_id;
    $category_name = $term->name;
    $category_slug = $term->slug;
    break;
}


text:
Q: Python - How to run cx_Freeze on Linux? I would like to know how to run my setup.py script on Linux. I've done this on Windows by placing the setup script and the program script (and it the files it uses) in the Python33 directory on the C:\ drive. However, Linux is obviously different. I tried placing the setup script in the /usr/bin/ directory since that's where Python3.3 is installed?
Linux is confusing me and I would very much like to create an exe of my program for Linux.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Did leaflet-bing-layer change? (Angular 6) So for the development of my app I've been using Esri's basemap.  I wanted to switch to bing.  This is my import as i saw in another question asked here.
import 'leaflet-bing-layer';

Then this is in my ngOnInit? The map loads fine but none of the other types besides the default Aerial will show up?  Any ideas
L.tileLayer.bing('key', {
      type: 'Road'
    }
).addTo(this.map);


text:
Q: knockoutjs sortable binding - how to get targetparentnode? I have a list of sortable lists, and I am dragging some items into those lists.
I need to know the id of the list I am saving the item into so I can create a link record and save this on the server end.
Each sortable list has DOM element name equal to the ID of that list.
The awesome knockoutjs sortable binding has arg.sourceParentNode but not arg.targetParentNode. How can I obtain the targetParentNode?
Thanks!
I am building a screen to link things together, basically just create relationships between database tables and insert a record into the many-to-many table. I hope it is just simple simple I am missing here...
I can't be the only one who would find it useful to know which DOM element corresponds to which observableArray, so I'm hoping I'm missing something simple here and someone has an easy solution to this. I always found it strange that knockout doesnt have a DomElementForObservable function, but in the past I was able to always work around that and not need it. In this case I'm stumped. Any ideas?
A generic way to obtain a DOM element for an observable would be awesome.

A: A good option is to try to put this functionality in the view model rather than relying on the DOM elements. For example, you can attach an id to the observableArray rather than the DOM element. Like:
this.myItems = ko.observableArray();
this.myItems.id = "myId";

Then, you can just look at arg.targetParent.id.
Alternatively, you can subscribe in your viewmodel like:
this.myItems.subscribe(function(newValue) {
   this.createLink("myItems", newValue); //or whatever you need to do in your code
}, this);

The beforeMove and afterMove handlers to pass the event and ui objects on as the second and third arguments, so you could inspect them and find the parent of the element.
Knockout does not have a generic way to get a DOM element from an observable, as an observable may be bound to many elements. Hope this gives you some ideas though.


text:
Q: using the re and urllib.request module im using python 3.7 and i wanted to write a program that takes name of a city and returns the weather forcast .
i started my code with :
import re
import urllib.request
#https://www.weather-forecast.com/locations/Tel-Aviv-Yafo/forecasts/latest
city=input("entercity:")
url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest"
data=urllib.request.urlopen(url).read
data1=data.decode("uf-8")
print(data1)

but when I wanted to read my data i got this error :

File
         "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
          result = func(*args)
          File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
          raise HTTPError(req.full_url, code, msg, hdrs, fp)
          urllib.error.HTTPError: HTTP Error 404: Not Found
          Process finished with exit code 1

=> can some one help me and tell what is the problem ?
thanks:)

A: There must be some spelling mistake in the city name you have entered. I tried running the following code
 import re
 import urllib2
 city=input("enter city:")
 url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest"
 data=urllib2.urlopen(url).read()
 print(data.decode('utf-8'))

It works properly when i input

enter city:'newyork'

While the same code throws HTTPError: HTTP Error 404: Not Found error if the input is

enter city:'newyolk'

You can solve this by using a try-except statement
city=input("enter city:")
url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest"
try:
    data=urllib2.urlopen(url).read()
    print(data.decode('utf-8'))
except:
    print('The entered city does not exist.Please enter a valid city name')

A: Tried with requests library it worked.
import requests

city = input("entercuty:")
url = "https://www.weather-forecast.com/locations/"+city+"/forecasts/latest"
data = requests.get(url)
print(data.status_code)
print(data.text)

Gave city as "Stuttgart".

Status code: 200


text:
Q: pymysql cannot execute query remotely I'm executing a set of very heavy queries remotely to the company databases from our central server. Unfortunately, python logging raises this error from the database when trying to execute certain INSERT query.
/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py:329: Warning: (1592, 'Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. Statement is unsafe because it uses a UDF which may not return the same value on the slave.')
  self._do_get_result()
/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py:329: Warning: (1592, 'Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. Statements writing to a table with an auto-increment column after selecting from another table are unsafe because the order in which rows are retrieved determines what (if any) rows will be written. This order cannot be predicted and may differ on master and the slave.')
  self._do_get_result()
/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py:329: Warning: (1592, 'Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. Statement is unsafe because it invokes a trigger or a stored function that inserts into an AUTO_INCREMENT column. Inserted values cannot be logged correctly.')
  self._do_get_result()

wihout python logging, the error es expressed differently, and does not locks the python program execution:
[2019-09-27 13:24:47,228 root ERROR] Fallo ejecucion de query: INSERT INTO movimiento (numero_sala, tipo_movimiento, fec_movimiento, hora_movimiento, nro_tarjeta, id_maquina, monto, lugar_im, fecha_hora_im)                     VALUES ( 3, 20, current_date, current_time, 157299522, 0, 40.000000, 2, current_timestamp)
Traceback (most recent call last):
  File "/opt/cruciscripts/crucidmcs/connectionManager.py", line 58, in alter
    cursor.execute(query)
  File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 170, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 328, in _query
    conn.query(q)
  File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 517, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 732, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1075, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 684, in _read_packet
    packet.check_error()
  File "/usr/local/lib/python3.5/dist-packages/pymysql/protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "/usr/local/lib/python3.5/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.InternalError: (1205, 'Lock wait timeout exceeded; try restarting transaction')

A: Depending on the SQL engine, there are limitations for the size of a query.
The obvious solution was to partition the query in smaller chunks.


text:
Q: hover on dynamically created list I have a menu with a list of items created dynamically using javascript.
They have different colour and country attributes created using setAttribute.

$("#menuList a").hover(
  function() {
    var countryName = $(this).attr('country');
    var fruitColour = $(this).attr('colour');
    $('#toshow').append($("countryName \n fruitColour"));
  },
  function() {}
);
.toshow {
  display: none;
}

#menuList a:hover div.toshow {
  top: 0;
  right: 0;
  display: block;
  position: absolute;
  z-index: 99999;
  background: red;
  width: 200px;
  height: 100px;
}

Watermelon

Grapes

Strawberry

Blueberry

Here, I want to have a separated hidden div (display at top right of the page or next to the menuList) that does not have any content until any of the  tag being hovered, and show its responding two attributes until no more mouse hovered.
The code does not have errors. But I don't see anything in red when the mouse hovered through the list. Is it possible to achieve what I am looking for?

A: You can use the mouseout event to hide the toshow div with hide as you leave a list element. And at each hover event, you can change the html of toshow to the values of the li element which the user is hovering over and use show to display it.
Also make sure you attach the event handlers after you've inserted the html of the dynamically generated list.:

function displayGeneratedList() {
  $('#menuList').html(`

Watermelon

Grapes

Strawberry

Blueberry

  `);
  $("#menuList a").hover(function() {
    var countryName = $(this).attr('country');
    var fruitColour = $(this).attr('colour');
    $('#toshow').html(`${countryName}<br>${fruitColour}`).show();
  });
  $('#menuList a').mouseout(function() {
    $('#toshow').hide();
  });
}

$(document).ready(function() {
  displayGeneratedList();
});
#menuList {
  display: inline-block;
}

.toshow {
  display: none;
  float: right;
  background: maroon;
  width: 200px;
  height: 100px;
  padding: 5px;
  color: white
}


text:
Q: charles proxy is capturing traffic from a port other than one i've set I've set up Charles to capture traffic going through port 8888. I've set up my mobile device send traffic to that port. It all works peachily.
However, when i browse to a site on my desktop, that traffic is also captured by Charles. As far as i know, traffic on my desktop flows through port 80. How can i stop Charles from logging traffic from my desktop?
EDIT:
I've tried changing the port that Charles listens on and the problem still occurs. Can anyone help me diagnose what's going on?

A: Charles will capture all traffic of devices that use your port 8888 as their proxy, AND of your Windows and Mozilla Firefox traffic by default.
To change this, go to the "Proxy" tab and uncheck "Windows Proxy" (for Windows itself as well as most browsers) and "Mozilla Firefox Proxy".
Cheers


text:
Q: Unable to schedule anything in asyncio. (Python 3.7.x) I am currently working on asyncio with python 3.7.x not sure about the exact version, right now I am trying to schedule a task. And I am unable to get an output, even when running the thing forever. Here is the code I currently have
import asyncio

async def print_now():
  print("Hi there")

loop = asyncio.get_event_loop()
loop.call_later(print_now())
loop.run_until_complete(asyncio.sleep(1))

This gives the following error:
Traceback (most recent call last):
  File "D:\Coding\python\async\main.py", line 7, in <module>
    loop.call_later(print_now())
TypeError: call_later() missing 1 required positional argument: 'callback'

The call back in call_later() is print_now I've tried just print_now and print_now()
I have also tried using loop.run_forever() instead of loop.run_until_complete() and so far I didn't get anything
Sometimes I get either no output or a different error.

A: First, yes, you're missing a delay argument . First one is supposed to be the delay while the second one is a callback (docs).
loop.call_later(delay, callback, *args, context=None)

Second, the callback is supposed to be a function. What you're passing is print_now() which is gonna evaluate to None. You might find out that

'NoneType' object is not callable

So you're gonna need to pass print_now — without parentheses — as a callback. This way you're passing a function instead of the result of its application.

Third, async functions are supposed to be awaited on. Your scenario doesn't seem to need that, so just drop the async keyword.

When you call an awaitable function, you create a new coroutine object. The code inside the function won't run until you then await on the function or run it as a task

From this post. You might want to check out


text:
Q: Using built in validation for records created on client I have an ASP.NET MVC4 application where I'm allowing users to add 1 to many records on the client using javascript templates. It's working fine and using the right naming convention, the model binding is correctly transforming the post data into the desired collection of objects for the action method.
My question is, is there any way to use the built in MVC validation for records added using this approach.  I've added data annotation attributes to my model but because I'm generating the html for each new record on the client I can't use the html helpers that typically make the process work.
Obviously, I can just add the client side validation myself and let the data annotations validate on the server but I'm wondering if there's a way to take advantage of the built in validation stack for this type of approach so I can maintain all my validation logic on the server.

A: For example:
The View has two form:form1 and form2。
The form1 has two part.
The first part:
There are two textbox and a Create button and a Save button.
The second part:
There are a .
so, when we fill in two textbox and press the Create button, if not pass validation, then show error messages.
if pass validation, then insert values into the  and insert values to the form2.
[HttpPost] Action Create has a parameter List models.
when we press the Save button, will take values of form2 to controller mapping to List models.
Model
public class HomeModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    public string Number { get; set; }
}

Controller:
    [HttpPost]
    public ActionResult Create(List<HomeModel> models)
    {
        // TODO: Add insert logic here
    }

View:
@model MvcApplication1.Models.HomeModel
@{
   ViewBag.Title = "Create";
 }

Create

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "form1" }))
{
@Html.ValidationSummary(true)

<fieldset>
    <legend>HomeModel</legend>

        @Html.LabelFor(model => model.Name)

        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)

        @Html.LabelFor(model => model.Number)

        @Html.EditorFor(model => model.Number)
        @Html.ValidationMessageFor(model => model.Number)

        <input type="submit" value="Create" id="btnCreate" />
        <input type="button" value="Save" id="btnSave" />

</fieldset>

}

    <form action="/Home/Create" id="form2" method="post"></form>

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

Example Download


text:
Q: Build Android Applications Based on FFmpeg getting Error I have download code this link
Import this project and convert it in to C / C ++ native project.
And also set Builder Settings to Build Command
bash C:\tools\android-ndk-r8b-windows\android-ndk-r8b\ndk-build

After run project then i am getting below Error.
make: *** Android NDK: Aborting    .  Stop. FFmpegTest

C:\tools\android-ndk-r5b\build\core\prebuilt-library.mk

I am develop above application in Windows 7 64 bit and Eclipse Juno.
Please guide me to resolved my Error.
Thanks

A: I was never able to compile ffmpeg for Android following the link you have posted (though I've heard others did succeed) same as I was never able to compile ffmpeg for Android under windows.
I have easily compiled ffmpeg under ubuntu using the following code
http://code.google.com/p/dolphin-player/.
Just go to
dolphin-player/p/native/ffmpeg/ffmpeg-0.11.1 and run build_android_r8.sh from there
Once compiled under unix you can then use the resulting *.so under windows.
You can emulate unix under windows using something like the free VirtualBox.
You can avoid compiling altogether by grabbing one of dolphin-player's apks (suitable for your architecture) renaming it into zip and extracting libffmeg.so from there.


text:
Q: Auto inject properties in Angular component to reduce boilerplate code We are developing a large AngularJS (1.5) application which consists of a large number of constants that almost every Angular components' templates would use.  Currently, we resort to manually assign those constants to every component's controller, but we would like to see if there are ways to simplify this.
Here is our current implementation
import TranslationKeys from '../keys/translationkeys';
import ApplicationConstants from '../constants/applicationconstants';

module.component('humbleComponent', {
    bindings: {},
    controller: () => {
        this.TranslationKeys = TranslationKeys;
        this.ApplicationConstants = ApplicationConstants;
    }
    template: '<div>{{ $ctrl.TranslationKeys.HELLO | translate }}</div>'
});

Our ideal outcome would be:

*

*Eliminate repeat assignment of TranslationKeys and ApplicationConstants

*Ideally, accessing those constants in the template would not even need to reference $ctrl.  Such as

import TranslationKeys from '../keys/translationkeys';
import ApplicationConstants from '../constants/applicationconstants';

module.component('humbleComponent', {
    bindings: {},
    controller: () => {
        //Look mom, no need to repeated keys/constants assignments here
    }
    template: '<div>{{ TranslationKeys.HELLO | translate }} <!-- No need to use $ctrl when accessing TranslationKeys--> </div>'
});

Just wondering what are the ways to achieve the goals above.


text:
Q: Moving repo from Bitbucket to existing repo in GitHub Hi I am very new to coding and git and need some help. I am working on a small project where the customer has decided to move depository from Bitbucket to GitHub. They have moved the code without letting me know. What I need to do is to disconnect my project from Bitbucket, connect it to the existing GitHub repository and commit my latest changes to GitHub. It is a small project and I am using Visual Studio Code for it.

A: Open the console in your project root and type:
$ git remote set-url origin <newGitHubURL>

The URL should be something like: https://github.com/username/projectname.git


text:
Q: representation of spinors I am trying to get from the abstract representation of Spinors,
as wave functions $|\Psi \rangle$ in the base of tensors products $| S_z \rangle \otimes | x \rangle$ of eigenvectors of the spin operator $\hat S_z$  and position operator $ \hat x$ to the representation in wave function form: $ \begin{pmatrix}{\Psi_+(x) \\ \Psi_-(x)} \end{pmatrix}$.
I seem to be missing something key. I would really apprechiate some help with this. Here is where i go wrong:
$$ \int dx \sum_{s_z} (| x \rangle \otimes | S_z\rangle) \; (\langle x|  \otimes \langle S_z|) |\Psi \rangle=\int dx \sum_{s_z} (| x \rangle \otimes | S_z\rangle) \; (\langle x|\Psi \rangle  \otimes \langle S_z|\Psi \rangle)
$$
which i would normally  read as
$$ =  \int dx \sum_{s_z} (| x \rangle \otimes | S_z\rangle) \; ( \Psi(x)  \; \langle S_z|\Psi \rangle) \\ =\int dx  (| x \rangle \otimes | +\rangle) \; ( \Psi(x)  \; \begin{pmatrix}{1 \\ 0} \end{pmatrix})+(| x \rangle \otimes | -\rangle) \; ( \Psi(x)  \; \begin{pmatrix}{0 \\ 1} \end{pmatrix}) $$
which then if i leave the summation over the base vectors out gives $ \begin{pmatrix}{\Psi(x) \\ \Psi(x)} \end{pmatrix}$ which is exactly not what i want. Since it is the same wave function in both components, what am i doing wrong here?
How do i get different wave functions for the different components using the dirace formalism? I would really be glad about some Tipps.


text:
Q: Spring Boot With Spring Security with Angular 2+ I am trying to use spring boot with spring security for large scale application and i want to use angular in the front end.
Unfortunately it seems that all the example are "hacks" and not something that intuitive to use.
We have 2 options we would like to do:

*

*One monolithic application that will have client and server under spring boot. In such case spring security will handle the pages and security

*Create 2 application.. 1 will be Gateway that needs to serve the pages and will pass request to the spring server that will have an API and should be secured with spring security.

If anyone has another idea you are more than welcome. We really want to use spring security because this is awesome framework.. But it seems that angular 2+ will require to use nodejs also.


text:
Q: FreqCount.available() only returning false I am a novice Arduino user trying to measure the frequency output of my HTF3228LF humidity sensor using the library FreqCount on my Arduino Teensy LC.
My circuit connects the output of my sensor to a voltage divider to cut the HIGH voltage from 5V to 2.5V, and feeds that signal into a unity gain buffer to successfully drive pin13's LED on my Teensy LC board.
I noticed a strange issue when trying to follow the FreqCount example script where FreqCount.available() only returns 0. Removing the if statement checking whether FreqCount is availabe seems to fix the issue, but I haven't been able to find mention of this issue anywhere else. Any help would be appreciated.
The following is my code
/*
 * testFreqCount.ino
 *
 * The purpose of this script is to test the FreqCount library and to make sure
 * it doesn't interrupt the running of the rest of the program like pulseIn() does
 */
#include <LiquidCrystal.h>
#include <FreqCount.h>

// Setting up pins
LiquidCrystal lcd(18,19,20,21,22,23);

// Setting RH reading
unsigned long RH;

// Setting timing
unsigned long currentTime;
int waitTimeDisplay = 500;
unsigned long lastProcDisplay = 0;

///////////////////////////////////////////////
// Helper functions
///////////////////////////////////////////////
float readHumidityHTF3228LF() {
    // This function requires that the user
    // attach their frequency to pin 13 by
    // default and requires no further input
    // USAGE: readHumidityHTF3228LF()
    // OUTPUT: unsigned long RH
    unsigned long frequencyH;
    //if(FreqCount.available()){                    <----------- Problematic
    frequencyH = FreqCount.read();
    //}
    return (-1*(frequencyH - 9595))/14.8;//relative humidity
}

///////////////////////////////////////////////
// Actual code
///////////////////////////////////////////////
void setup(){
  Serial.begin(57600);
  FreqCount.begin(1000);
  lcd.begin(16,2);
  currentTime = millis();
  RH = readHumidityHTF3228LF();
  lcd.setCursor(0,0);
  lcd.print(currentTime);
  lcd.setCursor(0,1);
  lcd.print(String(RH) + "%");
}

void loop(){
  currentTime = millis();
  RH = readHumidityHTF3228LF();
  if((currentTime - lastProcDisplay) >= waitTimeDisplay){
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(currentTime);
    lcd.setCursor(0,1);
    lcd.print(String(RH) + "%");
    lastProcDisplay = currentTime;
  }
}


text:
Q: Problem with ChoiceGroup, strings don't fit in screen I'm developing a J2ME application, and I need to show a .png picture, then right beneath it, a list of strings from which the user can select one. Since you can't append an image to a List, I tried using a Form, appending an ImageItem to it, then appending an ChoiceGroup with the options. This works very well on the Sun WTK emulator.
But now, I tried it on my phone (Nokia 5800) and it only shows the beginning of the options, since it will only let them fit on a single line. So, instead of having:

*

*I had a lovely evening yesterday.

*I had dinner with some friends.

It will show something like:

*

*I had a lov...

*I had dinne...

Which obviously it's not ideal. However, if I select 1 option, the complete text appears hovering in a little box.
The problem is, I tried this on Nokia S60 3rd edition emulator, and the little box doesn't appear, only the options cut short.
Is there any way to get around this to have an image then a list of options that the user can select? I've been reading about Custom Items, but it seems very complicated for essentially something that should be very simple. Maybe someone knows an already done implementation of a Custom Item that does this?
Any help at all will be much appreciated :-) Thanks!

A: Take a look at LWUIT, otherwise you are going to have to implement word wrapping yourself for a lot of the components easier to not reinvent the wheel

A: If you're targetting the Nokia 5800, you need to use the Series60 5th edition SDK emulator.
It is available from forum nokia and allows both C++ and J2ME development.
Hopefully, that should make the emulator's behaviour consistant with the device's.
I assume the device displays something that is more to you liking once you switch to landscape mode by pivoting the device...
If you want to target widely different phones (240x320 screen with keypad versus 360x640 touchscreen), you probably need to make at least 2 versions of your MIDlet GUI.
For the touchscreen, I would advise adding some StringItem to a Form using the StringItem.BUTTON appearance mode. I would hope that Nokia realized they needed to have the Form's ItemStateListener react to the user clicking on an Item.


text:
Q: Overloading ++ and -- checking on privately accessible min or max values How do I overload ++ and -- templates to increment and decrement with a min and max that is enforced at runtime within the operator overloads checking for max and min properties accessible only within the ++ and -- overloaded templates.
In this c# "pseudo code example"[sic] "not using overloaded templates"[sic]:
int x = 500;
int index = 503;

while(index > 0) {
   x--; // where operator overload min=0 and max = 1000;
   index -= 1;
 }
Console.Write("x={0}",x); // should see x=0

index = 0
while(index < 1050) {
   x++; // where operator overload min=0 and max = 1000;
   index += 1;
 }

Console.Write("x={0}",x); // should see x=1000

A: You question is very ill formulated..., but i think you're looking for
int max = 1000;
int min = 0;
int x = 500;

//Increment to max
while(x < max) x++;

Console.WriteLine(x); //Here you will see 1000

//Decrement to min
while(x > min) x--;

Console.WriteLine(x) //Here you will see 0

In the future, please be more specific when asking questions
Updated! From your comment i understand now that you want to overload the operators:
public static int operator ++ (int x)
{
    if(x > xmax) return x;
    return x++;
}

public static int operator -- (int x)
{
    if(x < xmin) return x;
    return x--;
}

This is how to do operator overloading but the above example won't work as you can overload primitive types as int, bool, etc.. But this would work for an object


text:
Q: Reduce font size of bibliography; overfull bibliography I am using Biber (backend of biblatex) to  make the bibliography. I have two questions about the bibliography.

*

*I want to use a reduced font ONLY for the bibliography (not the citation in the text, that in my text is in numeric style e.g. [1], [2] etc.). In particular, the font of my text is 11 pt and I want to print the bibliography in 10 pt.

*In the bibliography some text exceeds the text cage, because the ISBN is printed without a break. What is the command I should use for avoid this overfull hbox?

A: For the first question, in the bibliography section you can change the main font size, just as you do it in some particular section.
For example:
\bibliographystyle{Users/Daniele/Thesis/plainnat.bst}
%
{\small \bibliography{Users/Daniele/Thesis/bibliography}}

There are plenty font sizes: \tiny, \scriptsize, \footnotesize, \small, \normalsize, \large, \Large, \LARGE, \huge and \Huge.

A: I found this command:
\renewcommand*{\bibfont}{\small}

and work well. (first question).
For the second question, for now I used to break the ISBN with line (XXX-X-XXXX-XXXX-X, standard 13-number ISBN code). But I'm searching for a more general rule to avoid overfull in bibliography (for example, when I tried to use small font, a DOI URL exceeded the cage text; in this case a manual break doesn't work, because the URL doesn't work after text break)

A: Here is an option for people who use biblatex, add
\AtBeginBibliography{\small}

in the preamble after you import biblatex.

By the way, in Daniele's answer, please note that you also have to put \renewcommand*{\bibfont}{\small} after you import biblatex.


text:
Q: Modifying lists and environments I am reading Hadley Wickham advanced R on environments. Here it mentions:

Unlike most objects in R, when you modify an environment, it does not
  make a copy. For example, look at this modify() function.

modify <- function(x) {
  x$a <- 2
  invisible()
}

If you apply it to a list, the original list is not changed because
  modifying a list actually creates and modifies a copy.

x_l <- list()
x_l$a <- 1
modify(x_l)
x_l$a
## [1] 1

However, if you apply it to an environment, the original environment
  is modified:

x_e <- new.env()
x_e$a <- 1
modify(x_e)
x_e$a
## [1] 2

What does it mean that modifying a list creates and modifies a copy? I see that after applying modify(x_l), I would assume the object to which x_l points to has been modified. However, it hasn't (x_l$a is still 1). What is happening under the hood for the list not being updated by the modify function?

A: If a list is modified then a new list is created (and an object that is created in a function is local to that function and is removed when the function exits).  Note the computations below involving L1 and that the address of L1 has changed after it is modified.
On the other hand an environment has an identity distinct from its contents.  Changing the contents of an environment does not change the environment's identity. Note that after we modified the contents of the environment e1 that its address did not change.
library(pryr)

L1 <- list(a = 1)
address(L1)
## [1] "0xdb8aeb0"
L1$b <- 2
address(L1)
## [1] "0x841eca8"

e1 <- list2env(L1)
address(e1)
## [1] "0xbdf2420"
e1$c <- 3
address(e1)
## [1] "0xbdf2420"


text:
Q: AngularJS : Directive with watch in link I'm writing an angular directive that has a function called init() that needs to run when the page loads, and any time two variables change. I started out with this:
link: function(scope, elem, attrs){
    init();
    //Refresh the view when the the type or typeId changes
    scope.$watch("[type,typeId]", function(){init(scope)}, true);
},

But I noticed that init() was actually getting called twice. After I took the first init() out it obviously would only run once, but I'm just curious, is this expected behavior?
I thought watch functions only execute when something changes. Is it because they are technically "changing" (being initialized after link?) or is it just the natural behavior of $watch to immediately execute the function?

A: $watch listeners are called when they are registered. If you don't want to execute the code inside of your listener function when you are initializing the watcher, then you can do something like this:
scope.$watch("[type,typeId]", function(oldValue, newValue) {
    if (oldValue === newValue) return;

    // This code will only be hit when oldValue is different from newValue
    init(scope)
}, true);

A: appending to the accepted answer.. This even seems to be the "official" solution.

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.

http://docs.angularjs.org/api/ng.$rootScope.Scope#methods_$watch


text:
Q: Should I heat my room when I'm not here, energy-efficiently speaking? I was wondering as it's getting cold : is it better for my electricity bill to shut down completely my (electric) heater during day, and to turn it on again when I come home (then it will have to heat the room from something like 5°C to around 20°C), or should I keep the temperature around, say, 15°C while I'm away ?
I would naively guess it's better off, but I'm also wondering about inertia of the walls for instance...

A: The answer to your question depends on a number of variables that are not so easy to estimate.
If you have relatively weak isolation in the walls and windows it is better to lower the temperature during the day quite a bit, how much depends also on how long you are gone.
If the heat capacity of the room and the things in the room is high it will take a long time in the evening to heat up again, so you don't want to cool it down too much.
If you have tight sealing windows and doors lowering the temperature significantly during the day will put your room temperature below the condensation point of the water vapor, so you will have wet surface on which mold will grow on quickly.
There are quite a few engineers working on these problems but there is no answer from the pure physics side what is better. It all depends on what you want to achieve.
To estimate an answer you can use an electricity meter connected to your heater and measure the room temperature over time when you switch the heater off, the power you need to keep the temperature constant and the heating rate and maximum power when you warm up your room again. With these values you can work out the heat capacity as $$C \propto {\tau}{\kappa}$$ with the relaxation time constant $\tau$ and the thermal conductivity $\kappa$ (details for example in this Calorimeter description).

A: Let keep the problem as simple as possible. To start with some assumptions.

*

*The outside, or ambient temperature $T_a$ is constant.

*The temperature of your house $T_h$, is uniform over for your whole house, but a function of time $T_h(t)$. (Also known as an ideally stirred tank)

*The flow of heat out of your house is proportional can be cast into one heat transfer coefficient $h$ ($h$ will be smaller when your house is insulated better)

No heating
The budget of heat for your house, contains two terms, the change in amount of heat in your house, and the flow out of your house.
$$ c\frac{dT_h(t)}{dt}=-h(T_h(t)-T_a)$$
Where c is a constant related to the amount of heat that can be stored in your house (including the amount of heat stored in the walls, the size of your house, etc).
This is easy to solve $T_h(t)=T_a+(T_h(0)-T_a)e^{-\frac{h}{c} t}$
Now, if you come back at your home, you want to heat your house from $T_h(t)$ back to $T_h(0)$. Your electrical heater should gives this amount of heat, which is just $c(T_h(t)-T_h(0))$, which equals to
$$ Q_a = c \Big(T_a-T_h(0)\Big)\Big(1-e^{-\frac{h}{c}t_{away}}\Big)$$
where $Q$ is the amount of heat delivered by the heater and $t_{away}$ the time you've been absent.
Heater on
When you keep your heater on the whole time. The amount of heat delivered by your heater, is constant and equal to $$Q_b=-h t_{away} (T_h(0)-T_a)$$
Now, if you are away for a short period of time, you can linearize the exponent, and you see that the amount of heat that you need to put in your house by the heater is the same to first order. However, as your away-time increases, the amount of electricity you need in the first case will reach a constant value, while if you canstantly heat your house the electricity you need will increase linearly.
The heat capacity of the walls you mention, will in principle affect the constants $c$ (related to total heat capacity) and $h$ (related to heat lose), will only change the timescale for which both approaches are more or less equivalent, but it will not change the physics or equations.
So, to conclude: you should determine the values of $c$ and $h$ of your house. You can measure h by trying the second method once. And then c by trying out the first method. Good luck!

A: This is a very easy question to answer, though as some have pointed out, it's also easy to get confused by making it too hard. If you think about it correctly, the answer is immediately apparent.
Let me ask you an exactly equivalent question:
Let us suppose I have a leaky bucket, one with a hole in the bottom. I'm going to leave for the day, and I'm trying to decide whether I waste less water by keeping the bucket full all the time I'm gone, or whether it makes more sense for me just to let the bucket run dry and then refill it when I get home.
The answer is obvious: I waste far more water trying to keep the bucket filled. I should turn the water to the bucket off until I get home, then refill it. Note that this is true for any amount of time I'm gone; I always come out ahead when I don't keep the bucket full, because the pressure differential from having a full bucket leads to the water exiting the bucket faster than if the bucket were only partially full.
Similarly, you should turn off the heat to your home while you're away (assuming there is no other reason to keep your house warm, e.g. a pet or cold-sensitive items), then reheat it when you get back. You will always save money this way, since as the heat differential between the inside of the house and the outside lessens, your heat loss will in turn lessen.
This is true in all but the most contrived cases, such as, "I have a well-insulated heat source in my house that will lose its insulative properties and dump all its heat if the temperature drops below X degrees". Ignoring such silly "gotcha" scenarios, the answer is good for all realistic cases.

A: This problem is very simple, but it's easy to overcomplicate by looking at too small a scale. At every second – no matter what the heater does – you waste money by heating the outside of your house. The rate of heating – and thus the rate at which you waste money – is given by Newton's Law of Cooling. So
$$ \text{Wasted money} \propto \int (T_\text{in}-T_\text{out})\;dt $$
The lower your house's temperature, the less money you waste – no matter what. So set the thermostat to the lowest practical temperature when you're away.

A: The question is quite specific:  will my electricity bill be lower if I shut down my electric heater during the day when I am not there?  The answer is yes!!


text:
Q: How do I create/manage the stuff on private IP address of a device connected to LAN? Okay. I really didn't know how to explain the question in title. What I actually want to do is this:
Suppose a device is connected to WiFi, i.e. it's on LAN. It would have a private IP address like 192.168.xx.xx like that. What I want is my (android app/or technically general way) program to have access to that IP and display some info on it, like a webpage or maybe live screen of the device itself?
For ex: http://192.168.0.105:5901/thisScreen would stream live screen of a mobile device. This URL can opened by any device connected to LAN. How do I achieve that streaming access on that particular IP address assigned to the device? (Assume I've control to everything).
How do I even begin for this? Networking? How do I implement it? Any references? I tried to Google my problem but didn't find any help.

A: Since you ask in general, what you want is to serve sth on a lan ip ex: on 192.168.1.50:80 and that is available to everyone on the same lan to be precise in 192.168.1.0/24 right?
Well if you haven't done any configuration such as subnets smaller than /24 that is what happening by default.
To confirm that run a web server an nginx for example on a local machine and visit the ip of this machine from another device on the same lan, you will see the default page of nginx.
So the only thing you have to configure is a service to run on a local machine and serves sth.


text:
Q: Unable to assign values to a 3D char array Typing the following lines of code gives me errors:
private char[][][] amino = new char[4][4][4];
amino[2][1][3], amino[2][1][1], amino[2][1][0], amino[2][1][2] = 'A';
amino[1][2][3], amino[1][2][1], amino[1][2][0], amino[1][2][2] = 'R';
amino[0][0][3], amino[0][0][1] = 'N';

jGrasp (the IDE that I use) gives me error saying ']' expected.
Tried it in Eclipse and also gives me a similar error. What am I doing wrong!

A: The commas between amino[2][1][3], amino[2][1][1],... are not correct Java syntax.  Try this:
amino[2][1][3] = amino[2][1][1] = amino[2][1][0] = amino[2][1][2] = 'A';

A: You cant use variables like this.
You can use multiple declaration of variables of same type with adding the same value into them. But there are few restrictions :
You can do this :
    int a = 3, b = 5;

But you cant do this later :
     a = 1, b = 7;

For example this >
private char[][][] amino1, amino2, amino3 = new char[4][4][4];

Adds to amino3 the a new empty array of 4x4x4 and the amino1 and amino2 stays uninitialized.


text:
Q: Adding non-CMS (Django) page to Wagtail menu I may not be understanding something obvious, but I'm struggling to add a (top-level) menu item to my Wagtail based menu that hooks to a page rendered by an included app that doesn't know about Wagtail.  Ideally, it is just a normal Django TemplateView with standard urlconf, though I may need to add some custom code.
If I use the custom URL in the menu editor, I get a not found from Wagtails core.serve.  I've looked at snippets, wagtail hooks, RoutablePageMixin, and the custom URL in the menu editor and none seem like it accomplishes what I'm trying to do.
It may well be that I'm simply misunderstanding the docs, but is there a simple example of someone doing this?  The closest I've found so far is https://www.caktusgroup.com/blog/2016/02/15/wagtail-2-steps-adding-pages-outside-cms/.   I've also searched https://docs.wagtail.io/en/v2.4/advanced_topics/third_party_tutorials.html to now avail.  Any guidance appreciated.
Thx,
   --Don

A: Hope this is useful, but it seems that my problem was not the mixing of Wagtail and non-Wagtail items - it was in my URLConf - Wagtail.core.serve occurred before the Django url I was trying to reach and was trying to respond.   Once I reordered the URLConf appropriately, I am getting the view as I wanted.
Sigh...


text:
Q: Indexes for select performance I have a table:
CREATE TABLE `t1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` enum('new','paid') NOT NULL DEFAULT 'new',
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  `can_be_closed` tinyint(1) NOT NULL DEFAULT '1',
  `close_reason` varchar(255) DEFAULT NULL,
  `interval_before_close` int(11) NOT NULL DEFAULT '10',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

And following select:
SELECT `id`, `status`, `close_reason` AS `closeReason`, `createdAt`, `updatedAt`
FROM `t1` as t
WHERE (
`t`.`status` = 'new'
AND `t`.`updatedAt` < '2018-06-22 10:14:36' + INTERVAL `interval_before_close` MINUTE
AND `t`.`can_be_closed` = true
)

For this query, explain return a full table scan.
I tried to add the following indexes:
ALTER TABLE `t1`
ADD INDEX `updatedAt` (`updatedAt` ASC);

and:
ALTER TABLE `t1`
ADD INDEX `updatedAt` (`updatedAt` ASC, `interval_before_close` ASC);

but without any change in explain.
Fidle ex.: link

A: Plan A (not good):
Off hand, I would say it is optimal is to list = column(s) first, then a range:
INDEX(status, can_be_closed,   -- in either order
      updatedAt)               -- last

But...  It is more complicated than that.
'2018...' + INTERVAL interval_before_close ...

is essentially a function call to compute a date.  That makes it useless to put either updatedAt or interval_before_close in the index.
Plan B (wimpy):
So...  The following may be useful, but only if not many of the rows match those two flags:
INDEX(status, can_be_closed)   -- in either order

Cookbook
Plan C (complex):
If, on the other hand, you had a column (real or computed) that contained
updatedAt - INTERVAL interval_before_close MINUTE

Say that it column is called early_close; then change to
AND early_close < '2018-06-22 10:14:36'

and add
INDEX(status, can_be_closed, early_close)


text:
Q: Recreating a Postgres table with all cascading relations transferred I'm trying to optimize the structure of a table. To do so, I've put the columns in the most optimal order possible and then ran this query (simplified):
INSERT INTO table_new ("id", "some_field", "some_other_field") SELECT "id", "some_field", "some_other_field" FROM table_current;

Then I simply rename the table and add all the same indexes and foreign keys.
ALTER TABLE "table_current" RENAME TO "table_old";
ALTER TABLE "table_new" RENAME TO "table_current";
ALTER TABLE "table_current" ADD PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE;

This has worked great in the past, but in this particular case, there are a LOT of other tables with cascading foreign keys on this table.
So if I recreate and rename, then all the other tables still reference table_old in their foreign keys instead of the new table_current.
How do I do such a table migration like this without having to recreate the foreign keys on every other table as well?

A: There is no easy way to work around the problem. When you drop columns that other things are referencing, like views or foreign keys, you must manually inform all areas of the schema that have dependencies on that column.
There is no shortcut that I know of around this. No one really makes a habit of reordering tables. Most of the requests are for cosmetic reasons, however if you're really doing it for a valid reason (like table packing) then I wish you the best of luck.
It's been a feature request for a while, and it comes up frequently.


text:
Q: PHP outputs mysqli row values outside while loop I am trying to output row values outside while loop for this
$sql = mysqli_query($connection, "select username from accounts where rank='admin'");

         while($row = mysqli_fetch_array($sql)) {

           $username = $row['username'];

         }

I would like to output and print the result outside the while loop.
I Tried print_r but it doesn't seem to work, it only shows the last or first value but not all.

A: You need to save each value in an array inside of the while loop.
while($row = mysqli_fetch_array($sql)){
  //save in array
  $username[] = $row['username'];
}

//output values
print_r($username);

You need the brackets [] to save each value into the array. $username[]


text:
Q: I need help troubleshooting why mySQL queries are taking longer than expected I am troubleshooting why a php script takes so long to run and can sometimes time out. I have a database filled with product information (~50,000 total records) from a handful (9 total) of suppliers. The script pulls an XML file containing list of products that have changes from each supplier's feed, finds that record, then modifies it appropriately.
The query to find the single product record that matches the supplier's SKU and supplier ID in the product table is taking between 0.25 seconds and 0.5 seconds, so a small update of ~400 rows is taking over 2 minutes. I am new to database performance, and I am struggling to understand why I have a very simple query that's taking an incredibly long time to run.
I first commented out every query where it searched the database to see how long the script itself would take to iterate through the XML files. It would iterate through the 400 records in 1-2 seconds. I then added in the first query that is encountered in the iteration, which was executing the search to find the correct entry in the table for the product called out in the XML file. This is where the timing jumped to a 2 minute runtime for the script.
The iteration code, summarized for the relevant parts:
$checkq = "SELECT * FROM productLinks WHERE affiliateSKU=:sku AND supplierID=:sid";
$checkqs = $DBHa->prepare($checkq);

$xml = simplexml_load_file($supplierURL,"SimpleXMLElement",LIBXML_NOCDATA);
foreach($xml->children() as $products) {
 //Set variables from the XML

 $checkqs->execute(array(':sku'=>$sku, ':sid'=>$supplierID)); //This is the problem query
 //I capture the number of results (should always be 1 or 0),
 //and modify the entry if the result is 1, and insert a new entry if 0)
}

In my research for what the problem could be, I picked a random entry and ran the above query directly in phpMyAdmin and had times anywhere from 0.1 to 0.75 seconds. I used some troubleshooting steps I found while researching, but can't figure out what it really means.
I used the Explain statement, and returned the following:
id | select_type | table        | type | possible_keys | key        | key_len | ref   | rows  | Extra
1  | SIMPLE      | productLinks | ref  | supplierID    | supplierID | 4       | const | 11827 | Using where

I then ran Profile on the query, and while the query itself took 0.2218 seconds to return the 1 result according to phpMyAdmin, the Profile results returned a total of 0.00293 seconds as follows:
Status                Duration
starting              0.000132
checking permissions  0.000009
Opening tables        0.000007
init                  0.000011
optimizing            0.000007
executing             0.000010
end                   0.000007
query end             0.000006
closing tables        0.000019
freeing items         0.000075
cleaning up           0.000010

Can anyone help me understand exactly what is making my query take so long, and how I might be able to improve performance?

A: For better performance be sure you have  a composite index on
table  productLinks

columns  (affiliateSKU, supplierID)


text:
Q: sqlite insert on button click I have an embedded database with my app. it's in the asset folder. The user should be able to add new rows to the database on button click. I have the following code for that:
insertrow.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                db.open();
                try
                {
                    String editmacs=editmac.getText().toString();
                    db.insertrow(editmacs);
                //  Context context = getApplicationContext();

                }
                catch (Exception ex)
                {
                  Toast.makeText(getApplicationContext(), "cannot update", Toast.LENGTH_LONG).show();
                  }
                db.close();
            }
          });

and the relevant method in my SQliteOpenHelper class is:
public static SQLiteDatabase myDb;
public static String DATABASE_TABLE="access_points";
public static final String KEY_column1 = "col1";
public static final String KEY_column2 = "col2";
public static final String KEY_column3= "col3";
public static final String KEY_column4 = "col4";

public long insertrow(String editmacs)
        {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_column1, editmacs);
            initialValues.put(KEY_column2, "uf");
            initialValues.put(KEY_column3, "ub");
            initialValues.put(KEY_column4, "uz");
            return myDb.insert(DATABASE_TABLE, null, initialValues);
        }

The problem is with button click the editmacs (KEY_column1) is not inserted into the database. But the other values(FOR EXAMPLE "uz") are inserted(i tested the inserted values with sql query). During insertion using buttonpress i dont get any exception. Can anyone tell why editmacs value from edittext is not inserted? Thanks in advance.
Ok i got the solution from Guillaume's comments (see below). The queries related to insert are ok. The problem is elsewhere. Look at the following code:
buttonuserentry.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                db.open();
                try
                {
                    String mac = "";
                    mac = db.getuserentry();
                    Context context = getApplicationContext();
                    String text = mac;
                    int duration = Toast.LENGTH_LONG;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }
                catch (Exception ex)
                {
                    Context context = getApplicationContext();
                    CharSequence text = ex.toString();
                    int duration = Toast.LENGTH_LONG;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }
                db.close();

            }
        });

previously, i was using this:
CharSequence mac = "";
mac = db.getuserentry();
Context context = getApplicationContext();
String text = mac;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();

Because i was using CharSequence, it was showing the last inserted mac address from the original database. The original embedded database declared this column as Text(so that means Text= CharSequence in Sqliteman). My expected mac address is the last typed mac address by the user. This mac address from editmac view is converted to String. So, one must retrieve it as String, not as CharSequence. Thanks again to Guillaume's help in directing me to the solution.

A: There's nothing wrong with your code, it should insert the passed value in the column.
Try to make sure you have a value by adding some kind of debug alert, like a Toast:
String editmacs=editmac.getText().toString();
Toast.makeTest(getApplicationContext(), "Value to insert = " + editmacs, Toast.LENGTH_SHORT).show();
db.insertrow(editmacs);

And let me know if you get the value you expect. If no (which is my guess), then that's probably because you read the text value from the wrong TextView.
Are you sure editmac is correctly initialized from the right view?


text:
Q: Collapsing Categorical Feature Levels in Python StatsModels OLS output I am trying to create a multiple linear regression model to predict
the rating a guest gives to a hotel (Reviewer_Score) in Python using statsmodels.
Review_Total_Negative_Word_Counts is how long their negative comments about the hotel are
Total_Number_of_Reviews is how many reviews the hotel has
Review_Total_Positive_Word_Counts is how long their positive comments about the hotel are
Total_Number_of_Reviews_Revewier_Has_Given is how many reviews the guest has given on the site
Attitude is a categorical variable: GOOD or BAD
Reason is reason for visit (Leisure or Business)
Continent is the continent which the guest came from (multiple levels)
Solo is whether the traveler is a solo traveler ('Yes' or 'No')
Season is during which season the guest stayed at the hotel ('Fall', 'Winter', 'Summer', 'Spring')
As you can see, I have some numeric and also categorical features.
My code so far is:
import statsmodels.formula.api as smf
lm = smf.ols(formula = 'Reviewer_Score ~ Review_Total_Negative_Word_Counts + Total_Number_of_Reviews + Review_Total_Positive_Word_Counts + Total_Number_of_Reviews_Reviewer_Has_Given + Attitude + Reason + Continent + Solo + Season', data = Hotel).fit()

lm.params
lm.summary()
My issue is that when I look at the parameters (slopes and intercept estimates) also P-values, they look like:

The levels of each of the categorical features are included and I just want to have an output that shows us the slopes and p-values for numeric and categorical features (NOT the slopes and p-values for each level in the categorical features!)
Essentially, I want the slope output to look like:
Intercept
Total_Number_of_Reviews
Review_Total_Positive_Word_Counts
Total_Number_of_Reviews_Revewier_Has_Given
Attitude
Reason
Continent
Solo
Season
How would I do something like this to collapse the levels and just show the significance and slope value for each of the variables?

A: Right now, each of your original inputs to your model is being converted into dummy variables.*
The reason this clashes with your expectations, I suspect, is that you have three types of variables you call categorical in your model:

*

*Temporal ("Season")

*Binary ("Attitude", "Reason", "Solo")

*Categorical ("Continent")

OnlyContinent is truly non-binary categorical as there is no way to order the continents in a hierarchy without any further information. For "Season" the model/program has no indication that there are only four seasons, or that they occur in a temporal order. With the binary variables, it similarly doesn't know that there are only two possible values.
I recommend converting binary variables to 1,0, or Nan (you could first use a lambda function, followed by pd.fillna()).
For "Season" specifically, it sounds you want something more akin to "time of year, indicated by season/quarter." I'd map the seasons to 1,2,3 or 4.
For the "Continent" you could rank the continents by how many reviews you have from each, and convert each continent to its respective rank... but you'd be regressing on something more akin to a blend of "continent" + "population from originating continent."  (This, of course, may be useful to do anyways). Or, you could keep the dummy variable encoding that was already utilized.
Alternatively, you could come up with a random mapping for the continent, but include some indicator of the relative population from each continent in addition.
*To make this explicit, you can use pd.get_dummmies()


text:
Q: How do you limit a component to be in a certain spot I'm creating a slideshow using swing and trying to place it in the center of my JFrame. The slideshow works fine, but it's taking up the entire center section. How would I limit it to a small place under the banner?
Here's a picture of what it looks like.

Here's a picture of what I want it to look like

This is what I have so far, you run this class.
package com.RBV2.engine;

import javax.swing.*;

import com.RBV2.Settings;
import com.RBV2.panels.News;
import com.RBV2.panels.SlideShow;
import com.RBV2.panels.SlideShow.MovingPanel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import java.io.*;
/*
 * Author Jon & David
 *
 */
@SuppressWarnings("serial")
public class Client extends JFrame implements ActionListener {
    private JPanel bottomPanel, news;
    private JButton launch;
    private JLabel loading, banner;
    private MovingPanel slideshow;

    protected boolean updated = false;

    private void createLayout() {
        createPanel();
        addPanel();
        setVisible(true);
    }

     private void createPanel() {
         bottomPanel = new JPanel(new BorderLayout());
         news = new News();
         slideshow = new SlideShow.MovingPanel();
         launch = new JButton(new URL("http://www.runerebellion.com/clientImages/launch.png"));
         loading = new JLabel(new URL("http://www.runerebellion.com/clientImages/loader.gif"));
         banner = new JLabel(new URL("http://www.runerebellion.com/clientImages/201457.gif"));
         launch.addActionListener(this);
     }

     private void addPanel() {
         setTitle("RuneRebellionV2 Launcher");
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         setResizable(false);
         //Bottom Panel
         add(bottomPanel, BorderLayout.SOUTH);
         bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
         bottomPanel.setBackground(Color.BLACK);
         bottomPanel.add(launch, BorderLayout.EAST);
         launch.setPreferredSize(new Dimension(120, 40));
         //News Feed
         add(news, BorderLayout.CENTER);
         news.add(banner, BorderLayout.CENTER);
         banner.setPreferredSize(new Dimension(500, 70));
         //slideshow
         slideshow.setPreferredSize(new Dimension(610, 331));
         add(slideshow, BorderLayout.CENTER);
         //Sets size
         setSize(Settings.width, Settings.height);
     }

     public Client() throws IOException {
        createLayout();
    }

    public static void main(String args[]) throws IOException {
        final Client l = new Client();
        l.setVisible(true);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                l.setVisible(true);
            }
        });

    }

These specific lines of code call the slideshow(I commented out exactly where)
 private void addPanel() {
 setTitle("RuneRebellionV2 Launcher");
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 setResizable(false);
     //Bottom Panel
     add(bottomPanel, BorderLayout.SOUTH);
     bottomPanel.add(new JLabel(" Launcher, release " + Settings.version), BorderLayout.WEST);
     bottomPanel.setBackground(Color.BLACK);
     bottomPanel.add(launch, BorderLayout.EAST);
     launch.setPreferredSize(new Dimension(120, 40));
     //News Feed
     add(news, BorderLayout.CENTER);
     news.add(banner, BorderLayout.CENTER);
     banner.setPreferredSize(new Dimension(500, 70));
     //slideshow here
     slideshow.setPreferredSize(new Dimension(610, 331));
     add(slideshow, BorderLayout.CENTER);
     //Sets size
     setSize(Settings.width, Settings.height);
 }

Here is my slideshow class, you may need this also.
package com.RBV2.panels;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class SlideShow extends JFrame {
    public static class MovingPanel extends JPanel {
        public int i = 0;

    public MovingPanel() {
        Timer timer = new Timer(3000, new TimerListener());
        timer.start();
    }

    protected void paintComponent(Graphics x) {
        super.paintComponent(x);
        int y = i % 25;

        Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
        x.drawImage(showImg, 0, 0, getWidth(), getHeight(), 0, 0, 610, 331, null);
    }

    class TimerListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            i++;
            repaint();
            if (i >= 5)
                i = 1;
        }
    }

}
}

So my question is how would I limit the slideshow to be in a box in the very center under the banner.

A: Have a look at this picture (from Border layout Tutorial)

As you are only adding panels to the Center and South(PAGE_END) regions of the layout manager there is no other components to stop the center panel from stretching out as far as it can.
Note this relevant sentence of the tutorial

If the window is enlarged, the center area gets as much of the available space as possible. The other areas expand only as much as necessary to fill all available space. Often a container uses only one or two of the areas of the BorderLayout object — just the center, or the center and the bottom.

You either need to add blank panels on the other sides or make use of an empty border within your Center panel. See here about how to use borders.

A: I painted the background, then painted the images over the background
protected void paintComponent(Graphics x) {
            super.paintComponent(x);
            int y = i % 25;

            Image showImg = new ImageIcon("bin/slide/" + y + ".png").getImage();
            super.paintComponent(x);
            x.drawImage((Settings.background).getImage(), 0, 0, getWidth(), getHeight(), this);
            x.drawImage(showImg, 360, 260, getWidth(), getHeight(), 0, 0, 110, 31, null);
}


text:
Q: How to get difference between start and end time with duration? I have a table in which each row has StartTime, EndTime and duration with other columns, for example:
Unique_ID        SartTime             EndTime         Duration
    1       08:00:00.0000000      12:00:00.0000000      10

I need to write a query which returns result something similar to:
Unique_ID        SartTime             EndTime         Duration
    1       08:00:00.0000000      08:10:00.0000000      10
    1       08:10:00.0000000      08:20:00.0000000      10
    1       08:20:00.0000000      08:30:00.0000000      10
and so on... till
    1       11:50:00.0000000     12:00:00.0000000       10

Thanks in advance:)

A: I changed your data to show that the duration can be different, and that the query works with multiple rows. Also I changed it to make the results shorter.
DECLARE @yourTable TABLE (Unique_ID INT, StartTime TIME, EndTime TIME, Duration INT);
INSERT INTO @yourTable
VALUES  (1,'08:00:00.0000000','8:30:00.0000000',10),
        (2,'06:00:00.0000000','7:00:00.0000000',30);

;WITH CTE_Recursion
AS
(
    SELECT  Unique_ID,
            StartTime,
            DATEADD(MINUTE,Duration,StartTime) NextTime,
            EndTime,
            Duration
    FROM @yourTable

    UNION ALL

    SELECT Unique_ID, DATEADD(MINUTE,Duration,StartTime),DATEADD(MINUTE,Duration,NextTime),EndTime,Duration
    FROM CTE_Recursion
    WHERE DATEADD(MINUTE,Duration,StartTime) < EndTime
)

SELECT Unique_ID,StartTime,NextTime,Duration
FROM CTE_Recursion
ORDER BY Unique_ID,StartTime

Results:
Unique_ID   StartTime        NextTime         Duration
----------- ---------------- ---------------- -----------
1           08:00:00.0000000 08:10:00.0000000 10
1           08:10:00.0000000 08:20:00.0000000 10
1           08:20:00.0000000 08:30:00.0000000 10
2           06:00:00.0000000 06:30:00.0000000 30
2           06:30:00.0000000 07:00:00.0000000 30

A: If your DBMS doesn't support recursion you can utilize a cross join to a table with numbers in it. I use values between 0 and 1439 because a day has 1440 minutes, of course you should decrease this based on your data). This is pure Standard SQL:
SELECT Unique_ID
  ,StartTime + (n * INTERVAL '10' MINUTE)
  ,CASE
      WHEN StartTime + ((n +1) * INTERVAL '10' MINUTE) < EndTime
      THEN StartTime + ((n +1) * INTERVAL '10' MINUTE)
      ELSE EndTime
   end
FROM vt
CROSS JOIN
  (SELECT n FROM number_table WHERE n BETWEEN 0 AND 1439) AS numbers
WHERE StartTime + (n * INTERVAL '10' MINUTE) >= StartTime
  AND StartTime + (n * INTERVAL '10' MINUTE) <  EndTime
ORDER BY 1,2


text:
Q: Animated glow/flash of UIButton text I have a UIButton set as a custom button with button.TitleLabel.text set with some text.
This makes it look just like a label that can be pressed.
I'd like to have an animated glow on the text, so it draws the attention of the user.
Is this possible?
Thanks

A: Check out the RRSGlowLabel class. It extends UILabel, but you could find it useful to.
Hope this helps.


text:
Q: Create time operation that controls memory and CPU consumption ios Good evening.
My target is to create an application that runs in the background and consumes a controllable amount of recources. CPU, Memory, network resources, etc.
The user will set the time the operation will run for, the CPU consumption level, and the memory occupied by the app.
When he presses "start" the app will create the operation with a timer for a specific amount of time and will start a task that consumes the resources specified...
I am not really sure how to use controllable resources. Can someone, please point me to the right direction?
Regards,
LSonic

A: Once your app is in the background, you no longer have control of your resources. There are a few things that can be done to have some resources, but if your app attempts to hog or deliberately consume resources, you will be terminated.
While your app is in the foreground, you can use as much memory and CPU time as you want, but at your own hazard. If you stall the UI thread too long, you will be killed. If the system believes your background thread is hung at 100% CPU usage, you will also be killed.
Why are you trying to do this? If we knew your goals, we may be able to offer better ways to achieve them. What you are suggesting now is a dead end.


text:
Q: Android with Sqlite - How to check if table exist and if empty I want to show an alertbox if the table does not exist or the table content is empty.
To check if the table is empty I'm using:
        cCheckDB = db.rawQuery("SELECT COUNT(*) FROM " + MainActivity.TABLE_NAME +"", null);

        if (cCheckDB != null) {
            cCheckDB.moveToFirst();

            if (cCheckDB.getInt (0) == 0) {
                // EMPTY
            }
        }

But how to wrap this in an "if table exist"? What is the best way?
I know both ways to check if a table exist or to check if there is content in it. But I want to use the checks in a meaningful and way and not in single query if this is possible - that's my question.

A: Hope,This will be helpful to you. It's working well!!!
public boolean isTableExists(String tableName, boolean openDb) {
    if(openDb) {
        if(mDatabase == null || !mDatabase.isOpen()) {
            mDatabase = getReadableDatabase();
        }

        if(!mDatabase.isReadOnly()) {
            mDatabase.close();
            mDatabase = getReadableDatabase();
        }
    }

    Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
    if(cursor!=null) {
        if(cursor.getCount()>0) {
                            cursor.close();
            return true;
        }
                    cursor.close();
    }
    return false;
}

A: To check that your table exists or not, you can use:
SELECT name FROM sqlite_master WHERE type='table' AND name='table_name';
here, replace table_name with your table name you want to change
EX:
SELECT name FROM sqlite_master WHERE type='table' AND name='Employee_Details';

A: the more optimal way is to check if table exist then check if record exist or not
 private void clearTable(String tableName) {
        int count;
        Cursor cursor = db.rawQuery("SELECT count(*) FROM sqlite_master WHERE type='table' AND " +
                "name= " + tableName, null);
        cursor.moveToFirst();
        count = cursor.getInt(0);
        if (!cursor.isClosed())
            cursor.close();

        if (count > 0)//table exist now delete record if it exist
        {
            cursor=db.rawQuery("select exists(select 1 FROM " + tableName + ")", null);
            cursor.moveToFirst();
            count = cursor.getInt(0);
            if (!cursor.isClosed())
                cursor.close();
            if (count > 0)
                db.execSQL("delete from " + tableName);
        }
    }


text: Q: Android: Pull SwipeRefreshLayout from left to refresh I am using a horizontol recyclerview inside a SwipeRefreshLayout. Is it possible for me to activate the refresh on the recyclerview by pulling from left to right instead of top to bottom ? A question already exists but there are no solutions on that.


text:
Q: C: Trouble understanding pointers in the while loop of this code I'm using a debugger to read through this code, and I'm a little confused by while ((*d++ = *s2++)); - in the debugger variables, d seems to shorten after each loop (goes from 'Hello hello' to 'ello hello' while s1 changes to 'cello hello'). What is the while loop looping through (shouldn't it be while(condition); do(something))?
Why aren't the variable values of d and s1 the same (isn't d is a pointer to s1)? And when they return to the main function, is curdst = the pointer of dst?
/*
  Input: char pointers for source (s2) and destination (s1)

  Output: returns the pointer to the destination (s1)
*/

char *my_strcpy(char * , const char * );

int main()
{

  char src[] = "cs23!";
  char dst[]="Hello hello";
  char *curdst;
  int len=0;

  while(src[len++]);

  // do the copy

  curdst= my_strcpy(dst, src);

  // check to see if the NULL char is copied too.

  printf("dst array %s and last element %d\n", dst, atoi(&dst[len]));

  return 0;

}

char *my_strcpy(char *s1, const char *s2) {

  register char *d = s1;

  // print the pointer variables address and their contents, and first char

  printf("s2 address %p, its contents is a pointer %p to first char %c \n", (void *)&s2, (void *)s2, *s2);
  printf("s1 address %p, its contents is a pointer %p to first char %c \n", (void *)&s1, (void *)s1, *s1);

  while ((*d++ = *s2++));
  return(s1);

}

A: This is a rather typical didactic implementation of strcpy(). It works like this:

*

*my_strcpy() takes two arguments. The first argument is a pointer to the first element of a destination character array. The second argument is a pointer to the first element of a source character string, that is, a character array terminated by a NUL (aka \0) character. The function copies the characters from the source string to the destination buffer, including the NUL terminator, and returns a pointer to the first element of the destination buffer.
char *my_strcpy(char *s1, const char *s2) {

*First things first, make a copy of the first argument, because we need to return it after the copying is done.
char *d = s1;

*Then, copy the characters; this is done in a tight loop, working like this:

*

*Copy the current character * s2 to the place pointed to by d, as if executing * d = * s2; then

*Increment d to point to the next place in the destination buffer as if executing d++ and increment s2 to point to the next character to be copied as if executing s2++; and

*Exit the loop if the last character which was copied was NUL.

This is written in a very concise manner:
while (* d++ = * s2++);

* s2++ means "take the character pointed to by s2 then increment s2". Similarily, * d++ as a left-hand value means "use the variable pointed to by d then increment d". The order of precedence of operators helps dispense with parentheses because ++ has higher priority than * which has higher priority than =. The value of the assignment is the assigned value, so the loop ends when the assigned character has the value 0.

*Finally, return s1, which was not changed by the function.
return s1;
}


text:
Q: google maps api 3 change custom icon size upon zoom level event I am struggling to apply a icon zoom level change function to my google maps api script.
My current icon size is 48px and the actually graphic is also 48px.
jsfiddle.net/motocomdigital/hQkb3/6

Determined like this...
var image = new google.maps.MarkerImage(
  '<?php bloginfo('template_url'); ?>/images/marker-images/image-48px.png',
  new google.maps.Size(48,48),
  new google.maps.Point(0,0),
  new google.maps.Point(24,48)
);

I don't suppose it is possible to change these sizes and graphics depending on 3 zoom levels?

For example, when a zoom is at...
Zoom Level 0 > 6 - uses...
  '<?php bloginfo('template_url'); ?>/images/marker-images/image-12px.png',
  new google.maps.Size(12,12),
  new google.maps.Point(0,0),
  new google.maps.Point(6,6)

Zoom Level 6 > 8 - uses...
  '<?php bloginfo('template_url'); ?>/images/marker-images/image-24px.png',
  new google.maps.Size(24,24),
  new google.maps.Point(0,0),
  new google.maps.Point(12,12)

Zoom Level 8+ - uses...
  '<?php bloginfo('template_url'); ?>/images/marker-images/image-48px.png',
  new google.maps.Size(48,48),
  new google.maps.Point(0,0),
  new google.maps.Point(24,24)

This is my original script below...
jQuery(function($){

    var image = new google.maps.MarkerImage(
      '<?php bloginfo('template_url'); ?>/images/marker-images/image.png',
      new google.maps.Size(48,48),
      new google.maps.Point(0,0),
      new google.maps.Point(24,24)
    );

    $('#map_div').gmap3({
        action:'init',
        options: {
            center:[<?php echo $lt;?>,<?php echo $lo;?>],
            zoom: 7,
            scrollwheel: false
        }
    },
    {
        action: 'addMarkers',
        markers: [ <?php echo $lat_long;?> ],
        marker: {
            options: {
                draggable: false,
                icon: image
            },
            events:{
            mouseover: function(marker, event, data){
                var map = $(this).gmap3('get'),
                    infowindow = $(this).gmap3({ action:'get', name:'infowindow' });
                if (infowindow) {
                    infowindow.open(map, marker);
                    infowindow.setContent(data);
                } else {
                    $(this).gmap3({action:'addinfowindow', anchor:marker, options:{content: data}});
                }
            },
            mouseout: function(){
                var infowindow = $(this).gmap3({ action:'get', name:'infowindow' });
                if (infowindow){
                    infowindow.close();
                }
            }
        }

    }
    });
});

I am really not great with this level of scripting, and any pointers ideas or help would be great thanks.
Josh

A: I added a "zoom_changed" event to your map that changes all marker icons according to the zoom level.
function UseMarkerIcon(imageObj)
{
  var markers=$("#map_div").gmap3({action:'get',name:'marker',all:true});
  $.each(markers, function(i,marker)
  {
    marker.setIcon(imageObj);
  });
}

jQuery(function($) {
    var image12px = new google.maps.MarkerImage('http://motocomdigital.co.uk/assets/marker-images/map-marker-12px.png', new google.maps.Size(12, 12), new google.maps.Point(0, 0), new google.maps.Point(6, 6));
    var image24px = new google.maps.MarkerImage('http://motocomdigital.co.uk/assets/marker-images/map-marker-24px.png', new google.maps.Size(24, 24), new google.maps.Point(0, 0), new google.maps.Point(12, 12));
    var image48px = new google.maps.MarkerImage('http://motocomdigital.co.uk/assets/marker-images/map-marker-48px.png', new google.maps.Size(48, 48), new google.maps.Point(0, 0), new google.maps.Point(24, 24));

    $('#map_div').gmap3({
        action: 'init',
        options: {
            center: [50.799019, -1.132037],
            zoom: 5,
            scrollwheel: false
        },
              events:{
                      zoom_changed: function(map){
                          var zoomLevel = map.getZoom();

                          if (zoomLevel < 6)
                            UseMarkerIcon(image12px);
                          else if (zoomLevel >= 6 && zoomLevel <=8)
                            UseMarkerIcon(image24px);
                          else
                            UseMarkerIcon(image48px);
                      }
              }
    }, {
        action: 'addMarkers',
        markers: [{
            lat: 50.799019,
            lng: -1.132037,
            data: 'Test One'},
        {
            lat: 50.365162,
            lng: -4.712017,
            data: 'Test Two'},
        {
            lat: 54.518726,
            lng: -5.881054,
            data: 'Test Three'},
        {
            lat: 52.780964,
            lng: -1.211863,
            data: 'Test Four'},
        {
            lat: 51.433998,
            lng: -2.549690,
            data: 'Test Five'}],
        marker: {
            options: {
                draggable: false,
                icon: image12px
            },
            events: {
                mouseover: function(marker, event, data) {
                    var map = $(this).gmap3('get'),
                        infowindow = $(this).gmap3({
                            action: 'get',
                            name: 'infowindow'
                        });
                    if (infowindow) {
                        infowindow.open(map, marker);
                        infowindow.setContent(data);
                    } else {
                        $(this).gmap3({
                            action: 'addinfowindow',
                            anchor: marker,
                            options: {
                                content: data
                            }
                        });
                    }
                },
                mouseout: function() {
                    var infowindow = $(this).gmap3({
                        action: 'get',
                        name: 'infowindow'
                    });
                    if (infowindow) {
                        infowindow.close();
                    }
                }

            }

        }
    });
});

The function UseMarkerIcon(image) iterates through all your markers and sets the image you pass to it.


text:
Q: MongoDB - Geospatial intersection of two polygon Is there any way we can query and get location data using mongodb geospatial query that matches the following criteria?

*

*Getting all locations that are part of intersection between two boxes or in general two polygons.

For example below can we get in query output only those locations that are within the yellow area which actually is the common area for the purple and red geometric objects [ polygons ] ?

My study of mongodb document so far

*

*http://docs.mongodb.org/manual/reference/operator/query/geoWithin/

This provides results that are within one or more polygons [ I am looking for the intersection of these individual polygon results as output ]

Use case
    db.places.find( {
   loc: { $geoWithin: { $box:  [ [ 0, 0 ], [ 100, 100 ] ] } }
} )

Above query provides results within a rectangle geometric area [ I am looking for locations that are common to two such individual queries ]

    db.places.find( {
   loc: { $geoWithin: { $box:  [ [ 0, 0 ], [ 100, 100 ] ] } }
} )

    db.places.find( {
   loc: { $geoWithin: { $box:  [ [ 50, 50 ], [ 90, 120 ] ] } }
} )

A: So looking at this with a fresh mind the answer is staring me in the face. The key thing that you have already stated is that you want to find the "intersection" of two queries in a single response.
Another way to look at this is you want all of the points bound by the first query to then be "input" for the second query, and so on as required. That is essentially what an intersection does, but the logic is actually literal.
So just use the aggregation framework to chain the matching queries. For a simple example, consider the following documents:
{ "loc" : { "type" : "Point", "coordinates" : [ 4, 4 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 8, 8 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 12, 12 ] } }

And the chained aggregation pipeline, just two queries:
db.geotest.aggregate([
    { "$match": {
        "loc": {
            "$geoWithin": {
                "$box": [ [0,0], [10,10] ]
            }
        }
    }},
    { "$match": {
        "loc": {
            "$geoWithin": {
                "$box": [ [5,5], [20,20] ]
            }
        }
    }}
])

So if you consider that logically, the first result will find the points that fall within the bounds of the initial box or the first two items. Those results are then acted on by the second query, and since the new box bounds start at [5,5] that excludes the first point. The third point was already excluded, but if the box restrictions were reversed then the result would be the same middle document only.
How this works in quite unique to the $geoWithin query operator as compared to various other geo functions:

$geoWithin does not require a geospatial index. However, a geospatial index will improve query performance. Both 2dsphere and 2d geospatial indexes support $geoWithin.

So the results are both good and bad. Good in that you can do this type of operation without an index in place, but bad because once the aggregation pipeline has altered the collection results after the first query operation the no further index can be used. So any performance benefit of an index is lost on merging the "set" results from anything after the initial Polygon/MultiPolygon as supported.

For this reason I would still recommend that you calculate the intersection bounds "outside" of the query issued to MongoDB. Even though the aggregation framework can do this due to the "chained" nature of the pipeline, and even though resulting intersections will get smaller and smaller, your best performance is a single query with the correct bounds that can use all of the index benefits.
There are various methods for doing that, but for reference here is an implementation using the JSTS library, which is a JavaScript port of the popular JTS library for Java. There may be others or other language ports, but this has simple GeoJSON parsing and built in methods for such things as getting the intersection bounds:
var async = require('async');
    util = require('util'),
    jsts = require('jsts'),
    mongo = require('mongodb'),
    MongoClient = mongo.MongoClient;

var parser = new jsts.io.GeoJSONParser();

var polys= [
  {
    type: 'Polygon',
    coordinates: [[
      [ 0, 0 ], [ 0, 10 ], [ 10, 10 ], [ 10, 0 ], [ 0, 0 ]
    ]]
  },
  {
    type: 'Polygon',
    coordinates: [[
      [ 5, 5 ], [ 5, 20 ], [ 20, 20 ], [ 20, 5 ], [ 5, 5 ]
    ]]
  }
];

var points = [
  { type: 'Point', coordinates: [ 4, 4 ]  },
  { type: 'Point', coordinates: [ 8, 8 ]  },
  { type: 'Point', coordinates: [ 12, 12 ] }
];

MongoClient.connect('mongodb://localhost/test',function(err,db) {

  db.collection('geotest',function(err,geo) {

    if (err) throw err;

    async.series(
      [
        // Insert some data
        function(callback) {
          var bulk = geo.initializeOrderedBulkOp();
          bulk.find({}).remove();
          async.each(points,function(point,callback) {
            bulk.insert({ "loc": point });
            callback();
          },function(err) {
            bulk.execute(callback);
          });
        },

        // Run each version of the query
        function(callback) {
          async.parallel(
            [
              // Aggregation
              function(callback) {
                var pipeline = [];
                polys.forEach(function(poly) {
                  pipeline.push({
                    "$match": {
                      "loc": {
                        "$geoWithin": {
                          "$geometry": poly
                        }
                      }
                    }
                  });
                });

                geo.aggregate(pipeline,callback);
              },

              // Using external set resolution
              function(callback) {
                var geos = polys.map(function(poly) {
                  return parser.read( poly );
                });

                var bounds = geos[0];

                for ( var x=1; x<geos.length; x++ ) {
                  bounds = bounds.intersection( geos[x] );
                }

                var coords = parser.write( bounds );

                geo.find({
                  "loc": {
                    "$geoWithin": {
                      "$geometry": coords
                    }
                  }
                }).toArray(callback);
              }
            ],
            callback
          );
        }
      ],
      function(err,results) {
        if (err) throw err;
        console.log(
          util.inspect( results.slice(-1), false, 12, true ) );
        db.close();
      }
    );

  });

});

Using the full GeoJSON "Polygon" representations there as this translates to what JTS can understand and work with. Chances are any input you might receive for a real application would be in this format as well rather than applying conveniences such as $box.
So it can be done with the aggregation framework, or even parallel queries merging the "set" of results. But while the aggregation framework may do it better than merging sets of results externally, the best results will always come from computing the bounds first.

A: In case anyone else looks at this, as of mongo version 2.4, you can use $geoIntersects to find the intersection of GeoJSON objects, which supports intersections of two polygons, among other types.
{
  <location field>: {
     $geoIntersects: {
        $geometry: {
           type: "<GeoJSON object type>" ,
           coordinates: [ <coordinates> ]
        }
     }
  }
}

There is a nice write up on this blog.


text:
Q: .subscribe() is not triggering for GET request in Angularjs 4 Just want to console log a response of GET request on page load.
Route localhost:4200/register is bound to register.component.ts:
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Response } from '@angular/http';
import { RegisterService } from './register.service';

@Component({
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.css'],
    providers: [ RegisterService ]
})
export class RegisterComponent implements OnInit {
    constructor(private registerService: RegisterService) { }

    ngOnInit() {
        console.log("Start");
        this.registerService.getData()
            .subscribe((data: Response) => console.log(data));
        console.log("End");
    }
}

File register.service.ts which is included goes like this:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

@Injectable()
export class RegisterService {
    constructor(private http: Http) { }

    getData() {
        return this.http.get('https://userndot-a528b.firebaseio.com/code.json');
    }
}

When going to /register, console prints Start & End but not the response from the firebase dummy server. I've added RegisterService  in providers array in app.module.ts too. Compilation shows no error.

A: register.service.ts
getData() {
return this.http.get('https://userndot-a528b.firebaseio.com/code.json');
.map(res => res.json());
}

register.component.ts
this.registerService.getData()
.subscribe(data => {
console.log("data",data);
})

A: Can you try with the below code . Added the map operator to get the json. you may have to use  import 'rxjs/Rx'; if you have not done already.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

@Injectable()
export class RegisterService {

constructor(private http: Http) { }
  getData() {
  return this.http.get('https://userndot-a528b.firebaseio.com/code.json')
 .map((res: Response)=> res.json());;
 }
}

A: Yoc can change you service as described by @Niladri or @Ravi Teja
or you can change this
this.registerService.getData()
        .subscribe((data: Response) => console.log(data));

to
this.registerService.getData()
            .subscribe((data) => console.log(data.json));


text:
Q: Show / hide php mysql results with loader I have MySQL database results.
I want to show 3 rows and then hide rest.
When the user clicks to load more data then to appear all rows.
The problem is when I click show more, then only one more row appears.
<?php
$query_brands = mysql_query("SELECT distinct pd_filter1 from tbl_brands2 WHERE pd_code in (select pd_code from tbl_product where cat_id='2')") or die(mysql_error());
$count_brands  = mysql_num_rows($query_brands);
  if($count_brands > 0) {
  while($fetch_brands = mysql_fetch_array($query_brands)) {
    $record_brands[] = $fetch_brands;
  }
  }

$i_brands=0;
foreach($record_brands as $records_brands) {
?>

<?php
      $i_brands = $i_brands + 1;
      if ($i_brands > 3)
        {
?>

<?php
        }
      }
?>

        show more...

        show less...

JavaScript
function myFunction() {
    var x_filter1_1 = document.getElementById("myDIV_Filter1_1");
    var x_filter1_2 = document.getElementById("myDIV_Filter1_2");
    var x_filter1_3 = document.getElementById("myDIV_Filter1_3");
    if (x_filter1_1.style.display === "none") {
        x_filter1_1.style.display = "block";
        x_filter1_2.style.display = "none";
        x_filter1_3.style.display = "block";
    } else {
        x_filter1_1.style.display = "none";
        x_filter1_2.style.display = "block";
        x_filter1_3.style.display = "none";
    }
}

A: You have some errors on your code:
1) Try not to use return the way you are using right now in code lines like this one:
show more...

You can use it better like it's explained here
2) You have all your divs of the code example in display none, the user will never see the information in those divs because you don't have any code to start showing some of them. In the same line you put a ";" after the style but it must  be inside the style. This line has an error:

It must be this way:

The "show-hide" logic on your javascript function myFunction has an error because your div id="myDIV_Filter1_1" contains the other 2 div you have on your code example so you can't hide this particular div because you will lose the "show" or "hide" of the other 2 divs. That way it'll never show you the other 3 rows you wanted to see. I fixed all the errors you can check the code on my snippet here:

function myFunction() {
    var x_filter1_1 = document.getElementById("myDIV_Filter1_1");
    var x_filter1_2 = document.getElementById("myDIV_Filter1_2");
    var x_filter1_3 = document.getElementById("myDIV_Filter1_3");
    if (x_filter1_3.style.display === "none") {
        x_filter1_1.style.display = "block";
        x_filter1_2.style.display = "none";
        x_filter1_3.style.display = "block";
    } else {
        x_filter1_1.style.display = "block";
        x_filter1_2.style.display = "block";
        x_filter1_3.style.display = "none";
    }
}
<?php
$query_brands = mysql_query("SELECT distinct pd_filter1 from tbl_brands2 WHERE pd_code in (select pd_code from tbl_product where cat_id='2')") or die(mysql_error());
$count_brands  = mysql_num_rows($query_brands);
  if($count_brands > 0) {
  while($fetch_brands = mysql_fetch_array($query_brands)) {
    $record_brands[] = $fetch_brands;
  }
  }

$i_brands=0;
foreach($record_brands as $records_brands) {
?>

<?php
      $i_brands = $i_brands + 1;
      if ($i_brands > 3)
        {
?>

<?php
        }
      }
?>

        show more...

        show less...

Hope it helps!


text:
Q: JavaFX Scene Builder Passing Paramters before the window opens I am trying to pass a string to the next window so when it loads it will show the data retrieved from the database, based on that string.
I have run into an issue where it will only set the string AFTER the window has loaded and it has attempted to fill the data out from the database so I am always left with an empty table.
I hardcoded the string in to make sure my function that pulls and prints the data is correct and it is its working so that leaves me the issue where I am passing the string from the previous screen to the next.
This is my code
    Stage app_stage =(Stage) ((Node) event.getSource()).getScene().getWindow();
    FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLMenu.fxml"));
    Parent menuPage_parent = loader.load();
    FXMLMenuController menuCon = loader.<FXMLMenuController>getController();
    usernametoPass = usernameField.getText();
    menuCon.setUname(usernametoPass); //THIS is the function that sets the string

    Scene menuPage_scene = new Scene(menuPage_parent);
    app_stage.hide();
    app_stage.setScene(menuPage_scene);
    app_stage.show();

Now using this on load by printing the string I always get null because its not set. However if I print the string AFTER the load(via button press) it shows the correct string.
Is there a way to set it before it loads?